src/HOL/Tools/Ctr_Sugar/ctr_sugar.ML
author kuncar
Thu Apr 10 17:48:17 2014 +0200 (2014-04-10)
changeset 56523 2ae16e3d8b6d
parent 56522 f54003750e7d
child 56657 558afd429255
permissions -rw-r--r--
revert idiomatic handling of namings from 5a93b8f928a2 because in combination with Named_Target.theory_init global names are sometimes created
     1 (*  Title:      HOL/Tools/Ctr_Sugar/ctr_sugar.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2012, 2013
     4 
     5 Wrapping existing freely generated type's constructors.
     6 *)
     7 
     8 signature CTR_SUGAR =
     9 sig
    10   type ctr_sugar =
    11     {ctrs: term list,
    12      casex: term,
    13      discs: term list,
    14      selss: term list list,
    15      exhaust: thm,
    16      nchotomy: thm,
    17      injects: thm list,
    18      distincts: thm list,
    19      case_thms: thm list,
    20      case_cong: thm,
    21      weak_case_cong: thm,
    22      split: thm,
    23      split_asm: thm,
    24      disc_thmss: thm list list,
    25      discIs: thm list,
    26      sel_thmss: thm list list,
    27      disc_excludesss: thm list list list,
    28      disc_exhausts: thm list,
    29      sel_exhausts: thm list,
    30      collapses: thm list,
    31      expands: thm list,
    32      sel_splits: thm list,
    33      sel_split_asms: thm list,
    34      case_eq_ifs: thm list};
    35 
    36   val morph_ctr_sugar: morphism -> ctr_sugar -> ctr_sugar
    37   val transfer_ctr_sugar: Proof.context -> ctr_sugar -> ctr_sugar
    38   val ctr_sugar_of: Proof.context -> string -> ctr_sugar option
    39   val ctr_sugars_of: Proof.context -> ctr_sugar list
    40   val ctr_sugar_of_case: Proof.context -> string -> ctr_sugar option
    41   val ctr_sugar_interpretation: (ctr_sugar -> theory -> theory) -> theory -> theory
    42   val register_ctr_sugar: string -> ctr_sugar -> local_theory -> local_theory
    43   val default_register_ctr_sugar_global: string -> ctr_sugar -> theory -> theory
    44 
    45   val mk_half_pairss: 'a list * 'a list -> ('a * 'a) list list
    46   val join_halves: int -> 'a list list -> 'a list list -> 'a list * 'a list list list
    47 
    48   val mk_ctr: typ list -> term -> term
    49   val mk_case: typ list -> typ -> term -> term
    50   val mk_disc_or_sel: typ list -> term -> term
    51   val name_of_ctr: term -> string
    52   val name_of_disc: term -> string
    53   val dest_ctr: Proof.context -> string -> term -> term * term list
    54   val dest_case: Proof.context -> string -> typ list -> term ->
    55     (ctr_sugar * term list * term list) option
    56 
    57   type ('c, 'a, 'v) ctr_spec = ((binding * 'c) * 'a list) * (binding * 'v) list
    58 
    59   val disc_of_ctr_spec: ('c, 'a, 'v) ctr_spec -> binding
    60   val ctr_of_ctr_spec: ('c, 'a, 'v) ctr_spec -> 'c
    61   val args_of_ctr_spec: ('c, 'a, 'v) ctr_spec -> 'a list
    62   val sel_defaults_of_ctr_spec: ('c, 'a, 'v) ctr_spec -> (binding * 'v) list
    63 
    64   val free_constructors: ({prems: thm list, context: Proof.context} -> tactic) list list ->
    65     ((bool * bool) * binding) * (term, binding, term) ctr_spec list -> local_theory ->
    66     ctr_sugar * local_theory
    67   val parse_bound_term: (binding * string) parser
    68   val parse_ctr_options: (bool * bool) parser
    69   val parse_ctr_spec: 'c parser -> 'a parser -> ('c, 'a, string) ctr_spec parser
    70 end;
    71 
    72 structure Ctr_Sugar : CTR_SUGAR =
    73 struct
    74 
    75 open Ctr_Sugar_Util
    76 open Ctr_Sugar_Tactics
    77 open Ctr_Sugar_Code
    78 
    79 type ctr_sugar =
    80   {ctrs: term list,
    81    casex: term,
    82    discs: term list,
    83    selss: term list list,
    84    exhaust: thm,
    85    nchotomy: thm,
    86    injects: thm list,
    87    distincts: thm list,
    88    case_thms: thm list,
    89    case_cong: thm,
    90    weak_case_cong: thm,
    91    split: thm,
    92    split_asm: thm,
    93    disc_thmss: thm list list,
    94    discIs: thm list,
    95    sel_thmss: thm list list,
    96    disc_excludesss: thm list list list,
    97    disc_exhausts: thm list,
    98    sel_exhausts: thm list,
    99    collapses: thm list,
   100    expands: thm list,
   101    sel_splits: thm list,
   102    sel_split_asms: thm list,
   103    case_eq_ifs: thm list};
   104 
   105 fun morph_ctr_sugar phi {ctrs, casex, discs, selss, exhaust, nchotomy, injects, distincts,
   106     case_thms, case_cong, weak_case_cong, split, split_asm, disc_thmss, discIs, sel_thmss,
   107     disc_excludesss, disc_exhausts, sel_exhausts, collapses, expands, sel_splits, sel_split_asms,
   108     case_eq_ifs} =
   109   {ctrs = map (Morphism.term phi) ctrs,
   110    casex = Morphism.term phi casex,
   111    discs = map (Morphism.term phi) discs,
   112    selss = map (map (Morphism.term phi)) selss,
   113    exhaust = Morphism.thm phi exhaust,
   114    nchotomy = Morphism.thm phi nchotomy,
   115    injects = map (Morphism.thm phi) injects,
   116    distincts = map (Morphism.thm phi) distincts,
   117    case_thms = map (Morphism.thm phi) case_thms,
   118    case_cong = Morphism.thm phi case_cong,
   119    weak_case_cong = Morphism.thm phi weak_case_cong,
   120    split = Morphism.thm phi split,
   121    split_asm = Morphism.thm phi split_asm,
   122    disc_thmss = map (map (Morphism.thm phi)) disc_thmss,
   123    discIs = map (Morphism.thm phi) discIs,
   124    sel_thmss = map (map (Morphism.thm phi)) sel_thmss,
   125    disc_excludesss = map (map (map (Morphism.thm phi))) disc_excludesss,
   126    disc_exhausts = map (Morphism.thm phi) disc_exhausts,
   127    sel_exhausts = map (Morphism.thm phi) sel_exhausts,
   128    collapses = map (Morphism.thm phi) collapses,
   129    expands = map (Morphism.thm phi) expands,
   130    sel_splits = map (Morphism.thm phi) sel_splits,
   131    sel_split_asms = map (Morphism.thm phi) sel_split_asms,
   132    case_eq_ifs = map (Morphism.thm phi) case_eq_ifs};
   133 
   134 val transfer_ctr_sugar =
   135   morph_ctr_sugar o Morphism.transfer_morphism o Proof_Context.theory_of;
   136 
   137 structure Data = Generic_Data
   138 (
   139   type T = ctr_sugar Symtab.table;
   140   val empty = Symtab.empty;
   141   val extend = I;
   142   fun merge data : T = Symtab.merge (K true) data;
   143 );
   144 
   145 fun ctr_sugar_of ctxt =
   146   Symtab.lookup (Data.get (Context.Proof ctxt))
   147   #> Option.map (transfer_ctr_sugar ctxt);
   148 
   149 fun ctr_sugars_of ctxt =
   150   Symtab.fold (cons o transfer_ctr_sugar ctxt o snd) (Data.get (Context.Proof ctxt)) [];
   151 
   152 fun ctr_sugar_of_case ctxt s =
   153   find_first (fn {casex = Const (s', _), ...} => s' = s | _ => false) (ctr_sugars_of ctxt);
   154 
   155 structure Ctr_Sugar_Interpretation = Interpretation
   156 (
   157   type T = ctr_sugar;
   158   val eq: T * T -> bool = op = o pairself #ctrs;
   159 );
   160 
   161 (* FIXME naming *)
   162 fun with_repaired_path f (ctr_sugar as {ctrs = ctr1 :: _, ...} : ctr_sugar) thy =
   163   thy
   164   (*|> Sign.root_path*)
   165   |> Sign.add_path (Long_Name.qualifier (fst (dest_Type (body_type (fastype_of ctr1)))))
   166   (*|> (fn thy => f (morph_ctr_sugar (Morphism.transfer_morphism thy) ctr_sugar) thy)*)
   167   (*|> Sign.restore_naming thy*);
   168 
   169 val ctr_sugar_interpretation = Ctr_Sugar_Interpretation.interpretation o with_repaired_path;
   170 
   171 fun register_ctr_sugar key ctr_sugar =
   172   Local_Theory.declaration {syntax = false, pervasive = true}
   173     (fn phi => Data.map (Symtab.update (key, morph_ctr_sugar phi ctr_sugar)))
   174   #> Local_Theory.background_theory (Ctr_Sugar_Interpretation.data ctr_sugar);
   175 
   176 fun default_register_ctr_sugar_global key ctr_sugar thy =
   177   let val tab = Data.get (Context.Theory thy) in
   178     if Symtab.defined tab key then
   179       thy
   180     else
   181       thy
   182       |> Context.theory_map (Data.put (Symtab.update_new (key, ctr_sugar) tab))
   183       |> Ctr_Sugar_Interpretation.data ctr_sugar
   184   end;
   185 
   186 val isN = "is_";
   187 val unN = "un_";
   188 fun mk_unN 1 1 suf = unN ^ suf
   189   | mk_unN _ l suf = unN ^ suf ^ string_of_int l;
   190 
   191 val caseN = "case";
   192 val case_congN = "case_cong";
   193 val case_eq_ifN = "case_eq_if";
   194 val collapseN = "collapse";
   195 val disc_excludeN = "disc_exclude";
   196 val disc_exhaustN = "disc_exhaust";
   197 val discN = "disc";
   198 val discIN = "discI";
   199 val distinctN = "distinct";
   200 val exhaustN = "exhaust";
   201 val expandN = "expand";
   202 val injectN = "inject";
   203 val nchotomyN = "nchotomy";
   204 val selN = "sel";
   205 val sel_exhaustN = "sel_exhaust";
   206 val sel_splitN = "sel_split";
   207 val sel_split_asmN = "sel_split_asm";
   208 val splitN = "split";
   209 val splitsN = "splits";
   210 val split_asmN = "split_asm";
   211 val weak_case_cong_thmsN = "weak_case_cong";
   212 
   213 val cong_attrs = @{attributes [cong]};
   214 val dest_attrs = @{attributes [dest]};
   215 val safe_elim_attrs = @{attributes [elim!]};
   216 val iff_attrs = @{attributes [iff]};
   217 val inductsimp_attrs = @{attributes [induct_simp]};
   218 val nitpicksimp_attrs = @{attributes [nitpick_simp]};
   219 val simp_attrs = @{attributes [simp]};
   220 val code_nitpicksimp_attrs = Code.add_default_eqn_attrib :: nitpicksimp_attrs;
   221 val code_nitpicksimp_simp_attrs = code_nitpicksimp_attrs @ simp_attrs;
   222 
   223 fun unflat_lookup eq xs ys = map (fn xs' => permute_like_unique eq xs xs' ys);
   224 
   225 fun mk_half_pairss' _ ([], []) = []
   226   | mk_half_pairss' indent (x :: xs, _ :: ys) =
   227     indent @ fold_rev (cons o single o pair x) ys (mk_half_pairss' ([] :: indent) (xs, ys));
   228 
   229 fun mk_half_pairss p = mk_half_pairss' [[]] p;
   230 
   231 fun join_halves n half_xss other_half_xss =
   232   (splice (flat half_xss) (flat other_half_xss),
   233    map2 (map2 append) (Library.chop_groups n half_xss)
   234      (transpose (Library.chop_groups n other_half_xss)));
   235 
   236 fun mk_undefined T = Const (@{const_name undefined}, T);
   237 
   238 fun mk_ctr Ts t =
   239   let val Type (_, Ts0) = body_type (fastype_of t) in
   240     subst_nonatomic_types (Ts0 ~~ Ts) t
   241   end;
   242 
   243 fun mk_case Ts T t =
   244   let val (Type (_, Ts0), body) = strip_type (fastype_of t) |>> List.last in
   245     subst_nonatomic_types ((body, T) :: (Ts0 ~~ Ts)) t
   246   end;
   247 
   248 fun mk_disc_or_sel Ts t =
   249   subst_nonatomic_types (snd (Term.dest_Type (domain_type (fastype_of t))) ~~ Ts) t;
   250 
   251 fun name_of_const what t =
   252   (case head_of t of
   253     Const (s, _) => s
   254   | Free (s, _) => s
   255   | _ => error ("Cannot extract name of " ^ what));
   256 
   257 val name_of_ctr = name_of_const "constructor";
   258 
   259 val notN = "not_";
   260 val eqN = "eq_";
   261 val neqN = "neq_";
   262 
   263 fun name_of_disc t =
   264   (case head_of t of
   265     Abs (_, _, @{const Not} $ (t' $ Bound 0)) =>
   266     Long_Name.map_base_name (prefix notN) (name_of_disc t')
   267   | Abs (_, _, Const (@{const_name HOL.eq}, _) $ Bound 0 $ t') =>
   268     Long_Name.map_base_name (prefix eqN) (name_of_disc t')
   269   | Abs (_, _, @{const Not} $ (Const (@{const_name HOL.eq}, _) $ Bound 0 $ t')) =>
   270     Long_Name.map_base_name (prefix neqN) (name_of_disc t')
   271   | t' => name_of_const "destructor" t');
   272 
   273 val base_name_of_ctr = Long_Name.base_name o name_of_ctr;
   274 
   275 fun dest_ctr ctxt s t =
   276   let val (f, args) = Term.strip_comb t in
   277     (case ctr_sugar_of ctxt s of
   278       SOME {ctrs, ...} =>
   279       (case find_first (can (fo_match ctxt f)) ctrs of
   280         SOME f' => (f', args)
   281       | NONE => raise Fail "dest_ctr")
   282     | NONE => raise Fail "dest_ctr")
   283   end;
   284 
   285 fun dest_case ctxt s Ts t =
   286   (case Term.strip_comb t of
   287     (Const (c, _), args as _ :: _) =>
   288     (case ctr_sugar_of ctxt s of
   289       SOME (ctr_sugar as {casex = Const (case_name, _), discs = discs0, selss = selss0, ...}) =>
   290       if case_name = c then
   291         let val n = length discs0 in
   292           if n < length args then
   293             let
   294               val (branches, obj :: leftovers) = chop n args;
   295               val discs = map (mk_disc_or_sel Ts) discs0;
   296               val selss = map (map (mk_disc_or_sel Ts)) selss0;
   297               val conds = map (rapp obj) discs;
   298               val branch_argss = map (fn sels => map (rapp obj) sels @ leftovers) selss;
   299               val branches' = map2 (curry Term.betapplys) branches branch_argss;
   300             in
   301               SOME (ctr_sugar, conds, branches')
   302             end
   303           else
   304             NONE
   305         end
   306       else
   307         NONE
   308     | _ => NONE)
   309   | _ => NONE);
   310 
   311 fun eta_expand_arg xs f_xs = fold_rev Term.lambda xs f_xs;
   312 
   313 type ('c, 'a, 'v) ctr_spec = ((binding * 'c) * 'a list) * (binding * 'v) list;
   314 
   315 fun disc_of_ctr_spec (((disc, _), _), _) = disc;
   316 fun ctr_of_ctr_spec (((_, ctr), _), _) = ctr;
   317 fun args_of_ctr_spec ((_, args), _) = args;
   318 fun sel_defaults_of_ctr_spec (_, ds) = ds;
   319 
   320 fun prepare_free_constructors prep_term (((no_discs_sels, no_code), raw_case_binding), ctr_specs)
   321     no_defs_lthy =
   322   let
   323     (* TODO: sanity checks on arguments *)
   324 
   325     val raw_ctrs = map ctr_of_ctr_spec ctr_specs;
   326     val raw_disc_bindings = map disc_of_ctr_spec ctr_specs;
   327     val raw_sel_bindingss = map args_of_ctr_spec ctr_specs;
   328     val raw_sel_defaultss = map sel_defaults_of_ctr_spec ctr_specs;
   329 
   330     val n = length raw_ctrs;
   331     val ks = 1 upto n;
   332 
   333     val _ = if n > 0 then () else error "No constructors specified";
   334 
   335     val ctrs0 = map (prep_term no_defs_lthy) raw_ctrs;
   336     val sel_defaultss = map (map (apsnd (prep_term no_defs_lthy))) raw_sel_defaultss;
   337 
   338     val Type (fcT_name, As0) = body_type (fastype_of (hd ctrs0));
   339     val fc_b_name = Long_Name.base_name fcT_name;
   340     val fc_b = Binding.name fc_b_name;
   341 
   342     fun qualify mandatory = Binding.qualify mandatory fc_b_name;
   343 
   344     fun dest_TFree_or_TVar (TFree sS) = sS
   345       | dest_TFree_or_TVar (TVar ((s, _), S)) = (s, S)
   346       | dest_TFree_or_TVar _ = error "Invalid type argument";
   347 
   348     val (unsorted_As, B) =
   349       no_defs_lthy
   350       |> variant_tfrees (map (fst o dest_TFree_or_TVar) As0)
   351       ||> the_single o fst o mk_TFrees 1;
   352 
   353     val As = map2 (resort_tfree o snd o dest_TFree_or_TVar) As0 unsorted_As;
   354 
   355     val fcT = Type (fcT_name, As);
   356     val ctrs = map (mk_ctr As) ctrs0;
   357     val ctr_Tss = map (binder_types o fastype_of) ctrs;
   358 
   359     val ms = map length ctr_Tss;
   360 
   361     fun can_definitely_rely_on_disc k = not (Binding.is_empty (nth raw_disc_bindings (k - 1)));
   362     fun can_rely_on_disc k =
   363       can_definitely_rely_on_disc k orelse (k = 1 andalso not (can_definitely_rely_on_disc 2));
   364     fun should_omit_disc_binding k = n = 1 orelse (n = 2 andalso can_rely_on_disc (3 - k));
   365 
   366     fun is_disc_binding_valid b =
   367       not (Binding.is_empty b orelse Binding.eq_name (b, equal_binding));
   368 
   369     val standard_disc_binding = Binding.name o prefix isN o base_name_of_ctr;
   370 
   371     val disc_bindings =
   372       raw_disc_bindings
   373       |> map4 (fn k => fn m => fn ctr => fn disc =>
   374         qualify false
   375           (if Binding.is_empty disc then
   376              if should_omit_disc_binding k then disc else standard_disc_binding ctr
   377            else if Binding.eq_name (disc, equal_binding) then
   378              if m = 0 then disc
   379              else error "Cannot use \"=\" syntax for discriminating nonnullary constructor"
   380            else if Binding.eq_name (disc, standard_binding) then
   381              standard_disc_binding ctr
   382            else
   383              disc)) ks ms ctrs0;
   384 
   385     fun standard_sel_binding m l = Binding.name o mk_unN m l o base_name_of_ctr;
   386 
   387     val sel_bindingss =
   388       map3 (fn ctr => fn m => map2 (fn l => fn sel =>
   389         qualify false
   390           (if Binding.is_empty sel orelse Binding.eq_name (sel, standard_binding) then
   391             standard_sel_binding m l ctr
   392           else
   393             sel)) (1 upto m) o pad_list Binding.empty m) ctrs0 ms raw_sel_bindingss;
   394 
   395     val case_Ts = map (fn Ts => Ts ---> B) ctr_Tss;
   396 
   397     val (((((((([exh_y], (xss, xss')), yss), fs), gs), [u', v']), [w]), (p, p')), names_lthy) =
   398       no_defs_lthy
   399       |> mk_Frees "y" [fcT] (* for compatibility with "datatype_realizer.ML" *)
   400       ||>> mk_Freess' "x" ctr_Tss
   401       ||>> mk_Freess "y" ctr_Tss
   402       ||>> mk_Frees "f" case_Ts
   403       ||>> mk_Frees "g" case_Ts
   404       ||>> (apfst (map (rpair fcT)) oo Variable.variant_fixes) [fc_b_name, fc_b_name ^ "'"]
   405       ||>> mk_Frees "z" [B]
   406       ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "P") HOLogic.boolT;
   407 
   408     val u = Free u';
   409     val v = Free v';
   410     val q = Free (fst p', mk_pred1T B);
   411 
   412     val xctrs = map2 (curry Term.list_comb) ctrs xss;
   413     val yctrs = map2 (curry Term.list_comb) ctrs yss;
   414 
   415     val xfs = map2 (curry Term.list_comb) fs xss;
   416     val xgs = map2 (curry Term.list_comb) gs xss;
   417 
   418     (* TODO: Eta-expension is for compatibility with the old datatype package (but it also provides
   419        nicer names). Consider removing. *)
   420     val eta_fs = map2 eta_expand_arg xss xfs;
   421     val eta_gs = map2 eta_expand_arg xss xgs;
   422 
   423     val case_binding =
   424       qualify false
   425         (if Binding.is_empty raw_case_binding orelse
   426             Binding.eq_name (raw_case_binding, standard_binding) then
   427            Binding.prefix_name (caseN ^ "_") fc_b
   428          else
   429            raw_case_binding);
   430 
   431     fun mk_case_disj xctr xf xs =
   432       list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr), HOLogic.mk_eq (w, xf)));
   433 
   434     val case_rhs = fold_rev (fold_rev Term.lambda) [fs, [u]]
   435       (Const (@{const_name The}, (B --> HOLogic.boolT) --> B) $
   436          Term.lambda w (Library.foldr1 HOLogic.mk_disj (map3 mk_case_disj xctrs xfs xss)));
   437 
   438     val ((raw_case, (_, raw_case_def)), (lthy', lthy)) = no_defs_lthy
   439       |> Local_Theory.define ((case_binding, NoSyn),
   440         ((Binding.conceal (Thm.def_binding case_binding), []), case_rhs))
   441       ||> `Local_Theory.restore;
   442 
   443     val phi = Proof_Context.export_morphism lthy lthy';
   444 
   445     val case_def = Morphism.thm phi raw_case_def;
   446 
   447     val case0 = Morphism.term phi raw_case;
   448     val casex = mk_case As B case0;
   449 
   450     val fcase = Term.list_comb (casex, fs);
   451 
   452     val ufcase = fcase $ u;
   453     val vfcase = fcase $ v;
   454 
   455     val eta_fcase = Term.list_comb (casex, eta_fs);
   456     val eta_gcase = Term.list_comb (casex, eta_gs);
   457 
   458     val eta_ufcase = eta_fcase $ u;
   459     val eta_vgcase = eta_gcase $ v;
   460 
   461     fun mk_uu_eq () = HOLogic.mk_eq (u, u);
   462 
   463     val uv_eq = mk_Trueprop_eq (u, v);
   464 
   465     val exist_xs_u_eq_ctrs =
   466       map2 (fn xctr => fn xs => list_exists_free xs (HOLogic.mk_eq (u, xctr))) xctrs xss;
   467 
   468     val unique_disc_no_def = TrueI; (*arbitrary marker*)
   469     val alternate_disc_no_def = FalseE; (*arbitrary marker*)
   470 
   471     fun alternate_disc_lhs get_udisc k =
   472       HOLogic.mk_not
   473         (let val b = nth disc_bindings (k - 1) in
   474            if is_disc_binding_valid b then get_udisc b (k - 1) else nth exist_xs_u_eq_ctrs (k - 1)
   475          end);
   476 
   477     val (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy') =
   478       if no_discs_sels then
   479         (true, [], [], [], [], [], lthy')
   480       else
   481         let
   482           fun disc_free b = Free (Binding.name_of b, mk_pred1T fcT);
   483 
   484           fun disc_spec b exist_xs_u_eq_ctr = mk_Trueprop_eq (disc_free b $ u, exist_xs_u_eq_ctr);
   485 
   486           fun alternate_disc k =
   487             Term.lambda u (alternate_disc_lhs (K o rapp u o disc_free) (3 - k));
   488 
   489           fun mk_sel_case_args b proto_sels T =
   490             map2 (fn Ts => fn k =>
   491               (case AList.lookup (op =) proto_sels k of
   492                 NONE =>
   493                 (case AList.lookup Binding.eq_name (rev (nth sel_defaultss (k - 1))) b of
   494                   NONE => fold_rev (Term.lambda o curry Free Name.uu) Ts (mk_undefined T)
   495                 | SOME t => t |> Type.constraint (Ts ---> T) |> Syntax.check_term lthy)
   496               | SOME (xs, x) => fold_rev Term.lambda xs x)) ctr_Tss ks;
   497 
   498           fun sel_spec b proto_sels =
   499             let
   500               val _ =
   501                 (case duplicates (op =) (map fst proto_sels) of
   502                    k :: _ => error ("Duplicate selector name " ^ quote (Binding.name_of b) ^
   503                      " for constructor " ^
   504                      quote (Syntax.string_of_term lthy (nth ctrs (k - 1))))
   505                  | [] => ())
   506               val T =
   507                 (case distinct (op =) (map (fastype_of o snd o snd) proto_sels) of
   508                   [T] => T
   509                 | T :: T' :: _ => error ("Inconsistent range type for selector " ^
   510                     quote (Binding.name_of b) ^ ": " ^ quote (Syntax.string_of_typ lthy T) ^ " vs. "
   511                     ^ quote (Syntax.string_of_typ lthy T')));
   512             in
   513               mk_Trueprop_eq (Free (Binding.name_of b, fcT --> T) $ u,
   514                 Term.list_comb (mk_case As T case0, mk_sel_case_args b proto_sels T) $ u)
   515             end;
   516 
   517           val sel_bindings = flat sel_bindingss;
   518           val uniq_sel_bindings = distinct Binding.eq_name sel_bindings;
   519           val all_sels_distinct = (length uniq_sel_bindings = length sel_bindings);
   520 
   521           val sel_binding_index =
   522             if all_sels_distinct then 1 upto length sel_bindings
   523             else map (fn b => find_index (curry Binding.eq_name b) uniq_sel_bindings) sel_bindings;
   524 
   525           val proto_sels = flat (map3 (fn k => fn xs => map (fn x => (k, (xs, x)))) ks xss xss);
   526           val sel_infos =
   527             AList.group (op =) (sel_binding_index ~~ proto_sels)
   528             |> sort (int_ord o pairself fst)
   529             |> map snd |> curry (op ~~) uniq_sel_bindings;
   530           val sel_bindings = map fst sel_infos;
   531 
   532           fun unflat_selss xs = unflat_lookup Binding.eq_name sel_bindings xs sel_bindingss;
   533 
   534           val (((raw_discs, raw_disc_defs), (raw_sels, raw_sel_defs)), (lthy', lthy)) =
   535             lthy
   536             |> apfst split_list o fold_map3 (fn k => fn exist_xs_u_eq_ctr => fn b =>
   537                 if Binding.is_empty b then
   538                   if n = 1 then pair (Term.lambda u (mk_uu_eq ()), unique_disc_no_def)
   539                   else pair (alternate_disc k, alternate_disc_no_def)
   540                 else if Binding.eq_name (b, equal_binding) then
   541                   pair (Term.lambda u exist_xs_u_eq_ctr, refl)
   542                 else
   543                   Specification.definition (SOME (b, NONE, NoSyn),
   544                     ((Thm.def_binding b, []), disc_spec b exist_xs_u_eq_ctr)) #>> apsnd snd)
   545               ks exist_xs_u_eq_ctrs disc_bindings
   546             ||>> apfst split_list o fold_map (fn (b, proto_sels) =>
   547               Specification.definition (SOME (b, NONE, NoSyn),
   548                 ((Thm.def_binding b, []), sel_spec b proto_sels)) #>> apsnd snd) sel_infos
   549             ||> `Local_Theory.restore;
   550 
   551           val phi = Proof_Context.export_morphism lthy lthy';
   552 
   553           val disc_defs = map (Morphism.thm phi) raw_disc_defs;
   554           val sel_defs = map (Morphism.thm phi) raw_sel_defs;
   555           val sel_defss = unflat_selss sel_defs;
   556 
   557           val discs0 = map (Morphism.term phi) raw_discs;
   558           val selss0 = unflat_selss (map (Morphism.term phi) raw_sels);
   559 
   560           val discs = map (mk_disc_or_sel As) discs0;
   561           val selss = map (map (mk_disc_or_sel As)) selss0;
   562         in
   563           (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy')
   564         end;
   565 
   566     fun mk_imp_p Qs = Logic.list_implies (Qs, HOLogic.mk_Trueprop p);
   567 
   568     val exhaust_goal =
   569       let fun mk_prem xctr xs = fold_rev Logic.all xs (mk_imp_p [mk_Trueprop_eq (exh_y, xctr)]) in
   570         fold_rev Logic.all [p, exh_y] (mk_imp_p (map2 mk_prem xctrs xss))
   571       end;
   572 
   573     val inject_goalss =
   574       let
   575         fun mk_goal _ _ [] [] = []
   576           | mk_goal xctr yctr xs ys =
   577             [fold_rev Logic.all (xs @ ys) (mk_Trueprop_eq (HOLogic.mk_eq (xctr, yctr),
   578               Library.foldr1 HOLogic.mk_conj (map2 (curry HOLogic.mk_eq) xs ys)))];
   579       in
   580         map4 mk_goal xctrs yctrs xss yss
   581       end;
   582 
   583     val half_distinct_goalss =
   584       let
   585         fun mk_goal ((xs, xc), (xs', xc')) =
   586           fold_rev Logic.all (xs @ xs')
   587             (HOLogic.mk_Trueprop (HOLogic.mk_not (HOLogic.mk_eq (xc, xc'))));
   588       in
   589         map (map mk_goal) (mk_half_pairss (`I (xss ~~ xctrs)))
   590       end;
   591 
   592     val goalss = [exhaust_goal] :: inject_goalss @ half_distinct_goalss;
   593 
   594     fun after_qed thmss lthy =
   595       let
   596         val ([exhaust_thm0], (inject_thmss, half_distinct_thmss)) = (hd thmss, chop n (tl thmss));
   597         (* for "datatype_realizer.ML": *)
   598         val exhaust_thm =
   599           Thm.name_derivation (fcT_name ^ Long_Name.separator ^ exhaustN) exhaust_thm0;
   600 
   601         val inject_thms = flat inject_thmss;
   602 
   603         val rho_As = map (pairself (certifyT lthy)) (map Logic.varifyT_global As ~~ As);
   604 
   605         fun inst_thm t thm =
   606           Drule.instantiate' [] [SOME (certify lthy t)]
   607             (Thm.instantiate (rho_As, []) (Drule.zero_var_indexes thm));
   608 
   609         val uexhaust_thm = inst_thm u exhaust_thm;
   610 
   611         val exhaust_cases = map base_name_of_ctr ctrs;
   612 
   613         val other_half_distinct_thmss = map (map (fn thm => thm RS not_sym)) half_distinct_thmss;
   614 
   615         val (distinct_thms, (distinct_thmsss', distinct_thmsss)) =
   616           join_halves n half_distinct_thmss other_half_distinct_thmss ||> `transpose;
   617 
   618         val nchotomy_thm =
   619           let
   620             val goal =
   621               HOLogic.mk_Trueprop (HOLogic.mk_all (fst u', snd u',
   622                 Library.foldr1 HOLogic.mk_disj exist_xs_u_eq_ctrs));
   623           in
   624             Goal.prove_sorry lthy [] [] goal (fn _ => mk_nchotomy_tac n exhaust_thm)
   625             |> Thm.close_derivation
   626           end;
   627 
   628         val case_thms =
   629           let
   630             val goals =
   631               map3 (fn xctr => fn xf => fn xs =>
   632                 fold_rev Logic.all (fs @ xs) (mk_Trueprop_eq (fcase $ xctr, xf))) xctrs xfs xss;
   633           in
   634             map4 (fn k => fn goal => fn injects => fn distinctss =>
   635                 Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   636                   mk_case_tac ctxt n k case_def injects distinctss)
   637                 |> Thm.close_derivation)
   638               ks goals inject_thmss distinct_thmsss
   639           end;
   640 
   641         val (case_cong_thm, weak_case_cong_thm) =
   642           let
   643             fun mk_prem xctr xs xf xg =
   644               fold_rev Logic.all xs (Logic.mk_implies (mk_Trueprop_eq (v, xctr),
   645                 mk_Trueprop_eq (xf, xg)));
   646 
   647             val goal =
   648               Logic.list_implies (uv_eq :: map4 mk_prem xctrs xss xfs xgs,
   649                  mk_Trueprop_eq (eta_ufcase, eta_vgcase));
   650             val weak_goal = Logic.mk_implies (uv_eq, mk_Trueprop_eq (ufcase, vfcase));
   651           in
   652             (Goal.prove_sorry lthy [] [] goal (fn _ => mk_case_cong_tac lthy uexhaust_thm case_thms),
   653              Goal.prove_sorry lthy [] [] weak_goal (K (etac arg_cong 1)))
   654             |> pairself (singleton (Proof_Context.export names_lthy lthy) #>
   655               Thm.close_derivation)
   656           end;
   657 
   658         val split_lhs = q $ ufcase;
   659 
   660         fun mk_split_conjunct xctr xs f_xs =
   661           list_all_free xs (HOLogic.mk_imp (HOLogic.mk_eq (u, xctr), q $ f_xs));
   662         fun mk_split_disjunct xctr xs f_xs =
   663           list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr),
   664             HOLogic.mk_not (q $ f_xs)));
   665 
   666         fun mk_split_goal xctrs xss xfs =
   667           mk_Trueprop_eq (split_lhs, Library.foldr1 HOLogic.mk_conj
   668             (map3 mk_split_conjunct xctrs xss xfs));
   669         fun mk_split_asm_goal xctrs xss xfs =
   670           mk_Trueprop_eq (split_lhs, HOLogic.mk_not (Library.foldr1 HOLogic.mk_disj
   671             (map3 mk_split_disjunct xctrs xss xfs)));
   672 
   673         fun prove_split selss goal =
   674           Goal.prove_sorry lthy [] [] goal (fn _ =>
   675             mk_split_tac lthy uexhaust_thm case_thms selss inject_thmss distinct_thmsss)
   676           |> singleton (Proof_Context.export names_lthy lthy)
   677           |> Thm.close_derivation;
   678 
   679         fun prove_split_asm asm_goal split_thm =
   680           Goal.prove_sorry lthy [] [] asm_goal (fn {context = ctxt, ...} =>
   681             mk_split_asm_tac ctxt split_thm)
   682           |> singleton (Proof_Context.export names_lthy lthy)
   683           |> Thm.close_derivation;
   684 
   685         val (split_thm, split_asm_thm) =
   686           let
   687             val goal = mk_split_goal xctrs xss xfs;
   688             val asm_goal = mk_split_asm_goal xctrs xss xfs;
   689 
   690             val thm = prove_split (replicate n []) goal;
   691             val asm_thm = prove_split_asm asm_goal thm;
   692           in
   693             (thm, asm_thm)
   694           end;
   695 
   696         val (all_sel_thms, sel_thmss, disc_thmss, nontriv_disc_thmss, discI_thms,
   697              nontriv_discI_thms, disc_exclude_thms, disc_exclude_thmsss, disc_exhaust_thms,
   698              sel_exhaust_thms, all_collapse_thms, safe_collapse_thms, expand_thms, sel_split_thms,
   699              sel_split_asm_thms, case_eq_if_thms) =
   700           if no_discs_sels then
   701             ([], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [])
   702           else
   703             let
   704               val udiscs = map (rapp u) discs;
   705               val uselss = map (map (rapp u)) selss;
   706               val usel_ctrs = map2 (curry Term.list_comb) ctrs uselss;
   707               val usel_fs = map2 (curry Term.list_comb) fs uselss;
   708 
   709               val vdiscs = map (rapp v) discs;
   710               val vselss = map (map (rapp v)) selss;
   711 
   712               fun make_sel_thm xs' case_thm sel_def =
   713                 zero_var_indexes (Drule.gen_all (Drule.rename_bvars' (map (SOME o fst) xs')
   714                     (Drule.forall_intr_vars (case_thm RS (sel_def RS trans)))));
   715 
   716               val sel_thmss = map3 (map oo make_sel_thm) xss' case_thms sel_defss;
   717 
   718               fun has_undefined_rhs thm =
   719                 (case snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of thm))) of
   720                   Const (@{const_name undefined}, _) => true
   721                 | _ => false);
   722 
   723               val all_sel_thms =
   724                 (if all_sels_distinct andalso forall null sel_defaultss then
   725                    flat sel_thmss
   726                  else
   727                    map_product (fn s => fn (xs', c) => make_sel_thm xs' c s) sel_defs
   728                      (xss' ~~ case_thms))
   729                 |> filter_out has_undefined_rhs;
   730 
   731               fun mk_unique_disc_def () =
   732                 let
   733                   val m = the_single ms;
   734                   val goal = mk_Trueprop_eq (mk_uu_eq (), the_single exist_xs_u_eq_ctrs);
   735                 in
   736                   Goal.prove_sorry lthy [] [] goal (fn _ => mk_unique_disc_def_tac m uexhaust_thm)
   737                   |> singleton (Proof_Context.export names_lthy lthy)
   738                   |> Thm.close_derivation
   739                 end;
   740 
   741               fun mk_alternate_disc_def k =
   742                 let
   743                   val goal =
   744                     mk_Trueprop_eq (alternate_disc_lhs (K (nth udiscs)) (3 - k),
   745                       nth exist_xs_u_eq_ctrs (k - 1));
   746                 in
   747                   Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   748                     mk_alternate_disc_def_tac ctxt k (nth disc_defs (2 - k))
   749                       (nth distinct_thms (2 - k)) uexhaust_thm)
   750                   |> singleton (Proof_Context.export names_lthy lthy)
   751                   |> Thm.close_derivation
   752                 end;
   753 
   754               val has_alternate_disc_def =
   755                 exists (fn def => Thm.eq_thm_prop (def, alternate_disc_no_def)) disc_defs;
   756 
   757               val disc_defs' =
   758                 map2 (fn k => fn def =>
   759                   if Thm.eq_thm_prop (def, unique_disc_no_def) then mk_unique_disc_def ()
   760                   else if Thm.eq_thm_prop (def, alternate_disc_no_def) then mk_alternate_disc_def k
   761                   else def) ks disc_defs;
   762 
   763               val discD_thms = map (fn def => def RS iffD1) disc_defs';
   764               val discI_thms =
   765                 map2 (fn m => fn def => funpow m (fn thm => exI RS thm) (def RS iffD2)) ms
   766                   disc_defs';
   767               val not_discI_thms =
   768                 map2 (fn m => fn def => funpow m (fn thm => allI RS thm)
   769                     (unfold_thms lthy @{thms not_ex} (def RS @{thm ssubst[of _ _ Not]})))
   770                   ms disc_defs';
   771 
   772               val (disc_thmss', disc_thmss) =
   773                 let
   774                   fun mk_thm discI _ [] = refl RS discI
   775                     | mk_thm _ not_discI [distinct] = distinct RS not_discI;
   776                   fun mk_thms discI not_discI distinctss = map (mk_thm discI not_discI) distinctss;
   777                 in
   778                   map3 mk_thms discI_thms not_discI_thms distinct_thmsss' |> `transpose
   779                 end;
   780 
   781               val nontriv_disc_thmss =
   782                 map2 (fn b => if is_disc_binding_valid b then I else K []) disc_bindings disc_thmss;
   783 
   784               fun is_discI_boring b =
   785                 (n = 1 andalso Binding.is_empty b) orelse Binding.eq_name (b, equal_binding);
   786 
   787               val nontriv_discI_thms =
   788                 flat (map2 (fn b => if is_discI_boring b then K [] else single) disc_bindings
   789                   discI_thms);
   790 
   791               val (disc_exclude_thms, (disc_exclude_thmsss', disc_exclude_thmsss)) =
   792                 let
   793                   fun mk_goal [] = []
   794                     | mk_goal [((_, udisc), (_, udisc'))] =
   795                       [Logic.all u (Logic.mk_implies (HOLogic.mk_Trueprop udisc,
   796                          HOLogic.mk_Trueprop (HOLogic.mk_not udisc')))];
   797 
   798                   fun prove tac goal =
   799                     Goal.prove_sorry lthy [] [] goal (K tac)
   800                     |> Thm.close_derivation;
   801 
   802                   val half_pairss = mk_half_pairss (`I (ms ~~ discD_thms ~~ udiscs));
   803 
   804                   val half_goalss = map mk_goal half_pairss;
   805                   val half_thmss =
   806                     map3 (fn [] => K (K []) | [goal] => fn [(((m, discD), _), _)] =>
   807                         fn disc_thm => [prove (mk_half_disc_exclude_tac lthy m discD disc_thm) goal])
   808                       half_goalss half_pairss (flat disc_thmss');
   809 
   810                   val other_half_goalss = map (mk_goal o map swap) half_pairss;
   811                   val other_half_thmss =
   812                     map2 (map2 (prove o mk_other_half_disc_exclude_tac)) half_thmss
   813                       other_half_goalss;
   814                 in
   815                   join_halves n half_thmss other_half_thmss ||> `transpose
   816                   |>> has_alternate_disc_def ? K []
   817                 end;
   818 
   819               val disc_exhaust_thm =
   820                 let
   821                   fun mk_prem udisc = mk_imp_p [HOLogic.mk_Trueprop udisc];
   822                   val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem udiscs));
   823                 in
   824                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   825                     mk_disc_exhaust_tac n exhaust_thm discI_thms)
   826                   |> Thm.close_derivation
   827                 end;
   828 
   829               val (safe_collapse_thms, all_collapse_thms) =
   830                 let
   831                   fun mk_goal m udisc usel_ctr =
   832                     let
   833                       val prem = HOLogic.mk_Trueprop udisc;
   834                       val concl = mk_Trueprop_eq ((usel_ctr, u) |> m = 0 ? swap);
   835                     in
   836                       (prem aconv concl, Logic.all u (Logic.mk_implies (prem, concl)))
   837                     end;
   838                   val (trivs, goals) = map3 mk_goal ms udiscs usel_ctrs |> split_list;
   839                   val thms =
   840                     map5 (fn m => fn discD => fn sel_thms => fn triv => fn goal =>
   841                         Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   842                           mk_collapse_tac ctxt m discD sel_thms ORELSE HEADGOAL atac)
   843                         |> Thm.close_derivation
   844                         |> not triv ? perhaps (try (fn thm => refl RS thm)))
   845                       ms discD_thms sel_thmss trivs goals;
   846                 in
   847                   (map_filter (fn (true, _) => NONE | (false, thm) => SOME thm) (trivs ~~ thms),
   848                    thms)
   849                 end;
   850 
   851               val swapped_all_collapse_thms =
   852                 map2 (fn m => fn thm => if m = 0 then thm else thm RS sym) ms all_collapse_thms;
   853 
   854               val sel_exhaust_thm =
   855                 let
   856                   fun mk_prem usel_ctr = mk_imp_p [mk_Trueprop_eq (u, usel_ctr)];
   857                   val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem usel_ctrs));
   858                 in
   859                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   860                     mk_sel_exhaust_tac n disc_exhaust_thm swapped_all_collapse_thms)
   861                   |> Thm.close_derivation
   862                 end;
   863 
   864               val expand_thm =
   865                 let
   866                   fun mk_prems k udisc usels vdisc vsels =
   867                     (if k = n then [] else [mk_Trueprop_eq (udisc, vdisc)]) @
   868                     (if null usels then
   869                        []
   870                      else
   871                        [Logic.list_implies
   872                           (if n = 1 then [] else map HOLogic.mk_Trueprop [udisc, vdisc],
   873                              HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
   874                                (map2 (curry HOLogic.mk_eq) usels vsels)))]);
   875 
   876                   val goal =
   877                     Library.foldr Logic.list_implies
   878                       (map5 mk_prems ks udiscs uselss vdiscs vselss, uv_eq);
   879                   val uncollapse_thms =
   880                     map2 (fn thm => fn [] => thm | _ => thm RS sym) all_collapse_thms uselss;
   881                 in
   882                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   883                     mk_expand_tac lthy n ms (inst_thm u disc_exhaust_thm)
   884                       (inst_thm v disc_exhaust_thm) uncollapse_thms disc_exclude_thmsss
   885                       disc_exclude_thmsss')
   886                   |> singleton (Proof_Context.export names_lthy lthy)
   887                   |> Thm.close_derivation
   888                 end;
   889 
   890               val (sel_split_thm, sel_split_asm_thm) =
   891                 let
   892                   val zss = map (K []) xss;
   893                   val goal = mk_split_goal usel_ctrs zss usel_fs;
   894                   val asm_goal = mk_split_asm_goal usel_ctrs zss usel_fs;
   895 
   896                   val thm = prove_split sel_thmss goal;
   897                   val asm_thm = prove_split_asm asm_goal thm;
   898                 in
   899                   (thm, asm_thm)
   900                 end;
   901 
   902               val case_eq_if_thm =
   903                 let
   904                   val goal = mk_Trueprop_eq (ufcase, mk_IfN B udiscs usel_fs);
   905                 in
   906                   Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   907                     mk_case_eq_if_tac ctxt n uexhaust_thm case_thms disc_thmss' sel_thmss)
   908                   |> singleton (Proof_Context.export names_lthy lthy)
   909                   |> Thm.close_derivation
   910                 end;
   911             in
   912               (all_sel_thms, sel_thmss, disc_thmss, nontriv_disc_thmss, discI_thms,
   913                nontriv_discI_thms, disc_exclude_thms, disc_exclude_thmsss, [disc_exhaust_thm],
   914                [sel_exhaust_thm], all_collapse_thms, safe_collapse_thms, [expand_thm],
   915                [sel_split_thm], [sel_split_asm_thm], [case_eq_if_thm])
   916             end;
   917 
   918         val exhaust_case_names_attr = Attrib.internal (K (Rule_Cases.case_names exhaust_cases));
   919         val cases_type_attr = Attrib.internal (K (Induct.cases_type fcT_name));
   920 
   921         val nontriv_disc_eq_thmss =
   922           map (map (fn th => th RS @{thm eq_False[THEN iffD2]}
   923             handle THM _ => th RS @{thm eq_True[THEN iffD2]})) nontriv_disc_thmss;
   924 
   925         val anonymous_notes =
   926           [(map (fn th => th RS notE) distinct_thms, safe_elim_attrs),
   927            (flat nontriv_disc_eq_thmss, code_nitpicksimp_attrs)]
   928           |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
   929 
   930         val notes =
   931           [(caseN, case_thms, code_nitpicksimp_simp_attrs),
   932            (case_congN, [case_cong_thm], []),
   933            (case_eq_ifN, case_eq_if_thms, []),
   934            (collapseN, safe_collapse_thms, simp_attrs),
   935            (discN, flat nontriv_disc_thmss, simp_attrs),
   936            (discIN, nontriv_discI_thms, []),
   937            (disc_excludeN, disc_exclude_thms, dest_attrs),
   938            (disc_exhaustN, disc_exhaust_thms, [exhaust_case_names_attr]),
   939            (distinctN, distinct_thms, simp_attrs @ inductsimp_attrs),
   940            (exhaustN, [exhaust_thm], [exhaust_case_names_attr, cases_type_attr]),
   941            (expandN, expand_thms, []),
   942            (injectN, inject_thms, iff_attrs @ inductsimp_attrs),
   943            (nchotomyN, [nchotomy_thm], []),
   944            (selN, all_sel_thms, code_nitpicksimp_simp_attrs),
   945            (sel_exhaustN, sel_exhaust_thms, [exhaust_case_names_attr]),
   946            (sel_splitN, sel_split_thms, []),
   947            (sel_split_asmN, sel_split_asm_thms, []),
   948            (splitN, [split_thm], []),
   949            (split_asmN, [split_asm_thm], []),
   950            (splitsN, [split_thm, split_asm_thm], []),
   951            (weak_case_cong_thmsN, [weak_case_cong_thm], cong_attrs)]
   952           |> filter_out (null o #2)
   953           |> map (fn (thmN, thms, attrs) =>
   954             ((qualify true (Binding.name thmN), attrs), [(thms, [])]));
   955 
   956         val ctr_sugar =
   957           {ctrs = ctrs, casex = casex, discs = discs, selss = selss, exhaust = exhaust_thm,
   958            nchotomy = nchotomy_thm, injects = inject_thms, distincts = distinct_thms,
   959            case_thms = case_thms, case_cong = case_cong_thm, weak_case_cong = weak_case_cong_thm,
   960            split = split_thm, split_asm = split_asm_thm, disc_thmss = disc_thmss,
   961            discIs = discI_thms, sel_thmss = sel_thmss, disc_excludesss = disc_exclude_thmsss,
   962            disc_exhausts = disc_exhaust_thms, sel_exhausts = sel_exhaust_thms,
   963            collapses = all_collapse_thms, expands = expand_thms, sel_splits = sel_split_thms,
   964            sel_split_asms = sel_split_asm_thms, case_eq_ifs = case_eq_if_thms};
   965       in
   966         (ctr_sugar,
   967          lthy
   968          |> Spec_Rules.add Spec_Rules.Equational ([casex], case_thms)
   969          |> fold (Spec_Rules.add Spec_Rules.Equational)
   970            (AList.group (eq_list (op aconv)) (map (`(single o lhs_head_of)) all_sel_thms))
   971          |> fold (Spec_Rules.add Spec_Rules.Equational)
   972            (filter_out (null o snd) (map single discs ~~ nontriv_disc_eq_thmss))
   973          |> Local_Theory.declaration {syntax = false, pervasive = true}
   974               (fn phi => Case_Translation.register
   975                  (Morphism.term phi casex) (map (Morphism.term phi) ctrs))
   976          |> Local_Theory.background_theory (fold (fold Code.del_eqn) [disc_defs, sel_defs])
   977          |> not no_code ?
   978             Local_Theory.declaration {syntax = false, pervasive = false}
   979               (fn phi => Context.mapping
   980                 (add_ctr_code fcT_name (map (Morphism.typ phi) As)
   981                   (map (dest_Const o Morphism.term phi) ctrs) (Morphism.fact phi inject_thms)
   982                   (Morphism.fact phi distinct_thms) (Morphism.fact phi case_thms))
   983                 I)
   984          |> Local_Theory.notes (anonymous_notes @ notes) |> snd
   985          |> register_ctr_sugar fcT_name ctr_sugar)
   986       end;
   987   in
   988     (goalss, after_qed, lthy')
   989   end;
   990 
   991 fun free_constructors tacss = (fn (goalss, after_qed, lthy) =>
   992   map2 (map2 (Thm.close_derivation oo Goal.prove_sorry lthy [] [])) goalss tacss
   993   |> (fn thms => after_qed thms lthy)) oo prepare_free_constructors (K I);
   994 
   995 val free_constructors_cmd = (fn (goalss, after_qed, lthy) =>
   996   Proof.theorem NONE (snd oo after_qed) (map (map (rpair [])) goalss) lthy) oo
   997   prepare_free_constructors Syntax.read_term;
   998 
   999 val parse_bound_term = parse_binding --| @{keyword ":"} -- Parse.term;
  1000 
  1001 val parse_ctr_options =
  1002   Scan.optional (@{keyword "("} |-- Parse.list1
  1003         (Parse.reserved "no_discs_sels" >> K 0 || Parse.reserved "no_code" >> K 1) --|
  1004       @{keyword ")"}
  1005       >> (fn js => (member (op =) js 0, member (op =) js 1)))
  1006     (false, false);
  1007 
  1008 val parse_defaults =
  1009   @{keyword "("} |-- Parse.reserved "defaults" |-- Scan.repeat parse_bound_term --| @{keyword ")"};
  1010 
  1011 fun parse_ctr_spec parse_ctr parse_arg =
  1012   parse_opt_binding_colon -- parse_ctr -- Scan.repeat parse_arg --
  1013   Scan.optional parse_defaults [];
  1014 
  1015 val parse_ctr_specs = Parse.enum1 "|" (parse_ctr_spec Parse.term parse_binding);
  1016 
  1017 val _ =
  1018   Outer_Syntax.local_theory_to_proof @{command_spec "free_constructors"}
  1019     "register an existing freely generated type's constructors"
  1020     (parse_ctr_options -- parse_binding --| @{keyword "for"} -- parse_ctr_specs
  1021      >> free_constructors_cmd);
  1022 
  1023 val _ = Context.>> (Context.map_theory Ctr_Sugar_Interpretation.init);
  1024 
  1025 end;