src/HOL/Tools/Datatype/rep_datatype.ML
author wenzelm
Thu Apr 18 17:07:01 2013 +0200 (2013-04-18)
changeset 51717 9e7d1c139569
parent 51673 4dfa00e264d8
child 51798 ad3a241def73
permissions -rw-r--r--
simplifier uses proper Proof.context instead of historic type simpset;
     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 ctxt ((((i, (tname, _, constrs)), elim), T), T') (tac, intrs) =
   160       let
   161         val distinct_tac =
   162           if i < length newTs then
   163             full_simp_tac (put_simpset HOL_ss ctxt addsimps (nth dist_rewrites i)) 1
   164           else full_simp_tac (put_simpset HOL_ss ctxt 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       in
   207         Datatype_Aux.split_conj_thm (Goal.prove_sorry_global thy1 [] []
   208           (HOLogic.mk_Trueprop (Datatype_Aux.mk_conj rec_unique_ts))
   209           (fn {context = ctxt, ...} =>
   210             #1 (fold (mk_unique_tac ctxt) (descr' ~~ rec_elims ~~ recTs ~~ rec_result_Ts)
   211               (((rtac induct' THEN_ALL_NEW Object_Logic.atomize_prems_tac) 1 THEN
   212                   rewrite_goals_tac [mk_meta_eq @{thm choice_eq}], rec_intrs)))))
   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         fun tac ctxt =
   363           EVERY [rtac exhaustion' 1,
   364             ALLGOALS (asm_simp_tac
   365               (put_simpset HOL_ss ctxt addsimps (dist_rewrites' @ inject @ case_thms')))];
   366       in
   367         (Goal.prove_sorry_global thy [] [] t1 (tac o #context),
   368          Goal.prove_sorry_global thy [] [] t2 (tac o #context))
   369       end;
   370 
   371     val split_thm_pairs =
   372       map prove_split_thms
   373         (Datatype_Prop.make_splits case_names descr thy ~~ constr_inject ~~
   374           dist_rewrites ~~ casedist_thms ~~ case_thms ~~ newTs);
   375 
   376     val (split_thms, split_asm_thms) = split_list split_thm_pairs
   377 
   378   in
   379     thy
   380     |> Datatype_Aux.store_thms "split" new_type_names split_thms
   381     ||>> Datatype_Aux.store_thms "split_asm" new_type_names split_asm_thms
   382     |-> (fn (thms1, thms2) => pair (thms1 ~~ thms2))
   383   end;
   384 
   385 fun prove_weak_case_congs new_type_names case_names descr thy =
   386   let
   387     fun prove_weak_case_cong t =
   388      Goal.prove_sorry_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
   389        (fn {prems, ...} => EVERY [rtac (hd prems RS arg_cong) 1]);
   390 
   391     val weak_case_congs =
   392       map prove_weak_case_cong (Datatype_Prop.make_weak_case_congs case_names descr thy);
   393 
   394   in thy |> Datatype_Aux.store_thms "weak_case_cong" new_type_names weak_case_congs end;
   395 
   396 
   397 (* additional theorems for TFL *)
   398 
   399 fun prove_nchotomys (config : Datatype_Aux.config) new_type_names descr casedist_thms thy =
   400   let
   401     val _ = Datatype_Aux.message config "Proving additional theorems for TFL ...";
   402 
   403     fun prove_nchotomy (t, exhaustion) =
   404       let
   405         (* For goal i, select the correct disjunct to attack, then prove it *)
   406         fun tac i 0 = EVERY [TRY (rtac disjI1 i), hyp_subst_tac i, REPEAT (rtac exI i), rtac refl i]
   407           | tac i n = rtac disjI2 i THEN tac i (n - 1);
   408       in
   409         Goal.prove_sorry_global thy [] [] t
   410           (fn _ =>
   411             EVERY [rtac allI 1,
   412              Datatype_Aux.exh_tac (K exhaustion) 1,
   413              ALLGOALS (fn i => tac i (i - 1))])
   414       end;
   415 
   416     val nchotomys =
   417       map prove_nchotomy (Datatype_Prop.make_nchotomys descr ~~ casedist_thms);
   418 
   419   in thy |> Datatype_Aux.store_thms "nchotomy" new_type_names nchotomys end;
   420 
   421 fun prove_case_congs new_type_names case_names descr nchotomys case_thms thy =
   422   let
   423     fun prove_case_cong ((t, nchotomy), case_rewrites) =
   424       let
   425         val Const ("==>", _) $ tm $ _ = t;
   426         val Const (@{const_name Trueprop}, _) $ (Const (@{const_name HOL.eq}, _) $ _ $ Ma) = tm;
   427         val cert = cterm_of thy;
   428         val nchotomy' = nchotomy RS spec;
   429         val [v] = Term.add_vars (concl_of nchotomy') [];
   430         val nchotomy'' = cterm_instantiate [(cert (Var v), cert Ma)] nchotomy';
   431       in
   432         Goal.prove_sorry_global thy [] (Logic.strip_imp_prems t) (Logic.strip_imp_concl t)
   433           (fn {context = ctxt, prems, ...} =>
   434             let
   435               val simplify = asm_simp_tac (put_simpset HOL_ss ctxt addsimps (prems @ case_rewrites))
   436             in
   437               EVERY [
   438                 simp_tac (put_simpset HOL_ss ctxt addsimps [hd prems]) 1,
   439                 cut_tac nchotomy'' 1,
   440                 REPEAT (etac disjE 1 THEN REPEAT (etac exE 1) THEN simplify 1),
   441                 REPEAT (etac exE 1) THEN simplify 1 (* Get last disjunct *)]
   442             end)
   443       end;
   444 
   445     val case_congs =
   446       map prove_case_cong
   447         (Datatype_Prop.make_case_congs case_names descr thy ~~ nchotomys ~~ case_thms);
   448 
   449   in thy |> Datatype_Aux.store_thms "case_cong" new_type_names case_congs end;
   450 
   451 
   452 
   453 (** derive datatype props **)
   454 
   455 local
   456 
   457 fun make_dt_info descr induct inducts rec_names rec_rewrites
   458     (index, (((((((((((_, (tname, _, _))), inject), distinct),
   459       exhaust), nchotomy), case_name), case_rewrites), case_cong), weak_case_cong),
   460         (split, split_asm))) =
   461   (tname,
   462    {index = index,
   463     descr = descr,
   464     inject = inject,
   465     distinct = distinct,
   466     induct = induct,
   467     inducts = inducts,
   468     exhaust = exhaust,
   469     nchotomy = nchotomy,
   470     rec_names = rec_names,
   471     rec_rewrites = rec_rewrites,
   472     case_name = case_name,
   473     case_rewrites = case_rewrites,
   474     case_cong = case_cong,
   475     weak_case_cong = weak_case_cong,
   476     split = split,
   477     split_asm = split_asm});
   478 
   479 in
   480 
   481 fun derive_datatype_props config dt_names descr induct inject distinct thy1 =
   482   let
   483     val thy2 = thy1 |> Theory.checkpoint;
   484     val flat_descr = flat descr;
   485     val new_type_names = map Long_Name.base_name dt_names;
   486     val _ =
   487       Datatype_Aux.message config
   488         ("Deriving properties for datatype(s) " ^ commas_quote new_type_names);
   489 
   490     val (exhaust, thy3) = thy2
   491       |> prove_casedist_thms config new_type_names descr induct
   492         (Datatype_Data.mk_case_names_exhausts flat_descr dt_names);
   493     val (nchotomys, thy4) = thy3
   494       |> prove_nchotomys config new_type_names descr exhaust;
   495     val ((rec_names, rec_rewrites), thy5) = thy4
   496       |> prove_primrec_thms config new_type_names descr
   497         (#inject o the o Symtab.lookup (Datatype_Data.get_all thy4)) inject
   498         (distinct, Datatype_Data.all_distincts thy2 (Datatype_Aux.get_rec_types flat_descr)) induct;
   499     val ((case_rewrites, case_names), thy6) = thy5
   500       |> prove_case_thms config new_type_names descr rec_names rec_rewrites;
   501     val (case_congs, thy7) = thy6
   502       |> prove_case_congs new_type_names case_names descr nchotomys case_rewrites;
   503     val (weak_case_congs, thy8) = thy7
   504       |> prove_weak_case_congs new_type_names case_names descr;
   505     val (splits, thy9) = thy8
   506       |> prove_split_thms config new_type_names case_names descr
   507         inject distinct exhaust case_rewrites;
   508 
   509     val inducts = Project_Rule.projections (Proof_Context.init_global thy2) induct;
   510     val dt_infos =
   511       map_index
   512         (make_dt_info flat_descr induct inducts rec_names rec_rewrites)
   513         (hd descr ~~ inject ~~ distinct ~~ exhaust ~~ nchotomys ~~
   514           case_names ~~ case_rewrites ~~ case_congs ~~ weak_case_congs ~~ splits);
   515     val dt_names = map fst dt_infos;
   516     val prfx = Binding.qualify true (space_implode "_" new_type_names);
   517     val simps = flat (inject @ distinct @ case_rewrites) @ rec_rewrites;
   518     val named_rules = flat (map_index (fn (i, tname) =>
   519       [((Binding.empty, [Induct.induct_type tname]), [([nth inducts i], [])]),
   520        ((Binding.empty, [Induct.cases_type tname]), [([nth exhaust i], [])])]) dt_names);
   521     val unnamed_rules = map (fn induct =>
   522       ((Binding.empty, [Rule_Cases.inner_rule, Induct.induct_type ""]), [([induct], [])]))
   523         (drop (length dt_names) inducts);
   524 
   525     val ctxt = Proof_Context.init_global thy9;
   526     val case_combs = map (Proof_Context.read_const ctxt false dummyT) case_names;
   527     val constrss = map (fn (dtname, {descr, index, ...}) =>
   528       map (Proof_Context.read_const ctxt false dummyT o fst)
   529         (#3 (the (AList.lookup op = descr index)))) dt_infos
   530   in
   531     thy9
   532     |> Global_Theory.note_thmss ""
   533       ([((prfx (Binding.name "simps"), []), [(simps, [])]),
   534         ((prfx (Binding.name "inducts"), []), [(inducts, [])]),
   535         ((prfx (Binding.name "splits"), []), [(maps (fn (x, y) => [x, y]) splits, [])]),
   536         ((Binding.empty, [Simplifier.simp_add]),
   537           [(flat case_rewrites @ flat distinct @ rec_rewrites, [])]),
   538         ((Binding.empty, [Code.add_default_eqn_attribute]), [(rec_rewrites, [])]),
   539         ((Binding.empty, [iff_add]), [(flat inject, [])]),
   540         ((Binding.empty, [Classical.safe_elim NONE]),
   541           [(map (fn th => th RS notE) (flat distinct), [])]),
   542         ((Binding.empty, [Simplifier.cong_add]), [(weak_case_congs, [])]),
   543         ((Binding.empty, [Induct.induct_simp_add]), [(flat (distinct @ inject), [])])] @
   544           named_rules @ unnamed_rules)
   545     |> snd
   546     |> Datatype_Data.register dt_infos
   547     |> Context.theory_map (fold2 Case_Translation.register case_combs constrss)
   548     |> Datatype_Data.interpretation_data (config, dt_names)
   549     |> pair dt_names
   550   end;
   551 
   552 end;
   553 
   554 
   555 
   556 (** declare existing type as datatype **)
   557 
   558 local
   559 
   560 fun prove_rep_datatype config dt_names descr raw_inject half_distinct raw_induct thy1 =
   561   let
   562     val raw_distinct = (map o maps) (fn thm => [thm, thm RS not_sym]) half_distinct;
   563     val new_type_names = map Long_Name.base_name dt_names;
   564     val prfx = Binding.qualify true (space_implode "_" new_type_names);
   565     val (((inject, distinct), [(_, [induct])]), thy2) =
   566       thy1
   567       |> Datatype_Aux.store_thmss "inject" new_type_names raw_inject
   568       ||>> Datatype_Aux.store_thmss "distinct" new_type_names raw_distinct
   569       ||>> Global_Theory.note_thmss ""
   570         [((prfx (Binding.name "induct"), [Datatype_Data.mk_case_names_induct descr]),
   571           [([raw_induct], [])])];
   572   in
   573     thy2
   574     |> derive_datatype_props config dt_names [descr] induct inject distinct
   575  end;
   576 
   577 fun gen_rep_datatype prep_term config after_qed raw_ts thy =
   578   let
   579     val ctxt = Proof_Context.init_global thy;
   580 
   581     fun constr_of_term (Const (c, T)) = (c, T)
   582       | constr_of_term t = error ("Not a constant: " ^ Syntax.string_of_term ctxt t);
   583     fun no_constr (c, T) =
   584       error ("Bad constructor: " ^ Proof_Context.extern_const ctxt c ^ "::" ^
   585         Syntax.string_of_typ ctxt T);
   586     fun type_of_constr (cT as (_, T)) =
   587       let
   588         val frees = Term.add_tfreesT T [];
   589         val (tyco, vs) = (apsnd o map) dest_TFree (dest_Type (body_type T))
   590           handle TYPE _ => no_constr cT
   591         val _ = if has_duplicates (eq_fst (op =)) vs then no_constr cT else ();
   592         val _ = if length frees <> length vs then no_constr cT else ();
   593       in (tyco, (vs, cT)) end;
   594 
   595     val raw_cs =
   596       AList.group (op =) (map (type_of_constr o constr_of_term o prep_term thy) raw_ts);
   597     val _ =
   598       (case map_filter (fn (tyco, _) =>
   599           if Symtab.defined (Datatype_Data.get_all thy) tyco then SOME tyco else NONE) raw_cs of
   600         [] => ()
   601       | tycos => error ("Type(s) " ^ commas_quote tycos ^ " already represented inductively"));
   602     val raw_vss = maps (map (map snd o fst) o snd) raw_cs;
   603     val ms =
   604       (case distinct (op =) (map length raw_vss) of
   605          [n] => 0 upto n - 1
   606       | _ => error "Different types in given constructors");
   607     fun inter_sort m =
   608       map (fn xs => nth xs m) raw_vss
   609       |> foldr1 (Sorts.inter_sort (Sign.classes_of thy));
   610     val sorts = map inter_sort ms;
   611     val vs = Name.invent_names Name.context Name.aT sorts;
   612 
   613     fun norm_constr (raw_vs, (c, T)) =
   614       (c, map_atyps
   615         (TFree o (the o AList.lookup (op =) (map fst raw_vs ~~ vs)) o fst o dest_TFree) T);
   616 
   617     val cs = map (apsnd (map norm_constr)) raw_cs;
   618     val dtyps_of_typ = map (Datatype_Aux.dtyp_of_typ (map (rpair vs o fst) cs)) o binder_types;
   619     val dt_names = map fst cs;
   620 
   621     fun mk_spec (i, (tyco, constr)) =
   622       (i, (tyco, map Datatype_Aux.DtTFree vs, (map o apsnd) dtyps_of_typ constr));
   623     val descr = map_index mk_spec cs;
   624     val injs = Datatype_Prop.make_injs [descr];
   625     val half_distincts = Datatype_Prop.make_distincts [descr];
   626     val ind = Datatype_Prop.make_ind [descr];
   627     val rules = (map o map o map) Logic.close_form [[[ind]], injs, half_distincts];
   628 
   629     fun after_qed' raw_thms =
   630       let
   631         val [[[raw_induct]], raw_inject, half_distinct] =
   632           unflat rules (map Drule.zero_var_indexes_list raw_thms);
   633             (*FIXME somehow dubious*)
   634       in
   635         Proof_Context.background_theory_result  (* FIXME !? *)
   636           (prove_rep_datatype config dt_names descr raw_inject half_distinct raw_induct)
   637         #-> after_qed
   638       end;
   639   in
   640     ctxt
   641     |> Proof.theorem NONE after_qed' ((map o map) (rpair []) (flat rules))
   642   end;
   643 
   644 in
   645 
   646 val rep_datatype = gen_rep_datatype Sign.cert_term;
   647 val rep_datatype_cmd = gen_rep_datatype Syntax.read_term_global;
   648 
   649 end;
   650 
   651 
   652 (* outer syntax *)
   653 
   654 val _ =
   655   Outer_Syntax.command @{command_spec "rep_datatype"} "represent existing types inductively"
   656     (Scan.repeat1 Parse.term >> (fn ts =>
   657       Toplevel.print o
   658       Toplevel.theory_to_proof (rep_datatype_cmd Datatype_Aux.default_config (K I) ts)));
   659 
   660 end;