src/HOL/Tools/Datatype/datatype.ML
author haftmann
Mon Nov 30 11:42:49 2009 +0100 (2009-11-30)
changeset 33968 f94fb13ecbb3
parent 33963 977b94b64905
child 33969 1e7ca47c6c3d
permissions -rw-r--r--
modernized structures and tuned headers of datatype package modules; joined former datatype.ML and datatype_rep_proofs.ML
     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 add_datatype : config -> string list -> (string list * binding * mixfix *
    14     (binding * typ list * mixfix) list) list -> theory -> string list * theory
    15   val datatype_cmd : string list -> (string list * binding * mixfix *
    16     (binding * string list * mixfix) list) list -> theory -> theory
    17 end;
    18 
    19 structure Datatype : DATATYPE =
    20 struct
    21 
    22 (** auxiliary **)
    23 
    24 open Datatype_Aux;
    25 open Datatype_Data;
    26 
    27 val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
    28 
    29 val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
    30 
    31 fun exh_thm_of (dt_info : info Symtab.table) tname =
    32   #exhaust (the (Symtab.lookup dt_info tname));
    33 
    34 val node_name = @{type_name "Datatype.node"};
    35 val In0_name = @{const_name "Datatype.In0"};
    36 val In1_name = @{const_name "Datatype.In1"};
    37 val Scons_name = @{const_name "Datatype.Scons"};
    38 val Leaf_name = @{const_name "Datatype.Leaf"};
    39 val Numb_name = @{const_name "Datatype.Numb"};
    40 val Lim_name = @{const_name "Datatype.Lim"};
    41 val Suml_name = @{const_name "Sum_Type.Suml"};
    42 val Sumr_name = @{const_name "Sum_Type.Sumr"};
    43 
    44 val In0_inject = @{thm In0_inject};
    45 val In1_inject = @{thm In1_inject};
    46 val Scons_inject = @{thm Scons_inject};
    47 val Leaf_inject = @{thm Leaf_inject};
    48 val In0_eq = @{thm In0_eq};
    49 val In1_eq = @{thm In1_eq};
    50 val In0_not_In1 = @{thm In0_not_In1};
    51 val In1_not_In0 = @{thm In1_not_In0};
    52 val Lim_inject = @{thm Lim_inject};
    53 val Inl_inject = @{thm Inl_inject};
    54 val Inr_inject = @{thm Inr_inject};
    55 val Suml_inject = @{thm Suml_inject};
    56 val Sumr_inject = @{thm Sumr_inject};
    57 
    58 
    59 
    60 (** proof of characteristic theorems **)
    61 
    62 fun representation_proofs (config : config) (dt_info : info Symtab.table)
    63       new_type_names descr sorts types_syntax constr_syntax case_names_induct thy =
    64   let
    65     val descr' = flat descr;
    66     val big_name = space_implode "_" new_type_names;
    67     val thy1 = Sign.add_path big_name thy;
    68     val big_rec_name = big_name ^ "_rep_set";
    69     val rep_set_names' =
    70       (if length descr' = 1 then [big_rec_name] else
    71         (map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
    72           (1 upto (length descr'))));
    73     val rep_set_names = map (Sign.full_bname thy1) rep_set_names';
    74 
    75     val tyvars = map (fn (_, (_, Ts, _)) => map dest_DtTFree Ts) (hd descr);
    76     val leafTs' = get_nonrec_types descr' sorts;
    77     val branchTs = get_branching_types descr' sorts;
    78     val branchT = if null branchTs then HOLogic.unitT
    79       else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) branchTs;
    80     val arities = remove (op =) 0 (get_arities descr');
    81     val unneeded_vars =
    82       subtract (op =) (List.foldr OldTerm.add_typ_tfree_names [] (leafTs' @ branchTs)) (hd tyvars);
    83     val leafTs = leafTs' @ map (fn n => TFree (n, (the o AList.lookup (op =) sorts) n)) unneeded_vars;
    84     val recTs = get_rec_types descr' sorts;
    85     val (newTs, oldTs) = chop (length (hd descr)) recTs;
    86     val sumT = if null leafTs then HOLogic.unitT
    87       else Balanced_Tree.make (fn (T, U) => Type ("+", [T, U])) leafTs;
    88     val Univ_elT = HOLogic.mk_setT (Type (node_name, [sumT, branchT]));
    89     val UnivT = HOLogic.mk_setT Univ_elT;
    90     val UnivT' = Univ_elT --> HOLogic.boolT;
    91     val Collect = Const (@{const_name Collect}, UnivT' --> UnivT);
    92 
    93     val In0 = Const (In0_name, Univ_elT --> Univ_elT);
    94     val In1 = Const (In1_name, Univ_elT --> Univ_elT);
    95     val Leaf = Const (Leaf_name, sumT --> Univ_elT);
    96     val Lim = Const (Lim_name, (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 else
   104           let val n2 = n div 2;
   105               val Type (_, [T1, T2]) = T
   106           in
   107             if i <= n2 then
   108               Const (@{const_name "Sum_Type.Inl"}, T1 --> T) $ (mk_inj' T1 n2 i)
   109             else
   110               Const (@{const_name "Sum_Type.Inr"}, T2 --> T) $ (mk_inj' T2 (n - n2) (i - n2))
   111           end
   112       in mk_inj' sumT (length leafTs) (1 + find_index (fn T'' => T'' = T') leafTs)
   113       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 Scons_name) 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 else
   130           let
   131             val n2 = n div 2;
   132             val Type (_, [T1, T2]) = T;
   133             fun mkT U = (U --> Univ_elT) --> T --> Univ_elT
   134           in
   135             if i <= n2 then Const (Suml_name, mkT T1) $ mk_inj T1 n2 i
   136             else Const (Sumr_name, mkT T2) $ mk_inj T2 (n - n2) (i - n2)
   137           end
   138       in mk_inj branchT (length branchTs) (1 + find_index (fn T'' => T'' = T') branchTs)
   139       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 _ = 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 strip_dtyp dt of
   153             (dts, DtRec k) =>
   154               let
   155                 val Ts = map (typ_of_dtyp descr' sorts) dts;
   156                 val free_t =
   157                   app_bnds (mk_Free "x" (Ts ---> Univ_elT) j) (length Ts)
   158               in (j + 1, list_all (map (pair "x") Ts,
   159                   HOLogic.mk_Trueprop
   160                     (Free (nth rep_set_names' k, UnivT') $ free_t)) :: prems,
   161                 mk_lim free_t Ts :: ts)
   162               end
   163           | _ =>
   164               let val T = typ_of_dtyp descr' sorts dt
   165               in (j + 1, prems, (Leaf $ mk_inj T (mk_Free "x" T j))::ts)
   166               end);
   167 
   168         val (_, prems, ts) = fold_rev mk_prem cargs (1, [], []);
   169         val concl = HOLogic.mk_Trueprop
   170           (Free (s, UnivT') $ mk_univ_inj ts n i)
   171       in Logic.list_implies (prems, concl)
   172       end;
   173 
   174     val intr_ts = maps (fn ((_, (_, _, constrs)), rep_set_name) =>
   175       map (make_intr rep_set_name (length constrs))
   176         ((1 upto (length constrs)) ~~ constrs)) (descr' ~~ rep_set_names');
   177 
   178     val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy2) =
   179       thy1
   180       |> Sign.map_naming Name_Space.conceal
   181       |> Inductive.add_inductive_global
   182           {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name,
   183            coind = false, no_elim = true, no_ind = false, skip_mono = true, fork_mono = false}
   184           (map (fn s => ((Binding.name s, UnivT'), NoSyn)) rep_set_names') []
   185           (map (fn x => (Attrib.empty_binding, x)) intr_ts) []
   186       ||> Sign.restore_naming thy1
   187       ||> Theory.checkpoint;
   188 
   189     (********************************* typedef ********************************)
   190 
   191     val (typedefs, thy3) = thy2 |>
   192       Sign.parent_path |>
   193       fold_map (fn ((((name, mx), tvs), c), name') =>
   194           Typedef.add_typedef false (SOME (Binding.name name')) (name, tvs, mx)
   195             (Collect $ Const (c, UnivT')) NONE
   196             (rtac exI 1 THEN rtac CollectI 1 THEN
   197               QUIET_BREADTH_FIRST (has_fewer_prems 1)
   198               (resolve_tac rep_intrs 1)))
   199                 (types_syntax ~~ tyvars ~~
   200                   (take (length newTs) rep_set_names) ~~ new_type_names) ||>
   201       Sign.add_path big_name;
   202 
   203     (*********************** definition of constructors ***********************)
   204 
   205     val big_rep_name = (space_implode "_" new_type_names) ^ "_Rep_";
   206     val rep_names = map (curry op ^ "Rep_") new_type_names;
   207     val rep_names' = map (fn i => big_rep_name ^ (string_of_int i))
   208       (1 upto (length (flat (tl descr))));
   209     val all_rep_names = map (Sign.intern_const thy3) rep_names @
   210       map (Sign.full_bname thy3) rep_names';
   211 
   212     (* isomorphism declarations *)
   213 
   214     val iso_decls = map (fn (T, s) => (Binding.name s, T --> Univ_elT, NoSyn))
   215       (oldTs ~~ rep_names');
   216 
   217     (* constructor definitions *)
   218 
   219     fun make_constr_def tname T n ((cname, cargs), (cname', mx)) (thy, defs, eqns, i) =
   220       let
   221         fun constr_arg dt (j, l_args, r_args) =
   222           let val T = typ_of_dtyp descr' sorts dt;
   223               val free_t = mk_Free "x" T j
   224           in (case (strip_dtyp dt, strip_type T) of
   225               ((_, DtRec m), (Us, U)) => (j + 1, free_t :: l_args, mk_lim
   226                 (Const (nth all_rep_names m, U --> Univ_elT) $
   227                    app_bnds free_t (length Us)) Us :: r_args)
   228             | _ => (j + 1, free_t::l_args, (Leaf $ mk_inj T free_t)::r_args))
   229           end;
   230 
   231         val (_, l_args, r_args) = fold_rev constr_arg cargs (1, [], []);
   232         val constrT = (map (typ_of_dtyp descr' sorts) cargs) ---> T;
   233         val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
   234         val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
   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 = Long_Name.base_name cname ^ "_def";
   239         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   240           (Const (rep_name, T --> Univ_elT) $ lhs, rhs));
   241         val ([def_thm], thy') =
   242           thy
   243           |> Sign.add_consts_i [(cname', constrT, mx)]
   244           |> (PureThy.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), 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
   255           (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> Univ_elT));
   256         val cong' =
   257           Drule.standard (cterm_instantiate [(cterm_of thy cong_f, rep_const)] arg_cong);
   258         val dist =
   259           Drule.standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
   260         val (thy', defs', eqns', _) = fold ((make_constr_def tname T) (length constrs))
   261           (constrs ~~ constr_syntax) (Sign.add_path tname thy, defs, [], 1);
   262       in
   263         (Sign.parent_path thy', defs', eqns @ [eqns'],
   264           rep_congs @ [cong'], dist_lemmas @ [dist])
   265       end;
   266 
   267     val (thy4, constr_defs, constr_rep_eqns, rep_congs, dist_lemmas) =
   268       fold dt_constr_defs
   269         (hd descr ~~ new_type_names ~~ newTs ~~ constr_syntax)
   270         (thy3 |> Sign.add_consts_i iso_decls |> Sign.parent_path, [], [], [], []);
   271 
   272 
   273     (*********** isomorphisms for new types (introduced by typedef) ***********)
   274 
   275     val _ = message config "Proving isomorphism properties ...";
   276 
   277     val newT_iso_axms = map (fn (_, td) =>
   278       (collect_simp (#Abs_inverse td), #Rep_inverse td,
   279        collect_simp (#Rep td))) typedefs;
   280 
   281     val newT_iso_inj_thms = map (fn (_, td) =>
   282       (collect_simp (#Abs_inject td) RS iffD1, #Rep_inject td RS iffD1)) typedefs;
   283 
   284     (********* isomorphisms between existing types and "unfolded" types *******)
   285 
   286     (*---------------------------------------------------------------------*)
   287     (* isomorphisms are defined using primrec-combinators:                 *)
   288     (* generate appropriate functions for instantiating primrec-combinator *)
   289     (*                                                                     *)
   290     (*   e.g.  dt_Rep_i = list_rec ... (%h t y. In1 (Scons (Leaf h) y))    *)
   291     (*                                                                     *)
   292     (* also generate characteristic equations for isomorphisms             *)
   293     (*                                                                     *)
   294     (*   e.g.  dt_Rep_i (cons h t) = In1 (Scons (dt_Rep_j h) (dt_Rep_i t)) *)
   295     (*---------------------------------------------------------------------*)
   296 
   297     fun make_iso_def k ks n (cname, cargs) (fs, eqns, i) =
   298       let
   299         val argTs = map (typ_of_dtyp descr' sorts) cargs;
   300         val T = nth recTs k;
   301         val rep_name = nth all_rep_names k;
   302         val rep_const = Const (rep_name, T --> Univ_elT);
   303         val constr = Const (cname, argTs ---> T);
   304 
   305         fun process_arg ks' dt (i2, i2', ts, Ts) =
   306           let
   307             val T' = typ_of_dtyp descr' sorts dt;
   308             val (Us, U) = strip_type T'
   309           in (case strip_dtyp dt of
   310               (_, DtRec j) => if j mem ks' then
   311                   (i2 + 1, i2' + 1, ts @ [mk_lim (app_bnds
   312                      (mk_Free "y" (Us ---> Univ_elT) i2') (length Us)) Us],
   313                    Ts @ [Us ---> Univ_elT])
   314                 else
   315                   (i2 + 1, i2', ts @ [mk_lim
   316                      (Const (nth all_rep_names j, U --> Univ_elT) $
   317                         app_bnds (mk_Free "x" T' i2) (length Us)) Us], Ts)
   318             | _ => (i2 + 1, i2', ts @ [Leaf $ mk_inj T' (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 (mk_Free "x")) (argTs ~~ (1 upto (i2 - 1)));
   323         val ys = map (uncurry (mk_Free "y")) (Ts ~~ (1 upto (i2' - 1)));
   324         val f = list_abs_free (map dest_Free (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, (tname, _, constrs)) (fs, eqns, isos) =
   341           let
   342             val (fs', eqns', _) =
   343               fold (make_iso_def k ks (length constrs)) constrs (fs, eqns, 1);
   344             val iso = (nth recTs k, nth all_rep_names k)
   345           in (fs', eqns', isos @ [iso]) end;
   346         
   347         val (fs, eqns, isos) = fold process_dt ds ([], [], []);
   348         val fTs = map fastype_of fs;
   349         val defs = map (fn (rec_name, (T, iso_name)) => (Binding.name (Long_Name.base_name iso_name ^ "_def"),
   350           Logic.mk_equals (Const (iso_name, T --> Univ_elT),
   351             list_comb (Const (rec_name, fTs @ [T] ---> Univ_elT), fs)))) (rec_names ~~ isos);
   352         val (def_thms, thy') =
   353           apsnd Theory.checkpoint ((PureThy.add_defs false o map Thm.no_attributes) defs thy);
   354 
   355         (* prove characteristic equations *)
   356 
   357         val rewrites = def_thms @ (map mk_meta_eq rec_rewrites);
   358         val char_thms' = 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) = apfst Theory.checkpoint (fold_rev make_iso_defs
   364         (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 = OldTerm.add_term_tfree_names (a, []);
   374 
   375         fun mk_thm i =
   376           let
   377             val Ts = map (TFree o rpair HOLogic.typeS)
   378               (Name.variant_list used (replicate i "'t"));
   379             val f = Free ("f", Ts ---> U)
   380           in Skip_Proof.prove_global thy [] [] (Logic.mk_implies
   381             (HOLogic.mk_Trueprop (HOLogic.list_all
   382                (map (pair "x") Ts, S $ app_bnds f i)),
   383              HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
   384                r $ (a $ app_bnds f i)), f))))
   385             (fn _ => EVERY [REPEAT_DETERM_N i (rtac ext 1),
   386                REPEAT (etac allE 1), rtac thm 1, atac 1])
   387           end
   388       in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
   389 
   390     (* prove  inj dt_Rep_i  and  dt_Rep_i x : dt_rep_set_i *)
   391 
   392     val fun_congs = map (fn T => make_elim (Drule.instantiate'
   393       [SOME (ctyp_of thy5 T)] [] fun_cong)) branchTs;
   394 
   395     fun prove_iso_thms ds (inj_thms, elem_thms) =
   396       let
   397         val (_, (tname, _, _)) = hd ds;
   398         val induct = (#induct o the o Symtab.lookup dt_info) tname;
   399 
   400         fun mk_ind_concl (i, _) =
   401           let
   402             val T = nth recTs i;
   403             val Rep_t = Const (nth all_rep_names i, T --> Univ_elT);
   404             val rep_set_name = nth rep_set_names i
   405           in (HOLogic.all_const T $ Abs ("y", T, HOLogic.imp $
   406                 HOLogic.mk_eq (Rep_t $ mk_Free "x" T i, Rep_t $ Bound 0) $
   407                   HOLogic.mk_eq (mk_Free "x" T i, Bound 0)),
   408               Const (rep_set_name, UnivT') $ (Rep_t $ mk_Free "x" T i))
   409           end;
   410 
   411         val (ind_concl1, ind_concl2) = ListPair.unzip (map mk_ind_concl ds);
   412 
   413         val rewrites = map mk_meta_eq iso_char_thms;
   414         val inj_thms' = map snd newT_iso_inj_thms @
   415           map (fn r => r RS @{thm injD}) inj_thms;
   416 
   417         val inj_thm = Skip_Proof.prove_global thy5 [] []
   418           (HOLogic.mk_Trueprop (mk_conj ind_concl1)) (fn _ => EVERY
   419             [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   420              REPEAT (EVERY
   421                [rtac allI 1, rtac impI 1,
   422                 exh_tac (exh_thm_of dt_info) 1,
   423                 REPEAT (EVERY
   424                   [hyp_subst_tac 1,
   425                    rewrite_goals_tac rewrites,
   426                    REPEAT (dresolve_tac [In0_inject, In1_inject] 1),
   427                    (eresolve_tac [In0_not_In1 RS notE, In1_not_In0 RS notE] 1)
   428                    ORELSE (EVERY
   429                      [REPEAT (eresolve_tac (Scons_inject ::
   430                         map make_elim [Leaf_inject, Inl_inject, Inr_inject]) 1),
   431                       REPEAT (cong_tac 1), rtac refl 1,
   432                       REPEAT (atac 1 ORELSE (EVERY
   433                         [REPEAT (rtac ext 1),
   434                          REPEAT (eresolve_tac (mp :: allE ::
   435                            map make_elim (Suml_inject :: Sumr_inject ::
   436                              Lim_inject :: inj_thms') @ fun_congs) 1),
   437                          atac 1]))])])])]);
   438 
   439         val inj_thms'' = map (fn r => r RS @{thm datatype_injI})
   440                              (split_conj_thm inj_thm);
   441 
   442         val elem_thm = 
   443             Skip_Proof.prove_global thy5 [] [] (HOLogic.mk_Trueprop (mk_conj ind_concl2))
   444               (fn _ =>
   445                EVERY [(indtac induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   446                 rewrite_goals_tac rewrites,
   447                 REPEAT ((resolve_tac rep_intrs THEN_ALL_NEW
   448                   ((REPEAT o etac allE) THEN' ares_tac elem_thms)) 1)]);
   449 
   450       in (inj_thms'' @ inj_thms, elem_thms @ (split_conj_thm elem_thm))
   451       end;
   452 
   453     val (iso_inj_thms_unfolded, iso_elem_thms) =
   454       fold_rev prove_iso_thms (tl descr) ([], map #3 newT_iso_axms);
   455     val iso_inj_thms = map snd newT_iso_inj_thms @
   456       map (fn r => r RS @{thm injD}) iso_inj_thms_unfolded;
   457 
   458     (* prove  dt_rep_set_i x --> x : range dt_Rep_i *)
   459 
   460     fun mk_iso_t (((set_name, iso_name), i), T) =
   461       let val isoT = T --> Univ_elT
   462       in HOLogic.imp $ 
   463         (Const (set_name, UnivT') $ mk_Free "x" Univ_elT i) $
   464           (if i < length newTs then HOLogic.true_const
   465            else HOLogic.mk_mem (mk_Free "x" Univ_elT i,
   466              Const (@{const_name image}, isoT --> HOLogic.mk_setT T --> UnivT) $
   467                Const (iso_name, isoT) $ Const (@{const_name UNIV}, HOLogic.mk_setT T)))
   468       end;
   469 
   470     val iso_t = HOLogic.mk_Trueprop (mk_conj (map mk_iso_t
   471       (rep_set_names ~~ all_rep_names ~~ (0 upto (length descr' - 1)) ~~ recTs)));
   472 
   473     (* all the theorems are proved by one single simultaneous induction *)
   474 
   475     val range_eqs = map (fn r => mk_meta_eq (r RS @{thm range_ex1_eq}))
   476       iso_inj_thms_unfolded;
   477 
   478     val iso_thms = if length descr = 1 then [] else
   479       drop (length newTs) (split_conj_thm
   480         (Skip_Proof.prove_global thy5 [] [] iso_t (fn _ => EVERY
   481            [(indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   482             REPEAT (rtac TrueI 1),
   483             rewrite_goals_tac (mk_meta_eq choice_eq ::
   484               symmetric (mk_meta_eq @{thm expand_fun_eq}) :: range_eqs),
   485             rewrite_goals_tac (map symmetric range_eqs),
   486             REPEAT (EVERY
   487               [REPEAT (eresolve_tac ([rangeE, ex1_implies_ex RS exE] @
   488                  maps (mk_funs_inv thy5 o #1) newT_iso_axms) 1),
   489                TRY (hyp_subst_tac 1),
   490                rtac (sym RS range_eqI) 1,
   491                resolve_tac iso_char_thms 1])])));
   492 
   493     val Abs_inverse_thms' =
   494       map #1 newT_iso_axms @
   495       map2 (fn r_inj => fn r => @{thm f_the_inv_into_f} OF [r_inj, r RS mp])
   496         iso_inj_thms_unfolded iso_thms;
   497 
   498     val Abs_inverse_thms = maps (mk_funs_inv thy5) Abs_inverse_thms';
   499 
   500     (******************* freeness theorems for constructors *******************)
   501 
   502     val _ = message config "Proving freeness of constructors ...";
   503 
   504     (* prove theorem  Rep_i (Constr_j ...) = Inj_j ...  *)
   505     
   506     fun prove_constr_rep_thm eqn =
   507       let
   508         val inj_thms = map fst newT_iso_inj_thms;
   509         val rewrites = @{thm o_def} :: constr_defs @ (map (mk_meta_eq o #2) newT_iso_axms)
   510       in Skip_Proof.prove_global thy5 [] [] eqn (fn _ => EVERY
   511         [resolve_tac inj_thms 1,
   512          rewrite_goals_tac rewrites,
   513          rtac refl 3,
   514          resolve_tac rep_intrs 2,
   515          REPEAT (resolve_tac iso_elem_thms 1)])
   516       end;
   517 
   518     (*--------------------------------------------------------------*)
   519     (* constr_rep_thms and rep_congs are used to prove distinctness *)
   520     (* of constructors.                                             *)
   521     (*--------------------------------------------------------------*)
   522 
   523     val constr_rep_thms = map (map prove_constr_rep_thm) constr_rep_eqns;
   524 
   525     val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
   526       dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   527         (constr_rep_thms ~~ dist_lemmas);
   528 
   529     fun prove_distinct_thms dist_rewrites' (k, ts) =
   530       let
   531         fun prove [] = []
   532           | prove (t :: ts) =
   533               let
   534                 val dist_thm = Skip_Proof.prove_global thy5 [] [] t (fn _ =>
   535                   EVERY [simp_tac (HOL_ss addsimps dist_rewrites') 1])
   536               in dist_thm :: Drule.standard (dist_thm RS not_sym) :: prove ts end;
   537       in prove ts end;
   538 
   539     val distinct_thms = map2 (prove_distinct_thms)
   540       dist_rewrites (Datatype_Prop.make_distincts descr sorts);
   541 
   542     (* prove injectivity of constructors *)
   543 
   544     fun prove_constr_inj_thm rep_thms t =
   545       let val inj_thms = Scons_inject :: (map make_elim
   546         (iso_inj_thms @
   547           [In0_inject, In1_inject, Leaf_inject, Inl_inject, Inr_inject,
   548            Lim_inject, Suml_inject, Sumr_inject]))
   549       in Skip_Proof.prove_global thy5 [] [] t (fn _ => EVERY
   550         [rtac iffI 1,
   551          REPEAT (etac conjE 2), hyp_subst_tac 2, rtac refl 2,
   552          dresolve_tac rep_congs 1, dtac box_equals 1,
   553          REPEAT (resolve_tac rep_thms 1),
   554          REPEAT (eresolve_tac inj_thms 1),
   555          REPEAT (ares_tac [conjI] 1 ORELSE (EVERY [REPEAT (rtac ext 1),
   556            REPEAT (eresolve_tac (make_elim fun_cong :: inj_thms) 1),
   557            atac 1]))])
   558       end;
   559 
   560     val constr_inject = map (fn (ts, thms) => map (prove_constr_inj_thm thms) ts)
   561       ((Datatype_Prop.make_injs descr sorts) ~~ constr_rep_thms);
   562 
   563     val ((constr_inject', distinct_thms'), thy6) =
   564       thy5
   565       |> Sign.parent_path
   566       |> store_thmss "inject" new_type_names constr_inject
   567       ||>> store_thmss "distinct" new_type_names distinct_thms;
   568 
   569     (*************************** induction theorem ****************************)
   570 
   571     val _ = message config "Proving induction rule for datatypes ...";
   572 
   573     val Rep_inverse_thms = (map (fn (_, iso, _) => iso RS subst) newT_iso_axms) @
   574       (map (fn r => r RS @{thm the_inv_f_f} RS subst) iso_inj_thms_unfolded);
   575     val Rep_inverse_thms' = map (fn r => r RS @{thm the_inv_f_f}) iso_inj_thms_unfolded;
   576 
   577     fun mk_indrule_lemma ((i, _), T) (prems, concls) =
   578       let
   579         val Rep_t = Const (nth all_rep_names i, T --> Univ_elT) $
   580           mk_Free "x" T i;
   581 
   582         val Abs_t = if i < length newTs then
   583             Const (Sign.intern_const thy6
   584               ("Abs_" ^ (nth new_type_names i)), Univ_elT --> T)
   585           else Const (@{const_name the_inv_into},
   586               [HOLogic.mk_setT T, T --> Univ_elT, Univ_elT] ---> T) $
   587             HOLogic.mk_UNIV T $ Const (nth all_rep_names i, T --> Univ_elT)
   588 
   589       in (prems @ [HOLogic.imp $
   590             (Const (nth rep_set_names i, UnivT') $ Rep_t) $
   591               (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
   592           concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
   593       end;
   594 
   595     val (indrule_lemma_prems, indrule_lemma_concls) =
   596       fold mk_indrule_lemma (descr' ~~ recTs) ([], []);
   597 
   598     val cert = cterm_of thy6;
   599 
   600     val indrule_lemma = Skip_Proof.prove_global thy6 [] []
   601       (Logic.mk_implies
   602         (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
   603          HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
   604            [REPEAT (etac conjE 1),
   605             REPEAT (EVERY
   606               [TRY (rtac conjI 1), resolve_tac Rep_inverse_thms 1,
   607                etac mp 1, resolve_tac iso_elem_thms 1])]);
   608 
   609     val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
   610     val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
   611       map (Free o apfst fst o dest_Var) Ps;
   612     val indrule_lemma' = cterm_instantiate (map cert Ps ~~ map cert frees) indrule_lemma;
   613 
   614     val dt_induct_prop = Datatype_Prop.make_ind descr sorts;
   615     val dt_induct = Skip_Proof.prove_global thy6 []
   616       (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
   617       (fn {prems, ...} => EVERY
   618         [rtac indrule_lemma' 1,
   619          (indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
   620          EVERY (map (fn (prem, r) => (EVERY
   621            [REPEAT (eresolve_tac Abs_inverse_thms 1),
   622             simp_tac (HOL_basic_ss addsimps ((symmetric r)::Rep_inverse_thms')) 1,
   623             DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
   624                 (prems ~~ (constr_defs @ (map mk_meta_eq iso_char_thms))))]);
   625 
   626     val ([dt_induct'], thy7) =
   627       thy6
   628       |> Sign.add_path big_name
   629       |> PureThy.add_thms [((Binding.name "induct", dt_induct), [case_names_induct])]
   630       ||> Sign.parent_path
   631       ||> Theory.checkpoint;
   632 
   633   in
   634     ((constr_inject', distinct_thms', dt_induct'), thy7)
   635   end;
   636 
   637 
   638 
   639 (** definitional introduction of datatypes **)
   640 
   641 fun gen_add_datatype prep_typ config new_type_names dts thy =
   642   let
   643     val _ = Theory.requires thy "Datatype" "datatype definitions";
   644 
   645     (* this theory is used just for parsing *)
   646     val tmp_thy = thy |>
   647       Theory.copy |>
   648       Sign.add_types (map (fn (tvs, tname, mx, _) =>
   649         (tname, length tvs, mx)) dts);
   650 
   651     val (tyvars, _, _, _)::_ = dts;
   652     val (new_dts, types_syntax) = ListPair.unzip (map (fn (tvs, tname, mx, _) =>
   653       let val full_tname = Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname)
   654       in
   655         (case duplicates (op =) tvs of
   656           [] =>
   657             if eq_set (op =) (tyvars, tvs) then ((full_tname, tvs), (tname, mx))
   658             else error ("Mutually recursive datatypes must have same type parameters")
   659         | dups => error ("Duplicate parameter(s) for datatype " ^ quote (Binding.str_of tname) ^
   660             " : " ^ commas dups))
   661       end) dts);
   662     val dt_names = map fst new_dts;
   663 
   664     val _ =
   665       (case duplicates (op =) (map fst new_dts) @ duplicates (op =) new_type_names of
   666         [] => ()
   667       | dups => error ("Duplicate datatypes: " ^ commas dups));
   668 
   669     fun prep_dt_spec (tvs, tname, mx, constrs) tname' (dts', constr_syntax, sorts, i) =
   670       let
   671         fun prep_constr (cname, cargs, mx') (constrs, constr_syntax', sorts') =
   672           let
   673             val (cargs', sorts'') = fold_map (prep_typ tmp_thy) cargs sorts';
   674             val _ =
   675               (case subtract (op =) tvs (fold (curry OldTerm.add_typ_tfree_names) cargs' []) of
   676                 [] => ()
   677               | vs => error ("Extra type variables on rhs: " ^ commas vs))
   678           in (constrs @ [(Sign.full_name_path tmp_thy tname'
   679                   (Binding.map_name (Syntax.const_name mx') cname),
   680                    map (dtyp_of_typ new_dts) cargs')],
   681               constr_syntax' @ [(cname, mx')], sorts'')
   682           end handle ERROR msg => cat_error msg
   683            ("The error above occured in constructor " ^ quote (Binding.str_of cname) ^
   684             " of datatype " ^ quote (Binding.str_of tname));
   685 
   686         val (constrs', constr_syntax', sorts') =
   687           fold prep_constr constrs ([], [], sorts)
   688 
   689       in
   690         case duplicates (op =) (map fst constrs') of
   691            [] =>
   692              (dts' @ [(i, (Sign.full_name tmp_thy (Binding.map_name (Syntax.type_name mx) tname),
   693                 map DtTFree tvs, constrs'))],
   694               constr_syntax @ [constr_syntax'], sorts', i + 1)
   695          | dups => error ("Duplicate constructors " ^ commas dups ^
   696              " in datatype " ^ quote (Binding.str_of tname))
   697       end;
   698 
   699     val (dts', constr_syntax, sorts', i) =
   700       fold2 prep_dt_spec dts new_type_names ([], [], [], 0);
   701     val sorts = sorts' @ map (rpair (Sign.defaultS tmp_thy)) (subtract (op =) (map fst sorts') tyvars);
   702     val dt_info = Datatype_Data.get_all thy;
   703     val (descr, _) = unfold_datatypes tmp_thy dts' sorts dt_info dts' i;
   704     val _ = check_nonempty descr handle (exn as Datatype_Empty s) =>
   705       if #strict config then error ("Nonemptiness check failed for datatype " ^ s)
   706       else raise exn;
   707 
   708     val _ = message config ("Constructing datatype(s) " ^ commas_quote new_type_names);
   709 
   710   in
   711     thy
   712     |> representation_proofs config dt_info new_type_names descr sorts
   713         types_syntax constr_syntax (Datatype_Data.mk_case_names_induct (flat descr))
   714     |-> (fn (inject, distinct, induct) => Datatype_Data.derive_datatype_props
   715         config dt_names (SOME new_type_names) descr sorts
   716         induct inject distinct)
   717   end;
   718 
   719 val add_datatype = gen_add_datatype Datatype_Data.cert_typ;
   720 val datatype_cmd = snd ooo gen_add_datatype Datatype_Data.read_typ default_config;
   721 
   722 local
   723 
   724 structure P = OuterParse and K = OuterKeyword
   725 
   726 fun prep_datatype_decls args =
   727   let
   728     val names = map
   729       (fn ((((NONE, _), t), _), _) => Binding.name_of t | ((((SOME t, _), _), _), _) => t) args;
   730     val specs = map (fn ((((_, vs), t), mx), cons) =>
   731       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
   732   in (names, specs) end;
   733 
   734 val parse_datatype_decl =
   735   (Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.binding -- P.opt_infix --
   736     (P.$$$ "=" |-- P.enum1 "|" (P.binding -- Scan.repeat P.typ -- P.opt_mixfix)));
   737 
   738 val parse_datatype_decls = P.and_list1 parse_datatype_decl >> prep_datatype_decls;
   739 
   740 in
   741 
   742 val _ =
   743   OuterSyntax.command "datatype" "define inductive datatypes" K.thy_decl
   744     (parse_datatype_decls >> (fn (names, specs) => Toplevel.theory (datatype_cmd names specs)));
   745 
   746 end;
   747 
   748 end;