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