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