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