src/HOL/Tools/datatype_package/datatype_rep_proofs.ML
author haftmann
Tue Jun 16 16:37:07 2009 +0200 (2009-06-16)
changeset 31668 a616e56a5ec8
parent 31643 b040f1679f77
child 31723 f5cafe803b55
permissions -rw-r--r--
datatype packages: record datatype_config for configuration flags; less verbose signatures
     1 (*  Title:      HOL/Tools/datatype_rep_proofs.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Definitional introduction of datatypes
     5 Proof of characteristic theorems:
     6 
     7  - injectivity of constructors
     8  - distinctness of constructors
     9  - induction theorem
    10 *)
    11 
    12 signature DATATYPE_REP_PROOFS =
    13 sig
    14   type datatype_config = DatatypeAux.datatype_config
    15   type descr = DatatypeAux.descr
    16   type datatype_info = DatatypeAux.datatype_info
    17   val distinctness_limit : int Config.T
    18   val distinctness_limit_setup : theory -> theory
    19   val representation_proofs : datatype_config -> datatype_info Symtab.table ->
    20     string list -> descr list -> (string * sort) list ->
    21       (binding * mixfix) list -> (binding * mixfix) list list -> attribute
    22         -> theory -> (thm list list * thm list list * thm list list *
    23           DatatypeAux.simproc_dist list * thm) * theory
    24 end;
    25 
    26 structure DatatypeRepProofs : DATATYPE_REP_PROOFS =
    27 struct
    28 
    29 open DatatypeAux;
    30 
    31 (*the kind of distinctiveness axioms depends on number of constructors*)
    32 val (distinctness_limit, distinctness_limit_setup) =
    33   Attrib.config_int "datatype_distinctness_limit" 7;
    34 
    35 val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
    36 
    37 val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
    38 
    39 
    40 (** theory context references **)
    41 
    42 val f_myinv_f = thm "f_myinv_f";
    43 val myinv_f_f = thm "myinv_f_f";
    44 
    45 
    46 fun exh_thm_of (dt_info : datatype_info Symtab.table) tname =
    47   #exhaustion (the (Symtab.lookup dt_info tname));
    48 
    49 (******************************************************************************)
    50 
    51 fun representation_proofs (config : datatype_config) (dt_info : datatype_info Symtab.table)
    52       new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
    53   let
    54     val Datatype_thy = ThyInfo.the_theory "Datatype" thy;
    55     val node_name = "Datatype.node";
    56     val In0_name = "Datatype.In0";
    57     val In1_name = "Datatype.In1";
    58     val Scons_name = "Datatype.Scons";
    59     val Leaf_name = "Datatype.Leaf";
    60     val Numb_name = "Datatype.Numb";
    61     val Lim_name = "Datatype.Lim";
    62     val Suml_name = "Datatype.Suml";
    63     val Sumr_name = "Datatype.Sumr";
    64 
    65     val [In0_inject, In1_inject, Scons_inject, Leaf_inject,
    66          In0_eq, In1_eq, In0_not_In1, In1_not_In0,
    67          Lim_inject, Suml_inject, Sumr_inject] = map (PureThy.get_thm Datatype_thy)
    68           ["In0_inject", "In1_inject", "Scons_inject", "Leaf_inject",
    69            "In0_eq", "In1_eq", "In0_not_In1", "In1_not_In0",
    70            "Lim_inject", "Suml_inject", "Sumr_inject"];
    71 
    72     val descr' = flat descr;
    73 
    74     val big_name = space_implode "_" new_type_names;
    75     val thy1 = add_path (#flat_names config) big_name thy;
    76     val big_rec_name = big_name ^ "_rep_set";
    77     val rep_set_names' =
    78       (if length descr' = 1 then [big_rec_name] else
    79         (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
    80           (1 upto (length descr'))));
    81     val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
    82 
    83     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
    84     val leafTs' = get_nonrec_types descr' sorts;
    85     val branchTs = get_branching_types descr' sorts;
    86     val branchT = if null branchTs then HOLogic.unitT
    87       else BalancedTree.make (fn (T, U) => Type ("+", [T, U])) branchTs;
    88     val arities = get_arities descr' \ 0;
    89     val unneeded_vars = hd tyvars \\ List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs);
    90     val leafTs = leafTs' @ (map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars);
    91     val recTs = get_rec_types descr' sorts;
    92     val newTs = Library.take (length (hd descr), recTs);
    93     val oldTs = Library.drop (length (hd descr), recTs);
    94     val sumT = if null leafTs then HOLogic.unitT
    95       else BalancedTree.make (fn (T, U) => Type ("+", [T, U])) leafTs;
    96     val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
    97     val UnivT = HOLogic.mk_setT Univ_elT;
    98     val UnivT' = Univ_elT --> HOLogic.boolT;
    99     val Collect = Const ("Collect", UnivT' --> UnivT);
   100 
   101     val In0 = Const (In0_name, Univ_elT --> Univ_elT);
   102     val In1 = Const (In1_name, Univ_elT --> Univ_elT);
   103     val Leaf = Const (Leaf_name, sumT --> Univ_elT);
   104     val Lim = Const (Lim_name, (branchT --> Univ_elT) --> Univ_elT);
   105 
   106     (* make injections needed for embedding types in leaves *)
   107 
   108     fun mk_inj T' x =
   109       let
   110         fun mk_inj' T n i =
   111           if n = 1 then x else
   112           let val n2 = n div 2;
   113               val Type (_, [T1, T2]) = T
   114           in
   115             if i <= n2 then
   116               Const ("Sum_Type.Inl", T1 --> T) $ (mk_inj' T1 n2 i)
   117             else
   118               Const ("Sum_Type.Inr", T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
   119           end
   120       in mk_inj' sumT (length leafTs) (1 + find_index_eq T' leafTs)
   121       end;
   122 
   123     (* make injections for constructors *)
   124 
   125     fun mk_univ_inj ts = BalancedTree.access
   126       {left = fn t => In0 $ t,
   127         right = fn t => In1 $ t,
   128         init =
   129           if ts = [] then Const (@{const_name undefined}, Univ_elT)
   130           else foldr1 (HOLogic.mk_binop Scons_name) ts};
   131 
   132     (* function spaces *)
   133 
   134     fun mk_fun_inj T' x =
   135       let
   136         fun mk_inj T n i =
   137           if n = 1 then x else
   138           let
   139             val n2 = n div 2;
   140             val Type (_, [T1, T2]) = T;
   141             fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
   142           in
   143             if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
   144             else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
   145           end
   146       in mk_inj branchT (length branchTs) (1 + find_index_eq T' branchTs)
   147       end;
   148 
   149     val mk_lim = List.foldr (fn (T, t) => Lim $ mk_fun_inj T (Abs ("x", T, t)));
   150 
   151     (************** generate introduction rules for representing set **********)
   152 
   153     val _ = message config "Constructing representing sets ...";
   154 
   155     (* make introduction rule for a single constructor *)
   156 
   157     fun make_intr s n (i, (_, cargs)) =
   158       let
   159         fun mk_prem (dt, (j, prems, ts)) = (case strip_dtyp dt of
   160             (dts, DtRec k) =>
   161               let
   162                 val Ts = map (typ_of_dtyp descr' sorts) dts;
   163                 val free_t =
   164                   app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
   165               in (j + 1, list_all (map (pair "x") Ts,
   166                   HOLogic.mk_Trueprop
   167                     (Free (List.nth (rep_set_names', k), UnivT') $ free_t)) :: prems,
   168                 mk_lim free_t Ts :: ts)
   169               end
   170           | _ =>
   171               let val T = typ_of_dtyp descr' sorts dt
   172               in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
   173               end);
   174 
   175         val (_, prems, ts) = List.foldr mk_prem (1, [], []) cargs;
   176         val concl = HOLogic.mk_Trueprop
   177           (Free (s, UnivT') $ mk_univ_inj ts n i)
   178       in Logic.list_implies (prems, concl)
   179       end;
   180 
   181     val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
   182       map (make_intr rep_set_name (length constrs))
   183         ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
   184 
   185     val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
   186         InductivePackage.add_inductive_global (serial_string ())
   187           {quiet_mode = #quiet config, verbose = false, kind = Thm.internalK,
   188            alt_name = Binding.name big_rec_name, coind = false, no_elim = true, no_ind = false,
   189            skip_mono = true, fork_mono = false}
   190           (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
   191           (map (fn x => (Attrib.empty_binding, x)) intr_ts) [] thy1;
   192 
   193     (********************************* typedef ********************************)
   194 
   195     val (typedefs, thy3) = thy2 |>
   196       parent_path (#flat_names config) |>
   197       fold_map (fn ((((name, mx), tvs), c), name') =>
   198           TypedefPackage.add_typedef false (SOME (Binding.name name')) (name, tvs, mx)
   199             (Collect $ Const (c, UnivT')) NONE
   200             (rtac exI 1 THEN rtac CollectI 1 THEN
   201               QUIET_BREADTH_FIRST (has_fewer_prems 1)
   202               (resolve_tac rep_intrs 1)))
   203                 (types_syntax ~~ tyvars ~~
   204                   (Library.take (length newTs, rep_set_names)) ~~ new_type_names) ||>
   205       add_path (#flat_names config) big_name;
   206 
   207     (*********************** definition of constructors ***********************)
   208 
   209     val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
   210     val rep_names = map (curry op ^ "Rep_") new_type_names;
   211     val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
   212       (1 upto (length (flat (tl descr))));
   213     val all_rep_names = map (Sign.intern_const thy3) rep_names @
   214       map (Sign.full_bname thy3) rep_names';
   215 
   216     (* isomorphism declarations *)
   217 
   218     val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
   219       (oldTs ~~ rep_names');
   220 
   221     (* constructor definitions *)
   222 
   223     fun make_constr_def tname T n ((thy, defs, eqns, i), ((cname, cargs), (cname', mx))) =
   224       let
   225         fun constr_arg (dt, (j, l_args, r_args)) =
   226           let val T = typ_of_dtyp descr' sorts dt;
   227               val free_t = mk_Free "x" T j
   228           in (case (strip_dtyp dt, strip_type T) of
   229               ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim
   230                 (Const (List.nth (all_rep_names, m), U --> Univ_elT) $
   231                    app_bnds free_t (length Us)) Us :: r_args)
   232             | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
   233           end;
   234 
   235         val (_, l_args, r_args) = List.foldr constr_arg (1, [], []) cargs;
   236         val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
   237         val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
   238         val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
   239         val lhs = list_comb (Const (cname, constrT), l_args);
   240         val rhs = mk_univ_inj r_args n i;
   241         val def = Logic.mk_equals (lhs, Const (abs_name, Univ_elT --> T) $ rhs);
   242         val def_name = Long_Name.base_name cname ^ "_def";
   243         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   244           (Const (rep_name, T --> Univ_elT) $ lhs, rhs));
   245         val ([def_thm], thy') =
   246           thy
   247           |> Sign.add_consts_i [(cname', constrT, mx)]
   248           |> (PureThy.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
   249 
   250       in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
   251 
   252     (* constructor definitions for datatype *)
   253 
   254     fun dt_constr_defs ((thy, defs, eqns, rep_congs, dist_lemmas),
   255         ((((_, (_, _, constrs)), tname), T), constr_syntax)) =
   256       let
   257         val _ $ (_ $ (cong_f $ _) $ _) = concl_of arg_cong;
   258         val rep_const = cterm_of thy
   259           (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> Univ_elT));
   260         val cong' = standard (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
   261         val dist = standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
   262         val (thy', defs', eqns', _) = Library.foldl ((make_constr_def tname T) (length constrs))
   263           ((add_path (#flat_names config) tname thy, defs, [], 1), constrs ~~ constr_syntax)
   264       in
   265         (parent_path (#flat_names config) thy', defs', eqns @ [eqns'],
   266           rep_congs @ [cong'], dist_lemmas @ [dist])
   267       end;
   268 
   269     val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) = Library.foldl dt_constr_defs
   270       ((thy3 |> Sign.add_consts_i iso_decls |> parent_path (#flat_names config), [], [], [], []),
   271         hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax);
   272 
   273     (*********** isomorphisms for new types (introduced by typedef) ***********)
   274 
   275     val _ = message config "Proving isomorphism properties ...";
   276 
   277     val newT_iso_axms = map (fn (_, td) =>
   278       (collect_simp (#Abs_inverse td), #Rep_inverse td,
   279        collect_simp (#Rep td))) typedefs;
   280 
   281     val newT_iso_inj_thms = map (fn (_, td) =>
   282       (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
   283 
   284     (********* isomorphisms between existing types and "unfolded" types *******)
   285 
   286     (*---------------------------------------------------------------------*)
   287     (* isomorphisms are defined using primrec-combinators:                 *)
   288     (* generate appropriate functions for instantiating primrec-combinator *)
   289     (*                                                                     *)
   290     (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
   291     (*                                                                     *)
   292     (* also generate characteristic equations for isomorphisms             *)
   293     (*                                                                     *)
   294     (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
   295     (*---------------------------------------------------------------------*)
   296 
   297     fun make_iso_def k ks n ((fs, eqns, i), (cname, cargs)) =
   298       let
   299         val argTs = map (typ_of_dtyp descr' sorts) cargs;
   300         val T = List.nth (recTs, k);
   301         val rep_name = List.nth (all_rep_names, k);
   302         val rep_const = Const (rep_name, T --> Univ_elT);
   303         val constr = Const (cname, argTs ---> T);
   304 
   305         fun process_arg ks' ((i2, i2', ts, Ts), dt) =
   306           let
   307             val T' = typ_of_dtyp descr' sorts dt;
   308             val (Us, U) = strip_type T'
   309           in (case strip_dtyp dt of
   310               (_, DtRec j) => if j mem ks' then
   311                   (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
   312                      (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
   313                    Ts @ [Us ---> Univ_elT])
   314                 else
   315                   (i2 + 1, i2', ts @ [mk_lim
   316                      (Const (List.nth (all_rep_names, j), U --> Univ_elT) $
   317                         app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
   318             | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (mk_Free "x" T' i2)], Ts))
   319           end;
   320 
   321         val (i2, i2', ts, Ts) = Library.foldl (process_arg ks) ((1, 1, [], []), cargs);
   322         val xs = map (uncurry (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
   323         val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
   324         val f = list_abs_free (map dest_Free (xs @ ys), mk_univ_inj ts n i);
   325 
   326         val (_, _, ts', _) = Library.foldl (process_arg []) ((1, 1, [], []), cargs);
   327         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   328           (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
   329 
   330       in (fs @ [f], eqns @ [eqn], i + 1) end;
   331 
   332     (* define isomorphisms for all mutually recursive datatypes in list ds *)
   333 
   334     fun make_iso_defs (ds, (thy, char_thms)) =
   335       let
   336         val ks = map fst ds;
   337         val (_, (tname, _, _)) = hd ds;
   338         val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
   339 
   340         fun process_dt ((fs, eqns, isos), (k, (tname, _, constrs))) =
   341           let
   342             val (fs', eqns', _) = Library.foldl (make_iso_def k ks (length constrs))
   343               ((fs, eqns, 1), constrs);
   344             val iso = (List.nth (recTs, k), List.nth (all_rep_names, k))
   345           in (fs', eqns', isos @ [iso]) end;
   346         
   347         val (fs, eqns, isos) = Library.foldl process_dt (([], [], []), ds);
   348         val fTs = map fastype_of fs;
   349         val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
   350           Logic.mk_equals (Const (iso_name, T --> Univ_elT),
   351             list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
   352         val (def_thms, thy') =
   353           apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
   354 
   355         (* prove characteristic equations *)
   356 
   357         val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
   358         val char_thms' = map (fn eqn => SkipProof.prove_global thy' [] [] eqn
   359           (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
   360 
   361       in (thy', char_thms' @ char_thms) end;
   362 
   363     val (thy5, iso_char_thms) = apfst Theory.checkpoint (List.foldr make_iso_defs
   364       (add_path (#flat_names config) big_name thy4, []) (tl descr));
   365 
   366     (* prove isomorphism properties *)
   367 
   368     fun mk_funs_inv thy thm =
   369       let
   370         val prop = Thm.prop_of thm;
   371         val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
   372           (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.freeze prop;
   373         val used = OldTerm.add_term_tfree_names (a, []);
   374 
   375         fun mk_thm i =
   376           let
   377             val Ts = map (TFree o rpair HOLogic.typeS)
   378               (Name.variant_list used (replicate i "'t"));
   379             val f = Free ("f", Ts ---> U)
   380           in SkipProof.prove_global thy [] [] (Logic.mk_implies
   381             (HOLogic.mk_Trueprop (HOLogic.list_all
   382                (map (pair "x") Ts, S $ app_bnds f i)),
   383              HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
   384                r $ (a $ app_bnds f i)), f))))
   385             (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
   386                REPEAT (etac allE 1), rtac thm 1, atac 1])
   387           end
   388       in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
   389 
   390     (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
   391 
   392     val fun_congs = map (fn T => make_elim (Drule.instantiate'
   393       [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
   394 
   395     fun prove_iso_thms (ds, (inj_thms, elem_thms)) =
   396       let
   397         val (_, (tname, _, _)) = hd ds;
   398         val {induction, ...} = the (Symtab.lookup dt_info tname);
   399 
   400         fun mk_ind_concl (i, _) =
   401           let
   402             val T = List.nth (recTs, i);
   403             val Rep_t = Const (List.nth (all_rep_names, i), T --> Univ_elT);
   404             val rep_set_name = List.nth (rep_set_names, i)
   405           in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
   406                 HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
   407                   HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
   408               Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
   409           end;
   410 
   411         val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
   412 
   413         val rewrites = map mk_meta_eq iso_char_thms;
   414         val inj_thms' = map snd newT_iso_inj_thms @
   415           map (fn r => r RS @{thm injD}) inj_thms;
   416 
   417         val inj_thm = SkipProof.prove_global thy5 [] []
   418           (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
   419             [(indtac induction [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   420              REPEAT (EVERY
   421                [rtac allI 1, rtac impI 1,
   422                 exh_tac (exh_thm_of dt_info) 1,
   423                 REPEAT (EVERY
   424                   [hyp_subst_tac 1,
   425                    rewrite_goals_tac rewrites,
   426                    REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   427                    (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
   428                    ORELSE (EVERY
   429                      [REPEAT (eresolve_tac (Scons_inject ::
   430                         map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
   431                       REPEAT (cong_tac 1), rtac refl 1,
   432                       REPEAT (atac 1 ORELSE (EVERY
   433                         [REPEAT (rtac ext 1),
   434                          REPEAT (eresolve_tac (mp :: allE ::
   435                            map make_elim (Suml_inject :: Sumr_inject ::
   436                              Lim_inject :: inj_thms') @ fun_congs) 1),
   437                          atac 1]))])])])]);
   438 
   439         val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
   440                              (split_conj_thm inj_thm);
   441 
   442         val elem_thm = 
   443             SkipProof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
   444               (fn _ =>
   445                EVERY [(indtac induction [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   446                 rewrite_goals_tac rewrites,
   447                 REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
   448                   ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
   449 
   450       in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
   451       end;
   452 
   453     val (iso_inj_thms_unfolded, iso_elem_thms) = List.foldr prove_iso_thms
   454       ([], map #3 newT_iso_axms) (tl descr);
   455     val iso_inj_thms = map snd newT_iso_inj_thms @
   456       map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
   457 
   458     (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
   459 
   460     fun mk_iso_t (((set_name, iso_name), i), T) =
   461       let val isoT = T --> Univ_elT
   462       in HOLogic.imp $ 
   463         (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
   464           (if i < length newTs then HOLogic.true_const
   465            else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
   466              Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
   467                Const (iso_name, isoT) $ Const (@{const_name UNIV}, HOLogic.mk_setT T)))
   468       end;
   469 
   470     val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
   471       (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
   472 
   473     (* all the theorems are proved by one single simultaneous induction *)
   474 
   475     val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
   476       iso_inj_thms_unfolded;
   477 
   478     val iso_thms = if length descr = 1 then [] else
   479       Library.drop (length newTs, split_conj_thm
   480         (SkipProof.prove_global thy5 [] [] iso_t (fn _ => EVERY
   481            [(indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   482             REPEAT (rtac TrueI 1),
   483             rewrite_goals_tac (mk_meta_eq choice_eq ::
   484               symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
   485             rewrite_goals_tac (map symmetric range_eqs),
   486             REPEAT (EVERY
   487               [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
   488                  maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
   489                TRY (hyp_subst_tac 1),
   490                rtac (sym RS range_eqI) 1,
   491                resolve_tac iso_char_thms 1])])));
   492 
   493     val Abs_inverse_thms' =
   494       map #1 newT_iso_axms @
   495       map2 (fn r_inj => fn r => f_myinv_f OF [r_inj, r RS mp])
   496         iso_inj_thms_unfolded iso_thms;
   497 
   498     val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
   499 
   500     (******************* freeness theorems for constructors *******************)
   501 
   502     val _ = message config "Proving freeness of constructors ...";
   503 
   504     (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
   505     
   506     fun prove_constr_rep_thm eqn =
   507       let
   508         val inj_thms = map fst newT_iso_inj_thms;
   509         val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
   510       in SkipProof.prove_global thy5 [] [] eqn (fn _ => EVERY
   511         [resolve_tac inj_thms 1,
   512          rewrite_goals_tac rewrites,
   513          rtac refl 3,
   514          resolve_tac rep_intrs 2,
   515          REPEAT (resolve_tac iso_elem_thms 1)])
   516       end;
   517 
   518     (*--------------------------------------------------------------*)
   519     (* constr_rep_thms and rep_congs are used to prove distinctness *)
   520     (* of constructors.                                             *)
   521     (*--------------------------------------------------------------*)
   522 
   523     val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
   524 
   525     val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
   526       dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   527         (constr_rep_thms ~~ dist_lemmas);
   528 
   529     fun prove_distinct_thms _ _ (_, []) = []
   530       | prove_distinct_thms lim dist_rewrites' (k, ts as _ :: _) =
   531           if k >= lim then [] else let
   532             (*number of constructors < distinctness_limit : C_i ... ~= C_j ...*)
   533             fun prove [] = []
   534               | prove (t :: ts) =
   535                   let
   536                     val dist_thm = SkipProof.prove_global thy5 [] [] t (fn _ =>
   537                       EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
   538                   in dist_thm :: standard (dist_thm RS not_sym) :: prove ts end;
   539           in prove ts end;
   540 
   541     val distinct_thms = DatatypeProp.make_distincts descr sorts
   542       |> map2 (prove_distinct_thms
   543            (Config.get_thy thy5 distinctness_limit)) dist_rewrites;
   544 
   545     val simproc_dists = map (fn ((((_, (_, _, constrs)), rep_thms), congr), dists) =>
   546       if length constrs < Config.get_thy thy5 distinctness_limit
   547       then FewConstrs dists
   548       else ManyConstrs (congr, HOL_basic_ss addsimps rep_thms)) (hd descr ~~
   549         constr_rep_thms ~~ rep_congs ~~ distinct_thms);
   550 
   551     (* prove injectivity of constructors *)
   552 
   553     fun prove_constr_inj_thm rep_thms t =
   554       let val inj_thms = Scons_inject :: (map make_elim
   555         (iso_inj_thms @
   556           [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
   557            Lim_inject, Suml_inject, Sumr_inject]))
   558       in SkipProof.prove_global thy5 [] [] t (fn _ => EVERY
   559         [rtac iffI 1,
   560          REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
   561          dresolve_tac rep_congs 1, dtac box_equals 1,
   562          REPEAT (resolve_tac rep_thms 1),
   563          REPEAT (eresolve_tac inj_thms 1),
   564          REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
   565            REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
   566            atac 1]))])
   567       end;
   568 
   569     val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
   570       ((DatatypeProp.make_injs descr sorts) ~~ constr_rep_thms);
   571 
   572     val ((constr_inject', distinct_thms'), thy6) =
   573       thy5
   574       |> parent_path (#flat_names config)
   575       |> store_thmss "inject" new_type_names constr_inject
   576       ||>> store_thmss "distinct" new_type_names distinct_thms;
   577 
   578     (*************************** induction theorem ****************************)
   579 
   580     val _ = message config "Proving induction rule for datatypes ...";
   581 
   582     val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
   583       (map (fn r => r RS myinv_f_f RS subst) iso_inj_thms_unfolded);
   584     val Rep_inverse_thms' = map (fn r => r RS myinv_f_f) iso_inj_thms_unfolded;
   585 
   586     fun mk_indrule_lemma ((prems, concls), ((i, _), T)) =
   587       let
   588         val Rep_t = Const (List.nth (all_rep_names, i), T --> Univ_elT) $
   589           mk_Free "x" T i;
   590 
   591         val Abs_t = if i < length newTs then
   592             Const (Sign.intern_const thy6
   593               ("Abs_" ^ (List.nth (new_type_names, i))), Univ_elT --> T)
   594           else Const ("Inductive.myinv", [T --> Univ_elT, Univ_elT] ---> T) $
   595             Const (List.nth (all_rep_names, i), T --> Univ_elT)
   596 
   597       in (prems @ [HOLogic.imp $
   598             (Const (List.nth (rep_set_names, i), UnivT') $ Rep_t) $
   599               (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
   600           concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
   601       end;
   602 
   603     val (indrule_lemma_prems, indrule_lemma_concls) =
   604       Library.foldl mk_indrule_lemma (([], []), (descr' ~~ recTs));
   605 
   606     val cert = cterm_of thy6;
   607 
   608     val indrule_lemma = SkipProof.prove_global thy6 [] []
   609       (Logic.mk_implies
   610         (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
   611          HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
   612            [REPEAT (etac conjE 1),
   613             REPEAT (EVERY
   614               [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
   615                etac mp 1, resolve_tac iso_elem_thms 1])]);
   616 
   617     val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
   618     val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
   619       map (Free o apfst fst o dest_Var) Ps;
   620     val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
   621 
   622     val dt_induct_prop = DatatypeProp.make_ind descr sorts;
   623     val dt_induct = SkipProof.prove_global thy6 []
   624       (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
   625       (fn {prems, ...} => EVERY
   626         [rtac indrule_lemma' 1,
   627          (indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   628          EVERY (map (fn (prem, r) => (EVERY
   629            [REPEAT (eresolve_tac Abs_inverse_thms 1),
   630             simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
   631             DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
   632                 (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
   633 
   634     val ([dt_induct'], thy7) =
   635       thy6
   636       |> Sign.add_path big_name
   637       |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
   638       ||> Sign.parent_path
   639       ||> Theory.checkpoint;
   640 
   641   in
   642     ((constr_inject', distinct_thms', dist_rewrites, simproc_dists, dt_induct'), thy7)
   643   end;
   644 
   645 end;