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