src/HOL/Tools/Datatype/rep_datatype.ML
author traytel
Tue Jan 22 14:33:45 2013 +0100 (2013-01-22)
changeset 51673 4dfa00e264d8
parent 51672 d5c5e088ebdf
child 51717 9e7d1c139569
permissions -rw-r--r--
separate data used for case translation from the datatype package
     1 (*  Title:      HOL/Tools/Datatype/rep_datatype.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Representation of existing types as datatypes: proofs and definitions
     5 independent of concrete representation of datatypes (i.e. requiring
     6 only abstract properties: injectivity / distinctness of constructors
     7 and induction).
     8 *)
     9 
    10 signature REP_DATATYPE =
    11 sig
    12   val derive_datatype_props : Datatype_Aux.config -> string list -> Datatype_Aux.descr list ->
    13     thm -> thm list list -> thm list list -> theory -> string list * theory
    14   val rep_datatype : Datatype_Aux.config -> (string list -> Proof.context -> Proof.context) ->
    15     term list -> theory -> Proof.state
    16   val rep_datatype_cmd : Datatype_Aux.config -> (string list -> Proof.context -> Proof.context) ->
    17     string list -> theory -> Proof.state
    18 end;
    19 
    20 structure Rep_Datatype: REP_DATATYPE =
    21 struct
    22 
    23 (** derived definitions and proofs **)
    24 
    25 (* case distinction theorems *)
    26 
    27 fun prove_casedist_thms (config : Datatype_Aux.config)
    28     new_type_names descr induct case_names_exhausts thy =
    29   let
    30     val _ = Datatype_Aux.message config "Proving case distinction theorems ...";
    31 
    32     val descr' = flat descr;
    33     val recTs = Datatype_Aux.get_rec_types descr';
    34     val newTs = take (length (hd descr)) recTs;
    35 
    36     val maxidx = Thm.maxidx_of induct;
    37     val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
    38 
    39     fun prove_casedist_thm (i, (T, t)) =
    40       let
    41         val dummyPs = map (fn (Var (_, Type (_, [T', T'']))) =>
    42           Abs ("z", T', Const (@{const_name True}, T''))) induct_Ps;
    43         val P =
    44           Abs ("z", T, HOLogic.imp $ HOLogic.mk_eq (Var (("a", maxidx + 1), T), Bound 0) $
    45             Var (("P", 0), HOLogic.boolT));
    46         val insts = take i dummyPs @ (P :: drop (i + 1) dummyPs);
    47         val cert = cterm_of thy;
    48         val insts' = map cert induct_Ps ~~ map cert insts;
    49         val induct' =
    50           refl RS
    51             (nth (Datatype_Aux.split_conj_thm (cterm_instantiate insts' induct)) i RSN (2, rev_mp));
    52       in
    53         Goal.prove_sorry_global thy []
    54           (Logic.strip_imp_prems t)
    55           (Logic.strip_imp_concl t)
    56           (fn {prems, ...} =>
    57             EVERY
    58               [rtac induct' 1,
    59                REPEAT (rtac TrueI 1),
    60                REPEAT ((rtac impI 1) THEN (eresolve_tac prems 1)),
    61                REPEAT (rtac TrueI 1)])
    62       end;
    63 
    64     val casedist_thms =
    65       map_index prove_casedist_thm (newTs ~~ Datatype_Prop.make_casedists descr);
    66   in
    67     thy
    68     |> Datatype_Aux.store_thms_atts "exhaust" new_type_names
    69         (map single case_names_exhausts) casedist_thms
    70   end;
    71 
    72 
    73 (* primrec combinators *)
    74 
    75 fun prove_primrec_thms (config : Datatype_Aux.config) new_type_names descr
    76     injects_of constr_inject (dist_rewrites, other_dist_rewrites) induct thy =
    77   let
    78     val _ = Datatype_Aux.message config "Constructing primrec combinators ...";
    79 
    80     val big_name = space_implode "_" new_type_names;
    81     val thy0 = Sign.add_path big_name thy;
    82 
    83     val descr' = flat descr;
    84     val recTs = Datatype_Aux.get_rec_types descr';
    85     val used = fold Term.add_tfree_namesT recTs [];
    86     val newTs = take (length (hd descr)) recTs;
    87 
    88     val induct_Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
    89 
    90     val big_rec_name' = big_name ^ "_rec_set";
    91     val rec_set_names' =
    92       if length descr' = 1 then [big_rec_name']
    93       else map (prefix (big_rec_name' ^ "_") o string_of_int) (1 upto length descr');
    94     val rec_set_names = map (Sign.full_bname thy0) rec_set_names';
    95 
    96     val (rec_result_Ts, reccomb_fn_Ts) = Datatype_Prop.make_primrec_Ts descr used;
    97 
    98     val rec_set_Ts =
    99       map (fn (T1, T2) => (reccomb_fn_Ts @ [T1, T2]) ---> HOLogic.boolT) (recTs ~~ rec_result_Ts);
   100 
   101     val rec_fns =
   102       map (uncurry (Datatype_Aux.mk_Free "f")) (reccomb_fn_Ts ~~ (1 upto length reccomb_fn_Ts));
   103     val rec_sets' =
   104       map (fn c => list_comb (Free c, rec_fns)) (rec_set_names' ~~ rec_set_Ts);
   105     val rec_sets =
   106       map (fn c => list_comb (Const c, rec_fns)) (rec_set_names ~~ rec_set_Ts);
   107 
   108     (* introduction rules for graph of primrec function *)
   109 
   110     fun make_rec_intr T rec_set (cname, cargs) (rec_intr_ts, l) =
   111       let
   112         fun mk_prem (dt, U) (j, k, prems, t1s, t2s) =
   113           let val free1 = Datatype_Aux.mk_Free "x" U j in
   114             (case (Datatype_Aux.strip_dtyp dt, strip_type U) of
   115               ((_, Datatype_Aux.DtRec m), (Us, _)) =>
   116                 let
   117                   val free2 = Datatype_Aux.mk_Free "y" (Us ---> nth rec_result_Ts m) k;
   118                   val i = length Us;
   119                 in
   120                   (j + 1, k + 1,
   121                     HOLogic.mk_Trueprop (HOLogic.list_all
   122                       (map (pair "x") Us, nth rec_sets' m $
   123                         Datatype_Aux.app_bnds free1 i $ Datatype_Aux.app_bnds free2 i)) :: prems,
   124                     free1 :: t1s, free2 :: t2s)
   125                 end
   126             | _ => (j + 1, k, prems, free1 :: t1s, t2s))
   127           end;
   128 
   129         val Ts = map (Datatype_Aux.typ_of_dtyp descr') cargs;
   130         val (_, _, prems, t1s, t2s) = fold_rev mk_prem (cargs ~~ Ts) (1, 1, [], [], []);
   131 
   132       in
   133         (rec_intr_ts @
   134           [Logic.list_implies (prems, HOLogic.mk_Trueprop
   135             (rec_set $ list_comb (Const (cname, Ts ---> T), t1s) $
   136               list_comb (nth rec_fns l, t1s @ t2s)))], l + 1)
   137       end;
   138 
   139     val (rec_intr_ts, _) =
   140       fold (fn ((d, T), set_name) =>
   141         fold (make_rec_intr T set_name) (#3 (snd d))) (descr' ~~ recTs ~~ rec_sets') ([], 0);
   142 
   143     val ({intrs = rec_intrs, elims = rec_elims, ...}, thy1) =
   144       thy0
   145       |> Sign.map_naming Name_Space.conceal
   146       |> Inductive.add_inductive_global
   147           {quiet_mode = #quiet config, verbose = false, alt_name = Binding.name big_rec_name',
   148             coind = false, no_elim = false, no_ind = true, skip_mono = true}
   149           (map (fn (s, T) => ((Binding.name s, T), NoSyn)) (rec_set_names' ~~ rec_set_Ts))
   150           (map dest_Free rec_fns)
   151           (map (fn x => (Attrib.empty_binding, x)) rec_intr_ts) []
   152       ||> Sign.restore_naming thy0
   153       ||> Theory.checkpoint;
   154 
   155     (* prove uniqueness and termination of primrec combinators *)
   156 
   157     val _ = Datatype_Aux.message config "Proving termination and uniqueness of primrec functions ...";
   158 
   159     fun mk_unique_tac ((((i, (tname, _, constrs)), elim), T), T') (tac, intrs) =
   160       let
   161         val distinct_tac =
   162           if i < length newTs then
   163             full_simp_tac (HOL_ss addsimps (nth dist_rewrites i)) 1
   164           else full_simp_tac (HOL_ss addsimps (flat other_dist_rewrites)) 1;
   165 
   166         val inject =
   167           map (fn r => r RS iffD1)
   168             (if i < length newTs then nth constr_inject i else injects_of tname);
   169 
   170         fun mk_unique_constr_tac n (cname, cargs) (tac, intr :: intrs, j) =
   171           let
   172             val k = length (filter Datatype_Aux.is_rec_type cargs);
   173           in
   174             (EVERY
   175               [DETERM tac,
   176                 REPEAT (etac ex1E 1), rtac ex1I 1,
   177                 DEPTH_SOLVE_1 (ares_tac [intr] 1),
   178                 REPEAT_DETERM_N k (etac thin_rl 1 THEN rotate_tac 1 1),
   179                 etac elim 1,
   180                 REPEAT_DETERM_N j distinct_tac,
   181                 TRY (dresolve_tac inject 1),
   182                 REPEAT (etac conjE 1), hyp_subst_tac 1,
   183                 REPEAT (EVERY [etac allE 1, dtac mp 1, atac 1]),
   184                 TRY (hyp_subst_tac 1),
   185                 rtac refl 1,
   186                 REPEAT_DETERM_N (n - j - 1) distinct_tac],
   187               intrs, j + 1)
   188           end;
   189 
   190         val (tac', intrs', _) =
   191           fold (mk_unique_constr_tac (length constrs)) constrs (tac, intrs, 0);
   192       in (tac', intrs') end;
   193 
   194     val rec_unique_thms =
   195       let
   196         val rec_unique_ts =
   197           map (fn (((set_t, T1), T2), i) =>
   198             Const (@{const_name Ex1}, (T2 --> HOLogic.boolT) --> HOLogic.boolT) $
   199               absfree ("y", T2) (set_t $ Datatype_Aux.mk_Free "x" T1 i $ Free ("y", T2)))
   200                 (rec_sets ~~ recTs ~~ rec_result_Ts ~~ (1 upto length recTs));
   201         val cert = cterm_of thy1;
   202         val insts =
   203           map (fn ((i, T), t) => absfree ("x" ^ string_of_int i, T) t)
   204             ((1 upto length recTs) ~~ recTs ~~ rec_unique_ts);
   205         val induct' = cterm_instantiate (map cert induct_Ps ~~ map cert insts) induct;
   206         val (tac, _) =
   207           fold mk_unique_tac (descr' ~~ rec_elims ~~ recTs ~~ rec_result_Ts)
   208             (((rtac induct' THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1 THEN
   209                 rewrite_goals_tac [mk_meta_eq @{thm choice_eq}], rec_intrs));
   210       in
   211         Datatype_Aux.split_conj_thm (Goal.prove_sorry_global thy1 [] []
   212           (HOLogic.mk_Trueprop (Datatype_Aux.mk_conj rec_unique_ts)) (K tac))
   213       end;
   214 
   215     val rec_total_thms = map (fn r => r RS @{thm theI'}) rec_unique_thms;
   216 
   217     (* define primrec combinators *)
   218 
   219     val big_reccomb_name = space_implode "_" new_type_names ^ "_rec";
   220     val reccomb_names =
   221       map (Sign.full_bname thy1)
   222         (if length descr' = 1 then [big_reccomb_name]
   223          else map (prefix (big_reccomb_name ^ "_") o string_of_int) (1 upto length descr'));
   224     val reccombs =
   225       map (fn ((name, T), T') => Const (name, reccomb_fn_Ts @ [T] ---> T'))
   226         (reccomb_names ~~ recTs ~~ rec_result_Ts);
   227 
   228     val (reccomb_defs, thy2) =
   229       thy1
   230       |> Sign.add_consts_i (map (fn ((name, T), T') =>
   231             (Binding.name (Long_Name.base_name name), reccomb_fn_Ts @ [T] ---> T', NoSyn))
   232             (reccomb_names ~~ recTs ~~ rec_result_Ts))
   233       |> (Global_Theory.add_defs false o map Thm.no_attributes)
   234           (map
   235             (fn ((((name, comb), set), T), T') =>
   236               (Binding.name (Thm.def_name (Long_Name.base_name name)),
   237                 Logic.mk_equals (comb, fold_rev lambda rec_fns (absfree ("x", T)
   238                  (Const (@{const_name The}, (T' --> HOLogic.boolT) --> T') $ absfree ("y", T')
   239                    (set $ Free ("x", T) $ Free ("y", T')))))))
   240             (reccomb_names ~~ reccombs ~~ rec_sets ~~ recTs ~~ rec_result_Ts))
   241       ||> Sign.parent_path
   242       ||> Theory.checkpoint;
   243 
   244 
   245     (* prove characteristic equations for primrec combinators *)
   246 
   247     val _ = Datatype_Aux.message config "Proving characteristic theorems for primrec combinators ...";
   248 
   249     val rec_thms =
   250       map (fn t =>
   251         Goal.prove_sorry_global thy2 [] [] t
   252           (fn _ => EVERY
   253             [rewrite_goals_tac reccomb_defs,
   254              rtac @{thm the1_equality} 1,
   255              resolve_tac rec_unique_thms 1,
   256              resolve_tac rec_intrs 1,
   257              REPEAT (rtac allI 1 ORELSE resolve_tac rec_total_thms 1)]))
   258        (Datatype_Prop.make_primrecs reccomb_names descr thy2);
   259   in
   260     thy2
   261     |> Sign.add_path (space_implode "_" new_type_names)
   262     |> Global_Theory.note_thmss ""
   263       [((Binding.name "recs", [Nitpick_Simps.add]), [(rec_thms, [])])]
   264     ||> Sign.parent_path
   265     ||> Theory.checkpoint
   266     |-> (fn thms => pair (reccomb_names, maps #2 thms))
   267   end;
   268 
   269 
   270 (* case combinators *)
   271 
   272 fun prove_case_thms (config : Datatype_Aux.config)
   273     new_type_names descr reccomb_names primrec_thms thy =
   274   let
   275     val _ = Datatype_Aux.message config "Proving characteristic theorems for case combinators ...";
   276 
   277     val thy1 = Sign.add_path (space_implode "_" new_type_names) thy;
   278 
   279     val descr' = flat descr;
   280     val recTs = Datatype_Aux.get_rec_types descr';
   281     val used = fold Term.add_tfree_namesT recTs [];
   282     val newTs = take (length (hd descr)) recTs;
   283     val T' = TFree (singleton (Name.variant_list used) "'t", HOLogic.typeS);
   284 
   285     fun mk_dummyT dt = binder_types (Datatype_Aux.typ_of_dtyp descr' dt) ---> T';
   286 
   287     val case_dummy_fns =
   288       map (fn (_, (_, _, constrs)) => map (fn (_, cargs) =>
   289         let
   290           val Ts = map (Datatype_Aux.typ_of_dtyp descr') cargs;
   291           val Ts' = map mk_dummyT (filter Datatype_Aux.is_rec_type cargs)
   292         in Const (@{const_name undefined}, Ts @ Ts' ---> T') end) constrs) descr';
   293 
   294     val case_names = map (fn s => Sign.full_bname thy1 (s ^ "_case")) new_type_names;
   295 
   296     (* define case combinators via primrec combinators *)
   297 
   298     val (case_defs, thy2) =
   299       fold (fn ((((i, (_, _, constrs)), T), name), recname) => fn (defs, thy) =>
   300           let
   301             val (fns1, fns2) = split_list (map (fn ((_, cargs), j) =>
   302               let
   303                 val Ts = map (Datatype_Aux.typ_of_dtyp descr') cargs;
   304                 val Ts' = Ts @ map mk_dummyT (filter Datatype_Aux.is_rec_type cargs);
   305                 val frees' = map2 (Datatype_Aux.mk_Free "x") Ts' (1 upto length Ts');
   306                 val frees = take (length cargs) frees';
   307                 val free = Datatype_Aux.mk_Free "f" (Ts ---> T') j;
   308               in
   309                 (free, fold_rev (absfree o dest_Free) frees' (list_comb (free, frees)))
   310               end) (constrs ~~ (1 upto length constrs)));
   311 
   312             val caseT = map (snd o dest_Free) fns1 @ [T] ---> T';
   313             val fns = flat (take i case_dummy_fns) @ fns2 @ flat (drop (i + 1) case_dummy_fns);
   314             val reccomb = Const (recname, (map fastype_of fns) @ [T] ---> T');
   315             val decl = ((Binding.name (Long_Name.base_name name), caseT), NoSyn);
   316             val def =
   317               (Binding.name (Thm.def_name (Long_Name.base_name name)),
   318                 Logic.mk_equals (Const (name, caseT),
   319                   fold_rev lambda fns1
   320                     (list_comb (reccomb,
   321                       flat (take i case_dummy_fns) @ fns2 @ flat (drop (i + 1) case_dummy_fns)))));
   322             val ([def_thm], thy') =
   323               thy
   324               |> Sign.declare_const_global decl |> snd
   325               |> (Global_Theory.add_defs false o map Thm.no_attributes) [def];
   326 
   327           in (defs @ [def_thm], thy') end)
   328         (hd descr ~~ newTs ~~ case_names ~~ take (length newTs) reccomb_names) ([], thy1)
   329       ||> Theory.checkpoint;
   330 
   331     val case_thms =
   332       (map o map) (fn t =>
   333           Goal.prove_sorry_global thy2 [] [] t
   334             (fn _ =>
   335               EVERY [rewrite_goals_tac (case_defs @ map mk_meta_eq primrec_thms), rtac refl 1]))
   336         (Datatype_Prop.make_cases case_names descr thy2);
   337   in
   338     thy2
   339     |> Context.theory_map ((fold o fold) Nitpick_Simps.add_thm case_thms)
   340     |> Sign.parent_path
   341     |> Datatype_Aux.store_thmss "cases" new_type_names case_thms
   342     |-> (fn thmss => pair (thmss, case_names))
   343   end;
   344 
   345 
   346 (* case splitting *)
   347 
   348 fun prove_split_thms (config : Datatype_Aux.config)
   349     new_type_names case_names descr constr_inject dist_rewrites casedist_thms case_thms thy =
   350   let
   351     val _ = Datatype_Aux.message config "Proving equations for case splitting ...";
   352 
   353     val descr' = flat descr;
   354     val recTs = Datatype_Aux.get_rec_types descr';
   355     val newTs = take (length (hd descr)) recTs;
   356 
   357     fun prove_split_thms ((((((t1, t2), inject), dist_rewrites'), exhaustion), case_thms'), T) =
   358       let
   359         val cert = cterm_of thy;
   360         val _ $ (_ $ lhs $ _) = hd (Logic.strip_assums_hyp (hd (prems_of exhaustion)));
   361         val exhaustion' = cterm_instantiate [(cert lhs, cert (Free ("x", T)))] exhaustion;
   362         val tac =
   363           EVERY [rtac exhaustion' 1,
   364             ALLGOALS (asm_simp_tac (HOL_ss addsimps (dist_rewrites' @ inject @ case_thms')))];
   365       in
   366         (Goal.prove_sorry_global thy [] [] t1 (K tac),
   367          Goal.prove_sorry_global thy [] [] t2 (K tac))
   368       end;
   369 
   370     val split_thm_pairs =
   371       map prove_split_thms
   372         (Datatype_Prop.make_splits case_names descr thy ~~ constr_inject ~~
   373           dist_rewrites ~~ casedist_thms ~~ case_thms ~~ newTs);
   374 
   375     val (split_thms, split_asm_thms) = split_list split_thm_pairs
   376 
   377   in
   378     thy
   379     |> Datatype_Aux.store_thms "split" new_type_names split_thms
   380     ||>> Datatype_Aux.store_thms "split_asm" new_type_names split_asm_thms
   381     |-> (fn (thms1, thms2) => pair (thms1 ~~ thms2))
   382   end;
   383 
   384 fun prove_weak_case_congs new_type_names case_names descr thy =
   385   let
   386     fun prove_weak_case_cong t =
   387      Goal.prove_sorry_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
   388        (fn {prems, ...} => EVERY [rtac (hd prems RS arg_cong) 1]);
   389 
   390     val weak_case_congs =
   391       map prove_weak_case_cong (Datatype_Prop.make_weak_case_congs case_names descr thy);
   392 
   393   in thy |> Datatype_Aux.store_thms "weak_case_cong" new_type_names weak_case_congs end;
   394 
   395 
   396 (* additional theorems for TFL *)
   397 
   398 fun prove_nchotomys (config : Datatype_Aux.config) new_type_names descr casedist_thms thy =
   399   let
   400     val _ = Datatype_Aux.message config "Proving additional theorems for TFL ...";
   401 
   402     fun prove_nchotomy (t, exhaustion) =
   403       let
   404         (* For goal i, select the correct disjunct to attack, then prove it *)
   405         fun tac i 0 = EVERY [TRY (rtac disjI1 i), hyp_subst_tac i, REPEAT (rtac exI i), rtac refl i]
   406           | tac i n = rtac disjI2 i THEN tac i (n - 1);
   407       in
   408         Goal.prove_sorry_global thy [] [] t
   409           (fn _ =>
   410             EVERY [rtac allI 1,
   411              Datatype_Aux.exh_tac (K exhaustion) 1,
   412              ALLGOALS (fn i => tac i (i - 1))])
   413       end;
   414 
   415     val nchotomys =
   416       map prove_nchotomy (Datatype_Prop.make_nchotomys descr ~~ casedist_thms);
   417 
   418   in thy |> Datatype_Aux.store_thms "nchotomy" new_type_names nchotomys end;
   419 
   420 fun prove_case_congs new_type_names case_names descr nchotomys case_thms thy =
   421   let
   422     fun prove_case_cong ((t, nchotomy), case_rewrites) =
   423       let
   424         val Const ("==>", _) $ tm $ _ = t;
   425         val Const (@{const_name Trueprop}, _) $ (Const (@{const_name HOL.eq}, _) $ _ $ Ma) = tm;
   426         val cert = cterm_of thy;
   427         val nchotomy' = nchotomy RS spec;
   428         val [v] = Term.add_vars (concl_of nchotomy') [];
   429         val nchotomy'' = cterm_instantiate [(cert (Var v), cert Ma)] nchotomy';
   430       in
   431         Goal.prove_sorry_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
   432           (fn {prems, ...} =>
   433             let val simplify = asm_simp_tac (HOL_ss addsimps (prems @ case_rewrites)) in
   434               EVERY [
   435                 simp_tac (HOL_ss addsimps [hd prems]) 1,
   436                 cut_tac nchotomy'' 1,
   437                 REPEAT (etac disjE 1 THEN REPEAT (etac exE 1) THEN simplify 1),
   438                 REPEAT (etac exE 1) THEN simplify 1 (* Get last disjunct *)]
   439             end)
   440       end;
   441 
   442     val case_congs =
   443       map prove_case_cong
   444         (Datatype_Prop.make_case_congs case_names descr thy ~~ nchotomys ~~ case_thms);
   445 
   446   in thy |> Datatype_Aux.store_thms "case_cong" new_type_names case_congs end;
   447 
   448 
   449 
   450 (** derive datatype props **)
   451 
   452 local
   453 
   454 fun make_dt_info descr induct inducts rec_names rec_rewrites
   455     (index, (((((((((((_, (tname, _, _))), inject), distinct),
   456       exhaust), nchotomy), case_name), case_rewrites), case_cong), weak_case_cong),
   457         (split, split_asm))) =
   458   (tname,
   459    {index = index,
   460     descr = descr,
   461     inject = inject,
   462     distinct = distinct,
   463     induct = induct,
   464     inducts = inducts,
   465     exhaust = exhaust,
   466     nchotomy = nchotomy,
   467     rec_names = rec_names,
   468     rec_rewrites = rec_rewrites,
   469     case_name = case_name,
   470     case_rewrites = case_rewrites,
   471     case_cong = case_cong,
   472     weak_case_cong = weak_case_cong,
   473     split = split,
   474     split_asm = split_asm});
   475 
   476 in
   477 
   478 fun derive_datatype_props config dt_names descr induct inject distinct thy1 =
   479   let
   480     val thy2 = thy1 |> Theory.checkpoint;
   481     val flat_descr = flat descr;
   482     val new_type_names = map Long_Name.base_name dt_names;
   483     val _ =
   484       Datatype_Aux.message config
   485         ("Deriving properties for datatype(s) " ^ commas_quote new_type_names);
   486 
   487     val (exhaust, thy3) = thy2
   488       |> prove_casedist_thms config new_type_names descr induct
   489         (Datatype_Data.mk_case_names_exhausts flat_descr dt_names);
   490     val (nchotomys, thy4) = thy3
   491       |> prove_nchotomys config new_type_names descr exhaust;
   492     val ((rec_names, rec_rewrites), thy5) = thy4
   493       |> prove_primrec_thms config new_type_names descr
   494         (#inject o the o Symtab.lookup (Datatype_Data.get_all thy4)) inject
   495         (distinct, Datatype_Data.all_distincts thy2 (Datatype_Aux.get_rec_types flat_descr)) induct;
   496     val ((case_rewrites, case_names), thy6) = thy5
   497       |> prove_case_thms config new_type_names descr rec_names rec_rewrites;
   498     val (case_congs, thy7) = thy6
   499       |> prove_case_congs new_type_names case_names descr nchotomys case_rewrites;
   500     val (weak_case_congs, thy8) = thy7
   501       |> prove_weak_case_congs new_type_names case_names descr;
   502     val (splits, thy9) = thy8
   503       |> prove_split_thms config new_type_names case_names descr
   504         inject distinct exhaust case_rewrites;
   505 
   506     val inducts = Project_Rule.projections (Proof_Context.init_global thy2) induct;
   507     val dt_infos =
   508       map_index
   509         (make_dt_info flat_descr induct inducts rec_names rec_rewrites)
   510         (hd descr ~~ inject ~~ distinct ~~ exhaust ~~ nchotomys ~~
   511           case_names ~~ case_rewrites ~~ case_congs ~~ weak_case_congs ~~ splits);
   512     val dt_names = map fst dt_infos;
   513     val prfx = Binding.qualify true (space_implode "_" new_type_names);
   514     val simps = flat (inject @ distinct @ case_rewrites) @ rec_rewrites;
   515     val named_rules = flat (map_index (fn (i, tname) =>
   516       [((Binding.empty, [Induct.induct_type tname]), [([nth inducts i], [])]),
   517        ((Binding.empty, [Induct.cases_type tname]), [([nth exhaust i], [])])]) dt_names);
   518     val unnamed_rules = map (fn induct =>
   519       ((Binding.empty, [Rule_Cases.inner_rule, Induct.induct_type ""]), [([induct], [])]))
   520         (drop (length dt_names) inducts);
   521 
   522     val ctxt = Proof_Context.init_global thy9;
   523     val case_combs = map (Proof_Context.read_const ctxt false dummyT) case_names;
   524     val constrss = map (fn (dtname, {descr, index, ...}) =>
   525       map (Proof_Context.read_const ctxt false dummyT o fst)
   526         (#3 (the (AList.lookup op = descr index)))) dt_infos
   527   in
   528     thy9
   529     |> Global_Theory.note_thmss ""
   530       ([((prfx (Binding.name "simps"), []), [(simps, [])]),
   531         ((prfx (Binding.name "inducts"), []), [(inducts, [])]),
   532         ((prfx (Binding.name "splits"), []), [(maps (fn (x, y) => [x, y]) splits, [])]),
   533         ((Binding.empty, [Simplifier.simp_add]),
   534           [(flat case_rewrites @ flat distinct @ rec_rewrites, [])]),
   535         ((Binding.empty, [Code.add_default_eqn_attribute]), [(rec_rewrites, [])]),
   536         ((Binding.empty, [iff_add]), [(flat inject, [])]),
   537         ((Binding.empty, [Classical.safe_elim NONE]),
   538           [(map (fn th => th RS notE) (flat distinct), [])]),
   539         ((Binding.empty, [Simplifier.cong_add]), [(weak_case_congs, [])]),
   540         ((Binding.empty, [Induct.induct_simp_add]), [(flat (distinct @ inject), [])])] @
   541           named_rules @ unnamed_rules)
   542     |> snd
   543     |> Datatype_Data.register dt_infos
   544     |> Context.theory_map (fold2 Case_Translation.register case_combs constrss)
   545     |> Datatype_Data.interpretation_data (config, dt_names)
   546     |> pair dt_names
   547   end;
   548 
   549 end;
   550 
   551 
   552 
   553 (** declare existing type as datatype **)
   554 
   555 local
   556 
   557 fun prove_rep_datatype config dt_names descr raw_inject half_distinct raw_induct thy1 =
   558   let
   559     val raw_distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
   560     val new_type_names = map Long_Name.base_name dt_names;
   561     val prfx = Binding.qualify true (space_implode "_" new_type_names);
   562     val (((inject, distinct), [(_, [induct])]), thy2) =
   563       thy1
   564       |> Datatype_Aux.store_thmss "inject" new_type_names raw_inject
   565       ||>> Datatype_Aux.store_thmss "distinct" new_type_names raw_distinct
   566       ||>> Global_Theory.note_thmss ""
   567         [((prfx (Binding.name "induct"), [Datatype_Data.mk_case_names_induct descr]),
   568           [([raw_induct], [])])];
   569   in
   570     thy2
   571     |> derive_datatype_props config dt_names [descr] induct inject distinct
   572  end;
   573 
   574 fun gen_rep_datatype prep_term config after_qed raw_ts thy =
   575   let
   576     val ctxt = Proof_Context.init_global thy;
   577 
   578     fun constr_of_term (Const (c, T)) = (c, T)
   579       | constr_of_term t = error ("Not a constant: " ^ Syntax.string_of_term ctxt t);
   580     fun no_constr (c, T) =
   581       error ("Bad constructor: " ^ Proof_Context.extern_const ctxt c ^ "::" ^
   582         Syntax.string_of_typ ctxt T);
   583     fun type_of_constr (cT as (_, T)) =
   584       let
   585         val frees = Term.add_tfreesT T [];
   586         val (tyco, vs) = (apsnd o map) dest_TFree (dest_Type (body_type T))
   587           handle TYPE _ => no_constr cT
   588         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
   589         val _ = if length frees <> length vs then no_constr cT else ();
   590       in (tyco, (vs, cT)) end;
   591 
   592     val raw_cs =
   593       AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
   594     val _ =
   595       (case map_filter (fn (tyco, _) =>
   596           if Symtab.defined (Datatype_Data.get_all thy) tyco then SOME tyco else NONE) raw_cs of
   597         [] => ()
   598       | tycos => error ("Type(s) " ^ commas_quote tycos ^ " already represented inductively"));
   599     val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
   600     val ms =
   601       (case distinct (op =) (map length raw_vss) of
   602          [n] => 0 upto n - 1
   603       | _ => error "Different types in given constructors");
   604     fun inter_sort m =
   605       map (fn xs => nth xs m) raw_vss
   606       |> foldr1 (Sorts.inter_sort (Sign.classes_of thy));
   607     val sorts = map inter_sort ms;
   608     val vs = Name.invent_names Name.context Name.aT sorts;
   609 
   610     fun norm_constr (raw_vs, (c, T)) =
   611       (c, map_atyps
   612         (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
   613 
   614     val cs = map (apsnd (map norm_constr)) raw_cs;
   615     val dtyps_of_typ = map (Datatype_Aux.dtyp_of_typ (map (rpair vs o fst) cs)) o binder_types;
   616     val dt_names = map fst cs;
   617 
   618     fun mk_spec (i, (tyco, constr)) =
   619       (i, (tyco, map Datatype_Aux.DtTFree vs, (map o apsnd) dtyps_of_typ constr));
   620     val descr = map_index mk_spec cs;
   621     val injs = Datatype_Prop.make_injs [descr];
   622     val half_distincts = Datatype_Prop.make_distincts [descr];
   623     val ind = Datatype_Prop.make_ind [descr];
   624     val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
   625 
   626     fun after_qed' raw_thms =
   627       let
   628         val [[[raw_induct]], raw_inject, half_distinct] =
   629           unflat rules (map Drule.zero_var_indexes_list raw_thms);
   630             (*FIXME somehow dubious*)
   631       in
   632         Proof_Context.background_theory_result  (* FIXME !? *)
   633           (prove_rep_datatype config dt_names descr raw_inject half_distinct raw_induct)
   634         #-> after_qed
   635       end;
   636   in
   637     ctxt
   638     |> Proof.theorem NONE after_qed' ((map o map) (rpair []) (flat rules))
   639   end;
   640 
   641 in
   642 
   643 val rep_datatype = gen_rep_datatype Sign.cert_term;
   644 val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global;
   645 
   646 end;
   647 
   648 
   649 (* outer syntax *)
   650 
   651 val _ =
   652   Outer_Syntax.command @{command_spec "rep_datatype"} "represent existing types inductively"
   653     (Scan.repeat1 Parse.term >> (fn ts =>
   654       Toplevel.print o
   655       Toplevel.theory_to_proof (rep_datatype_cmd Datatype_Aux.default_config (K I) ts)));
   656 
   657 end;