src/HOL/Tools/Ctr_Sugar/ctr_sugar.ML
author blanchet
Fri Feb 14 07:53:46 2014 +0100 (2014-02-14)
changeset 55471 198498f861ee
parent 55470 46e6e1d91056
child 55480 59cc4a8bc28a
permissions -rw-r--r--
more precise spec rules for selectors
     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 = map (map (apsnd (prep_term no_defs_lthy))) raw_sel_defaultss;
   312 
   313     val Type (fcT_name, As0) = body_type (fastype_of (hd ctrs0));
   314     val fc_b_name = Long_Name.base_name fcT_name;
   315     val fc_b = Binding.name fc_b_name;
   316 
   317     fun qualify mandatory = Binding.qualify mandatory fc_b_name;
   318 
   319     fun dest_TFree_or_TVar (TFree sS) = sS
   320       | dest_TFree_or_TVar (TVar ((s, _), S)) = (s, S)
   321       | dest_TFree_or_TVar _ = error "Invalid type argument";
   322 
   323     val (unsorted_As, B) =
   324       no_defs_lthy
   325       |> variant_tfrees (map (fst o dest_TFree_or_TVar) As0)
   326       ||> the_single o fst o mk_TFrees 1;
   327 
   328     val As = map2 (resort_tfree o snd o dest_TFree_or_TVar) As0 unsorted_As;
   329 
   330     val fcT = Type (fcT_name, As);
   331     val ctrs = map (mk_ctr As) ctrs0;
   332     val ctr_Tss = map (binder_types o fastype_of) ctrs;
   333 
   334     val ms = map length ctr_Tss;
   335 
   336     fun can_definitely_rely_on_disc k = not (Binding.is_empty (nth raw_disc_bindings (k - 1)));
   337     fun can_rely_on_disc k =
   338       can_definitely_rely_on_disc k orelse (k = 1 andalso not (can_definitely_rely_on_disc 2));
   339     fun should_omit_disc_binding k = n = 1 orelse (n = 2 andalso can_rely_on_disc (3 - k));
   340 
   341     fun is_disc_binding_valid b =
   342       not (Binding.is_empty b orelse Binding.eq_name (b, equal_binding));
   343 
   344     val standard_disc_binding = Binding.name o prefix isN o base_name_of_ctr;
   345 
   346     val disc_bindings =
   347       raw_disc_bindings
   348       |> map4 (fn k => fn m => fn ctr => fn disc =>
   349         qualify false
   350           (if Binding.is_empty disc then
   351              if should_omit_disc_binding k then disc else standard_disc_binding ctr
   352            else if Binding.eq_name (disc, equal_binding) then
   353              if m = 0 then disc
   354              else error "Cannot use \"=\" syntax for discriminating nonnullary constructor"
   355            else if Binding.eq_name (disc, standard_binding) then
   356              standard_disc_binding ctr
   357            else
   358              disc)) ks ms ctrs0;
   359 
   360     fun standard_sel_binding m l = Binding.name o mk_unN m l o base_name_of_ctr;
   361 
   362     val sel_bindingss =
   363       map3 (fn ctr => fn m => map2 (fn l => fn sel =>
   364         qualify false
   365           (if Binding.is_empty sel orelse Binding.eq_name (sel, standard_binding) then
   366             standard_sel_binding m l ctr
   367           else
   368             sel)) (1 upto m) o pad_list Binding.empty m) ctrs0 ms raw_sel_bindingss;
   369 
   370     val case_Ts = map (fn Ts => Ts ---> B) ctr_Tss;
   371 
   372     val (((((((([exh_y], (xss, xss')), yss), fs), gs), [u', v']), [w]), (p, p')), names_lthy) =
   373       no_defs_lthy
   374       |> mk_Frees "y" [fcT] (* for compatibility with "datatype_realizer.ML" *)
   375       ||>> mk_Freess' "x" ctr_Tss
   376       ||>> mk_Freess "y" ctr_Tss
   377       ||>> mk_Frees "f" case_Ts
   378       ||>> mk_Frees "g" case_Ts
   379       ||>> (apfst (map (rpair fcT)) oo Variable.variant_fixes) [fc_b_name, fc_b_name ^ "'"]
   380       ||>> mk_Frees "z" [B]
   381       ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "P") HOLogic.boolT;
   382 
   383     val u = Free u';
   384     val v = Free v';
   385     val q = Free (fst p', mk_pred1T B);
   386 
   387     val xctrs = map2 (curry Term.list_comb) ctrs xss;
   388     val yctrs = map2 (curry Term.list_comb) ctrs yss;
   389 
   390     val xfs = map2 (curry Term.list_comb) fs xss;
   391     val xgs = map2 (curry Term.list_comb) gs xss;
   392 
   393     (* TODO: Eta-expension is for compatibility with the old datatype package (but it also provides
   394        nicer names). Consider removing. *)
   395     val eta_fs = map2 eta_expand_arg xss xfs;
   396     val eta_gs = map2 eta_expand_arg xss xgs;
   397 
   398     val case_binding =
   399       qualify false
   400         (if Binding.is_empty raw_case_binding orelse
   401             Binding.eq_name (raw_case_binding, standard_binding) then
   402            Binding.prefix_name (caseN ^ "_") fc_b
   403          else
   404            raw_case_binding);
   405 
   406     fun mk_case_disj xctr xf xs =
   407       list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr), HOLogic.mk_eq (w, xf)));
   408 
   409     val case_rhs = fold_rev (fold_rev Term.lambda) [fs, [u]]
   410       (Const (@{const_name The}, (B --> HOLogic.boolT) --> B) $
   411          Term.lambda w (Library.foldr1 HOLogic.mk_disj (map3 mk_case_disj xctrs xfs xss)));
   412 
   413     val ((raw_case, (_, raw_case_def)), (lthy', lthy)) = no_defs_lthy
   414       |> Local_Theory.define ((case_binding, NoSyn),
   415         ((Binding.conceal (Thm.def_binding case_binding), []), case_rhs))
   416       ||> `Local_Theory.restore;
   417 
   418     val phi = Proof_Context.export_morphism lthy lthy';
   419 
   420     val case_def = Morphism.thm phi raw_case_def;
   421 
   422     val case0 = Morphism.term phi raw_case;
   423     val casex = mk_case As B case0;
   424 
   425     val fcase = Term.list_comb (casex, fs);
   426 
   427     val ufcase = fcase $ u;
   428     val vfcase = fcase $ v;
   429 
   430     val eta_fcase = Term.list_comb (casex, eta_fs);
   431     val eta_gcase = Term.list_comb (casex, eta_gs);
   432 
   433     val eta_ufcase = eta_fcase $ u;
   434     val eta_vgcase = eta_gcase $ v;
   435 
   436     fun mk_uu_eq () = HOLogic.mk_eq (u, u);
   437 
   438     val uv_eq = mk_Trueprop_eq (u, v);
   439 
   440     val exist_xs_u_eq_ctrs =
   441       map2 (fn xctr => fn xs => list_exists_free xs (HOLogic.mk_eq (u, xctr))) xctrs xss;
   442 
   443     val unique_disc_no_def = TrueI; (*arbitrary marker*)
   444     val alternate_disc_no_def = FalseE; (*arbitrary marker*)
   445 
   446     fun alternate_disc_lhs get_udisc k =
   447       HOLogic.mk_not
   448         (let val b = nth disc_bindings (k - 1) in
   449            if is_disc_binding_valid b then get_udisc b (k - 1) else nth exist_xs_u_eq_ctrs (k - 1)
   450          end);
   451 
   452     val (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy') =
   453       if no_discs_sels then
   454         (true, [], [], [], [], [], lthy')
   455       else
   456         let
   457           fun disc_free b = Free (Binding.name_of b, mk_pred1T fcT);
   458 
   459           fun disc_spec b exist_xs_u_eq_ctr = mk_Trueprop_eq (disc_free b $ u, exist_xs_u_eq_ctr);
   460 
   461           fun alternate_disc k =
   462             Term.lambda u (alternate_disc_lhs (K o rapp u o disc_free) (3 - k));
   463 
   464           fun mk_sel_case_args b proto_sels T =
   465             map2 (fn Ts => fn k =>
   466               (case AList.lookup (op =) proto_sels k of
   467                 NONE =>
   468                 (case AList.lookup Binding.eq_name (rev (nth sel_defaultss (k - 1))) b of
   469                   NONE => fold_rev (Term.lambda o curry Free Name.uu) Ts (mk_undefined T)
   470                 | SOME t => t |> Type.constraint (Ts ---> T) |> Syntax.check_term lthy)
   471               | SOME (xs, x) => fold_rev Term.lambda xs x)) ctr_Tss ks;
   472 
   473           fun sel_spec b proto_sels =
   474             let
   475               val _ =
   476                 (case duplicates (op =) (map fst proto_sels) of
   477                    k :: _ => error ("Duplicate selector name " ^ quote (Binding.name_of b) ^
   478                      " for constructor " ^
   479                      quote (Syntax.string_of_term lthy (nth ctrs (k - 1))))
   480                  | [] => ())
   481               val T =
   482                 (case distinct (op =) (map (fastype_of o snd o snd) proto_sels) of
   483                   [T] => T
   484                 | T :: T' :: _ => error ("Inconsistent range type for selector " ^
   485                     quote (Binding.name_of b) ^ ": " ^ quote (Syntax.string_of_typ lthy T) ^ " vs. "
   486                     ^ quote (Syntax.string_of_typ lthy T')));
   487             in
   488               mk_Trueprop_eq (Free (Binding.name_of b, fcT --> T) $ u,
   489                 Term.list_comb (mk_case As T case0, mk_sel_case_args b proto_sels T) $ u)
   490             end;
   491 
   492           val sel_bindings = flat sel_bindingss;
   493           val uniq_sel_bindings = distinct Binding.eq_name sel_bindings;
   494           val all_sels_distinct = (length uniq_sel_bindings = length sel_bindings);
   495 
   496           val sel_binding_index =
   497             if all_sels_distinct then 1 upto length sel_bindings
   498             else map (fn b => find_index (curry Binding.eq_name b) uniq_sel_bindings) sel_bindings;
   499 
   500           val proto_sels = flat (map3 (fn k => fn xs => map (fn x => (k, (xs, x)))) ks xss xss);
   501           val sel_infos =
   502             AList.group (op =) (sel_binding_index ~~ proto_sels)
   503             |> sort (int_ord o pairself fst)
   504             |> map snd |> curry (op ~~) uniq_sel_bindings;
   505           val sel_bindings = map fst sel_infos;
   506 
   507           fun unflat_selss xs = unflat_lookup Binding.eq_name sel_bindings xs sel_bindingss;
   508 
   509           val (((raw_discs, raw_disc_defs), (raw_sels, raw_sel_defs)), (lthy', lthy)) =
   510             lthy
   511             |> apfst split_list o fold_map3 (fn k => fn exist_xs_u_eq_ctr => fn b =>
   512                 if Binding.is_empty b then
   513                   if n = 1 then pair (Term.lambda u (mk_uu_eq ()), unique_disc_no_def)
   514                   else pair (alternate_disc k, alternate_disc_no_def)
   515                 else if Binding.eq_name (b, equal_binding) then
   516                   pair (Term.lambda u exist_xs_u_eq_ctr, refl)
   517                 else
   518                   Specification.definition (SOME (b, NONE, NoSyn),
   519                     ((Thm.def_binding b, []), disc_spec b exist_xs_u_eq_ctr)) #>> apsnd snd)
   520               ks exist_xs_u_eq_ctrs disc_bindings
   521             ||>> apfst split_list o fold_map (fn (b, proto_sels) =>
   522               Specification.definition (SOME (b, NONE, NoSyn),
   523                 ((Thm.def_binding b, []), sel_spec b proto_sels)) #>> apsnd snd) sel_infos
   524             ||> `Local_Theory.restore;
   525 
   526           val phi = Proof_Context.export_morphism lthy lthy';
   527 
   528           val disc_defs = map (Morphism.thm phi) raw_disc_defs;
   529           val sel_defs = map (Morphism.thm phi) raw_sel_defs;
   530           val sel_defss = unflat_selss sel_defs;
   531 
   532           val discs0 = map (Morphism.term phi) raw_discs;
   533           val selss0 = unflat_selss (map (Morphism.term phi) raw_sels);
   534 
   535           val discs = map (mk_disc_or_sel As) discs0;
   536           val selss = map (map (mk_disc_or_sel As)) selss0;
   537         in
   538           (all_sels_distinct, discs, selss, disc_defs, sel_defs, sel_defss, lthy')
   539         end;
   540 
   541     fun mk_imp_p Qs = Logic.list_implies (Qs, HOLogic.mk_Trueprop p);
   542 
   543     val exhaust_goal =
   544       let fun mk_prem xctr xs = fold_rev Logic.all xs (mk_imp_p [mk_Trueprop_eq (exh_y, xctr)]) in
   545         fold_rev Logic.all [p, exh_y] (mk_imp_p (map2 mk_prem xctrs xss))
   546       end;
   547 
   548     val inject_goalss =
   549       let
   550         fun mk_goal _ _ [] [] = []
   551           | mk_goal xctr yctr xs ys =
   552             [fold_rev Logic.all (xs @ ys) (mk_Trueprop_eq (HOLogic.mk_eq (xctr, yctr),
   553               Library.foldr1 HOLogic.mk_conj (map2 (curry HOLogic.mk_eq) xs ys)))];
   554       in
   555         map4 mk_goal xctrs yctrs xss yss
   556       end;
   557 
   558     val half_distinct_goalss =
   559       let
   560         fun mk_goal ((xs, xc), (xs', xc')) =
   561           fold_rev Logic.all (xs @ xs')
   562             (HOLogic.mk_Trueprop (HOLogic.mk_not (HOLogic.mk_eq (xc, xc'))));
   563       in
   564         map (map mk_goal) (mk_half_pairss (`I (xss ~~ xctrs)))
   565       end;
   566 
   567     val goalss = [exhaust_goal] :: inject_goalss @ half_distinct_goalss;
   568 
   569     fun after_qed thmss lthy =
   570       let
   571         val ([exhaust_thm0], (inject_thmss, half_distinct_thmss)) = (hd thmss, chop n (tl thmss));
   572         (* for "datatype_realizer.ML": *)
   573         val exhaust_thm =
   574           Thm.name_derivation (fcT_name ^ Long_Name.separator ^ exhaustN) exhaust_thm0;
   575 
   576         val inject_thms = flat inject_thmss;
   577 
   578         val rho_As = map (pairself (certifyT lthy)) (map Logic.varifyT_global As ~~ As);
   579 
   580         fun inst_thm t thm =
   581           Drule.instantiate' [] [SOME (certify lthy t)]
   582             (Thm.instantiate (rho_As, []) (Drule.zero_var_indexes thm));
   583 
   584         val uexhaust_thm = inst_thm u exhaust_thm;
   585 
   586         val exhaust_cases = map base_name_of_ctr ctrs;
   587 
   588         val other_half_distinct_thmss = map (map (fn thm => thm RS not_sym)) half_distinct_thmss;
   589 
   590         val (distinct_thms, (distinct_thmsss', distinct_thmsss)) =
   591           join_halves n half_distinct_thmss other_half_distinct_thmss ||> `transpose;
   592 
   593         val nchotomy_thm =
   594           let
   595             val goal =
   596               HOLogic.mk_Trueprop (HOLogic.mk_all (fst u', snd u',
   597                 Library.foldr1 HOLogic.mk_disj exist_xs_u_eq_ctrs));
   598           in
   599             Goal.prove_sorry lthy [] [] goal (fn _ => mk_nchotomy_tac n exhaust_thm)
   600             |> Thm.close_derivation
   601           end;
   602 
   603         val case_thms =
   604           let
   605             val goals =
   606               map3 (fn xctr => fn xf => fn xs =>
   607                 fold_rev Logic.all (fs @ xs) (mk_Trueprop_eq (fcase $ xctr, xf))) xctrs xfs xss;
   608           in
   609             map4 (fn k => fn goal => fn injects => fn distinctss =>
   610                 Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   611                   mk_case_tac ctxt n k case_def injects distinctss)
   612                 |> Thm.close_derivation)
   613               ks goals inject_thmss distinct_thmsss
   614           end;
   615 
   616         val (case_cong_thm, weak_case_cong_thm) =
   617           let
   618             fun mk_prem xctr xs xf xg =
   619               fold_rev Logic.all xs (Logic.mk_implies (mk_Trueprop_eq (v, xctr),
   620                 mk_Trueprop_eq (xf, xg)));
   621 
   622             val goal =
   623               Logic.list_implies (uv_eq :: map4 mk_prem xctrs xss xfs xgs,
   624                  mk_Trueprop_eq (eta_ufcase, eta_vgcase));
   625             val weak_goal = Logic.mk_implies (uv_eq, mk_Trueprop_eq (ufcase, vfcase));
   626           in
   627             (Goal.prove_sorry lthy [] [] goal (fn _ => mk_case_cong_tac lthy uexhaust_thm case_thms),
   628              Goal.prove_sorry lthy [] [] weak_goal (K (etac arg_cong 1)))
   629             |> pairself (singleton (Proof_Context.export names_lthy lthy) #>
   630               Thm.close_derivation)
   631           end;
   632 
   633         val split_lhs = q $ ufcase;
   634 
   635         fun mk_split_conjunct xctr xs f_xs =
   636           list_all_free xs (HOLogic.mk_imp (HOLogic.mk_eq (u, xctr), q $ f_xs));
   637         fun mk_split_disjunct xctr xs f_xs =
   638           list_exists_free xs (HOLogic.mk_conj (HOLogic.mk_eq (u, xctr),
   639             HOLogic.mk_not (q $ f_xs)));
   640 
   641         fun mk_split_goal xctrs xss xfs =
   642           mk_Trueprop_eq (split_lhs, Library.foldr1 HOLogic.mk_conj
   643             (map3 mk_split_conjunct xctrs xss xfs));
   644         fun mk_split_asm_goal xctrs xss xfs =
   645           mk_Trueprop_eq (split_lhs, HOLogic.mk_not (Library.foldr1 HOLogic.mk_disj
   646             (map3 mk_split_disjunct xctrs xss xfs)));
   647 
   648         fun prove_split selss goal =
   649           Goal.prove_sorry lthy [] [] goal (fn _ =>
   650             mk_split_tac lthy uexhaust_thm case_thms selss inject_thmss distinct_thmsss)
   651           |> singleton (Proof_Context.export names_lthy lthy)
   652           |> Thm.close_derivation;
   653 
   654         fun prove_split_asm asm_goal split_thm =
   655           Goal.prove_sorry lthy [] [] asm_goal (fn {context = ctxt, ...} =>
   656             mk_split_asm_tac ctxt split_thm)
   657           |> singleton (Proof_Context.export names_lthy lthy)
   658           |> Thm.close_derivation;
   659 
   660         val (split_thm, split_asm_thm) =
   661           let
   662             val goal = mk_split_goal xctrs xss xfs;
   663             val asm_goal = mk_split_asm_goal xctrs xss xfs;
   664 
   665             val thm = prove_split (replicate n []) goal;
   666             val asm_thm = prove_split_asm asm_goal thm;
   667           in
   668             (thm, asm_thm)
   669           end;
   670 
   671         val (all_sel_thms, sel_thmss, disc_thmss, nontriv_disc_thmss, discI_thms,
   672              nontriv_discI_thms, disc_exclude_thms, disc_exclude_thmsss, disc_exhaust_thms,
   673              sel_exhaust_thms, all_collapse_thms, safe_collapse_thms, expand_thms, sel_split_thms,
   674              sel_split_asm_thms, case_eq_if_thms) =
   675           if no_discs_sels then
   676             ([], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [])
   677           else
   678             let
   679               val udiscs = map (rapp u) discs;
   680               val uselss = map (map (rapp u)) selss;
   681               val usel_ctrs = map2 (curry Term.list_comb) ctrs uselss;
   682               val usel_fs = map2 (curry Term.list_comb) fs uselss;
   683 
   684               val vdiscs = map (rapp v) discs;
   685               val vselss = map (map (rapp v)) selss;
   686 
   687               fun make_sel_thm xs' case_thm sel_def =
   688                 zero_var_indexes (Drule.gen_all (Drule.rename_bvars' (map (SOME o fst) xs')
   689                     (Drule.forall_intr_vars (case_thm RS (sel_def RS trans)))));
   690 
   691               val sel_thmss = map3 (map oo make_sel_thm) xss' case_thms sel_defss;
   692 
   693               fun has_undefined_rhs thm =
   694                 (case snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of thm))) of
   695                   Const (@{const_name undefined}, _) => true
   696                 | _ => false);
   697 
   698               val all_sel_thms =
   699                 (if all_sels_distinct andalso forall null sel_defaultss then
   700                    flat sel_thmss
   701                  else
   702                    map_product (fn s => fn (xs', c) => make_sel_thm xs' c s) sel_defs
   703                      (xss' ~~ case_thms))
   704                 |> filter_out has_undefined_rhs;
   705 
   706               fun mk_unique_disc_def () =
   707                 let
   708                   val m = the_single ms;
   709                   val goal = mk_Trueprop_eq (mk_uu_eq (), the_single exist_xs_u_eq_ctrs);
   710                 in
   711                   Goal.prove_sorry lthy [] [] goal (fn _ => mk_unique_disc_def_tac m uexhaust_thm)
   712                   |> singleton (Proof_Context.export names_lthy lthy)
   713                   |> Thm.close_derivation
   714                 end;
   715 
   716               fun mk_alternate_disc_def k =
   717                 let
   718                   val goal =
   719                     mk_Trueprop_eq (alternate_disc_lhs (K (nth udiscs)) (3 - k),
   720                       nth exist_xs_u_eq_ctrs (k - 1));
   721                 in
   722                   Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   723                     mk_alternate_disc_def_tac ctxt k (nth disc_defs (2 - k))
   724                       (nth distinct_thms (2 - k)) uexhaust_thm)
   725                   |> singleton (Proof_Context.export names_lthy lthy)
   726                   |> Thm.close_derivation
   727                 end;
   728 
   729               val has_alternate_disc_def =
   730                 exists (fn def => Thm.eq_thm_prop (def, alternate_disc_no_def)) disc_defs;
   731 
   732               val disc_defs' =
   733                 map2 (fn k => fn def =>
   734                   if Thm.eq_thm_prop (def, unique_disc_no_def) then mk_unique_disc_def ()
   735                   else if Thm.eq_thm_prop (def, alternate_disc_no_def) then mk_alternate_disc_def k
   736                   else def) ks disc_defs;
   737 
   738               val discD_thms = map (fn def => def RS iffD1) disc_defs';
   739               val discI_thms =
   740                 map2 (fn m => fn def => funpow m (fn thm => exI RS thm) (def RS iffD2)) ms
   741                   disc_defs';
   742               val not_discI_thms =
   743                 map2 (fn m => fn def => funpow m (fn thm => allI RS thm)
   744                     (unfold_thms lthy @{thms not_ex} (def RS @{thm ssubst[of _ _ Not]})))
   745                   ms disc_defs';
   746 
   747               val (disc_thmss', disc_thmss) =
   748                 let
   749                   fun mk_thm discI _ [] = refl RS discI
   750                     | mk_thm _ not_discI [distinct] = distinct RS not_discI;
   751                   fun mk_thms discI not_discI distinctss = map (mk_thm discI not_discI) distinctss;
   752                 in
   753                   map3 mk_thms discI_thms not_discI_thms distinct_thmsss' |> `transpose
   754                 end;
   755 
   756               val nontriv_disc_thmss =
   757                 map2 (fn b => if is_disc_binding_valid b then I else K []) disc_bindings disc_thmss;
   758 
   759               fun is_discI_boring b =
   760                 (n = 1 andalso Binding.is_empty b) orelse Binding.eq_name (b, equal_binding);
   761 
   762               val nontriv_discI_thms =
   763                 flat (map2 (fn b => if is_discI_boring b then K [] else single) disc_bindings
   764                   discI_thms);
   765 
   766               val (disc_exclude_thms, (disc_exclude_thmsss', disc_exclude_thmsss)) =
   767                 let
   768                   fun mk_goal [] = []
   769                     | mk_goal [((_, udisc), (_, udisc'))] =
   770                       [Logic.all u (Logic.mk_implies (HOLogic.mk_Trueprop udisc,
   771                          HOLogic.mk_Trueprop (HOLogic.mk_not udisc')))];
   772 
   773                   fun prove tac goal =
   774                     Goal.prove_sorry lthy [] [] goal (K tac)
   775                     |> Thm.close_derivation;
   776 
   777                   val half_pairss = mk_half_pairss (`I (ms ~~ discD_thms ~~ udiscs));
   778 
   779                   val half_goalss = map mk_goal half_pairss;
   780                   val half_thmss =
   781                     map3 (fn [] => K (K []) | [goal] => fn [(((m, discD), _), _)] =>
   782                         fn disc_thm => [prove (mk_half_disc_exclude_tac lthy m discD disc_thm) goal])
   783                       half_goalss half_pairss (flat disc_thmss');
   784 
   785                   val other_half_goalss = map (mk_goal o map swap) half_pairss;
   786                   val other_half_thmss =
   787                     map2 (map2 (prove o mk_other_half_disc_exclude_tac)) half_thmss
   788                       other_half_goalss;
   789                 in
   790                   join_halves n half_thmss other_half_thmss ||> `transpose
   791                   |>> has_alternate_disc_def ? K []
   792                 end;
   793 
   794               val disc_exhaust_thm =
   795                 let
   796                   fun mk_prem udisc = mk_imp_p [HOLogic.mk_Trueprop udisc];
   797                   val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem udiscs));
   798                 in
   799                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   800                     mk_disc_exhaust_tac n exhaust_thm discI_thms)
   801                   |> Thm.close_derivation
   802                 end;
   803 
   804               val (safe_collapse_thms, all_collapse_thms) =
   805                 let
   806                   fun mk_goal m udisc usel_ctr =
   807                     let
   808                       val prem = HOLogic.mk_Trueprop udisc;
   809                       val concl = mk_Trueprop_eq ((usel_ctr, u) |> m = 0 ? swap);
   810                     in
   811                       (prem aconv concl, Logic.all u (Logic.mk_implies (prem, concl)))
   812                     end;
   813                   val (trivs, goals) = map3 mk_goal ms udiscs usel_ctrs |> split_list;
   814                   val thms =
   815                     map5 (fn m => fn discD => fn sel_thms => fn triv => fn goal =>
   816                         Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   817                           mk_collapse_tac ctxt m discD sel_thms ORELSE HEADGOAL atac)
   818                         |> Thm.close_derivation
   819                         |> not triv ? perhaps (try (fn thm => refl RS thm)))
   820                       ms discD_thms sel_thmss trivs goals;
   821                 in
   822                   (map_filter (fn (true, _) => NONE | (false, thm) => SOME thm) (trivs ~~ thms),
   823                    thms)
   824                 end;
   825 
   826               val swapped_all_collapse_thms =
   827                 map2 (fn m => fn thm => if m = 0 then thm else thm RS sym) ms all_collapse_thms;
   828 
   829               val sel_exhaust_thm =
   830                 let
   831                   fun mk_prem usel_ctr = mk_imp_p [mk_Trueprop_eq (u, usel_ctr)];
   832                   val goal = fold_rev Logic.all [p, u] (mk_imp_p (map mk_prem usel_ctrs));
   833                 in
   834                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   835                     mk_sel_exhaust_tac n disc_exhaust_thm swapped_all_collapse_thms)
   836                   |> Thm.close_derivation
   837                 end;
   838 
   839               val expand_thm =
   840                 let
   841                   fun mk_prems k udisc usels vdisc vsels =
   842                     (if k = n then [] else [mk_Trueprop_eq (udisc, vdisc)]) @
   843                     (if null usels then
   844                        []
   845                      else
   846                        [Logic.list_implies
   847                           (if n = 1 then [] else map HOLogic.mk_Trueprop [udisc, vdisc],
   848                              HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
   849                                (map2 (curry HOLogic.mk_eq) usels vsels)))]);
   850 
   851                   val goal =
   852                     Library.foldr Logic.list_implies
   853                       (map5 mk_prems ks udiscs uselss vdiscs vselss, uv_eq);
   854                   val uncollapse_thms =
   855                     map2 (fn thm => fn [] => thm | _ => thm RS sym) all_collapse_thms uselss;
   856                 in
   857                   Goal.prove_sorry lthy [] [] goal (fn _ =>
   858                     mk_expand_tac lthy n ms (inst_thm u disc_exhaust_thm)
   859                       (inst_thm v disc_exhaust_thm) uncollapse_thms disc_exclude_thmsss
   860                       disc_exclude_thmsss')
   861                   |> singleton (Proof_Context.export names_lthy lthy)
   862                   |> Thm.close_derivation
   863                 end;
   864 
   865               val (sel_split_thm, sel_split_asm_thm) =
   866                 let
   867                   val zss = map (K []) xss;
   868                   val goal = mk_split_goal usel_ctrs zss usel_fs;
   869                   val asm_goal = mk_split_asm_goal usel_ctrs zss usel_fs;
   870 
   871                   val thm = prove_split sel_thmss goal;
   872                   val asm_thm = prove_split_asm asm_goal thm;
   873                 in
   874                   (thm, asm_thm)
   875                 end;
   876 
   877               val case_eq_if_thm =
   878                 let
   879                   val goal = mk_Trueprop_eq (ufcase, mk_IfN B udiscs usel_fs);
   880                 in
   881                   Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   882                     mk_case_eq_if_tac ctxt n uexhaust_thm case_thms disc_thmss' sel_thmss)
   883                   |> singleton (Proof_Context.export names_lthy lthy)
   884                   |> Thm.close_derivation
   885                 end;
   886             in
   887               (all_sel_thms, sel_thmss, disc_thmss, nontriv_disc_thmss, discI_thms,
   888                nontriv_discI_thms, disc_exclude_thms, disc_exclude_thmsss, [disc_exhaust_thm],
   889                [sel_exhaust_thm], all_collapse_thms, safe_collapse_thms, [expand_thm],
   890                [sel_split_thm], [sel_split_asm_thm], [case_eq_if_thm])
   891             end;
   892 
   893         val exhaust_case_names_attr = Attrib.internal (K (Rule_Cases.case_names exhaust_cases));
   894         val cases_type_attr = Attrib.internal (K (Induct.cases_type fcT_name));
   895 
   896         val nontriv_disc_eq_thmss =
   897           map (map (fn th => th RS @{thm eq_False[THEN iffD2]}
   898             handle THM _ => th RS @{thm eq_True[THEN iffD2]})) nontriv_disc_thmss;
   899 
   900         val anonymous_notes =
   901           [(map (fn th => th RS notE) distinct_thms, safe_elim_attrs),
   902            (flat nontriv_disc_eq_thmss, code_nitpicksimp_attrs)]
   903           |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
   904 
   905         val notes =
   906           [(caseN, case_thms, code_nitpicksimp_simp_attrs),
   907            (case_congN, [case_cong_thm], []),
   908            (case_eq_ifN, case_eq_if_thms, []),
   909            (collapseN, safe_collapse_thms, simp_attrs),
   910            (discN, flat nontriv_disc_thmss, simp_attrs),
   911            (discIN, nontriv_discI_thms, []),
   912            (disc_excludeN, disc_exclude_thms, dest_attrs),
   913            (disc_exhaustN, disc_exhaust_thms, [exhaust_case_names_attr]),
   914            (distinctN, distinct_thms, simp_attrs @ inductsimp_attrs),
   915            (exhaustN, [exhaust_thm], [exhaust_case_names_attr, cases_type_attr]),
   916            (expandN, expand_thms, []),
   917            (injectN, inject_thms, iff_attrs @ inductsimp_attrs),
   918            (nchotomyN, [nchotomy_thm], []),
   919            (selN, all_sel_thms, code_nitpicksimp_simp_attrs),
   920            (sel_exhaustN, sel_exhaust_thms, [exhaust_case_names_attr]),
   921            (sel_splitN, sel_split_thms, []),
   922            (sel_split_asmN, sel_split_asm_thms, []),
   923            (splitN, [split_thm], []),
   924            (split_asmN, [split_asm_thm], []),
   925            (splitsN, [split_thm, split_asm_thm], []),
   926            (weak_case_cong_thmsN, [weak_case_cong_thm], cong_attrs)]
   927           |> filter_out (null o #2)
   928           |> map (fn (thmN, thms, attrs) =>
   929             ((qualify true (Binding.name thmN), attrs), [(thms, [])]));
   930 
   931         val ctr_sugar =
   932           {ctrs = ctrs, casex = casex, discs = discs, selss = selss, exhaust = exhaust_thm,
   933            nchotomy = nchotomy_thm, injects = inject_thms, distincts = distinct_thms,
   934            case_thms = case_thms, case_cong = case_cong_thm, weak_case_cong = weak_case_cong_thm,
   935            split = split_thm, split_asm = split_asm_thm, disc_thmss = disc_thmss,
   936            discIs = discI_thms, sel_thmss = sel_thmss, disc_excludesss = disc_exclude_thmsss,
   937            disc_exhausts = disc_exhaust_thms, sel_exhausts = sel_exhaust_thms,
   938            collapses = all_collapse_thms, expands = expand_thms, sel_splits = sel_split_thms,
   939            sel_split_asms = sel_split_asm_thms, case_eq_ifs = case_eq_if_thms};
   940       in
   941         (ctr_sugar,
   942          lthy
   943          |> Spec_Rules.add Spec_Rules.Equational ([casex], case_thms)
   944          |> fold (Spec_Rules.add Spec_Rules.Equational)
   945            (AList.group (eq_list (op aconv)) (map (`lhs_heads_of) all_sel_thms))
   946          |> fold (Spec_Rules.add Spec_Rules.Equational)
   947            (filter_out (null o snd) (map single discs ~~ nontriv_disc_eq_thmss))
   948          |> Local_Theory.declaration {syntax = false, pervasive = true}
   949               (fn phi => Case_Translation.register
   950                  (Morphism.term phi casex) (map (Morphism.term phi) ctrs))
   951          |> Local_Theory.background_theory (fold (fold Code.del_eqn) [disc_defs, sel_defs])
   952          |> not no_code ?
   953             Local_Theory.declaration {syntax = false, pervasive = false}
   954               (fn phi => Context.mapping
   955                 (add_ctr_code fcT_name (map (Morphism.typ phi) As)
   956                   (map (dest_Const o Morphism.term phi) ctrs) (Morphism.fact phi inject_thms)
   957                   (Morphism.fact phi distinct_thms) (Morphism.fact phi case_thms))
   958                 I)
   959          |> Local_Theory.notes (anonymous_notes @ notes) |> snd
   960          |> register_ctr_sugar fcT_name ctr_sugar)
   961       end;
   962   in
   963     (goalss, after_qed, lthy')
   964   end;
   965 
   966 fun free_constructors tacss = (fn (goalss, after_qed, lthy) =>
   967   map2 (map2 (Thm.close_derivation oo Goal.prove_sorry lthy [] [])) goalss tacss
   968   |> (fn thms => after_qed thms lthy)) oo prepare_free_constructors (K I);
   969 
   970 val free_constructors_cmd = (fn (goalss, after_qed, lthy) =>
   971   Proof.theorem NONE (snd oo after_qed) (map (map (rpair [])) goalss) lthy) oo
   972   prepare_free_constructors Syntax.read_term;
   973 
   974 val parse_bound_term = parse_binding --| @{keyword ":"} -- Parse.term;
   975 
   976 val parse_ctr_options =
   977   Scan.optional (@{keyword "("} |-- Parse.list1
   978         (Parse.reserved "no_discs_sels" >> K 0 || Parse.reserved "no_code" >> K 1) --|
   979       @{keyword ")"}
   980       >> (fn js => (member (op =) js 0, member (op =) js 1)))
   981     (false, false);
   982 
   983 val parse_defaults =
   984   @{keyword "("} |-- Parse.reserved "defaults" |-- Scan.repeat parse_bound_term --| @{keyword ")"};
   985 
   986 fun parse_ctr_spec parse_ctr parse_arg =
   987   parse_opt_binding_colon -- parse_ctr -- Scan.repeat parse_arg --
   988   Scan.optional parse_defaults [];
   989 
   990 val parse_ctr_specs = Parse.enum1 "|" (parse_ctr_spec Parse.term parse_binding);
   991 
   992 val _ =
   993   Outer_Syntax.local_theory_to_proof @{command_spec "free_constructors"}
   994     "register an existing freely generated type's constructors"
   995     (parse_ctr_options -- parse_binding --| @{keyword "for"} -- parse_ctr_specs
   996      >> free_constructors_cmd);
   997 
   998 end;