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