src/HOL/Tools/Old_Datatype/old_datatype.ML
author wenzelm
Sun Nov 26 21:08:32 2017 +0100 (18 months ago)
changeset 67091 1393c2340eec
parent 63352 4eaf35781b23
child 67318 0ee38196509e
permissions -rw-r--r--
more symbols;
     1 (*  Title:      HOL/Tools/Old_Datatype/old_datatype.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Datatype package: definitional introduction of datatypes
     5 with proof of characteristic theorems: injectivity / distinctness
     6 of constructors and induction.  Main interface to datatypes
     7 after full bootstrap of datatype package.
     8 *)
     9 
    10 signature OLD_DATATYPE =
    11 sig
    12   include OLD_DATATYPE_COMMON
    13 
    14   val distinct_lemma: thm
    15   type spec_cmd =
    16     (binding * (string * string option) list * mixfix) * (binding * string list * mixfix) list
    17   val read_specs: spec_cmd list -> theory -> spec list * Proof.context
    18   val check_specs: spec list -> theory -> spec list * Proof.context
    19   val add_datatype: config -> spec list -> theory -> string list * theory
    20   val add_datatype_cmd: config -> spec_cmd list -> theory -> string list * theory
    21   val spec_cmd: spec_cmd parser
    22 end;
    23 
    24 structure Old_Datatype : OLD_DATATYPE =
    25 struct
    26 
    27 (** auxiliary **)
    28 
    29 val distinct_lemma = @{lemma "f x \<noteq> f y ==> x \<noteq> y" by iprover};
    30 val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (Thm.prems_of distinct_lemma);
    31 
    32 fun exh_thm_of (dt_info : Old_Datatype_Aux.info Symtab.table) tname =
    33   #exhaust (the (Symtab.lookup dt_info tname));
    34 
    35 val In0_inject = @{thm In0_inject};
    36 val In1_inject = @{thm In1_inject};
    37 val Scons_inject = @{thm Scons_inject};
    38 val Leaf_inject = @{thm Leaf_inject};
    39 val In0_eq = @{thm In0_eq};
    40 val In1_eq = @{thm In1_eq};
    41 val In0_not_In1 = @{thm In0_not_In1};
    42 val In1_not_In0 = @{thm In1_not_In0};
    43 val Lim_inject = @{thm Lim_inject};
    44 val Inl_inject = @{thm Inl_inject};
    45 val Inr_inject = @{thm Inr_inject};
    46 val Suml_inject = @{thm Suml_inject};
    47 val Sumr_inject = @{thm Sumr_inject};
    48 
    49 val datatype_injI =
    50   @{lemma "(\<And>x. \<forall>y. f x = f y \<longrightarrow> x = y) \<Longrightarrow> inj f" by (simp add: inj_on_def)};
    51 
    52 
    53 (** proof of characteristic theorems **)
    54 
    55 fun representation_proofs (config : Old_Datatype_Aux.config)
    56     (dt_info : Old_Datatype_Aux.info Symtab.table) descr types_syntax constr_syntax case_names_induct
    57     thy =
    58   let
    59     val descr' = flat descr;
    60     val new_type_names = map (Binding.name_of o fst) types_syntax;
    61     val big_name = space_implode "_" new_type_names;
    62     val thy1 = Sign.add_path big_name thy;
    63     val big_rec_name = "rep_set_" ^ big_name;
    64     val rep_set_names' =
    65       if length descr' = 1 then [big_rec_name]
    66       else map (prefix (big_rec_name ^ "_") o string_of_int) (1 upto length descr');
    67     val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
    68 
    69     val tyvars = map (fn (_, (_, Ts, _)) => map Old_Datatype_Aux.dest_DtTFree Ts) (hd descr);
    70     val leafTs' = Old_Datatype_Aux.get_nonrec_types descr';
    71     val branchTs = Old_Datatype_Aux.get_branching_types descr';
    72     val branchT =
    73       if null branchTs then HOLogic.unitT
    74       else Balanced_Tree.make (fn (T, U) => Type (@{type_name Sum_Type.sum}, [T, U])) branchTs;
    75     val arities = remove (op =) 0 (Old_Datatype_Aux.get_arities descr');
    76     val unneeded_vars =
    77       subtract (op =) (fold Term.add_tfreesT (leafTs' @ branchTs) []) (hd tyvars);
    78     val leafTs = leafTs' @ map TFree unneeded_vars;
    79     val recTs = Old_Datatype_Aux.get_rec_types descr';
    80     val (newTs, oldTs) = chop (length (hd descr)) recTs;
    81     val sumT =
    82       if null leafTs then HOLogic.unitT
    83       else Balanced_Tree.make (fn (T, U) => Type (@{type_name Sum_Type.sum}, [T, U])) leafTs;
    84     val Univ_elT = HOLogic.mk_setT (Type (@{type_name Old_Datatype.node}, [sumT, branchT]));
    85     val UnivT = HOLogic.mk_setT Univ_elT;
    86     val UnivT' = Univ_elT --> HOLogic.boolT;
    87     val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
    88 
    89     val In0 = Const (@{const_name Old_Datatype.In0}, Univ_elT --> Univ_elT);
    90     val In1 = Const (@{const_name Old_Datatype.In1}, Univ_elT --> Univ_elT);
    91     val Leaf = Const (@{const_name Old_Datatype.Leaf}, sumT --> Univ_elT);
    92     val Lim = Const (@{const_name Old_Datatype.Lim}, (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
   100           else
   101             let
   102               val n2 = n div 2;
   103               val Type (_, [T1, T2]) = T;
   104             in
   105               if i <= n2
   106               then Const (@{const_name Inl}, T1 --> T) $ mk_inj' T1 n2 i
   107               else Const (@{const_name Inr}, T2 --> T) $ mk_inj' T2 (n - n2) (i - n2)
   108             end;
   109       in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs) 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 @{const_name Old_Datatype.Scons}) 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
   126           else
   127             let
   128               val n2 = n div 2;
   129               val Type (_, [T1, T2]) = T;
   130               fun mkT U = (U --> Univ_elT) --> T --> Univ_elT;
   131             in
   132               if i <= n2 then Const (@{const_name Sum_Type.Suml}, mkT T1) $ mk_inj T1 n2 i
   133               else Const (@{const_name Sum_Type.Sumr}, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
   134             end;
   135       in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs) 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 _ = Old_Datatype_Aux.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 Old_Datatype_Aux.strip_dtyp dt of
   149             (dts, Old_Datatype_Aux.DtRec k) =>
   150               let
   151                 val Ts = map (Old_Datatype_Aux.typ_of_dtyp descr') dts;
   152                 val free_t =
   153                   Old_Datatype_Aux.app_bnds (Old_Datatype_Aux.mk_Free "x" (Ts ---> Univ_elT) j)
   154                     (length Ts)
   155               in
   156                 (j + 1, Logic.list_all (map (pair "x") Ts,
   157                   HOLogic.mk_Trueprop
   158                     (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
   159                 mk_lim free_t Ts :: ts)
   160               end
   161           | _ =>
   162               let val T = Old_Datatype_Aux.typ_of_dtyp descr' dt
   163               in (j + 1, prems, (Leaf $ mk_inj T (Old_Datatype_Aux.mk_Free "x" T j)) :: ts) end);
   164 
   165         val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
   166         val concl = HOLogic.mk_Trueprop (Free (s, UnivT') $ mk_univ_inj ts n i);
   167       in Logic.list_implies (prems, concl) end;
   168 
   169     val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
   170       map (make_intr rep_set_name (length constrs))
   171         ((1 upto length constrs) ~~ constrs)) (descr' ~~ rep_set_names');
   172 
   173     val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
   174       thy1
   175       |> Sign.concealed
   176       |> Inductive.add_inductive_global
   177           {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
   178            coind = false, no_elim = true, no_ind = false, skip_mono = true}
   179           (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
   180           (map (fn x => (Binding.empty_atts, x)) intr_ts) []
   181       ||> Sign.restore_naming thy1;
   182 
   183     (********************************* typedef ********************************)
   184 
   185     val (typedefs, thy3) = thy2
   186       |> Sign.parent_path
   187       |> fold_map
   188         (fn (((name, mx), tvs), c) =>
   189           Typedef.add_typedef_global {overloaded = false} (name, tvs, mx)
   190             (Collect $ Const (c, UnivT')) NONE
   191             (fn ctxt =>
   192               resolve_tac ctxt [exI] 1 THEN
   193               resolve_tac ctxt [CollectI] 1 THEN
   194               QUIET_BREADTH_FIRST (has_fewer_prems 1)
   195               (resolve_tac ctxt rep_intrs 1)))
   196         (types_syntax ~~ tyvars ~~ take (length newTs) rep_set_names)
   197       ||> Sign.add_path big_name;
   198 
   199     (*********************** definition of constructors ***********************)
   200 
   201     val big_rep_name = big_name ^ "_Rep_";
   202     val rep_names' = map (fn i => big_rep_name ^ string_of_int i) (1 upto length (flat (tl descr)));
   203     val all_rep_names =
   204       map (#Rep_name o #1 o #2) typedefs @
   205       map (Sign.full_bname thy3) rep_names';
   206 
   207     (* isomorphism declarations *)
   208 
   209     val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
   210       (oldTs ~~ rep_names');
   211 
   212     (* constructor definitions *)
   213 
   214     fun make_constr_def (typedef: Typedef.info) T n
   215         ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
   216       let
   217         fun constr_arg dt (j, l_args, r_args) =
   218           let
   219             val T = Old_Datatype_Aux.typ_of_dtyp descr' dt;
   220             val free_t = Old_Datatype_Aux.mk_Free "x" T j;
   221           in
   222             (case (Old_Datatype_Aux.strip_dtyp dt, strip_type T) of
   223               ((_, Old_Datatype_Aux.DtRec m), (Us, U)) =>
   224                 (j + 1, free_t :: l_args, mk_lim
   225                   (Const (nth all_rep_names m, U --> Univ_elT) $
   226                     Old_Datatype_Aux.app_bnds free_t (length Us)) Us :: r_args)
   227             | _ => (j + 1, free_t :: l_args, (Leaf $ mk_inj T free_t) :: r_args))
   228           end;
   229 
   230         val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
   231         val constrT = map (Old_Datatype_Aux.typ_of_dtyp descr') cargs ---> T;
   232         val ({Abs_name, Rep_name, ...}, _) = typedef;
   233         val lhs = list_comb (Const (cname, constrT), l_args);
   234         val rhs = mk_univ_inj r_args n i;
   235         val def = Logic.mk_equals (lhs, Const (Abs_name, Univ_elT --> T) $ rhs);
   236         val def_name = Thm.def_name (Long_Name.base_name cname);
   237         val eqn =
   238           HOLogic.mk_Trueprop (HOLogic.mk_eq (Const (Rep_name, T --> Univ_elT) $ lhs, rhs));
   239         val ([def_thm], thy') =
   240           thy
   241           |> Sign.add_consts [(cname', constrT, mx)]
   242           |> (Global_Theory.add_defs false o map Thm.no_attributes) [(Binding.name def_name, def)];
   243 
   244       in (thy', defs @ [def_thm], eqns @ [eqn], i + 1) end;
   245 
   246     (* constructor definitions for datatype *)
   247 
   248     fun dt_constr_defs (((((_, (_, _, constrs)), tname), typedef: Typedef.info), T), constr_syntax)
   249         (thy, defs, eqns, rep_congs, dist_lemmas) =
   250       let
   251         val ctxt = Proof_Context.init_global thy;
   252         val _ $ (_ $ (cong_f $ _) $ _) = Thm.concl_of arg_cong;
   253         val rep_const = Thm.cterm_of ctxt (Const (#Rep_name (#1 typedef), T --> Univ_elT));
   254         val cong' = infer_instantiate ctxt [(#1 (dest_Var cong_f), rep_const)] arg_cong;
   255         val dist = infer_instantiate ctxt [(#1 (dest_Var distinct_f), rep_const)] distinct_lemma;
   256         val (thy', defs', eqns', _) =
   257           fold (make_constr_def typedef T (length constrs))
   258             (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
   259       in
   260         (Sign.parent_path thy', defs', eqns @ [eqns'],
   261           rep_congs @ [cong'], dist_lemmas @ [dist])
   262       end;
   263 
   264     val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
   265       fold dt_constr_defs
   266         (hd descr ~~ new_type_names ~~ map #2 typedefs ~~ newTs ~~ constr_syntax)
   267         (thy3 |> Sign.add_consts iso_decls |> Sign.parent_path, [], [], [], []);
   268 
   269 
   270     (*********** isomorphisms for new types (introduced by typedef) ***********)
   271 
   272     val _ = Old_Datatype_Aux.message config "Proving isomorphism properties ...";
   273 
   274     val collect_simp = rewrite_rule (Proof_Context.init_global thy4) [mk_meta_eq mem_Collect_eq];
   275 
   276     val newT_iso_axms = typedefs |> map (fn (_, (_, {Abs_inverse, Rep_inverse, Rep, ...})) =>
   277       (collect_simp Abs_inverse, Rep_inverse, collect_simp Rep));
   278 
   279     val newT_iso_inj_thms = typedefs |> map (fn (_, (_, {Abs_inject, Rep_inject, ...})) =>
   280       (collect_simp Abs_inject RS iffD1, Rep_inject RS iffD1));
   281 
   282     (********* isomorphisms between existing types and "unfolded" types *******)
   283 
   284     (*---------------------------------------------------------------------*)
   285     (* isomorphisms are defined using primrec-combinators:                 *)
   286     (* generate appropriate functions for instantiating primrec-combinator *)
   287     (*                                                                     *)
   288     (*   e.g.  Rep_dt_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
   289     (*                                                                     *)
   290     (* also generate characteristic equations for isomorphisms             *)
   291     (*                                                                     *)
   292     (*   e.g.  Rep_dt_i (cons h t) = In1 (Scons (Rep_dt_j h) (Rep_dt_i t)) *)
   293     (*---------------------------------------------------------------------*)
   294 
   295     fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
   296       let
   297         val argTs = map (Old_Datatype_Aux.typ_of_dtyp descr') cargs;
   298         val T = nth recTs k;
   299         val rep_const = Const (nth all_rep_names k, T --> Univ_elT);
   300         val constr = Const (cname, argTs ---> T);
   301 
   302         fun process_arg ks' dt (i2, i2', ts, Ts) =
   303           let
   304             val T' = Old_Datatype_Aux.typ_of_dtyp descr' dt;
   305             val (Us, U) = strip_type T'
   306           in
   307             (case Old_Datatype_Aux.strip_dtyp dt of
   308               (_, Old_Datatype_Aux.DtRec j) =>
   309                 if member (op =) ks' j then
   310                   (i2 + 1, i2' + 1, ts @ [mk_lim (Old_Datatype_Aux.app_bnds
   311                      (Old_Datatype_Aux.mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
   312                    Ts @ [Us ---> Univ_elT])
   313                 else
   314                   (i2 + 1, i2', ts @ [mk_lim
   315                      (Const (nth all_rep_names j, U --> Univ_elT) $
   316                         Old_Datatype_Aux.app_bnds
   317                           (Old_Datatype_Aux.mk_Free "x" T' i2) (length Us)) Us], Ts)
   318             | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (Old_Datatype_Aux.mk_Free "x" T' i2)], Ts))
   319           end;
   320 
   321         val (i2, i2', ts, Ts) = fold (process_arg ks) cargs (1, 1, [], []);
   322         val xs = map (uncurry (Old_Datatype_Aux.mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
   323         val ys = map (uncurry (Old_Datatype_Aux.mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
   324         val f = fold_rev lambda (xs @ ys) (mk_univ_inj ts n i);
   325 
   326         val (_, _, ts', _) = fold (process_arg []) cargs (1, 1, [], []);
   327         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   328           (rep_const $ list_comb (constr, xs), mk_univ_inj ts' n i))
   329 
   330       in (fs @ [f], eqns @ [eqn], i + 1) end;
   331 
   332     (* define isomorphisms for all mutually recursive datatypes in list ds *)
   333 
   334     fun make_iso_defs ds (thy, char_thms) =
   335       let
   336         val ks = map fst ds;
   337         val (_, (tname, _, _)) = hd ds;
   338         val {rec_rewrites, rec_names, ...} = the (Symtab.lookup dt_info tname);
   339 
   340         fun process_dt (k, (_, _, constrs)) (fs, eqns, isos) =
   341           let
   342             val (fs', eqns', _) = fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
   343             val iso = (nth recTs k, nth all_rep_names k);
   344           in (fs', eqns', isos @ [iso]) end;
   345 
   346         val (fs, eqns, isos) = fold process_dt ds ([], [], []);
   347         val fTs = map fastype_of fs;
   348         val defs =
   349           map (fn (rec_name, (T, iso_name)) =>
   350             (Binding.name (Thm.def_name (Long_Name.base_name iso_name)),
   351               Logic.mk_equals (Const (iso_name, T --> Univ_elT),
   352                 list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
   353         val (def_thms, thy') =
   354           (Global_Theory.add_defs false o map Thm.no_attributes) defs thy;
   355 
   356         (* prove characteristic equations *)
   357 
   358         val rewrites = def_thms @ map mk_meta_eq rec_rewrites;
   359         val char_thms' =
   360           map (fn eqn => Goal.prove_sorry_global thy' [] [] eqn
   361             (fn {context = ctxt, ...} =>
   362               EVERY [rewrite_goals_tac ctxt rewrites, resolve_tac ctxt [refl] 1])) eqns;
   363 
   364       in (thy', char_thms' @ char_thms) end;
   365 
   366     val (thy5, iso_char_thms) =
   367       fold_rev make_iso_defs (tl descr) (Sign.add_path big_name thy4, []);
   368 
   369     (* prove isomorphism properties *)
   370 
   371     fun mk_funs_inv thy thm =
   372       let
   373         val prop = Thm.prop_of thm;
   374         val _ $ (_ $ ((S as Const (_, Type (_, [U, _]))) $ _ )) $
   375           (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.legacy_freeze prop;
   376         val used = Term.add_tfree_names a [];
   377 
   378         fun mk_thm i =
   379           let
   380             val Ts = map (TFree o rpair @{sort type}) (Name.variant_list used (replicate i "'t"));
   381             val f = Free ("f", Ts ---> U);
   382           in
   383             Goal.prove_sorry_global thy [] []
   384               (Logic.mk_implies
   385                 (HOLogic.mk_Trueprop (HOLogic.list_all
   386                    (map (pair "x") Ts, S $ Old_Datatype_Aux.app_bnds f i)),
   387                  HOLogic.mk_Trueprop (HOLogic.mk_eq (fold_rev (Term.abs o pair "x") Ts
   388                    (r $ (a $ Old_Datatype_Aux.app_bnds f i)), f))))
   389               (fn {context = ctxt, ...} =>
   390                 EVERY [REPEAT_DETERM_N i (resolve_tac ctxt @{thms ext} 1),
   391                  REPEAT (eresolve_tac ctxt [allE] 1),
   392                  resolve_tac ctxt [thm] 1,
   393                  assume_tac ctxt 1])
   394           end
   395       in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
   396 
   397     (* prove  inj Rep_dt_i  and  Rep_dt_i x : rep_set_dt_i *)
   398 
   399     val fun_congs =
   400       map (fn T => make_elim (Thm.instantiate' [SOME (Thm.global_ctyp_of thy5 T)] [] fun_cong)) branchTs;
   401 
   402     fun prove_iso_thms ds (inj_thms, elem_thms) =
   403       let
   404         val (_, (tname, _, _)) = hd ds;
   405         val induct = #induct (the (Symtab.lookup dt_info tname));
   406 
   407         fun mk_ind_concl (i, _) =
   408           let
   409             val T = nth recTs i;
   410             val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
   411             val rep_set_name = nth rep_set_names i;
   412             val concl1 =
   413               HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
   414                 HOLogic.mk_eq (Rep_t $ Old_Datatype_Aux.mk_Free "x" T i, Rep_t $ Bound 0) $
   415                   HOLogic.mk_eq (Old_Datatype_Aux.mk_Free "x" T i, Bound 0));
   416             val concl2 = Const (rep_set_name, UnivT') $ (Rep_t $ Old_Datatype_Aux.mk_Free "x" T i);
   417           in (concl1, concl2) end;
   418 
   419         val (ind_concl1, ind_concl2) = split_list (map mk_ind_concl ds);
   420 
   421         val rewrites = map mk_meta_eq iso_char_thms;
   422         val inj_thms' = map snd newT_iso_inj_thms @ map (fn r => r RS @{thm injD}) inj_thms;
   423 
   424         val inj_thm =
   425           Goal.prove_sorry_global thy5 [] []
   426             (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj ind_concl1))
   427             (fn {context = ctxt, ...} => EVERY
   428               [(Old_Datatype_Aux.ind_tac ctxt induct [] THEN_ALL_NEW
   429                   Object_Logic.atomize_prems_tac ctxt) 1,
   430                REPEAT (EVERY
   431                  [resolve_tac ctxt [allI] 1, resolve_tac ctxt [impI] 1,
   432                   Old_Datatype_Aux.exh_tac ctxt (exh_thm_of dt_info) 1,
   433                   REPEAT (EVERY
   434                     [hyp_subst_tac ctxt 1,
   435                      rewrite_goals_tac ctxt rewrites,
   436                      REPEAT (dresolve_tac ctxt [In0_inject, In1_inject] 1),
   437                      (eresolve_tac ctxt [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
   438                      ORELSE (EVERY
   439                        [REPEAT (eresolve_tac ctxt (Scons_inject ::
   440                           map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
   441                         REPEAT (cong_tac ctxt 1), resolve_tac ctxt [refl] 1,
   442                         REPEAT (assume_tac ctxt 1 ORELSE (EVERY
   443                           [REPEAT (resolve_tac ctxt @{thms ext} 1),
   444                            REPEAT (eresolve_tac ctxt (mp :: allE ::
   445                              map make_elim (Suml_inject :: Sumr_inject ::
   446                                Lim_inject :: inj_thms') @ fun_congs) 1),
   447                            assume_tac ctxt 1]))])])])]);
   448 
   449         val inj_thms'' = map (fn r => r RS datatype_injI) (Old_Datatype_Aux.split_conj_thm inj_thm);
   450 
   451         val elem_thm =
   452           Goal.prove_sorry_global thy5 [] []
   453             (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj ind_concl2))
   454             (fn {context = ctxt, ...} =>
   455               EVERY [
   456                 (Old_Datatype_Aux.ind_tac ctxt induct [] THEN_ALL_NEW
   457                   Object_Logic.atomize_prems_tac ctxt) 1,
   458                 rewrite_goals_tac ctxt rewrites,
   459                 REPEAT ((resolve_tac ctxt rep_intrs THEN_ALL_NEW
   460                   ((REPEAT o eresolve_tac ctxt [allE]) THEN' ares_tac ctxt elem_thms)) 1)]);
   461 
   462       in (inj_thms'' @ inj_thms, elem_thms @ Old_Datatype_Aux.split_conj_thm elem_thm) end;
   463 
   464     val (iso_inj_thms_unfolded, iso_elem_thms) =
   465       fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
   466     val iso_inj_thms =
   467       map snd newT_iso_inj_thms @ map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
   468 
   469     (* prove  rep_set_dt_i x --> x : range Rep_dt_i *)
   470 
   471     fun mk_iso_t (((set_name, iso_name), i), T) =
   472       let val isoT = T --> Univ_elT in
   473         HOLogic.imp $
   474           (Const (set_name, UnivT') $ Old_Datatype_Aux.mk_Free "x" Univ_elT i) $
   475             (if i < length newTs then @{term True}
   476              else HOLogic.mk_mem (Old_Datatype_Aux.mk_Free "x" Univ_elT i,
   477                Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
   478                  Const (iso_name, isoT) $ Const (@{const_abbrev UNIV}, HOLogic.mk_setT T)))
   479       end;
   480 
   481     val iso_t = HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj (map mk_iso_t
   482       (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
   483 
   484     (* all the theorems are proved by one single simultaneous induction *)
   485 
   486     val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq})) iso_inj_thms_unfolded;
   487 
   488     val iso_thms =
   489       if length descr = 1 then []
   490       else
   491         drop (length newTs) (Old_Datatype_Aux.split_conj_thm
   492           (Goal.prove_sorry_global thy5 [] [] iso_t (fn {context = ctxt, ...} => EVERY
   493              [(Old_Datatype_Aux.ind_tac ctxt rep_induct [] THEN_ALL_NEW
   494                  Object_Logic.atomize_prems_tac ctxt) 1,
   495               REPEAT (resolve_tac ctxt [TrueI] 1),
   496               rewrite_goals_tac ctxt (mk_meta_eq @{thm choice_eq} ::
   497                 Thm.symmetric (mk_meta_eq @{thm fun_eq_iff}) :: range_eqs),
   498               rewrite_goals_tac ctxt (map Thm.symmetric range_eqs),
   499               REPEAT (EVERY
   500                 [REPEAT (eresolve_tac ctxt ([rangeE, @{thm ex1_implies_ex} RS exE] @
   501                    maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
   502                  TRY (hyp_subst_tac ctxt 1),
   503                  resolve_tac ctxt [sym RS range_eqI] 1,
   504                  resolve_tac ctxt iso_char_thms 1])])));
   505 
   506     val Abs_inverse_thms' =
   507       map #1 newT_iso_axms @
   508       map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
   509         iso_inj_thms_unfolded iso_thms;
   510 
   511     val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
   512 
   513     (******************* freeness theorems for constructors *******************)
   514 
   515     val _ = Old_Datatype_Aux.message config "Proving freeness of constructors ...";
   516 
   517     (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
   518 
   519     fun prove_constr_rep_thm eqn =
   520       let
   521         val inj_thms = map fst newT_iso_inj_thms;
   522         val rewrites = @{thm o_def} :: constr_defs @ map (mk_meta_eq o #2) newT_iso_axms;
   523       in
   524         Goal.prove_sorry_global thy5 [] [] eqn
   525         (fn {context = ctxt, ...} => EVERY
   526           [resolve_tac ctxt inj_thms 1,
   527            rewrite_goals_tac ctxt rewrites,
   528            resolve_tac ctxt [refl] 3,
   529            resolve_tac ctxt rep_intrs 2,
   530            REPEAT (resolve_tac ctxt iso_elem_thms 1)])
   531       end;
   532 
   533     (*--------------------------------------------------------------*)
   534     (* constr_rep_thms and rep_congs are used to prove distinctness *)
   535     (* of constructors.                                             *)
   536     (*--------------------------------------------------------------*)
   537 
   538     val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
   539 
   540     val dist_rewrites =
   541       map (fn (rep_thms, dist_lemma) =>
   542         dist_lemma :: (rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   543           (constr_rep_thms ~~ dist_lemmas);
   544 
   545     fun prove_distinct_thms dist_rewrites' =
   546       let
   547         fun prove [] = []
   548           | prove (t :: ts) =
   549               let
   550                 val dist_thm = Goal.prove_sorry_global thy5 [] [] t (fn {context = ctxt, ...} =>
   551                   EVERY [simp_tac (put_simpset HOL_ss ctxt addsimps dist_rewrites') 1])
   552               in dist_thm :: Drule.zero_var_indexes (dist_thm RS not_sym) :: prove ts end;
   553       in prove end;
   554 
   555     val distinct_thms =
   556       map2 (prove_distinct_thms) dist_rewrites (Old_Datatype_Prop.make_distincts descr);
   557 
   558     (* prove injectivity of constructors *)
   559 
   560     fun prove_constr_inj_thm rep_thms t =
   561       let
   562         val inj_thms = Scons_inject ::
   563           map make_elim
   564             (iso_inj_thms @
   565               [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
   566                Lim_inject, Suml_inject, Sumr_inject])
   567       in
   568         Goal.prove_sorry_global thy5 [] [] t
   569           (fn {context = ctxt, ...} => EVERY
   570             [resolve_tac ctxt [iffI] 1,
   571              REPEAT (eresolve_tac ctxt [conjE] 2), hyp_subst_tac ctxt 2,
   572              resolve_tac ctxt [refl] 2,
   573              dresolve_tac ctxt rep_congs 1,
   574              dresolve_tac ctxt @{thms box_equals} 1,
   575              REPEAT (resolve_tac ctxt rep_thms 1),
   576              REPEAT (eresolve_tac ctxt inj_thms 1),
   577              REPEAT (ares_tac ctxt [conjI] 1 ORELSE (EVERY [REPEAT (resolve_tac ctxt @{thms ext} 1),
   578                REPEAT (eresolve_tac ctxt (make_elim fun_cong :: inj_thms) 1),
   579                assume_tac ctxt 1]))])
   580       end;
   581 
   582     val constr_inject =
   583       map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
   584         (Old_Datatype_Prop.make_injs descr ~~ constr_rep_thms);
   585 
   586     val ((constr_inject', distinct_thms'), thy6) =
   587       thy5
   588       |> Sign.parent_path
   589       |> Old_Datatype_Aux.store_thmss "inject" new_type_names constr_inject
   590       ||>> Old_Datatype_Aux.store_thmss "distinct" new_type_names distinct_thms;
   591 
   592     (*************************** induction theorem ****************************)
   593 
   594     val _ = Old_Datatype_Aux.message config "Proving induction rule for datatypes ...";
   595 
   596     val Rep_inverse_thms =
   597       map (fn (_, iso, _) => iso RS subst) newT_iso_axms @
   598       map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded;
   599     val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
   600 
   601     fun mk_indrule_lemma (i, _) T =
   602       let
   603         val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $ Old_Datatype_Aux.mk_Free "x" T i;
   604         val Abs_t =
   605           if i < length newTs then
   606             Const (#Abs_name (#1 (#2 (nth typedefs i))), Univ_elT --> T)
   607           else
   608             Const (@{const_name the_inv_into},
   609               [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
   610             HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT);
   611         val prem =
   612           HOLogic.imp $
   613             (Const (nth rep_set_names i, UnivT') $ Rep_t) $
   614               (Old_Datatype_Aux.mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t));
   615         val concl =
   616           Old_Datatype_Aux.mk_Free "P" (T --> HOLogic.boolT) (i + 1) $
   617             Old_Datatype_Aux.mk_Free "x" T i;
   618       in (prem, concl) end;
   619 
   620     val (indrule_lemma_prems, indrule_lemma_concls) =
   621       split_list (map2 mk_indrule_lemma descr' recTs);
   622 
   623     val indrule_lemma =
   624       Goal.prove_sorry_global thy6 [] []
   625         (Logic.mk_implies
   626           (HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj indrule_lemma_prems),
   627            HOLogic.mk_Trueprop (Old_Datatype_Aux.mk_conj indrule_lemma_concls)))
   628         (fn {context = ctxt, ...} =>
   629           EVERY
   630            [REPEAT (eresolve_tac ctxt [conjE] 1),
   631             REPEAT (EVERY
   632               [TRY (resolve_tac ctxt [conjI] 1), resolve_tac ctxt Rep_inverse_thms 1,
   633                eresolve_tac ctxt [mp] 1, resolve_tac ctxt iso_elem_thms 1])]);
   634 
   635     val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (Thm.concl_of indrule_lemma)));
   636     val frees =
   637       if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))]
   638       else map (Free o apfst fst o dest_Var) Ps;
   639 
   640     val dt_induct_prop = Old_Datatype_Prop.make_ind descr;
   641     val dt_induct =
   642       Goal.prove_sorry_global thy6 []
   643       (Logic.strip_imp_prems dt_induct_prop)
   644       (Logic.strip_imp_concl dt_induct_prop)
   645       (fn {context = ctxt, prems, ...} =>
   646         let
   647           val indrule_lemma' =
   648             infer_instantiate ctxt
   649               (map (#1 o dest_Var) Ps ~~ map (Thm.cterm_of ctxt) frees) indrule_lemma;
   650         in
   651           EVERY
   652             [resolve_tac ctxt [indrule_lemma'] 1,
   653              (Old_Datatype_Aux.ind_tac ctxt rep_induct [] THEN_ALL_NEW
   654                 Object_Logic.atomize_prems_tac ctxt) 1,
   655              EVERY (map (fn (prem, r) => (EVERY
   656                [REPEAT (eresolve_tac ctxt Abs_inverse_thms 1),
   657                 simp_tac (put_simpset HOL_basic_ss ctxt
   658                   addsimps (Thm.symmetric r :: Rep_inverse_thms')) 1,
   659                 DEPTH_SOLVE_1 (ares_tac ctxt [prem] 1 ORELSE eresolve_tac ctxt [allE] 1)]))
   660                     (prems ~~ (constr_defs @ map mk_meta_eq iso_char_thms)))]
   661         end);
   662 
   663     val ([(_, [dt_induct'])], thy7) =
   664       thy6
   665       |> Global_Theory.note_thmss ""
   666         [((Binding.qualify true big_name (Binding.name "induct"), [case_names_induct]),
   667           [([dt_induct], [])])];
   668   in
   669     ((constr_inject', distinct_thms', dt_induct'), thy7)
   670   end;
   671 
   672 
   673 
   674 (** datatype definition **)
   675 
   676 (* specifications *)
   677 
   678 type spec_cmd =
   679   (binding * (string * string option) list * mixfix) * (binding * string list * mixfix) list;
   680 
   681 local
   682 
   683 fun parse_spec ctxt ((b, args, mx), constrs) =
   684   ((b, map (apsnd (Typedecl.read_constraint ctxt)) args, mx),
   685     constrs |> map (fn (c, Ts, mx') => (c, map (Syntax.parse_typ ctxt) Ts, mx')));
   686 
   687 fun check_specs ctxt (specs: Old_Datatype_Aux.spec list) =
   688   let
   689     fun prep_spec ((tname, args, mx), constrs) tys =
   690       let
   691         val (args', tys1) = chop (length args) tys;
   692         val (constrs', tys3) = (constrs, tys1) |-> fold_map (fn (cname, cargs, mx') => fn tys2 =>
   693           let val (cargs', tys3) = chop (length cargs) tys2;
   694           in ((cname, cargs', mx'), tys3) end);
   695       in (((tname, map dest_TFree args', mx), constrs'), tys3) end;
   696 
   697     val all_tys =
   698       specs |> maps (fn ((_, args, _), cs) => map TFree args @ maps #2 cs)
   699       |> Syntax.check_typs ctxt;
   700 
   701   in #1 (fold_map prep_spec specs all_tys) end;
   702 
   703 fun prep_specs parse raw_specs thy =
   704   let
   705     val ctxt = thy
   706       |> Sign.add_types_global (map (fn ((b, args, mx), _) => (b, length args, mx)) raw_specs)
   707       |> Proof_Context.init_global
   708       |> fold (fn ((_, args, _), _) => fold (fn (a, _) =>
   709           Variable.declare_typ (TFree (a, dummyS))) args) raw_specs;
   710     val specs = check_specs ctxt (map (parse ctxt) raw_specs);
   711   in (specs, ctxt) end;
   712 
   713 in
   714 
   715 val read_specs = prep_specs parse_spec;
   716 val check_specs = prep_specs (K I);
   717 
   718 end;
   719 
   720 
   721 (* main commands *)
   722 
   723 fun gen_add_datatype prep_specs config raw_specs thy =
   724   let
   725     val (dts, spec_ctxt) = prep_specs raw_specs thy;
   726     val ((_, tyvars, _), _) :: _ = dts;
   727     val string_of_tyvar = Syntax.string_of_typ spec_ctxt o TFree;
   728 
   729     val (new_dts, types_syntax) = dts |> map (fn ((tname, tvs, mx), _) =>
   730       let val full_tname = Sign.full_name thy tname in
   731         (case duplicates (op =) tvs of
   732           [] =>
   733             if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   734             else error "Mutually recursive datatypes must have same type parameters"
   735         | dups =>
   736             error ("Duplicate parameter(s) for datatype " ^ Binding.print tname ^
   737               " : " ^ commas (map string_of_tyvar dups)))
   738       end) |> split_list;
   739     val dt_names = map fst new_dts;
   740 
   741     val _ =
   742       (case duplicates (op =) (map fst new_dts) of
   743         [] => ()
   744       | dups => error ("Duplicate datatypes: " ^ commas_quote dups));
   745 
   746     fun prep_dt_spec ((tname, tvs, _), constrs) (dts', constr_syntax, i) =
   747       let
   748         fun prep_constr (cname, cargs, mx) (constrs, constr_syntax') =
   749           let
   750             val _ =
   751               (case subtract (op =) tvs (fold Term.add_tfreesT cargs []) of
   752                 [] => ()
   753               | vs => error ("Extra type variables on rhs: " ^ commas (map string_of_tyvar vs)));
   754             val c = Sign.full_name_path thy (Binding.name_of tname) cname;
   755           in
   756             (constrs @ [(c, map (Old_Datatype_Aux.dtyp_of_typ new_dts) cargs)],
   757               constr_syntax' @ [(cname, mx)])
   758           end handle ERROR msg =>
   759             cat_error msg ("The error above occurred in constructor " ^ Binding.print cname ^
   760               " of datatype " ^ Binding.print tname);
   761 
   762         val (constrs', constr_syntax') = fold prep_constr constrs ([], []);
   763       in
   764         (case duplicates (op =) (map fst constrs') of
   765           [] =>
   766             (dts' @ [(i, (Sign.full_name thy tname, map Old_Datatype_Aux.DtTFree tvs, constrs'))],
   767               constr_syntax @ [constr_syntax'], i + 1)
   768         | dups =>
   769             error ("Duplicate constructors " ^ commas_quote dups ^
   770               " in datatype " ^ Binding.print tname))
   771       end;
   772 
   773     val (dts', constr_syntax, i) = fold prep_dt_spec dts ([], [], 0);
   774 
   775     val dt_info = Old_Datatype_Data.get_all thy;
   776     val (descr, _) = Old_Datatype_Aux.unfold_datatypes spec_ctxt dts' dt_info dts' i;
   777     val _ =
   778       Old_Datatype_Aux.check_nonempty descr
   779         handle (exn as Old_Datatype_Aux.Datatype_Empty s) =>
   780           if #strict config then error ("Nonemptiness check failed for datatype " ^ quote s)
   781           else Exn.reraise exn;
   782 
   783     val _ =
   784       Old_Datatype_Aux.message config
   785         ("Constructing datatype(s) " ^ commas_quote (map (Binding.name_of o #1 o #1) dts));
   786   in
   787     thy
   788     |> representation_proofs config dt_info descr types_syntax constr_syntax
   789       (Old_Datatype_Data.mk_case_names_induct (flat descr))
   790     |-> (fn (inject, distinct, induct) =>
   791       Old_Rep_Datatype.derive_datatype_props config dt_names descr induct inject distinct)
   792   end;
   793 
   794 val add_datatype = gen_add_datatype check_specs;
   795 val add_datatype_cmd = gen_add_datatype read_specs;
   796 
   797 
   798 (* outer syntax *)
   799 
   800 val spec_cmd =
   801   Parse.type_args_constrained -- Parse.binding -- Parse.opt_mixfix --
   802   (@{keyword "="} |-- Parse.enum1 "|" (Parse.binding -- Scan.repeat Parse.typ -- Parse.opt_mixfix))
   803   >> (fn (((vs, t), mx), cons) => ((t, vs, mx), map Scan.triple1 cons));
   804 
   805 val _ =
   806   Outer_Syntax.command @{command_keyword old_datatype} "define old-style inductive datatypes"
   807     (Parse.and_list1 spec_cmd
   808       >> (Toplevel.theory o (snd oo add_datatype_cmd Old_Datatype_Aux.default_config)));
   809 
   810 open Old_Datatype_Aux;
   811 
   812 end;