src/HOL/Tools/Datatype/datatype.ML
author wenzelm
Sun Mar 07 12:19:47 2010 +0100 (2010-03-07)
changeset 35625 9c818cab0dd0
parent 35410 1ea89d2a1bd4
child 35742 eb8d2f668bfc
permissions -rw-r--r--
modernized structure Object_Logic;
     1 (*  Title:      HOL/Tools/Datatype/datatype.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Datatype package: definitional introduction of datatypes
     5 with proof of characteristic theorems: injectivity / distinctness
     6 of constructors and induction.  Main interface to datatypes
     7 after full bootstrap of datatype package.
     8 *)
     9 
    10 signature DATATYPE =
    11 sig
    12   include DATATYPE_DATA
    13   val add_datatype : config -> string list -> (string list * binding * mixfix *
    14     (binding * typ list * mixfix) list) list -> theory -> string list * theory
    15   val datatype_cmd : string list -> (string list * binding * mixfix *
    16     (binding * string list * mixfix) list) list -> theory -> theory
    17 end;
    18 
    19 structure Datatype : DATATYPE =
    20 struct
    21 
    22 (** auxiliary **)
    23 
    24 open Datatype_Aux;
    25 open Datatype_Data;
    26 
    27 val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
    28 
    29 val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
    30 
    31 fun exh_thm_of (dt_info : info Symtab.table) tname =
    32   #exhaust (the (Symtab.lookup dt_info tname));
    33 
    34 val node_name = @{type_name "Datatype.node"};
    35 val In0_name = @{const_name "Datatype.In0"};
    36 val In1_name = @{const_name "Datatype.In1"};
    37 val Scons_name = @{const_name "Datatype.Scons"};
    38 val Leaf_name = @{const_name "Datatype.Leaf"};
    39 val Lim_name = @{const_name "Datatype.Lim"};
    40 val Suml_name = @{const_name "Sum_Type.Suml"};
    41 val Sumr_name = @{const_name "Sum_Type.Sumr"};
    42 
    43 val In0_inject = @{thm In0_inject};
    44 val In1_inject = @{thm In1_inject};
    45 val Scons_inject = @{thm Scons_inject};
    46 val Leaf_inject = @{thm Leaf_inject};
    47 val In0_eq = @{thm In0_eq};
    48 val In1_eq = @{thm In1_eq};
    49 val In0_not_In1 = @{thm In0_not_In1};
    50 val In1_not_In0 = @{thm In1_not_In0};
    51 val Lim_inject = @{thm Lim_inject};
    52 val Inl_inject = @{thm Inl_inject};
    53 val Inr_inject = @{thm Inr_inject};
    54 val Suml_inject = @{thm Suml_inject};
    55 val Sumr_inject = @{thm Sumr_inject};
    56 
    57 
    58 
    59 (** proof of characteristic theorems **)
    60 
    61 fun representation_proofs (config : config) (dt_info : info Symtab.table)
    62       new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
    63   let
    64     val descr' = flat descr;
    65     val big_name = space_implode "_" new_type_names;
    66     val thy1 = Sign.add_path big_name thy;
    67     val big_rec_name = big_name ^ "_rep_set";
    68     val rep_set_names' =
    69       (if length descr' = 1 then [big_rec_name] else
    70         (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
    71           (1 upto (length descr'))));
    72     val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
    73 
    74     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
    75     val leafTs' = get_nonrec_types descr' sorts;
    76     val branchTs = get_branching_types descr' sorts;
    77     val branchT = if null branchTs then HOLogic.unitT
    78       else Balanced_Tree.make (fn (T, U) => Type (@{type_name "+"}, [T, U])) branchTs;
    79     val arities = remove (op =) 0 (get_arities descr');
    80     val unneeded_vars =
    81       subtract (op =) (List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs)) (hd tyvars);
    82     val leafTs = leafTs' @ map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars;
    83     val recTs = get_rec_types descr' sorts;
    84     val (newTs, oldTs) = chop (length (hd descr)) recTs;
    85     val sumT = if null leafTs then HOLogic.unitT
    86       else Balanced_Tree.make (fn (T, U) => Type (@{type_name "+"}, [T, U])) leafTs;
    87     val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
    88     val UnivT = HOLogic.mk_setT Univ_elT;
    89     val UnivT' = Univ_elT --> HOLogic.boolT;
    90     val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
    91 
    92     val In0 = Const (In0_name, Univ_elT --> Univ_elT);
    93     val In1 = Const (In1_name, Univ_elT --> Univ_elT);
    94     val Leaf = Const (Leaf_name, sumT --> Univ_elT);
    95     val Lim = Const (Lim_name, (branchT --> Univ_elT) --> Univ_elT);
    96 
    97     (* make injections needed for embedding types in leaves *)
    98 
    99     fun mk_inj T' x =
   100       let
   101         fun mk_inj' T n i =
   102           if n = 1 then x else
   103           let val n2 = n div 2;
   104               val Type (_, [T1, T2]) = T
   105           in
   106             if i <= n2 then
   107               Const (@{const_name Inl}, T1 --> T) $ (mk_inj' T1 n2 i)
   108             else
   109               Const (@{const_name Inr}, T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
   110           end
   111       in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs)
   112       end;
   113 
   114     (* make injections for constructors *)
   115 
   116     fun mk_univ_inj ts = Balanced_Tree.access
   117       {left = fn t => In0 $ t,
   118         right = fn t => In1 $ t,
   119         init =
   120           if ts = [] then Const (@{const_name undefined}, Univ_elT)
   121           else foldr1 (HOLogic.mk_binop Scons_name) ts};
   122 
   123     (* function spaces *)
   124 
   125     fun mk_fun_inj T' x =
   126       let
   127         fun mk_inj T n i =
   128           if n = 1 then x else
   129           let
   130             val n2 = n div 2;
   131             val Type (_, [T1, T2]) = T;
   132             fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
   133           in
   134             if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
   135             else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
   136           end
   137       in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs)
   138       end;
   139 
   140     fun mk_lim t Ts = fold_rev (fn T => fn t => Lim $ mk_fun_inj T (Abs ("x", T, t))) Ts t;
   141 
   142     (************** generate introduction rules for representing set **********)
   143 
   144     val _ = message config "Constructing representing sets ...";
   145 
   146     (* make introduction rule for a single constructor *)
   147 
   148     fun make_intr s n (i, (_, cargs)) =
   149       let
   150         fun mk_prem dt (j, prems, ts) =
   151           (case strip_dtyp dt of
   152             (dts, DtRec k) =>
   153               let
   154                 val Ts = map (typ_of_dtyp descr' sorts) dts;
   155                 val free_t =
   156                   app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
   157               in (j + 1, list_all (map (pair "x") Ts,
   158                   HOLogic.mk_Trueprop
   159                     (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
   160                 mk_lim free_t Ts :: ts)
   161               end
   162           | _ =>
   163               let val T = typ_of_dtyp descr' sorts dt
   164               in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
   165               end);
   166 
   167         val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
   168         val concl = HOLogic.mk_Trueprop
   169           (Free (s, UnivT') $ mk_univ_inj ts n i)
   170       in Logic.list_implies (prems, concl)
   171       end;
   172 
   173     val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
   174       map (make_intr rep_set_name (length constrs))
   175         ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
   176 
   177     val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
   178       thy1
   179       |> Sign.map_naming Name_Space.conceal
   180       |> Inductive.add_inductive_global
   181           {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
   182            coind = false, no_elim = true, no_ind = false, skip_mono = true, fork_mono = false}
   183           (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
   184           (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
   185       ||> Sign.restore_naming thy1
   186       ||> Theory.checkpoint;
   187 
   188     (********************************* typedef ********************************)
   189 
   190     val (typedefs, thy3) = thy2 |>
   191       Sign.parent_path |>
   192       fold_map (fn ((((name, mx), tvs), c), name') =>
   193           Typedef.add_typedef false (SOME (Binding.name name')) (name, tvs, mx)
   194             (Collect $ Const (c, UnivT')) NONE
   195             (rtac exI 1 THEN rtac CollectI 1 THEN
   196               QUIET_BREADTH_FIRST (has_fewer_prems 1)
   197               (resolve_tac rep_intrs 1)))
   198                 (types_syntax ~~ tyvars ~~
   199                   (take (length newTs) rep_set_names) ~~ new_type_names) ||>
   200       Sign.add_path big_name;
   201 
   202     (*********************** definition of constructors ***********************)
   203 
   204     val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
   205     val rep_names = map (curry op ^ "Rep_") new_type_names;
   206     val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
   207       (1 upto (length (flat (tl descr))));
   208     val all_rep_names = map (Sign.intern_const thy3) rep_names @
   209       map (Sign.full_bname thy3) rep_names';
   210 
   211     (* isomorphism declarations *)
   212 
   213     val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
   214       (oldTs ~~ rep_names');
   215 
   216     (* constructor definitions *)
   217 
   218     fun make_constr_def tname T n ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
   219       let
   220         fun constr_arg dt (j, l_args, r_args) =
   221           let val T = typ_of_dtyp descr' sorts dt;
   222               val free_t = mk_Free "x" T j
   223           in (case (strip_dtyp dt, strip_type T) of
   224               ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim
   225                 (Const (nth all_rep_names m, U --> Univ_elT) $
   226                    app_bnds free_t (length Us)) Us :: r_args)
   227             | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
   228           end;
   229 
   230         val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
   231         val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
   232         val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
   233         val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
   234         val lhs = list_comb (Const (cname, constrT), l_args);
   235         val rhs = mk_univ_inj r_args n i;
   236         val def = Logic.mk_equals (lhs, Const (abs_name, Univ_elT --> T) $ rhs);
   237         val def_name = Long_Name.base_name cname ^ "_def";
   238         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   239           (Const (rep_name, T --> Univ_elT) $ lhs, rhs));
   240         val ([def_thm], thy') =
   241           thy
   242           |> Sign.add_consts_i [(cname', constrT, mx)]
   243           |> (PureThy.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
   244 
   245       in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
   246 
   247     (* constructor definitions for datatype *)
   248 
   249     fun dt_constr_defs ((((_, (_, _, constrs)), tname), T), constr_syntax)
   250         (thy, defs, eqns, rep_congs, dist_lemmas) =
   251       let
   252         val _ $ (_ $ (cong_f $ _) $ _) = concl_of arg_cong;
   253         val rep_const = cterm_of thy
   254           (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> Univ_elT));
   255         val cong' =
   256           Drule.export_without_context
   257             (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
   258         val dist =
   259           Drule.export_without_context
   260             (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
   261         val (thy', defs', eqns', _) = fold ((make_constr_def tname T) (length constrs))
   262           (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
   263       in
   264         (Sign.parent_path thy', defs', eqns @ [eqns'],
   265           rep_congs @ [cong'], dist_lemmas @ [dist])
   266       end;
   267 
   268     val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
   269       fold dt_constr_defs
   270         (hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax)
   271         (thy3 |> Sign.add_consts_i iso_decls |> Sign.parent_path, [], [], [], []);
   272 
   273 
   274     (*********** isomorphisms for new types (introduced by typedef) ***********)
   275 
   276     val _ = message config "Proving isomorphism properties ...";
   277 
   278     val newT_iso_axms = map (fn (_, td) =>
   279       (collect_simp (#Abs_inverse td), #Rep_inverse td,
   280        collect_simp (#Rep td))) typedefs;
   281 
   282     val newT_iso_inj_thms = map (fn (_, td) =>
   283       (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
   284 
   285     (********* isomorphisms between existing types and "unfolded" types *******)
   286 
   287     (*---------------------------------------------------------------------*)
   288     (* isomorphisms are defined using primrec-combinators:                 *)
   289     (* generate appropriate functions for instantiating primrec-combinator *)
   290     (*                                                                     *)
   291     (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
   292     (*                                                                     *)
   293     (* also generate characteristic equations for isomorphisms             *)
   294     (*                                                                     *)
   295     (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
   296     (*---------------------------------------------------------------------*)
   297 
   298     fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
   299       let
   300         val argTs = map (typ_of_dtyp descr' sorts) cargs;
   301         val T = nth recTs k;
   302         val rep_name = nth all_rep_names k;
   303         val rep_const = Const (rep_name, T --> Univ_elT);
   304         val constr = Const (cname, argTs ---> T);
   305 
   306         fun process_arg ks' dt (i2, i2', ts, Ts) =
   307           let
   308             val T' = typ_of_dtyp descr' sorts dt;
   309             val (Us, U) = strip_type T'
   310           in (case strip_dtyp dt of
   311               (_, DtRec j) => if j mem ks' then
   312                   (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
   313                      (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
   314                    Ts @ [Us ---> Univ_elT])
   315                 else
   316                   (i2 + 1, i2', ts @ [mk_lim
   317                      (Const (nth all_rep_names j, U --> Univ_elT) $
   318                         app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
   319             | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
   320           end;
   321 
   322         val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
   323         val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
   324         val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
   325         val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
   326 
   327         val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
   328         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   329           (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
   330 
   331       in (fs @ [f], eqns @ [eqn], i + 1) end;
   332 
   333     (* define isomorphisms for all mutually recursive datatypes in list ds *)
   334 
   335     fun make_iso_defs ds (thy, char_thms) =
   336       let
   337         val ks = map fst ds;
   338         val (_, (tname, _, _)) = hd ds;
   339         val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
   340 
   341         fun process_dt (k, (tname, _, constrs)) (fs, eqns, isos) =
   342           let
   343             val (fs', eqns', _) =
   344               fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
   345             val iso = (nth recTs k, nth all_rep_names k)
   346           in (fs', eqns', isos @ [iso]) end;
   347         
   348         val (fs, eqns, isos) = fold process_dt ds ([], [], []);
   349         val fTs = map fastype_of fs;
   350         val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
   351           Logic.mk_equals (Const (iso_name, T --> Univ_elT),
   352             list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
   353         val (def_thms, thy') =
   354           apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
   355 
   356         (* prove characteristic equations *)
   357 
   358         val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
   359         val char_thms' = map (fn eqn => Skip_Proof.prove_global thy' [] [] eqn
   360           (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
   361 
   362       in (thy', char_thms' @ char_thms) end;
   363 
   364     val (thy5, iso_char_thms) = apfst Theory.checkpoint (fold_rev make_iso_defs
   365         (tl descr) (Sign.add_path big_name thy4, []));
   366 
   367     (* prove isomorphism properties *)
   368 
   369     fun mk_funs_inv thy thm =
   370       let
   371         val prop = Thm.prop_of thm;
   372         val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
   373           (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
   374         val used = OldTerm.add_term_tfree_names (a, []);
   375 
   376         fun mk_thm i =
   377           let
   378             val Ts = map (TFree o rpair HOLogic.typeS)
   379               (Name.variant_list used (replicate i "'t"));
   380             val f = Free ("f", Ts ---> U)
   381           in Skip_Proof.prove_global thy [] [] (Logic.mk_implies
   382             (HOLogic.mk_Trueprop (HOLogic.list_all
   383                (map (pair "x") Ts, S $ app_bnds f i)),
   384              HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
   385                r $ (a $ app_bnds f i)), f))))
   386             (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
   387                REPEAT (etac allE 1), rtac thm 1, atac 1])
   388           end
   389       in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
   390 
   391     (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
   392 
   393     val fun_congs = map (fn T => make_elim (Drule.instantiate'
   394       [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
   395 
   396     fun prove_iso_thms ds (inj_thms, elem_thms) =
   397       let
   398         val (_, (tname, _, _)) = hd ds;
   399         val induct = (#induct o the o Symtab.lookup dt_info) tname;
   400 
   401         fun mk_ind_concl (i, _) =
   402           let
   403             val T = nth recTs i;
   404             val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
   405             val rep_set_name = nth rep_set_names i
   406           in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
   407                 HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
   408                   HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
   409               Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
   410           end;
   411 
   412         val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
   413 
   414         val rewrites = map mk_meta_eq iso_char_thms;
   415         val inj_thms' = map snd newT_iso_inj_thms @
   416           map (fn r => r RS @{thm injD}) inj_thms;
   417 
   418         val inj_thm = Skip_Proof.prove_global thy5 [] []
   419           (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
   420             [(indtac induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
   421              REPEAT (EVERY
   422                [rtac allI 1, rtac impI 1,
   423                 exh_tac (exh_thm_of dt_info) 1,
   424                 REPEAT (EVERY
   425                   [hyp_subst_tac 1,
   426                    rewrite_goals_tac rewrites,
   427                    REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   428                    (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
   429                    ORELSE (EVERY
   430                      [REPEAT (eresolve_tac (Scons_inject ::
   431                         map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
   432                       REPEAT (cong_tac 1), rtac refl 1,
   433                       REPEAT (atac 1 ORELSE (EVERY
   434                         [REPEAT (rtac ext 1),
   435                          REPEAT (eresolve_tac (mp :: allE ::
   436                            map make_elim (Suml_inject :: Sumr_inject ::
   437                              Lim_inject :: inj_thms') @ fun_congs) 1),
   438                          atac 1]))])])])]);
   439 
   440         val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
   441                              (split_conj_thm inj_thm);
   442 
   443         val elem_thm = 
   444             Skip_Proof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
   445               (fn _ =>
   446                EVERY [(indtac induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
   447                 rewrite_goals_tac rewrites,
   448                 REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
   449                   ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
   450 
   451       in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
   452       end;
   453 
   454     val (iso_inj_thms_unfolded, iso_elem_thms) =
   455       fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
   456     val iso_inj_thms = map snd newT_iso_inj_thms @
   457       map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
   458 
   459     (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
   460 
   461     fun mk_iso_t (((set_name, iso_name), i), T) =
   462       let val isoT = T --> Univ_elT
   463       in HOLogic.imp $ 
   464         (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
   465           (if i < length newTs then HOLogic.true_const
   466            else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
   467              Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
   468                Const (iso_name, isoT) $ Const (@{const_abbrev UNIV}, HOLogic.mk_setT T)))
   469       end;
   470 
   471     val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
   472       (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
   473 
   474     (* all the theorems are proved by one single simultaneous induction *)
   475 
   476     val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
   477       iso_inj_thms_unfolded;
   478 
   479     val iso_thms = if length descr = 1 then [] else
   480       drop (length newTs) (split_conj_thm
   481         (Skip_Proof.prove_global thy5 [] [] iso_t (fn _ => EVERY
   482            [(indtac rep_induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
   483             REPEAT (rtac TrueI 1),
   484             rewrite_goals_tac (mk_meta_eq @{thm choice_eq} ::
   485               symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
   486             rewrite_goals_tac (map symmetric range_eqs),
   487             REPEAT (EVERY
   488               [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
   489                  maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
   490                TRY (hyp_subst_tac 1),
   491                rtac (sym RS range_eqI) 1,
   492                resolve_tac iso_char_thms 1])])));
   493 
   494     val Abs_inverse_thms' =
   495       map #1 newT_iso_axms @
   496       map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
   497         iso_inj_thms_unfolded iso_thms;
   498 
   499     val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
   500 
   501     (******************* freeness theorems for constructors *******************)
   502 
   503     val _ = message config "Proving freeness of constructors ...";
   504 
   505     (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
   506     
   507     fun prove_constr_rep_thm eqn =
   508       let
   509         val inj_thms = map fst newT_iso_inj_thms;
   510         val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
   511       in Skip_Proof.prove_global thy5 [] [] eqn (fn _ => EVERY
   512         [resolve_tac inj_thms 1,
   513          rewrite_goals_tac rewrites,
   514          rtac refl 3,
   515          resolve_tac rep_intrs 2,
   516          REPEAT (resolve_tac iso_elem_thms 1)])
   517       end;
   518 
   519     (*--------------------------------------------------------------*)
   520     (* constr_rep_thms and rep_congs are used to prove distinctness *)
   521     (* of constructors.                                             *)
   522     (*--------------------------------------------------------------*)
   523 
   524     val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
   525 
   526     val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
   527       dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   528         (constr_rep_thms ~~ dist_lemmas);
   529 
   530     fun prove_distinct_thms dist_rewrites' (k, ts) =
   531       let
   532         fun prove [] = []
   533           | prove (t :: ts) =
   534               let
   535                 val dist_thm = Skip_Proof.prove_global thy5 [] [] t (fn _ =>
   536                   EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
   537               in dist_thm :: Drule.export_without_context (dist_thm RS not_sym) :: prove ts end;
   538       in prove ts end;
   539 
   540     val distinct_thms = map2 (prove_distinct_thms)
   541       dist_rewrites (Datatype_Prop.make_distincts descr sorts);
   542 
   543     (* prove injectivity of constructors *)
   544 
   545     fun prove_constr_inj_thm rep_thms t =
   546       let val inj_thms = Scons_inject :: (map make_elim
   547         (iso_inj_thms @
   548           [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
   549            Lim_inject, Suml_inject, Sumr_inject]))
   550       in Skip_Proof.prove_global thy5 [] [] t (fn _ => EVERY
   551         [rtac iffI 1,
   552          REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
   553          dresolve_tac rep_congs 1, dtac box_equals 1,
   554          REPEAT (resolve_tac rep_thms 1),
   555          REPEAT (eresolve_tac inj_thms 1),
   556          REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
   557            REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
   558            atac 1]))])
   559       end;
   560 
   561     val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
   562       ((Datatype_Prop.make_injs descr sorts) ~~ constr_rep_thms);
   563 
   564     val ((constr_inject', distinct_thms'), thy6) =
   565       thy5
   566       |> Sign.parent_path
   567       |> store_thmss "inject" new_type_names constr_inject
   568       ||>> store_thmss "distinct" new_type_names distinct_thms;
   569 
   570     (*************************** induction theorem ****************************)
   571 
   572     val _ = message config "Proving induction rule for datatypes ...";
   573 
   574     val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
   575       (map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded);
   576     val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
   577 
   578     fun mk_indrule_lemma ((i, _), T) (prems, concls) =
   579       let
   580         val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $
   581           mk_Free "x" T i;
   582 
   583         val Abs_t = if i < length newTs then
   584             Const (Sign.intern_const thy6
   585               ("Abs_" ^ (nth new_type_names i)), Univ_elT --> T)
   586           else Const (@{const_name the_inv_into},
   587               [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
   588             HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT)
   589 
   590       in (prems @ [HOLogic.imp $
   591             (Const (nth rep_set_names i, UnivT') $ Rep_t) $
   592               (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
   593           concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
   594       end;
   595 
   596     val (indrule_lemma_prems, indrule_lemma_concls) =
   597       fold mk_indrule_lemma (descr' ~~ recTs) ([], []);
   598 
   599     val cert = cterm_of thy6;
   600 
   601     val indrule_lemma = Skip_Proof.prove_global thy6 [] []
   602       (Logic.mk_implies
   603         (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
   604          HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
   605            [REPEAT (etac conjE 1),
   606             REPEAT (EVERY
   607               [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
   608                etac mp 1, resolve_tac iso_elem_thms 1])]);
   609 
   610     val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
   611     val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
   612       map (Free o apfst fst o dest_Var) Ps;
   613     val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
   614 
   615     val dt_induct_prop = Datatype_Prop.make_ind descr sorts;
   616     val dt_induct = Skip_Proof.prove_global thy6 []
   617       (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
   618       (fn {prems, ...} => EVERY
   619         [rtac indrule_lemma' 1,
   620          (indtac rep_induct [] THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1,
   621          EVERY (map (fn (prem, r) => (EVERY
   622            [REPEAT (eresolve_tac Abs_inverse_thms 1),
   623             simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
   624             DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
   625                 (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
   626 
   627     val ([dt_induct'], thy7) =
   628       thy6
   629       |> Sign.add_path big_name
   630       |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
   631       ||> Sign.parent_path
   632       ||> Theory.checkpoint;
   633 
   634   in
   635     ((constr_inject', distinct_thms', dt_induct'), thy7)
   636   end;
   637 
   638 
   639 
   640 (** definitional introduction of datatypes **)
   641 
   642 fun gen_add_datatype prep_typ config new_type_names dts thy =
   643   let
   644     val _ = Theory.requires thy "Datatype" "datatype definitions";
   645 
   646     (* this theory is used just for parsing *)
   647     val tmp_thy = thy |>
   648       Theory.copy |>
   649       Sign.add_types (map (fn (tvs, tname, mx, _) =>
   650         (tname, length tvs, mx)) dts);
   651 
   652     val (tyvars, _, _, _)::_ = dts;
   653     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   654       let val full_tname = Sign.full_name tmp_thy tname
   655       in
   656         (case duplicates (op =) tvs of
   657           [] =>
   658             if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   659             else error ("Mutually recursive datatypes must have same type parameters")
   660         | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
   661             " : " ^ commas dups))
   662       end) dts);
   663     val dt_names = map fst new_dts;
   664 
   665     val _ =
   666       (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
   667         [] => ()
   668       | dups => error ("Duplicate datatypes: " ^ commas dups));
   669 
   670     fun prep_dt_spec (tvs, tname, mx, constrs) tname' (dts', constr_syntax, sorts, i) =
   671       let
   672         fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
   673           let
   674             val (cargs', sorts'') = fold_map (prep_typ tmp_thy) cargs sorts';
   675             val _ =
   676               (case subtract (op =) tvs (fold (curry OldTerm.add_typ_tfree_names) cargs' []) of
   677                 [] => ()
   678               | vs => error ("Extra type variables on rhs: " ^ commas vs));
   679             val c = Sign.full_name_path tmp_thy tname' cname;
   680           in
   681             (constrs @ [(c, map (dtyp_of_typ new_dts) cargs')],
   682               constr_syntax' @ [(cname, mx')], sorts'')
   683           end handle ERROR msg => cat_error msg
   684            ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
   685             " of datatype " ^ quote (Binding.str_of tname));
   686 
   687         val (constrs', constr_syntax', sorts') =
   688           fold prep_constr constrs ([], [], sorts)
   689       in
   690         case duplicates (op =) (map fst constrs') of
   691           [] =>
   692             (dts' @ [(i, (Sign.full_name tmp_thy tname, map DtTFree tvs, constrs'))],
   693               constr_syntax @ [constr_syntax'], sorts', i + 1)
   694         | dups => error ("Duplicate constructors " ^ commas dups ^
   695              " in datatype " ^ quote (Binding.str_of tname))
   696       end;
   697 
   698     val (dts', constr_syntax, sorts', i) =
   699       fold2 prep_dt_spec dts new_type_names ([], [], [], 0);
   700     val sorts = sorts' @ map (rpair (Sign.defaultS tmp_thy)) (subtract (op =) (map fst sorts') tyvars);
   701     val dt_info = Datatype_Data.get_all thy;
   702     val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
   703     val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
   704       if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
   705       else raise exn;
   706 
   707     val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
   708 
   709   in
   710     thy
   711     |> representation_proofs config dt_info new_type_names descr sorts
   712         types_syntax constr_syntax (Datatype_Data.mk_case_names_induct (flat descr))
   713     |-> (fn (inject, distinct, induct) => Datatype_Data.derive_datatype_props
   714         config dt_names (SOME new_type_names) descr sorts
   715         induct inject distinct)
   716   end;
   717 
   718 val add_datatype = gen_add_datatype Datatype_Data.cert_typ;
   719 val datatype_cmd = snd ooo gen_add_datatype Datatype_Data.read_typ default_config;
   720 
   721 local
   722 
   723 structure P = OuterParse and K = OuterKeyword
   724 
   725 fun prep_datatype_decls args =
   726   let
   727     val names = map
   728       (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
   729     val specs = map (fn ((((_, vs), t), mx), cons) =>
   730       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   731   in (names, specs) end;
   732 
   733 val parse_datatype_decl =
   734   (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_mixfix --
   735     (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
   736 
   737 val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
   738 
   739 in
   740 
   741 val _ =
   742   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   743     (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
   744 
   745 end;
   746 
   747 end;