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