src/HOL/Tools/BNF/bnf_fp_def_sugar.ML
author blanchet
Mon Aug 18 17:19:58 2014 +0200 (2014-08-18)
changeset 57983 6edc3529bb4e
parent 57932 c29659f77f8d
child 57987 ecb227b40907
permissions -rw-r--r--
reordered some (co)datatype property names for more consistency
     1 (*  Title:      HOL/Tools/BNF/bnf_fp_def_sugar.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Author:     Martin Desharnais, TU Muenchen
     4     Copyright   2012, 2013, 2014
     5 
     6 Sugared datatype and codatatype constructions.
     7 *)
     8 
     9 signature BNF_FP_DEF_SUGAR =
    10 sig
    11   val fp_sugar_of: Proof.context -> string -> BNF_FP_Util.fp_sugar option
    12   val fp_sugars_of: Proof.context -> BNF_FP_Util.fp_sugar list
    13   val fp_sugar_interpretation: (BNF_FP_Util.fp_sugar list -> theory -> theory) -> theory -> theory
    14   val register_fp_sugars: BNF_FP_Util.fp_sugar list -> local_theory -> local_theory
    15 
    16   val co_induct_of: 'a list -> 'a
    17   val strong_co_induct_of: 'a list -> 'a
    18 
    19   val flat_corec_preds_predsss_gettersss: 'a list -> 'a list list list -> 'a list list list ->
    20     'a list
    21   val nesting_bnfs: Proof.context -> typ list list list -> typ list -> BNF_Def.bnf list
    22 
    23   type lfp_sugar_thms =
    24     (thm list * thm * Args.src list) * (thm list list * Args.src list)
    25 
    26   val morph_lfp_sugar_thms: morphism -> lfp_sugar_thms -> lfp_sugar_thms
    27   val transfer_lfp_sugar_thms: Proof.context -> lfp_sugar_thms -> lfp_sugar_thms
    28 
    29   type gfp_sugar_thms =
    30     ((thm list * thm) list * (Args.src list * Args.src list))
    31     * thm list list
    32     * thm list list
    33     * (thm list list * Args.src list)
    34     * (thm list list list * Args.src list)
    35 
    36   val morph_gfp_sugar_thms: morphism -> gfp_sugar_thms -> gfp_sugar_thms
    37   val transfer_gfp_sugar_thms: Proof.context -> gfp_sugar_thms -> gfp_sugar_thms
    38 
    39   val mk_co_recs_prelims: BNF_Util.fp_kind -> typ list list list -> typ list -> typ list ->
    40      typ list -> typ list -> int list -> int list list -> term list -> Proof.context ->
    41      (term list
    42       * (typ list list * typ list list list list * term list list * term list list list list) option
    43       * (string * term list * term list list
    44          * ((term list list * term list list list) * typ list)) option)
    45      * Proof.context
    46   val repair_nullary_single_ctr: typ list list -> typ list list
    47   val mk_corec_p_pred_types: typ list -> int list -> typ list list
    48   val mk_corec_fun_arg_types: typ list list list -> typ list -> typ list -> typ list -> int list ->
    49     int list list -> term ->
    50     typ list list
    51     * (typ list list list list * typ list list list * typ list list list list * typ list)
    52   val define_rec:
    53     typ list list * typ list list list list * term list list * term list list list list ->
    54     (string -> binding) -> typ list -> typ list -> term list -> term -> Proof.context ->
    55     (term * thm) * Proof.context
    56   val define_corec: 'a * term list * term list list
    57       * ((term list list * term list list list) * typ list) -> (string -> binding) -> 'b list ->
    58     typ list -> term list -> term -> local_theory -> (term * thm) * local_theory
    59   val derive_induct_recs_thms_for_types: BNF_Def.bnf list ->
    60      ('a * typ list list list list * term list list * 'b) option -> thm -> thm list ->
    61      BNF_Def.bnf list -> BNF_Def.bnf list -> typ list -> typ list -> typ list ->
    62      typ list list list -> thm list -> thm list -> thm list -> term list list -> thm list list ->
    63      term list -> thm list -> Proof.context -> lfp_sugar_thms
    64   val derive_coinduct_corecs_thms_for_types: BNF_Def.bnf list ->
    65     string * term list * term list list * ((term list list * term list list list) * typ list) ->
    66     thm -> thm list -> thm list -> thm list -> BNF_Def.bnf list -> typ list -> typ list ->
    67     typ list -> typ list list list -> int list list -> int list list -> int list -> thm list ->
    68     thm list -> (thm -> thm) -> thm list list -> Ctr_Sugar.ctr_sugar list -> term list ->
    69     thm list -> (thm list -> thm list) -> Proof.context -> gfp_sugar_thms
    70 
    71   val co_datatypes: BNF_Util.fp_kind -> (mixfix list -> binding list -> binding list ->
    72       binding list list -> binding list -> (string * sort) list -> typ list * typ list list ->
    73       BNF_Def.bnf list -> BNF_Comp.absT_info list -> local_theory ->
    74       BNF_FP_Util.fp_result * local_theory) ->
    75     (bool * bool)
    76     * ((((((binding option * (typ * sort)) list * binding) * mixfix)
    77          * ((binding, binding * typ) Ctr_Sugar.ctr_spec * mixfix) list) * (binding * binding))
    78        * term list) list ->
    79     local_theory -> local_theory
    80   val parse_co_datatype_cmd: BNF_Util.fp_kind -> (mixfix list -> binding list -> binding list ->
    81       binding list list -> binding list -> (string * sort) list -> typ list * typ list list ->
    82       BNF_Def.bnf list -> BNF_Comp.absT_info list -> local_theory ->
    83       BNF_FP_Util.fp_result * local_theory) ->
    84     (local_theory -> local_theory) parser
    85 end;
    86 
    87 structure BNF_FP_Def_Sugar : BNF_FP_DEF_SUGAR =
    88 struct
    89 
    90 open Ctr_Sugar
    91 open BNF_FP_Rec_Sugar_Util
    92 open BNF_Util
    93 open BNF_Comp
    94 open BNF_Def
    95 open BNF_FP_Util
    96 open BNF_FP_Def_Sugar_Tactics
    97 open BNF_LFP_Size
    98 
    99 val EqN = "Eq_";
   100 
   101 val corec_codeN = "corec_code";
   102 val map_disc_iffN = "map_disc_iff";
   103 val map_selN = "map_sel";
   104 val set_casesN = "set_cases";
   105 val set_emptyN = "set_empty";
   106 val set_introsN = "set_intros";
   107 val set_inductN = "set_induct";
   108 val set_selN = "set_sel";
   109 
   110 structure Data = Generic_Data
   111 (
   112   type T = fp_sugar Symtab.table;
   113   val empty = Symtab.empty;
   114   val extend = I;
   115   fun merge data : T = Symtab.merge (K true) data;
   116 );
   117 
   118 fun zipping_map f =
   119   let
   120     fun zmap _ [] = []
   121       | zmap xs (y :: ys) = f (xs, y, ys) :: zmap (xs @ [y]) ys
   122   in zmap [] end;
   123 
   124 fun choose_binary_fun fs AB =
   125   find_first (fastype_of #> binder_types #> (fn [A, B] => AB = (A, B))) fs;
   126 fun build_binary_fun_app fs a b =
   127   Option.map (rapp b o rapp a) (choose_binary_fun fs (fastype_of a, fastype_of b));
   128 
   129 fun build_the_rel ctxt Rs Ts A B = build_rel ctxt Ts (the o choose_binary_fun Rs) (A, B);
   130 fun build_rel_app ctxt Rs Ts a b = build_the_rel ctxt Rs Ts (fastype_of a) (fastype_of b) $ a $ b;
   131 
   132 val name_of_set = name_of_const "set";
   133 
   134 fun fp_sugar_of ctxt =
   135   Symtab.lookup (Data.get (Context.Proof ctxt))
   136   #> Option.map (transfer_fp_sugar ctxt);
   137 
   138 fun fp_sugars_of ctxt =
   139   Symtab.fold (cons o transfer_fp_sugar ctxt o snd) (Data.get (Context.Proof ctxt)) [];
   140 
   141 fun co_induct_of (i :: _) = i;
   142 fun strong_co_induct_of [_, s] = s;
   143 
   144 structure FP_Sugar_Interpretation = Interpretation
   145 (
   146   type T = fp_sugar list;
   147   val eq: T * T -> bool = op = o pairself (map #T);
   148 );
   149 
   150 fun with_repaired_path f (fp_sugars as ({T = Type (s, _), ...} : fp_sugar) :: _) thy =
   151   thy
   152   |> Sign.root_path
   153   |> Sign.add_path (Long_Name.qualifier s)
   154   |> f fp_sugars
   155   |> Sign.restore_naming thy;
   156 
   157 fun fp_sugar_interpretation f = FP_Sugar_Interpretation.interpretation (with_repaired_path f);
   158 
   159 fun register_fp_sugars (fp_sugars as {fp, ...} :: _) =
   160   fold (fn fp_sugar as {T = Type (s, _), ...} =>
   161       Local_Theory.declaration {syntax = false, pervasive = true}
   162         (fn phi => Data.map (Symtab.update (s, morph_fp_sugar phi fp_sugar))))
   163     fp_sugars
   164   #> fp = Least_FP ? generate_lfp_size fp_sugars
   165   #> Local_Theory.background_theory (FP_Sugar_Interpretation.data fp_sugars);
   166 
   167 fun register_as_fp_sugars Ts BTs Xs fp pre_bnfs absT_infos fp_nesting_bnfs live_nesting_bnfs fp_res
   168     ctrXs_Tsss ctr_defss ctr_sugars co_recs co_rec_defs mapss common_co_inducts co_inductss
   169     co_rec_thmss disc_co_recss sel_co_recsss rel_injectss rel_distinctss noted =
   170   let
   171     val fp_sugars =
   172       map_index (fn (kk, T) =>
   173         {T = T, BT = nth BTs kk, X = nth Xs kk, fp = fp, fp_res = fp_res, fp_res_index = kk,
   174          pre_bnf = nth pre_bnfs kk, absT_info = nth absT_infos kk,
   175          fp_nesting_bnfs = fp_nesting_bnfs, live_nesting_bnfs = live_nesting_bnfs,
   176          ctrXs_Tss = nth ctrXs_Tsss kk, ctr_defs = nth ctr_defss kk, ctr_sugar = nth ctr_sugars kk,
   177          co_rec = nth co_recs kk, co_rec_def = nth co_rec_defs kk, maps = nth mapss kk,
   178          common_co_inducts = common_co_inducts, co_inducts = nth co_inductss kk,
   179          co_rec_thms = nth co_rec_thmss kk, disc_co_recs = nth disc_co_recss kk,
   180          sel_co_recss = nth sel_co_recsss kk, rel_injects = nth rel_injectss kk,
   181          rel_distincts = nth rel_distinctss kk}
   182         |> morph_fp_sugar (substitute_noted_thm noted)) Ts;
   183   in
   184     register_fp_sugars fp_sugars
   185   end;
   186 
   187 (* This function could produce (fairly harmless) clashes in contrived examples (e.g., "x.A",
   188    "x.x_A", "y.A"). *)
   189 fun quasi_unambiguous_case_names names =
   190   let
   191     val ps = map (`Long_Name.base_name) names;
   192     val dups = Library.duplicates (op =) (map fst ps);
   193     fun underscore s =
   194       let val ss = space_explode Long_Name.separator s in
   195         space_implode "_" (drop (length ss - 2) ss)
   196       end;
   197   in
   198     map (fn (base, full) => if member (op =) dups base then underscore full else base) ps
   199   end;
   200 
   201 val mp_conj = @{thm mp_conj};
   202 
   203 val fundefcong_attrs = @{attributes [fundef_cong]};
   204 val nitpicksimp_attrs = @{attributes [nitpick_simp]};
   205 val code_nitpicksimp_attrs = Code.add_default_eqn_attrib :: nitpicksimp_attrs;
   206 val simp_attrs = @{attributes [simp]};
   207 
   208 val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs));
   209 
   210 fun flat_corec_predss_getterss qss gss = maps (op @) (qss ~~ gss);
   211 
   212 fun flat_corec_preds_predsss_gettersss [] [qss] [gss] = flat_corec_predss_getterss qss gss
   213   | flat_corec_preds_predsss_gettersss (p :: ps) (qss :: qsss) (gss :: gsss) =
   214     p :: flat_corec_predss_getterss qss gss @ flat_corec_preds_predsss_gettersss ps qsss gsss;
   215 
   216 fun mk_flip (x, Type (_, [T1, Type (_, [T2, T3])])) =
   217   Abs ("x", T1, Abs ("y", T2, Var (x, T2 --> T1 --> T3) $ Bound 0 $ Bound 1));
   218 
   219 fun flip_rels lthy n thm =
   220   let
   221     val Rs = Term.add_vars (prop_of thm) [];
   222     val Rs' = rev (drop (length Rs - n) Rs);
   223     val cRs = map (fn f => (certify lthy (Var f), certify lthy (mk_flip f))) Rs';
   224   in
   225     Drule.cterm_instantiate cRs thm
   226   end;
   227 
   228 fun mk_ctor_or_dtor get_T Ts t =
   229   let val Type (_, Ts0) = get_T (fastype_of t) in
   230     Term.subst_atomic_types (Ts0 ~~ Ts) t
   231   end;
   232 
   233 val mk_ctor = mk_ctor_or_dtor range_type;
   234 val mk_dtor = mk_ctor_or_dtor domain_type;
   235 
   236 fun mk_xtor_co_recs thy fp fpTs Cs ts0 =
   237   let
   238     val nn = length fpTs;
   239     val (fpTs0, Cs0) =
   240       map ((fp = Greatest_FP ? swap) o dest_funT o snd o strip_typeN nn o fastype_of) ts0
   241       |> split_list;
   242     val rho = tvar_subst thy (fpTs0 @ Cs0) (fpTs @ Cs);
   243   in
   244     map (Term.subst_TVars rho) ts0
   245   end;
   246 
   247 fun mk_set Ts t =
   248   subst_nonatomic_types (snd (Term.dest_Type (domain_type (fastype_of t))) ~~ Ts) t;
   249 
   250 fun unzip_recT (Type (@{type_name prod}, _)) T = [T]
   251   | unzip_recT _ (Type (@{type_name prod}, Ts)) = Ts
   252   | unzip_recT _ T = [T];
   253 
   254 fun unzip_corecT (Type (@{type_name sum}, _)) T = [T]
   255   | unzip_corecT _ (Type (@{type_name sum}, Ts)) = Ts
   256   | unzip_corecT _ T = [T];
   257 
   258 fun liveness_of_fp_bnf n bnf =
   259   (case T_of_bnf bnf of
   260     Type (_, Ts) => map (not o member (op =) (deads_of_bnf bnf)) Ts
   261   | _ => replicate n false);
   262 
   263 fun cannot_merge_types fp =
   264   error ("Mutually " ^ co_prefix fp ^ "recursive types must have the same type parameters");
   265 
   266 fun merge_type_arg fp T T' = if T = T' then T else cannot_merge_types fp;
   267 
   268 fun merge_type_args fp (As, As') =
   269   if length As = length As' then map2 (merge_type_arg fp) As As' else cannot_merge_types fp;
   270 
   271 fun type_args_named_constrained_of_spec (((((ncAs, _), _), _), _), _) = ncAs;
   272 fun type_binding_of_spec (((((_, b), _), _), _), _) = b;
   273 fun mixfix_of_spec ((((_, mx), _), _), _) = mx;
   274 fun mixfixed_ctr_specs_of_spec (((_, mx_ctr_specs), _), _) = mx_ctr_specs;
   275 fun map_binding_of_spec ((_, (b, _)), _) = b;
   276 fun rel_binding_of_spec ((_, (_, b)), _) = b;
   277 fun sel_default_eqs_of_spec (_, ts) = ts;
   278 
   279 fun add_nesting_bnf_names Us =
   280   let
   281     fun add (Type (s, Ts)) ss =
   282         let val (needs, ss') = fold_map add Ts ss in
   283           if exists I needs then (true, insert (op =) s ss') else (false, ss')
   284         end
   285       | add T ss = (member (op =) Us T, ss);
   286   in snd oo add end;
   287 
   288 fun nesting_bnfs ctxt ctr_Tsss Us =
   289   map_filter (bnf_of ctxt) (fold (fold (fold (add_nesting_bnf_names Us))) ctr_Tsss []);
   290 
   291 fun indexify proj xs f p = f (find_index (curry (op =) (proj p)) xs) p;
   292 
   293 type lfp_sugar_thms =
   294   (thm list * thm * Args.src list) * (thm list list * Args.src list);
   295 
   296 fun morph_lfp_sugar_thms phi ((inducts, induct, induct_attrs), (recss, rec_attrs)) =
   297   ((map (Morphism.thm phi) inducts, Morphism.thm phi induct, induct_attrs),
   298    (map (map (Morphism.thm phi)) recss, rec_attrs))
   299   : lfp_sugar_thms;
   300 
   301 val transfer_lfp_sugar_thms =
   302   morph_lfp_sugar_thms o Morphism.transfer_morphism o Proof_Context.theory_of;
   303 
   304 type gfp_sugar_thms =
   305   ((thm list * thm) list * (Args.src list * Args.src list))
   306   * thm list list
   307   * thm list list
   308   * (thm list list * Args.src list)
   309   * (thm list list list * Args.src list);
   310 
   311 fun morph_gfp_sugar_thms phi ((coinducts_pairs, coinduct_attrs_pair),
   312     corecss, corec_discss, (corec_disc_iffss, corec_disc_iff_attrs),
   313     (corec_selsss, corec_sel_attrs)) =
   314   ((map (apfst (map (Morphism.thm phi)) o apsnd (Morphism.thm phi)) coinducts_pairs,
   315     coinduct_attrs_pair),
   316    map (map (Morphism.thm phi)) corecss,
   317    map (map (Morphism.thm phi)) corec_discss,
   318    (map (map (Morphism.thm phi)) corec_disc_iffss, corec_disc_iff_attrs),
   319    (map (map (map (Morphism.thm phi))) corec_selsss, corec_sel_attrs)) : gfp_sugar_thms;
   320 
   321 val transfer_gfp_sugar_thms =
   322   morph_gfp_sugar_thms o Morphism.transfer_morphism o Proof_Context.theory_of;
   323 
   324 fun mk_recs_args_types ctr_Tsss Cs absTs repTs ns mss ctor_rec_fun_Ts lthy =
   325   let
   326     val Css = map2 replicate ns Cs;
   327     val x_Tssss =
   328       map6 (fn absT => fn repT => fn n => fn ms => fn ctr_Tss => fn ctor_rec_fun_T =>
   329           map2 (map2 unzip_recT)
   330             ctr_Tss (dest_absumprodT absT repT n ms (domain_type ctor_rec_fun_T)))
   331         absTs repTs ns mss ctr_Tsss ctor_rec_fun_Ts;
   332 
   333     val x_Tsss' = map (map flat_rec_arg_args) x_Tssss;
   334     val f_Tss = map2 (map2 (curry (op --->))) x_Tsss' Css;
   335 
   336     val ((fss, xssss), lthy) =
   337       lthy
   338       |> mk_Freess "f" f_Tss
   339       ||>> mk_Freessss "x" x_Tssss;
   340   in
   341     ((f_Tss, x_Tssss, fss, xssss), lthy)
   342   end;
   343 
   344 (*avoid "'a itself" arguments in corecursors*)
   345 fun repair_nullary_single_ctr [[]] = [[HOLogic.unitT]]
   346   | repair_nullary_single_ctr Tss = Tss;
   347 
   348 fun mk_corec_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss fun_Ts =
   349   let
   350     val ctr_Tsss' = map repair_nullary_single_ctr ctr_Tsss;
   351     val g_absTs = map range_type fun_Ts;
   352     val g_Tsss = map repair_nullary_single_ctr (map5 dest_absumprodT absTs repTs ns mss g_absTs);
   353     val g_Tssss = map3 (fn C => map2 (map2 (map (curry (op -->) C) oo unzip_corecT)))
   354       Cs ctr_Tsss' g_Tsss;
   355     val q_Tssss = map (map (map (fn [_] => [] | [_, T] => [mk_pred1T (domain_type T)]))) g_Tssss;
   356   in
   357     (q_Tssss, g_Tsss, g_Tssss, g_absTs)
   358   end;
   359 
   360 fun mk_corec_p_pred_types Cs ns = map2 (fn n => replicate (Int.max (0, n - 1)) o mk_pred1T) ns Cs;
   361 
   362 fun mk_corec_fun_arg_types ctr_Tsss Cs absTs repTs ns mss dtor_corec =
   363   (mk_corec_p_pred_types Cs ns,
   364    mk_corec_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss
   365      (binder_fun_types (fastype_of dtor_corec)));
   366 
   367 fun mk_corecs_args_types ctr_Tsss Cs absTs repTs ns mss dtor_corec_fun_Ts lthy =
   368   let
   369     val p_Tss = mk_corec_p_pred_types Cs ns;
   370 
   371     val (q_Tssss, g_Tsss, g_Tssss, corec_types) =
   372       mk_corec_fun_arg_types0 ctr_Tsss Cs absTs repTs ns mss dtor_corec_fun_Ts;
   373 
   374     val (((((Free (x, _), cs), pss), qssss), gssss), lthy) =
   375       lthy
   376       |> yield_singleton (mk_Frees "x") dummyT
   377       ||>> mk_Frees "a" Cs
   378       ||>> mk_Freess "p" p_Tss
   379       ||>> mk_Freessss "q" q_Tssss
   380       ||>> mk_Freessss "g" g_Tssss;
   381 
   382     val cpss = map2 (map o rapp) cs pss;
   383 
   384     fun build_sum_inj mk_inj = build_map lthy [] (uncurry mk_inj o dest_sumT o snd);
   385 
   386     fun build_dtor_corec_arg _ [] [cg] = cg
   387       | build_dtor_corec_arg T [cq] [cg, cg'] =
   388         mk_If cq (build_sum_inj Inl_const (fastype_of cg, T) $ cg)
   389           (build_sum_inj Inr_const (fastype_of cg', T) $ cg');
   390 
   391     val pgss = map3 flat_corec_preds_predsss_gettersss pss qssss gssss;
   392     val cqssss = map2 (map o map o map o rapp) cs qssss;
   393     val cgssss = map2 (map o map o map o rapp) cs gssss;
   394     val cqgsss = map3 (map3 (map3 build_dtor_corec_arg)) g_Tsss cqssss cgssss;
   395   in
   396     ((x, cs, cpss, ((pgss, cqgsss), corec_types)), lthy)
   397   end;
   398 
   399 fun mk_co_recs_prelims fp ctr_Tsss fpTs Cs absTs repTs ns mss xtor_co_recs0 lthy =
   400   let
   401     val thy = Proof_Context.theory_of lthy;
   402 
   403     val (xtor_co_rec_fun_Ts, xtor_co_recs) =
   404       mk_xtor_co_recs thy fp fpTs Cs xtor_co_recs0 |> `(binder_fun_types o fastype_of o hd);
   405 
   406     val ((recs_args_types, corecs_args_types), lthy') =
   407       if fp = Least_FP then
   408         mk_recs_args_types ctr_Tsss Cs absTs repTs ns mss xtor_co_rec_fun_Ts lthy
   409         |>> (rpair NONE o SOME)
   410       else
   411         mk_corecs_args_types ctr_Tsss Cs absTs repTs ns mss xtor_co_rec_fun_Ts lthy
   412         |>> (pair NONE o SOME);
   413   in
   414     ((xtor_co_recs, recs_args_types, corecs_args_types), lthy')
   415   end;
   416 
   417 fun mk_preds_getterss_join c cps absT abs cqgss =
   418   let
   419     val n = length cqgss;
   420     val ts = map2 (mk_absumprod absT abs n) (1 upto n) cqgss;
   421   in
   422     Term.lambda c (mk_IfN absT cps ts)
   423   end;
   424 
   425 fun define_co_rec fp fpT Cs b rhs lthy0 =
   426   let
   427     val thy = Proof_Context.theory_of lthy0;
   428 
   429     val maybe_conceal_def_binding = Thm.def_binding
   430       #> Config.get lthy0 bnf_note_all = false ? Binding.conceal;
   431 
   432     val ((cst, (_, def)), (lthy', lthy)) = lthy0
   433       |> Local_Theory.define ((b, NoSyn), ((maybe_conceal_def_binding b, []), rhs))
   434       ||> `Local_Theory.restore;
   435 
   436     val phi = Proof_Context.export_morphism lthy lthy';
   437 
   438     val cst' = mk_co_rec thy fp fpT Cs (Morphism.term phi cst);
   439     val def' = Morphism.thm phi def;
   440   in
   441     ((cst', def'), lthy')
   442   end;
   443 
   444 fun define_rec (_, _, fss, xssss) mk_binding fpTs Cs reps ctor_rec =
   445   let
   446     val nn = length fpTs;
   447     val (ctor_rec_absTs, fpT) = strip_typeN nn (fastype_of ctor_rec)
   448       |>> map domain_type ||> domain_type;
   449   in
   450     define_co_rec Least_FP fpT Cs (mk_binding recN)
   451       (fold_rev (fold_rev Term.lambda) fss (Term.list_comb (ctor_rec,
   452          map4 (fn ctor_rec_absT => fn rep => fn fs => fn xsss =>
   453              mk_case_absumprod ctor_rec_absT rep fs (map (map HOLogic.mk_tuple) xsss)
   454                (map flat_rec_arg_args xsss))
   455            ctor_rec_absTs reps fss xssss)))
   456   end;
   457 
   458 fun define_corec (_, cs, cpss, ((pgss, cqgsss), f_absTs)) mk_binding fpTs Cs abss dtor_corec =
   459   let
   460     val nn = length fpTs;
   461     val fpT = range_type (snd (strip_typeN nn (fastype_of dtor_corec)));
   462   in
   463     define_co_rec Greatest_FP fpT Cs (mk_binding corecN)
   464       (fold_rev (fold_rev Term.lambda) pgss (Term.list_comb (dtor_corec,
   465          map5 mk_preds_getterss_join cs cpss f_absTs abss cqgsss)))
   466   end;
   467 
   468 fun postproc_co_induct lthy nn prop prop_conj =
   469   Drule.zero_var_indexes
   470   #> `(conj_dests nn)
   471   #>> map (fn thm => Thm.permute_prems 0 (~1) (thm RS prop))
   472   ##> (fn thm => Thm.permute_prems 0 (~nn)
   473     (if nn = 1 then thm RS prop
   474      else funpow nn (fn thm => unfold_thms lthy @{thms conj_assoc} (thm RS prop_conj)) thm));
   475 
   476 fun mk_induct_attrs ctrss =
   477   let
   478     val induct_cases = quasi_unambiguous_case_names (maps (map name_of_ctr) ctrss);
   479     val induct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names induct_cases));
   480   in
   481     [induct_case_names_attr]
   482   end;
   483 
   484 fun derive_rel_induct_thms_for_types lthy fpA_Ts As Bs ctrAss ctrAs_Tsss exhausts ctor_rel_induct
   485     ctor_defss ctor_injects pre_rel_defs abs_inverses live_nesting_rel_eqs =
   486   let
   487     val B_ify = typ_subst_nonatomic (As ~~ Bs)
   488     val fpB_Ts = map B_ify fpA_Ts;
   489     val ctrBs_Tsss = map (map (map B_ify)) ctrAs_Tsss;
   490     val ctrBss = map (map (subst_nonatomic_types (As ~~ Bs))) ctrAss;
   491 
   492     val ((((Rs, IRs), ctrAsss), ctrBsss), names_lthy) = lthy
   493       |> mk_Frees "R" (map2 mk_pred2T As Bs)
   494       ||>> mk_Frees "IR" (map2 mk_pred2T fpA_Ts fpB_Ts)
   495       ||>> mk_Freesss "a" ctrAs_Tsss
   496       ||>> mk_Freesss "b" ctrBs_Tsss;
   497 
   498     val premises =
   499       let
   500         fun mk_prem ctrA ctrB argAs argBs =
   501           fold_rev Logic.all (argAs @ argBs) (fold_rev (curry Logic.mk_implies)
   502             (map2 (HOLogic.mk_Trueprop oo build_rel_app names_lthy (Rs @ IRs) fpA_Ts) argAs argBs)
   503             (HOLogic.mk_Trueprop (build_rel_app names_lthy (Rs @ IRs) fpA_Ts
   504               (Term.list_comb (ctrA, argAs)) (Term.list_comb (ctrB, argBs)))));
   505       in
   506         flat (map4 (map4 mk_prem) ctrAss ctrBss ctrAsss ctrBsss)
   507       end;
   508 
   509     val goal = HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 mk_leq
   510       (map2 (build_the_rel lthy (Rs @ IRs) []) fpA_Ts fpB_Ts) IRs));
   511 
   512     val rel_induct0_thm =
   513       Goal.prove_sorry lthy [] premises goal (fn {context = ctxt, prems} =>
   514         mk_rel_induct0_tac ctxt ctor_rel_induct prems (map (certify ctxt) IRs) exhausts ctor_defss
   515           ctor_injects pre_rel_defs abs_inverses live_nesting_rel_eqs)
   516       |> singleton (Proof_Context.export names_lthy lthy)
   517       |> Thm.close_derivation;
   518   in
   519     (postproc_co_induct lthy (length fpA_Ts) @{thm predicate2D} @{thm predicate2D_conj}
   520        rel_induct0_thm,
   521      mk_induct_attrs ctrAss)
   522   end;
   523 
   524 fun derive_induct_recs_thms_for_types pre_bnfs rec_args_typess ctor_induct ctor_rec_thms
   525     live_nesting_bnfs fp_nesting_bnfs fpTs Cs Xs ctrXs_Tsss fp_abs_inverses fp_type_definitions
   526     abs_inverses ctrss ctr_defss recs rec_defs lthy =
   527   let
   528     val ctr_Tsss = map (map (binder_types o fastype_of)) ctrss;
   529 
   530     val nn = length pre_bnfs;
   531     val ns = map length ctr_Tsss;
   532     val mss = map (map length) ctr_Tsss;
   533 
   534     val pre_map_defs = map map_def_of_bnf pre_bnfs;
   535     val pre_set_defss = map set_defs_of_bnf pre_bnfs;
   536     val live_nesting_map_ident0s = map map_ident0_of_bnf live_nesting_bnfs;
   537     val fp_nesting_map_ident0s = map map_ident0_of_bnf fp_nesting_bnfs;
   538     val fp_nesting_set_maps = maps set_map_of_bnf fp_nesting_bnfs;
   539 
   540     val fp_b_names = map base_name_of_typ fpTs;
   541 
   542     val ((((ps, ps'), xsss), us'), names_lthy) =
   543       lthy
   544       |> mk_Frees' "P" (map mk_pred1T fpTs)
   545       ||>> mk_Freesss "x" ctr_Tsss
   546       ||>> Variable.variant_fixes fp_b_names;
   547 
   548     val us = map2 (curry Free) us' fpTs;
   549 
   550     fun mk_sets bnf =
   551       let
   552         val Type (T_name, Us) = T_of_bnf bnf;
   553         val lives = lives_of_bnf bnf;
   554         val sets = sets_of_bnf bnf;
   555         fun mk_set U =
   556           (case find_index (curry (op =) U) lives of
   557             ~1 => Term.dummy
   558           | i => nth sets i);
   559       in
   560         (T_name, map mk_set Us)
   561       end;
   562 
   563     val setss_fp_nesting = map mk_sets fp_nesting_bnfs;
   564 
   565     val (induct_thms, induct_thm) =
   566       let
   567         fun mk_raw_prem_prems _ (x as Free (_, Type _)) (X as TFree _) =
   568             [([], (find_index (curry (op =) X) Xs + 1, x))]
   569           | mk_raw_prem_prems names_lthy (x as Free (s, Type (T_name, Ts0))) (Type (_, Xs_Ts0)) =
   570             (case AList.lookup (op =) setss_fp_nesting T_name of
   571               NONE => []
   572             | SOME raw_sets0 =>
   573               let
   574                 val (Xs_Ts, (Ts, raw_sets)) =
   575                   filter (exists_subtype_in Xs o fst) (Xs_Ts0 ~~ (Ts0 ~~ raw_sets0))
   576                   |> split_list ||> split_list;
   577                 val sets = map (mk_set Ts0) raw_sets;
   578                 val (ys, names_lthy') = names_lthy |> mk_Frees s Ts;
   579                 val xysets = map (pair x) (ys ~~ sets);
   580                 val ppremss = map2 (mk_raw_prem_prems names_lthy') ys Xs_Ts;
   581               in
   582                 flat (map2 (map o apfst o cons) xysets ppremss)
   583               end)
   584           | mk_raw_prem_prems _ _ _ = [];
   585 
   586         fun close_prem_prem xs t =
   587           fold_rev Logic.all (map Free (drop (nn + length xs)
   588             (rev (Term.add_frees t (map dest_Free xs @ ps'))))) t;
   589 
   590         fun mk_prem_prem xs (xysets, (j, x)) =
   591           close_prem_prem xs (Logic.list_implies (map (fn (x', (y, set)) =>
   592               mk_Trueprop_mem (y, set $ x')) xysets,
   593             HOLogic.mk_Trueprop (nth ps (j - 1) $ x)));
   594 
   595         fun mk_raw_prem phi ctr ctr_Ts ctrXs_Ts =
   596           let
   597             val (xs, names_lthy') = names_lthy |> mk_Frees "x" ctr_Ts;
   598             val pprems = flat (map2 (mk_raw_prem_prems names_lthy') xs ctrXs_Ts);
   599           in (xs, pprems, HOLogic.mk_Trueprop (phi $ Term.list_comb (ctr, xs))) end;
   600 
   601         fun mk_prem (xs, raw_pprems, concl) =
   602           fold_rev Logic.all xs (Logic.list_implies (map (mk_prem_prem xs) raw_pprems, concl));
   603 
   604         val raw_premss = map4 (map3 o mk_raw_prem) ps ctrss ctr_Tsss ctrXs_Tsss;
   605 
   606         val goal =
   607           Library.foldr (Logic.list_implies o apfst (map mk_prem)) (raw_premss,
   608             HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 (curry (op $)) ps us)));
   609 
   610         val kksss = map (map (map (fst o snd) o #2)) raw_premss;
   611 
   612         val ctor_induct' = ctor_induct OF (map2 mk_absumprodE fp_type_definitions mss);
   613 
   614         val thm =
   615           Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   616             mk_induct_tac ctxt nn ns mss kksss (flat ctr_defss) ctor_induct' fp_abs_inverses
   617               abs_inverses fp_nesting_set_maps pre_set_defss)
   618           |> singleton (Proof_Context.export names_lthy lthy);
   619       in
   620         `(conj_dests nn) thm
   621       end;
   622 
   623     val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
   624 
   625     fun mk_rec_thmss (_, x_Tssss, fss, _) recs rec_defs ctor_rec_thms =
   626       let
   627         val frecs = map (lists_bmoc fss) recs;
   628 
   629         fun mk_goal frec xctr f xs fxs =
   630           fold_rev (fold_rev Logic.all) (xs :: fss)
   631             (mk_Trueprop_eq (frec $ xctr, Term.list_comb (f, fxs)));
   632 
   633         fun maybe_tick (T, U) u f =
   634           if try (fst o HOLogic.dest_prodT) U = SOME T then
   635             Term.lambda u (HOLogic.mk_prod (u, f $ u))
   636           else
   637             f;
   638 
   639         fun build_rec (x as Free (_, T)) U =
   640           if T = U then
   641             x
   642           else
   643             build_map lthy [] (indexify (perhaps (try (snd o HOLogic.dest_prodT)) o snd) Cs
   644               (fn kk => fn TU => maybe_tick TU (nth us kk) (nth frecs kk))) (T, U) $ x;
   645 
   646         val fxsss = map2 (map2 (flat_rec_arg_args oo map2 (map o build_rec))) xsss x_Tssss;
   647         val goalss = map5 (map4 o mk_goal) frecs xctrss fss xsss fxsss;
   648 
   649         val tacss = map4 (map ooo
   650               mk_rec_tac pre_map_defs (fp_nesting_map_ident0s @ live_nesting_map_ident0s) rec_defs)
   651             ctor_rec_thms fp_abs_inverses abs_inverses ctr_defss;
   652 
   653         fun prove goal tac =
   654           Goal.prove_sorry lthy [] [] goal (tac o #context)
   655           |> Thm.close_derivation;
   656       in
   657         map2 (map2 prove) goalss tacss
   658       end;
   659 
   660     val rec_thmss = mk_rec_thmss (the rec_args_typess) recs rec_defs ctor_rec_thms;
   661   in
   662     ((induct_thms, induct_thm, mk_induct_attrs ctrss),
   663      (rec_thmss, code_nitpicksimp_attrs @ simp_attrs))
   664   end;
   665 
   666 fun mk_coinduct_attributes fpTs ctrss discss mss =
   667   let
   668     val nn = length fpTs;
   669     val fp_b_names = map base_name_of_typ fpTs;
   670 
   671     fun mk_coinduct_concls ms discs ctrs =
   672       let
   673         fun mk_disc_concl disc = [name_of_disc disc];
   674         fun mk_ctr_concl 0 _ = []
   675           | mk_ctr_concl _ ctor = [name_of_ctr ctor];
   676         val disc_concls = map mk_disc_concl (fst (split_last discs)) @ [[]];
   677         val ctr_concls = map2 mk_ctr_concl ms ctrs;
   678       in
   679         flat (map2 append disc_concls ctr_concls)
   680       end;
   681 
   682     val coinduct_cases = quasi_unambiguous_case_names (map (prefix EqN) fp_b_names);
   683     val coinduct_conclss =
   684       map3 (quasi_unambiguous_case_names ooo mk_coinduct_concls) mss discss ctrss;
   685 
   686     val common_coinduct_consumes_attr = Attrib.internal (K (Rule_Cases.consumes nn));
   687     val coinduct_consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
   688 
   689     val coinduct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names coinduct_cases));
   690     val coinduct_case_concl_attrs =
   691       map2 (fn casex => fn concls =>
   692           Attrib.internal (K (Rule_Cases.case_conclusion (casex, concls))))
   693         coinduct_cases coinduct_conclss;
   694 
   695     val common_coinduct_attrs =
   696       common_coinduct_consumes_attr :: coinduct_case_names_attr :: coinduct_case_concl_attrs;
   697     val coinduct_attrs =
   698       coinduct_consumes_attr :: coinduct_case_names_attr :: coinduct_case_concl_attrs;
   699   in
   700     (coinduct_attrs, common_coinduct_attrs)
   701   end;
   702 
   703 fun derive_rel_coinduct_thm_for_types lthy fpA_Ts ns As Bs mss (ctr_sugars : ctr_sugar list)
   704     abs_inverses abs_injects ctor_injects dtor_ctors rel_pre_defs ctor_defss dtor_rel_coinduct
   705     live_nesting_rel_eqs =
   706   let
   707     val fpB_Ts = map (typ_subst_nonatomic (As ~~ Bs)) fpA_Ts;
   708 
   709     val (Rs, IRs, fpAs, fpBs, names_lthy) =
   710       let
   711         val fp_names = map base_name_of_typ fpA_Ts;
   712         val ((((Rs, IRs), fpAs_names), fpBs_names), names_lthy) = lthy
   713           |> mk_Frees "R" (map2 mk_pred2T As Bs)
   714           ||>> mk_Frees "IR" (map2 mk_pred2T fpA_Ts fpB_Ts)
   715           ||>> Variable.variant_fixes fp_names
   716           ||>> Variable.variant_fixes (map (suffix "'") fp_names);
   717       in
   718         (Rs, IRs,
   719           map2 (curry Free) fpAs_names fpA_Ts,
   720           map2 (curry Free) fpBs_names fpB_Ts,
   721           names_lthy)
   722       end;
   723 
   724     val ((discA_tss, selA_tsss), (discB_tss, selB_tsss)) =
   725       let
   726         val discss = map #discs ctr_sugars;
   727         val selsss = map #selss ctr_sugars;
   728         fun mk_discss ts Ts = map2 (map o rapp) ts (map (map (mk_disc_or_sel Ts)) discss);
   729         fun mk_selsss ts Ts = map2 (map o map o rapp) ts (map (map (map (mk_disc_or_sel Ts)))
   730           selsss);
   731       in
   732         ((mk_discss fpAs As, mk_selsss fpAs As),
   733          (mk_discss fpBs Bs, mk_selsss fpBs Bs))
   734       end;
   735 
   736     val premises =
   737       let
   738         fun mk_prem_ctr_concls n k discA_t selA_ts discB_t selB_ts =
   739           (if k = n then [] else [HOLogic.mk_eq (discA_t, discB_t)]) @
   740           (case (selA_ts, selB_ts) of
   741             ([], []) => []
   742           | (_ :: _, _ :: _) =>
   743             [Library.foldr HOLogic.mk_imp
   744               (if n = 1 then [] else [discA_t, discB_t],
   745                Library.foldr1 HOLogic.mk_conj
   746                  (map2 (build_rel_app lthy (Rs @ IRs) fpA_Ts) selA_ts selB_ts))]);
   747 
   748         fun mk_prem_concl n discA_ts selA_tss discB_ts selB_tss =
   749           Library.foldr1 HOLogic.mk_conj (flat (map5 (mk_prem_ctr_concls n)
   750             (1 upto n) discA_ts selA_tss discB_ts selB_tss))
   751           handle List.Empty => @{term True};
   752 
   753         fun mk_prem IR tA tB n discA_ts selA_tss discB_ts selB_tss =
   754           fold_rev Logic.all [tA, tB] (Logic.mk_implies (HOLogic.mk_Trueprop (IR $ tA $ tB),
   755             HOLogic.mk_Trueprop (mk_prem_concl n discA_ts selA_tss discB_ts selB_tss)));
   756       in
   757         map8 mk_prem IRs fpAs fpBs ns discA_tss selA_tsss discB_tss selB_tsss
   758       end;
   759 
   760     val goal = HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 mk_leq
   761       IRs (map2 (build_the_rel lthy (Rs @ IRs) []) fpA_Ts fpB_Ts)));
   762 
   763     val rel_coinduct0_thm =
   764       Goal.prove_sorry lthy [] premises goal (fn {context = ctxt, prems} =>
   765         mk_rel_coinduct0_tac ctxt dtor_rel_coinduct (map (certify ctxt) IRs) prems
   766           (map #exhaust ctr_sugars) (map (flat o #disc_thmss) ctr_sugars)
   767           (map (flat o #sel_thmss) ctr_sugars) ctor_defss dtor_ctors ctor_injects abs_injects
   768           rel_pre_defs abs_inverses live_nesting_rel_eqs)
   769       |> singleton (Proof_Context.export names_lthy lthy)
   770       |> Thm.close_derivation;
   771   in
   772     (postproc_co_induct lthy (length fpA_Ts) @{thm predicate2D} @{thm predicate2D_conj}
   773        rel_coinduct0_thm,
   774      mk_coinduct_attributes fpA_Ts (map #ctrs ctr_sugars) (map #discs ctr_sugars) mss)
   775   end;
   776 
   777 fun derive_set_induct_thms_for_types lthy nn fpTs ctrss setss dtor_set_inducts exhausts
   778     set_pre_defs ctor_defs dtor_ctors Abs_pre_inverses =
   779   let
   780     fun mk_prems A Ps ctr_args t ctxt =
   781       (case fastype_of t of
   782         Type (type_name, innerTs) =>
   783         (case bnf_of ctxt type_name of
   784           NONE => ([], ctxt)
   785         | SOME bnf =>
   786           let
   787             fun seq_assm a set ctxt =
   788               let
   789                 val X = HOLogic.dest_setT (range_type (fastype_of set));
   790                 val (x, ctxt') = yield_singleton (mk_Frees "x") X ctxt;
   791                 val assm = mk_Trueprop_mem (x, set $ a);
   792               in
   793                 (case build_binary_fun_app Ps x a of
   794                   NONE =>
   795                   mk_prems A Ps ctr_args x ctxt'
   796                   |>> map (Logic.all x o Logic.mk_implies o pair assm)
   797                 | SOME f =>
   798                   ([Logic.all x
   799                       (Logic.mk_implies (assm,
   800                          Logic.mk_implies (HOLogic.mk_Trueprop f,
   801                            HOLogic.mk_Trueprop (the (build_binary_fun_app Ps x ctr_args)))))],
   802                    ctxt'))
   803               end;
   804           in
   805             fold_map (seq_assm t o mk_set innerTs) (sets_of_bnf bnf) ctxt
   806             |>> flat
   807           end)
   808       | T =>
   809         if T = A then ([HOLogic.mk_Trueprop (the (build_binary_fun_app Ps t ctr_args))], ctxt)
   810         else ([], ctxt));
   811 
   812     fun mk_prems_for_ctr A Ps ctr ctxt =
   813       let
   814         val (args, ctxt') = mk_Frees "z" (binder_types (fastype_of ctr)) ctxt;
   815       in
   816         fold_map (mk_prems A Ps (list_comb (ctr, args))) args ctxt'
   817         |>> map (fold_rev Logic.all args) o flat
   818         |>> (fn prems => (prems, mk_names (length prems) (name_of_ctr ctr)))
   819       end;
   820 
   821     fun mk_prems_and_concl_for_type A Ps ((fpT, ctrs), set) ctxt =
   822       let
   823         val ((x, fp), ctxt') = ctxt
   824           |> yield_singleton (mk_Frees "x") A
   825           ||>> yield_singleton (mk_Frees "a") fpT;
   826         val concl = mk_Ball (set $ fp) (Term.absfree (dest_Free x)
   827           (the (build_binary_fun_app Ps x fp)));
   828       in
   829         fold_map (mk_prems_for_ctr A Ps) ctrs ctxt'
   830         |>> split_list
   831         |>> map_prod flat flat
   832         |>> apfst (rpair concl)
   833       end;
   834 
   835     fun mk_thm ctxt fpTs ctrss sets =
   836       let
   837         val A = HOLogic.dest_setT (range_type (fastype_of (hd sets)));
   838         val (Ps, ctxt') = mk_Frees "P" (map (fn fpT => A --> fpT --> HOLogic.boolT) fpTs) ctxt;
   839         val (((premises, conclusion), case_names), ctxt'') =
   840           (fold_map (mk_prems_and_concl_for_type A Ps) (fpTs ~~ ctrss ~~ sets) ctxt')
   841           |>> apfst split_list o split_list
   842           |>> apfst (apfst flat)
   843           |>> apfst (apsnd (Library.foldr1 HOLogic.mk_conj))
   844           |>> apsnd flat;
   845 
   846         val thm =
   847           Goal.prove_sorry lthy [] premises (HOLogic.mk_Trueprop conclusion)
   848             (fn {context = ctxt, prems} =>
   849                mk_set_induct0_tac ctxt (map (certify ctxt'') Ps) prems dtor_set_inducts exhausts
   850                  set_pre_defs ctor_defs dtor_ctors Abs_pre_inverses)
   851           |> singleton (Proof_Context.export ctxt'' ctxt)
   852           |> Thm.close_derivation;
   853 
   854         val case_names_attr =
   855           Attrib.internal (K (Rule_Cases.case_names (quasi_unambiguous_case_names case_names)));
   856         val induct_set_attrs = map (Attrib.internal o K o Induct.induct_pred o name_of_set) sets;
   857       in
   858         (thm, case_names_attr :: induct_set_attrs)
   859       end
   860     val consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
   861   in
   862     map (fn Asets =>
   863       let
   864         fun massage_thm thm = rotate_prems (~1) (thm RS bspec);
   865       in
   866         mk_thm lthy fpTs ctrss Asets |> nn = 1 ? map_prod massage_thm (cons consumes_attr)
   867       end) (transpose setss)
   868   end;
   869 
   870 fun derive_coinduct_corecs_thms_for_types pre_bnfs (x, cs, cpss, ((pgss, cqgsss), _))
   871     dtor_coinduct dtor_injects dtor_ctors dtor_corec_thms live_nesting_bnfs fpTs Cs Xs ctrXs_Tsss
   872     kss mss ns fp_abs_inverses abs_inverses mk_vimage2p ctr_defss (ctr_sugars : ctr_sugar list)
   873     corecs corec_defs export_args lthy =
   874   let
   875     fun mk_ctor_dtor_corec_thm dtor_inject dtor_ctor corec =
   876       iffD1 OF [dtor_inject, trans OF [corec, dtor_ctor RS sym]];
   877 
   878     val ctor_dtor_corec_thms = map3 mk_ctor_dtor_corec_thm dtor_injects dtor_ctors dtor_corec_thms;
   879 
   880     val nn = length pre_bnfs;
   881 
   882     val pre_map_defs = map map_def_of_bnf pre_bnfs;
   883     val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
   884     val live_nesting_map_ident0s = map map_ident0_of_bnf live_nesting_bnfs;
   885     val live_nesting_rel_eqs = map rel_eq_of_bnf live_nesting_bnfs;
   886 
   887     val fp_b_names = map base_name_of_typ fpTs;
   888 
   889     val ctrss = map #ctrs ctr_sugars;
   890     val discss = map #discs ctr_sugars;
   891     val selsss = map #selss ctr_sugars;
   892     val exhausts = map #exhaust ctr_sugars;
   893     val disc_thmsss = map #disc_thmss ctr_sugars;
   894     val discIss = map #discIs ctr_sugars;
   895     val sel_thmsss = map #sel_thmss ctr_sugars;
   896 
   897     val (((rs, us'), vs'), names_lthy) =
   898       lthy
   899       |> mk_Frees "R" (map (fn T => mk_pred2T T T) fpTs)
   900       ||>> Variable.variant_fixes fp_b_names
   901       ||>> Variable.variant_fixes (map (suffix "'") fp_b_names);
   902 
   903     val us = map2 (curry Free) us' fpTs;
   904     val udiscss = map2 (map o rapp) us discss;
   905     val uselsss = map2 (map o map o rapp) us selsss;
   906 
   907     val vs = map2 (curry Free) vs' fpTs;
   908     val vdiscss = map2 (map o rapp) vs discss;
   909     val vselsss = map2 (map o map o rapp) vs selsss;
   910 
   911     val coinduct_thms_pairs =
   912       let
   913         val uvrs = map3 (fn r => fn u => fn v => r $ u $ v) rs us vs;
   914         val uv_eqs = map2 (curry HOLogic.mk_eq) us vs;
   915         val strong_rs =
   916           map4 (fn u => fn v => fn uvr => fn uv_eq =>
   917             fold_rev Term.lambda [u, v] (HOLogic.mk_disj (uvr, uv_eq))) us vs uvrs uv_eqs;
   918 
   919         fun build_the_rel rs' T Xs_T =
   920           build_rel lthy [] (fn (_, X) => nth rs' (find_index (curry (op =) X) Xs)) (T, Xs_T)
   921           |> Term.subst_atomic_types (Xs ~~ fpTs);
   922 
   923         fun build_rel_app rs' usel vsel Xs_T =
   924           fold rapp [usel, vsel] (build_the_rel rs' (fastype_of usel) Xs_T);
   925 
   926         fun mk_prem_ctr_concls rs' n k udisc usels vdisc vsels ctrXs_Ts =
   927           (if k = n then [] else [HOLogic.mk_eq (udisc, vdisc)]) @
   928           (if null usels then
   929              []
   930            else
   931              [Library.foldr HOLogic.mk_imp (if n = 1 then [] else [udisc, vdisc],
   932                 Library.foldr1 HOLogic.mk_conj (map3 (build_rel_app rs') usels vsels ctrXs_Ts))]);
   933 
   934         fun mk_prem_concl rs' n udiscs uselss vdiscs vselss ctrXs_Tss =
   935           Library.foldr1 HOLogic.mk_conj (flat (map6 (mk_prem_ctr_concls rs' n)
   936             (1 upto n) udiscs uselss vdiscs vselss ctrXs_Tss))
   937           handle List.Empty => @{term True};
   938 
   939         fun mk_prem rs' uvr u v n udiscs uselss vdiscs vselss ctrXs_Tss =
   940           fold_rev Logic.all [u, v] (Logic.mk_implies (HOLogic.mk_Trueprop uvr,
   941             HOLogic.mk_Trueprop (mk_prem_concl rs' n udiscs uselss vdiscs vselss ctrXs_Tss)));
   942 
   943         val concl =
   944           HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
   945             (map3 (fn uvr => fn u => fn v => HOLogic.mk_imp (uvr, HOLogic.mk_eq (u, v)))
   946                uvrs us vs));
   947 
   948         fun mk_goal rs' =
   949           Logic.list_implies (map9 (mk_prem rs') uvrs us vs ns udiscss uselsss vdiscss vselsss
   950             ctrXs_Tsss, concl);
   951 
   952         val goals = map mk_goal [rs, strong_rs];
   953 
   954         fun prove dtor_coinduct' goal =
   955           Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   956             mk_coinduct_tac ctxt live_nesting_rel_eqs nn ns dtor_coinduct' pre_rel_defs
   957               fp_abs_inverses abs_inverses dtor_ctors exhausts ctr_defss disc_thmsss sel_thmsss)
   958           |> singleton (Proof_Context.export names_lthy lthy)
   959           |> Thm.close_derivation;
   960 
   961         val rel_eqs = map rel_eq_of_bnf pre_bnfs;
   962         val rel_monos = map rel_mono_of_bnf pre_bnfs;
   963         val dtor_coinducts =
   964           [dtor_coinduct, mk_coinduct_strong_thm dtor_coinduct rel_eqs rel_monos mk_vimage2p lthy]
   965       in
   966         map2 (postproc_co_induct lthy nn mp mp_conj oo prove) dtor_coinducts goals
   967       end;
   968 
   969     fun mk_maybe_not pos = not pos ? HOLogic.mk_not;
   970 
   971     val gcorecs = map (lists_bmoc pgss) corecs;
   972 
   973     val corec_thmss =
   974       let
   975         fun mk_goal c cps gcorec n k ctr m cfs' =
   976           fold_rev (fold_rev Logic.all) ([c] :: pgss)
   977             (Logic.list_implies (seq_conds (HOLogic.mk_Trueprop oo mk_maybe_not) n k cps,
   978                mk_Trueprop_eq (gcorec $ c, Term.list_comb (ctr, take m cfs'))));
   979 
   980         val mk_U = typ_subst_nonatomic (map2 (fn C => fn fpT => (mk_sumT (fpT, C), fpT)) Cs fpTs);
   981 
   982         fun tack (c, u) f =
   983           let val x' = Free (x, mk_sumT (fastype_of u, fastype_of c)) in
   984             Term.lambda x' (mk_case_sum (Term.lambda u u, Term.lambda c (f $ c)) $ x')
   985           end;
   986 
   987         fun build_corec cqg =
   988           let val T = fastype_of cqg in
   989             if exists_subtype_in Cs T then
   990               let val U = mk_U T in
   991                 build_map lthy [] (indexify fst (map2 (curry mk_sumT) fpTs Cs) (fn kk => fn _ =>
   992                   tack (nth cs kk, nth us kk) (nth gcorecs kk))) (T, U) $ cqg
   993               end
   994             else
   995               cqg
   996           end;
   997 
   998         val cqgsss' = map (map (map build_corec)) cqgsss;
   999         val goalss = map8 (map4 oooo mk_goal) cs cpss gcorecs ns kss ctrss mss cqgsss';
  1000 
  1001         val tacss =
  1002           map4 (map ooo mk_corec_tac corec_defs live_nesting_map_ident0s)
  1003             ctor_dtor_corec_thms pre_map_defs abs_inverses ctr_defss;
  1004 
  1005         fun prove goal tac =
  1006           Goal.prove_sorry lthy [] [] goal (tac o #context)
  1007           |> Thm.close_derivation;
  1008       in
  1009         map2 (map2 prove) goalss tacss
  1010         |> map (map (unfold_thms lthy @{thms case_sum_if}))
  1011       end;
  1012 
  1013     val corec_disc_iff_thmss =
  1014       let
  1015         fun mk_goal c cps gcorec n k disc =
  1016           mk_Trueprop_eq (disc $ (gcorec $ c),
  1017             if n = 1 then @{const True}
  1018             else Library.foldr1 HOLogic.mk_conj (seq_conds mk_maybe_not n k cps));
  1019 
  1020         val goalss = map6 (map2 oooo mk_goal) cs cpss gcorecs ns kss discss;
  1021 
  1022         fun mk_case_split' cp = Drule.instantiate' [] [SOME (certify lthy cp)] @{thm case_split};
  1023 
  1024         val case_splitss' = map (map mk_case_split') cpss;
  1025 
  1026         val tacss = map3 (map oo mk_corec_disc_iff_tac) case_splitss' corec_thmss disc_thmsss;
  1027 
  1028         fun prove goal tac =
  1029           Goal.prove_sorry lthy [] [] goal (tac o #context)
  1030           |> singleton export_args
  1031           |> singleton (Proof_Context.export names_lthy lthy)
  1032           |> Thm.close_derivation;
  1033 
  1034         fun proves [_] [_] = []
  1035           | proves goals tacs = map2 prove goals tacs;
  1036       in
  1037         map2 proves goalss tacss
  1038       end;
  1039 
  1040     fun mk_corec_disc_thms corecs discIs = map (op RS) (corecs ~~ discIs);
  1041 
  1042     val corec_disc_thmss = map2 mk_corec_disc_thms corec_thmss discIss;
  1043 
  1044     fun mk_corec_sel_thm corec_thm sel sel_thm =
  1045       let
  1046         val (domT, ranT) = dest_funT (fastype_of sel);
  1047         val arg_cong' =
  1048           Drule.instantiate' (map (SOME o certifyT lthy) [domT, ranT])
  1049             [NONE, NONE, SOME (certify lthy sel)] arg_cong
  1050           |> Thm.varifyT_global;
  1051         val sel_thm' = sel_thm RSN (2, trans);
  1052       in
  1053         corec_thm RS arg_cong' RS sel_thm'
  1054       end;
  1055 
  1056     fun mk_corec_sel_thms corec_thmss =
  1057       map3 (map3 (map2 o mk_corec_sel_thm)) corec_thmss selsss sel_thmsss;
  1058 
  1059     val corec_sel_thmsss = mk_corec_sel_thms corec_thmss;
  1060   in
  1061     ((coinduct_thms_pairs,
  1062       mk_coinduct_attributes fpTs (map #ctrs ctr_sugars) (map #discs ctr_sugars) mss),
  1063      corec_thmss,
  1064      corec_disc_thmss,
  1065      (corec_disc_iff_thmss, simp_attrs),
  1066      (corec_sel_thmsss, simp_attrs))
  1067   end;
  1068 
  1069 fun define_co_datatypes prepare_constraint prepare_typ prepare_term fp construct_fp
  1070     ((discs_sels0, no_code), specs) no_defs_lthy0 =
  1071   let
  1072     (* TODO: sanity checks on arguments *)
  1073 
  1074     val discs_sels = discs_sels0 orelse fp = Greatest_FP;
  1075 
  1076     val nn = length specs;
  1077     val fp_bs = map type_binding_of_spec specs;
  1078     val fp_b_names = map Binding.name_of fp_bs;
  1079     val fp_common_name = mk_common_name fp_b_names;
  1080     val map_bs = map map_binding_of_spec specs;
  1081     val rel_bs = map rel_binding_of_spec specs;
  1082 
  1083     fun prepare_type_arg (_, (ty, c)) =
  1084       let val TFree (s, _) = prepare_typ no_defs_lthy0 ty in
  1085         TFree (s, prepare_constraint no_defs_lthy0 c)
  1086       end;
  1087 
  1088     val Ass0 = map (map prepare_type_arg o type_args_named_constrained_of_spec) specs;
  1089     val unsorted_Ass0 = map (map (resort_tfree @{sort type})) Ass0;
  1090     val unsorted_As = Library.foldr1 (merge_type_args fp) unsorted_Ass0;
  1091     val num_As = length unsorted_As;
  1092 
  1093     val set_boss = map (map fst o type_args_named_constrained_of_spec) specs;
  1094     val set_bss = map (map (the_default Binding.empty)) set_boss;
  1095 
  1096     val (((Bs0, Cs), Xs), no_defs_lthy) =
  1097       no_defs_lthy0
  1098       |> fold (Variable.declare_typ o resort_tfree dummyS) unsorted_As
  1099       |> mk_TFrees num_As
  1100       ||>> mk_TFrees nn
  1101       ||>> variant_tfrees fp_b_names;
  1102 
  1103     fun add_fake_type spec =
  1104       Typedecl.basic_typedecl (type_binding_of_spec spec, num_As, mixfix_of_spec spec);
  1105 
  1106     val (fake_T_names, fake_lthy) = fold_map add_fake_type specs no_defs_lthy0;
  1107 
  1108     val qsoty = quote o Syntax.string_of_typ fake_lthy;
  1109 
  1110     val _ = (case Library.duplicates (op =) unsorted_As of [] => ()
  1111       | A :: _ => error ("Duplicate type parameter " ^ qsoty A ^ " in " ^ co_prefix fp ^
  1112           "datatype specification"));
  1113 
  1114     val bad_args =
  1115       map (Logic.type_map (singleton (Variable.polymorphic no_defs_lthy0))) unsorted_As
  1116       |> filter_out Term.is_TVar;
  1117     val _ = null bad_args orelse
  1118       error ("Locally fixed type argument " ^ qsoty (hd bad_args) ^ " in " ^ co_prefix fp ^
  1119         "datatype specification");
  1120 
  1121     val mixfixes = map mixfix_of_spec specs;
  1122 
  1123     val _ = (case Library.duplicates Binding.eq_name fp_bs of [] => ()
  1124       | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
  1125 
  1126     val mx_ctr_specss = map mixfixed_ctr_specs_of_spec specs;
  1127     val ctr_specss = map (map fst) mx_ctr_specss;
  1128     val ctr_mixfixess = map (map snd) mx_ctr_specss;
  1129 
  1130     val disc_bindingss = map (map disc_of_ctr_spec) ctr_specss;
  1131     val ctr_bindingss =
  1132       map2 (fn fp_b_name => map (Binding.qualify false fp_b_name o ctr_of_ctr_spec)) fp_b_names
  1133         ctr_specss;
  1134     val ctr_argsss = map (map args_of_ctr_spec) ctr_specss;
  1135 
  1136     val sel_bindingsss = map (map (map fst)) ctr_argsss;
  1137     val fake_ctr_Tsss0 = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
  1138     val raw_sel_default_eqss = map sel_default_eqs_of_spec specs;
  1139 
  1140     val (As :: _) :: fake_ctr_Tsss =
  1141       burrow (burrow (Syntax.check_typs fake_lthy)) (Ass0 :: fake_ctr_Tsss0);
  1142     val As' = map dest_TFree As;
  1143 
  1144     val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
  1145     val _ = (case subtract (op =) As' rhs_As' of [] => ()
  1146       | extras => error ("Extra type variables on right-hand side: " ^
  1147           commas (map (qsoty o TFree) extras)));
  1148 
  1149     val fake_Ts = map (fn s => Type (s, As)) fake_T_names;
  1150 
  1151     fun eq_fpT_check (T as Type (s, Ts)) (T' as Type (s', Ts')) =
  1152         s = s' andalso (Ts = Ts' orelse
  1153           error ("Wrong type arguments in " ^ co_prefix fp ^ "recursive type " ^ qsoty T ^
  1154             " (expected " ^ qsoty T' ^ ")"))
  1155       | eq_fpT_check _ _ = false;
  1156 
  1157     fun freeze_fp (T as Type (s, Ts)) =
  1158         (case find_index (eq_fpT_check T) fake_Ts of
  1159           ~1 => Type (s, map freeze_fp Ts)
  1160         | kk => nth Xs kk)
  1161       | freeze_fp T = T;
  1162 
  1163     val unfreeze_fp = Term.typ_subst_atomic (Xs ~~ fake_Ts);
  1164 
  1165     val ctrXs_Tsss = map (map (map freeze_fp)) fake_ctr_Tsss;
  1166     val ctrXs_repTs = map mk_sumprodT_balanced ctrXs_Tsss;
  1167 
  1168     val fp_eqs =
  1169       map dest_TFree Xs ~~ map (Term.typ_subst_atomic (As ~~ unsorted_As)) ctrXs_repTs;
  1170 
  1171     val rhsXs_As' = fold (fold (fold Term.add_tfreesT)) ctrXs_Tsss [];
  1172     val _ = (case subtract (op =) rhsXs_As' As' of [] => ()
  1173       | extras => List.app (fn extra => warning ("Unused type variable on right-hand side of " ^
  1174           co_prefix fp ^ "datatype definition: " ^ qsoty (TFree extra))) extras);
  1175 
  1176     val killed_As =
  1177       map_filter (fn (A, set_bos) => if exists is_none set_bos then SOME A else NONE)
  1178         (unsorted_As ~~ transpose set_boss);
  1179 
  1180     val ((pre_bnfs, absT_infos), (fp_res as {bnfs = fp_bnfs as any_fp_bnf :: _, ctors = ctors0,
  1181              dtors = dtors0, xtor_co_recs = xtor_co_recs0, xtor_co_induct, dtor_ctors,
  1182              ctor_dtors, ctor_injects, dtor_injects, xtor_map_thms, xtor_set_thmss, xtor_rel_thms,
  1183              xtor_co_rec_thms, rel_xtor_co_induct_thm, dtor_set_induct_thms, ...},
  1184            lthy)) =
  1185       fp_bnf (construct_fp mixfixes map_bs rel_bs set_bss) fp_bs (map dest_TFree unsorted_As)
  1186         (map dest_TFree killed_As) fp_eqs no_defs_lthy0
  1187       handle BAD_DEAD (X, X_backdrop) =>
  1188         (case X_backdrop of
  1189           Type (bad_tc, _) =>
  1190           let
  1191             val fake_T = qsoty (unfreeze_fp X);
  1192             val fake_T_backdrop = qsoty (unfreeze_fp X_backdrop);
  1193             fun register_hint () =
  1194               "\nUse the " ^ quote (fst (fst @{command_spec "bnf"})) ^ " command to register " ^
  1195               quote bad_tc ^ " as a bounded natural functor to allow nested (co)recursion through \
  1196               \it";
  1197           in
  1198             if is_some (bnf_of no_defs_lthy bad_tc) orelse
  1199                is_some (fp_sugar_of no_defs_lthy bad_tc) then
  1200               error ("Inadmissible " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
  1201                 " in type expression " ^ fake_T_backdrop)
  1202             else if is_some (Datatype_Data.get_info (Proof_Context.theory_of no_defs_lthy)
  1203                 bad_tc) then
  1204               error ("Unsupported " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
  1205                 " via the old-style datatype " ^ quote bad_tc ^ " in type expression " ^
  1206                 fake_T_backdrop ^ register_hint ())
  1207             else
  1208               error ("Unsupported " ^ co_prefix fp ^ "recursive occurrence of type " ^ fake_T ^
  1209                 " via type constructor " ^ quote bad_tc ^ " in type expression " ^ fake_T_backdrop ^
  1210                 register_hint ())
  1211           end);
  1212 
  1213     val abss = map #abs absT_infos;
  1214     val reps = map #rep absT_infos;
  1215     val absTs = map #absT absT_infos;
  1216     val repTs = map #repT absT_infos;
  1217     val abs_injects = map #abs_inject absT_infos;
  1218     val abs_inverses = map #abs_inverse absT_infos;
  1219     val type_definitions = map #type_definition absT_infos;
  1220 
  1221     val time = time lthy;
  1222     val timer = time (Timer.startRealTimer ());
  1223 
  1224     val fp_nesting_bnfs = nesting_bnfs lthy ctrXs_Tsss Xs;
  1225     val live_nesting_bnfs = nesting_bnfs lthy ctrXs_Tsss As;
  1226 
  1227     val pre_map_defs = map map_def_of_bnf pre_bnfs;
  1228     val pre_set_defss = map set_defs_of_bnf pre_bnfs;
  1229     val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
  1230     val fp_nesting_set_maps = maps set_map_of_bnf fp_nesting_bnfs;
  1231     val live_nesting_set_maps = maps set_map_of_bnf live_nesting_bnfs;
  1232 
  1233     val live = live_of_bnf any_fp_bnf;
  1234     val _ =
  1235       if live = 0 andalso exists (not o Binding.is_empty) (map_bs @ rel_bs) then
  1236         warning "Map function and relator names ignored"
  1237       else
  1238         ();
  1239 
  1240     val Bs =
  1241       map3 (fn alive => fn A as TFree (_, S) => fn B => if alive then resort_tfree S B else A)
  1242         (liveness_of_fp_bnf num_As any_fp_bnf) As Bs0;
  1243 
  1244     val B_ify = Term.typ_subst_atomic (As ~~ Bs);
  1245 
  1246     val ctors = map (mk_ctor As) ctors0;
  1247     val dtors = map (mk_dtor As) dtors0;
  1248 
  1249     val fpTs = map (domain_type o fastype_of) dtors;
  1250     val fpBTs = map B_ify fpTs;
  1251 
  1252     fun massage_simple_notes base =
  1253       filter_out (null o #2)
  1254       #> map (fn (thmN, thms, f_attrs) =>
  1255         ((Binding.qualify true base (Binding.name thmN), []), map_index (fn (i, thm) => ([thm], f_attrs i)) thms));
  1256 
  1257     val massage_multi_notes =
  1258       maps (fn (thmN, thmss, attrs) =>
  1259         map3 (fn fp_b_name => fn Type (T_name, _) => fn thms =>
  1260             ((Binding.qualify true fp_b_name (Binding.name thmN), attrs T_name), [(thms, [])]))
  1261           fp_b_names fpTs thmss)
  1262       #> filter_out (null o fst o hd o snd);
  1263 
  1264     val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctrXs_Tsss;
  1265     val ns = map length ctr_Tsss;
  1266     val kss = map (fn n => 1 upto n) ns;
  1267     val mss = map (map length) ctr_Tsss;
  1268 
  1269     val ((xtor_co_recs, recs_args_types, corecs_args_types), lthy') =
  1270       mk_co_recs_prelims fp ctr_Tsss fpTs Cs absTs repTs ns mss xtor_co_recs0 lthy;
  1271 
  1272     fun define_ctrs_dtrs_for_type (((((((((((((((((((((((((((fp_bnf, fp_b), fpT), ctor), dtor),
  1273               xtor_co_rec), ctor_dtor), dtor_ctor), ctor_inject), pre_map_def), pre_set_defs),
  1274             pre_rel_def), fp_map_thm), fp_set_thms), fp_rel_thm), n), ks), ms), abs),
  1275           abs_inject), abs_inverse), type_definition), ctr_bindings), ctr_mixfixes), ctr_Tss),
  1276         disc_bindings), sel_bindingss), raw_sel_default_eqs) no_defs_lthy =
  1277       let
  1278         val fp_b_name = Binding.name_of fp_b;
  1279         val fpBT = B_ify fpT;
  1280 
  1281         val ctr_absT = domain_type (fastype_of ctor);
  1282 
  1283         val ((((w, xss), yss), u'), names_lthy) =
  1284           no_defs_lthy
  1285           |> yield_singleton (mk_Frees "w") ctr_absT
  1286           ||>> mk_Freess "x" ctr_Tss
  1287           ||>> mk_Freess "y" (map (map B_ify) ctr_Tss)
  1288           ||>> yield_singleton Variable.variant_fixes fp_b_name;
  1289 
  1290         val u = Free (u', fpT);
  1291 
  1292         val ctr_rhss =
  1293           map2 (fn k => fn xs => fold_rev Term.lambda xs (ctor $ mk_absumprod ctr_absT abs n k xs))
  1294             ks xss;
  1295 
  1296         val maybe_conceal_def_binding = Thm.def_binding
  1297           #> Config.get no_defs_lthy bnf_note_all = false ? Binding.conceal;
  1298 
  1299         val ((raw_ctrs, raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
  1300           |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
  1301               Local_Theory.define ((b, mx), ((maybe_conceal_def_binding b, []), rhs)) #>> apsnd snd)
  1302             ctr_bindings ctr_mixfixes ctr_rhss
  1303           ||> `Local_Theory.restore;
  1304 
  1305         val phi = Proof_Context.export_morphism lthy lthy';
  1306 
  1307         val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
  1308         val ctr_defs' =
  1309           map2 (fn m => fn def => mk_unabs_def m (def RS meta_eq_to_obj_eq)) ms ctr_defs;
  1310 
  1311         val ctrs0 = map (Morphism.term phi) raw_ctrs;
  1312         val ctrs = map (mk_ctr As) ctrs0;
  1313 
  1314         fun wrap_ctrs lthy =
  1315           let
  1316             fun exhaust_tac {context = ctxt, prems = _} =
  1317               let
  1318                 val ctor_iff_dtor_thm =
  1319                   let
  1320                     val goal =
  1321                       fold_rev Logic.all [w, u]
  1322                         (mk_Trueprop_eq (HOLogic.mk_eq (u, ctor $ w), HOLogic.mk_eq (dtor $ u, w)));
  1323                   in
  1324                     Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
  1325                       mk_ctor_iff_dtor_tac ctxt (map (SOME o certifyT lthy) [ctr_absT, fpT])
  1326                         (certify lthy ctor) (certify lthy dtor) ctor_dtor dtor_ctor)
  1327                     |> Morphism.thm phi
  1328                     |> Thm.close_derivation
  1329                   end;
  1330 
  1331                 val sumEN_thm' =
  1332                   unfold_thms lthy @{thms unit_all_eq1} (mk_absumprodE type_definition ms)
  1333                   |> Morphism.thm phi;
  1334               in
  1335                 mk_exhaust_tac ctxt n ctr_defs ctor_iff_dtor_thm sumEN_thm'
  1336               end;
  1337 
  1338             val inject_tacss =
  1339               map2 (fn ctr_def => fn 0 => [] | _ => [fn {context = ctxt, ...} =>
  1340                 mk_inject_tac ctxt ctr_def ctor_inject abs_inject]) ctr_defs ms;
  1341 
  1342             val half_distinct_tacss =
  1343               map (map (fn (def, def') => fn {context = ctxt, ...} =>
  1344                   mk_half_distinct_tac ctxt ctor_inject abs_inject [def, def']))
  1345                 (mk_half_pairss (`I ctr_defs));
  1346 
  1347             val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss;
  1348 
  1349             val sel_Tss = map (map (curry (op -->) fpT)) ctr_Tss;
  1350             val sel_bTs =
  1351               flat sel_bindingss ~~ flat sel_Tss
  1352               |> filter_out (Binding.is_empty o fst)
  1353               |> distinct (Binding.eq_name o pairself fst);
  1354             val sel_default_lthy = fake_local_theory_for_sel_defaults sel_bTs lthy;
  1355 
  1356             val sel_default_eqs = map (prepare_term sel_default_lthy) raw_sel_default_eqs;
  1357 
  1358             fun ctr_spec_of disc_b ctr0 sel_bs = ((disc_b, ctr0), sel_bs);
  1359             val ctr_specs = map3 ctr_spec_of disc_bindings ctrs0 sel_bindingss;
  1360           in
  1361             free_constructors tacss ((((discs_sels, no_code), standard_binding), ctr_specs),
  1362               sel_default_eqs) lthy
  1363           end;
  1364 
  1365         fun derive_maps_sets_rels (ctr_sugar as {case_cong, discs, selss, ctrs, exhaust, disc_thmss,
  1366             sel_thmss, injects, distincts, ...} : ctr_sugar, lthy) =
  1367           if live = 0 then
  1368             ((([], [], [], []), ctr_sugar), lthy)
  1369           else
  1370             let
  1371               val rel_flip = rel_flip_of_bnf fp_bnf;
  1372               val nones = replicate live NONE;
  1373 
  1374               val ctor_cong =
  1375                 if fp = Least_FP then
  1376                   Drule.dummy_thm
  1377                 else
  1378                   let val ctor' = mk_ctor Bs ctor in
  1379                     cterm_instantiate_pos [NONE, NONE, SOME (certify lthy ctor')] arg_cong
  1380                   end;
  1381 
  1382               fun mk_cIn ctor k xs =
  1383                 let val absT = domain_type (fastype_of ctor) in
  1384                   mk_absumprod absT abs n k xs
  1385                   |> fp = Greatest_FP ? curry (op $) ctor
  1386                   |> certify lthy
  1387                 end;
  1388 
  1389               val cxIns = map2 (mk_cIn ctor) ks xss;
  1390               val cyIns = map2 (mk_cIn (Term.map_types B_ify ctor)) ks yss;
  1391 
  1392               fun mk_map_thm ctr_def' cxIn =
  1393                 fold_thms lthy [ctr_def']
  1394                   (unfold_thms lthy (o_apply :: pre_map_def ::
  1395                        (if fp = Least_FP then [] else [dtor_ctor]) @ sumprod_thms_map @
  1396                        abs_inverses)
  1397                      (cterm_instantiate_pos (nones @ [SOME cxIn])
  1398                         (if fp = Least_FP then fp_map_thm
  1399                          else fp_map_thm RS ctor_cong RS (ctor_dtor RS sym RS trans))))
  1400                 |> singleton (Proof_Context.export names_lthy no_defs_lthy);
  1401 
  1402               fun mk_set0_thm fp_set_thm ctr_def' cxIn =
  1403                 fold_thms lthy [ctr_def']
  1404                   (unfold_thms lthy (pre_set_defs @ fp_nesting_set_maps @ live_nesting_set_maps @
  1405                        (if fp = Least_FP then [] else [dtor_ctor]) @ basic_sumprod_thms_set @
  1406                        @{thms UN_Un sup_assoc[THEN sym]} @ abs_inverses)
  1407                      (cterm_instantiate_pos [SOME cxIn] fp_set_thm))
  1408                 |> singleton (Proof_Context.export names_lthy no_defs_lthy);
  1409 
  1410               fun mk_set0_thms fp_set_thm = map2 (mk_set0_thm fp_set_thm) ctr_defs' cxIns;
  1411 
  1412               val map_thms = map2 mk_map_thm ctr_defs' cxIns;
  1413               val set0_thmss = map mk_set0_thms fp_set_thms;
  1414               val set0_thms = flat set0_thmss;
  1415               val set_thms = set0_thms
  1416                 |> map (unfold_thms lthy @{thms insert_is_Un[THEN sym] Un_empty_left
  1417                   Un_insert_left});
  1418 
  1419               val sets = map (mk_set (snd (Term.dest_Type fpT))) (sets_of_bnf fp_bnf);
  1420 
  1421               val set_empty_thms =
  1422                 let
  1423                   val ctr_argT_namess = map ((fn Ts => fold Term.add_tfree_namesT Ts []) o
  1424                     binder_types o fastype_of) ctrs;
  1425                   val setTs = map (HOLogic.dest_setT o range_type o fastype_of) sets;
  1426                   val setT_names = map (fn T => the_single (Term.add_tfree_namesT T [])) setTs;
  1427 
  1428                   fun mk_set_empty_goal disc set T =
  1429                     Logic.mk_implies (HOLogic.mk_Trueprop (disc $ u),
  1430                       mk_Trueprop_eq (set $ u, HOLogic.mk_set T []));
  1431 
  1432                   val goals =
  1433                     if null discs then
  1434                       []
  1435                     else
  1436                       map_filter I (flat
  1437                         (map2 (fn names => fn disc =>
  1438                           map3 (fn name => fn setT => fn set =>
  1439                             if member (op =) names name then NONE
  1440                             else SOME (mk_set_empty_goal disc set setT))
  1441                           setT_names setTs sets)
  1442                         ctr_argT_namess discs));
  1443                 in
  1444                   if null goals then
  1445                     []
  1446                   else
  1447                     Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
  1448                       (fn {context = ctxt, prems = _} =>
  1449                         mk_set_empty_tac ctxt (certify ctxt u) exhaust set0_thms (flat disc_thmss))
  1450                     |> Conjunction.elim_balanced (length goals)
  1451                     |> Proof_Context.export names_lthy lthy
  1452                     |> map Thm.close_derivation
  1453                 end;
  1454 
  1455               val rel_infos = (ctr_defs' ~~ cxIns, ctr_defs' ~~ cyIns);
  1456 
  1457               fun mk_rel_thm postproc ctr_defs' cxIn cyIn =
  1458                 fold_thms lthy ctr_defs'
  1459                   (unfold_thms lthy (pre_rel_def :: abs_inverse ::
  1460                        (if fp = Least_FP then [] else [dtor_ctor]) @ sumprod_thms_rel @
  1461                        @{thms vimage2p_def sum.inject sum.distinct(1)[THEN eq_False[THEN iffD2]]})
  1462                      (cterm_instantiate_pos (nones @ [SOME cxIn, SOME cyIn]) fp_rel_thm))
  1463                 |> postproc
  1464                 |> singleton (Proof_Context.export names_lthy no_defs_lthy);
  1465 
  1466               fun mk_rel_inject_thm ((ctr_def', cxIn), (_, cyIn)) =
  1467                 mk_rel_thm (unfold_thms lthy @{thms eq_sym_Unity_conv}) [ctr_def'] cxIn cyIn;
  1468 
  1469               fun mk_rel_intro_thm thm =
  1470                 let
  1471                   fun impl thm = rotate_prems (~1) (impl (rotate_prems 1 (conjI RS thm)))
  1472                     handle THM _ => thm
  1473                 in
  1474                   impl (thm RS iffD2)
  1475                   handle THM _ => thm
  1476                 end;
  1477 
  1478               fun mk_half_rel_distinct_thm ((xctr_def', cxIn), (yctr_def', cyIn)) =
  1479                 mk_rel_thm (fn thm => thm RS @{thm eq_False[THEN iffD1]}) [xctr_def', yctr_def']
  1480                   cxIn cyIn;
  1481 
  1482               fun mk_other_half_rel_distinct_thm thm =
  1483                 flip_rels lthy live thm
  1484                 RS (rel_flip RS sym RS @{thm arg_cong[of _ _ Not]} RS iffD2);
  1485 
  1486               val rel_inject_thms = map mk_rel_inject_thm (op ~~ rel_infos);
  1487               val rel_intro_thms = map mk_rel_intro_thm rel_inject_thms;
  1488 
  1489               val half_rel_distinct_thmss =
  1490                 map (map mk_half_rel_distinct_thm) (mk_half_pairss rel_infos);
  1491               val other_half_rel_distinct_thmss =
  1492                 map (map mk_other_half_rel_distinct_thm) half_rel_distinct_thmss;
  1493               val (rel_distinct_thms, _) =
  1494                 join_halves n half_rel_distinct_thmss other_half_rel_distinct_thmss;
  1495 
  1496               val rel_eq_thms =
  1497                 map (fn th => th RS @{thm eq_False[THEN iffD2]}) rel_distinct_thms @
  1498                 map2 (fn th => fn 0 => th RS @{thm eq_True[THEN iffD2]} | _ => th)
  1499                   rel_inject_thms ms;
  1500 
  1501               val (map_disc_iff_thms, map_sel_thms, set_sel_thms, rel_sel_thms, set_intros_thms,
  1502                    (set_cases_thms, set_cases_attrss), (rel_cases_thm, rel_cases_attrs)) =
  1503                 let
  1504                   val live_AsBs = filter (op <>) (As ~~ Bs);
  1505                   val fTs = map (op -->) live_AsBs;
  1506                   val rel = mk_rel live As Bs (rel_of_bnf fp_bnf);
  1507                   val (((((fs, Rs), ta), tb), thesis), names_lthy) = names_lthy
  1508                     |> mk_Frees "f" fTs
  1509                     ||>> mk_Frees "R" (map (uncurry mk_pred2T) live_AsBs)
  1510                     ||>> yield_singleton (mk_Frees "a") fpT
  1511                     ||>> yield_singleton (mk_Frees "b") fpBT
  1512                     ||>> apfst HOLogic.mk_Trueprop o
  1513                       yield_singleton (mk_Frees "thesis") HOLogic.boolT;
  1514                   val map_term = mk_map live As Bs (map_of_bnf fp_bnf);
  1515                   val ctrAs = map (mk_ctr As) ctrs;
  1516                   val setAs = map (mk_set As) (sets_of_bnf fp_bnf);
  1517                   val discAs = map (mk_disc_or_sel As) discs;
  1518                   val selAss = map (map (mk_disc_or_sel As)) selss;
  1519                   val discAs_selAss = flat (map2 (map o pair) discAs selAss);
  1520 
  1521                   val (set_cases_thms, set_cases_attrss) =
  1522                     let
  1523                       fun mk_prems assms elem t ctxt =
  1524                         (case fastype_of t of
  1525                           Type (type_name, xs) =>
  1526                           (case bnf_of ctxt type_name of
  1527                             NONE => ([], ctxt)
  1528                           | SOME bnf =>
  1529                             apfst flat (fold_map (fn set => fn ctxt =>
  1530                               let
  1531                                 val X = HOLogic.dest_setT (range_type (fastype_of set));
  1532                                 val new_var = not (X = fastype_of elem);
  1533                                 val (x, ctxt') =
  1534                                   if new_var then yield_singleton (mk_Frees "x") X ctxt
  1535                                   else (elem, ctxt);
  1536                               in
  1537                                 mk_prems (mk_Trueprop_mem (x, set $ t) :: assms) elem x ctxt'
  1538                                 |>> map (if new_var then Logic.all x else I)
  1539                               end) (map (mk_set xs) (sets_of_bnf bnf)) ctxt))
  1540                         | T => rpair ctxt
  1541                           (if T = fastype_of elem then [fold (curry Logic.mk_implies) assms thesis]
  1542                            else []));
  1543                     in
  1544                       split_list (map (fn set =>
  1545                         let
  1546                           val A = HOLogic.dest_setT (range_type (fastype_of set));
  1547                           val (elem, names_lthy) = yield_singleton (mk_Frees "e") A names_lthy;
  1548                           val premss =
  1549                             map (fn ctr =>
  1550                               let
  1551                                 val (args, names_lthy) =
  1552                                   mk_Frees "z" (binder_types (fastype_of ctr)) names_lthy;
  1553                               in
  1554                                 flat (zipping_map (fn (prev_args, arg, next_args) =>
  1555                                   let
  1556                                     val (args_with_elem, args_without_elem) =
  1557                                       if fastype_of arg = A then
  1558                                         (prev_args @ [elem] @ next_args, prev_args @ next_args)
  1559                                       else
  1560                                         `I (prev_args @ [arg] @ next_args);
  1561                                   in
  1562                                     mk_prems
  1563                                       [mk_Trueprop_eq (ta, Term.list_comb (ctr, args_with_elem))]
  1564                                       elem arg names_lthy
  1565                                     |> fst
  1566                                     |> map (fold_rev Logic.all args_without_elem)
  1567                                   end) args)
  1568                               end) ctrAs;
  1569                           val goal = Logic.mk_implies (mk_Trueprop_mem (elem, set $ ta), thesis);
  1570                           val thm =
  1571                             Goal.prove_sorry lthy [] (flat premss) goal
  1572                               (fn {context = ctxt, prems} =>
  1573                                 mk_set_cases_tac ctxt (certify ctxt ta) prems exhaust set_thms)
  1574                             |> singleton (Proof_Context.export names_lthy lthy)
  1575                             |> Thm.close_derivation
  1576                             |> rotate_prems ~1;
  1577                         in
  1578                           (thm, [](* TODO: [@{attributes [elim?]},
  1579                             Attrib.internal (K (Induct.cases_pred (name_of_set set)))] *))
  1580                         end) setAs)
  1581                     end;
  1582 
  1583                   val set_intros_thms =
  1584                     let
  1585                       fun mk_goals A setA ctr_args t ctxt =
  1586                         (case fastype_of t of
  1587                           Type (type_name, innerTs) =>
  1588                           (case bnf_of ctxt type_name of
  1589                             NONE => ([], ctxt)
  1590                           | SOME bnf =>
  1591                             apfst flat (fold_map (fn set => fn ctxt =>
  1592                               let
  1593                                 val X = HOLogic.dest_setT (range_type (fastype_of set));
  1594                                 val (x, ctxt') = yield_singleton (mk_Frees "x") X ctxt;
  1595                                 val assm = mk_Trueprop_mem (x, set $ t);
  1596                               in
  1597                                 apfst (map (Logic.mk_implies o pair assm))
  1598                                   (mk_goals A setA ctr_args x ctxt')
  1599                               end) (map (mk_set innerTs) (sets_of_bnf bnf)) ctxt))
  1600                         | T =>
  1601                           (if T = A then [mk_Trueprop_mem (t, setA $ ctr_args)] else [], ctxt));
  1602 
  1603                       val (goals, names_lthy) =
  1604                         apfst flat (fold_map (fn set => fn ctxt =>
  1605                           let
  1606                             val A = HOLogic.dest_setT (range_type (fastype_of set));
  1607                           in
  1608                             apfst flat (fold_map (fn ctr => fn ctxt =>
  1609                               let
  1610                                 val (args, ctxt') =
  1611                                   mk_Frees "arg" (binder_types (fastype_of ctr)) ctxt;
  1612                                 val ctr_args = Term.list_comb (ctr, args);
  1613                               in
  1614                                 apfst flat (fold_map (mk_goals A set ctr_args) args ctxt')
  1615                               end) ctrAs ctxt)
  1616                           end) setAs lthy);
  1617                     in
  1618                       if null goals then []
  1619                       else
  1620                         Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
  1621                           (fn {context = ctxt, prems = _} => mk_set_intros_tac ctxt set0_thms)
  1622                         |> Conjunction.elim_balanced (length goals)
  1623                         |> Proof_Context.export names_lthy lthy
  1624                         |> map Thm.close_derivation
  1625                     end;
  1626 
  1627                   val rel_sel_thms =
  1628                     let
  1629                       val discBs = map (mk_disc_or_sel Bs) discs;
  1630                       val selBss = map (map (mk_disc_or_sel Bs)) selss;
  1631                       val n = length discAs;
  1632 
  1633                       fun mk_rhs n k discA selAs discB selBs =
  1634                         (if k = n then [] else [HOLogic.mk_eq (discA $ ta, discB $ tb)]) @
  1635                         (case (selAs, selBs) of
  1636                            ([], []) => []
  1637                          | (_ :: _, _ :: _) => [Library.foldr HOLogic.mk_imp
  1638                            (if n = 1 then [] else [discA $ ta, discB $ tb],
  1639                             Library.foldr1 HOLogic.mk_conj (map2 (build_rel_app names_lthy Rs [])
  1640                               (map (rapp ta) selAs) (map (rapp tb) selBs)))]);
  1641 
  1642                       val goals = if n = 0 then []
  1643                         else [mk_Trueprop_eq
  1644                           (build_rel_app names_lthy Rs [] ta tb,
  1645                            Library.foldr1 HOLogic.mk_conj
  1646                              (flat (map5 (mk_rhs n) (1 upto n) discAs selAss discBs selBss)))];
  1647                     in
  1648                       if null goals then
  1649                         []
  1650                       else
  1651                         Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
  1652                           (fn {context = ctxt, prems = _} =>
  1653                             mk_rel_sel_tac ctxt (certify ctxt ta) (certify ctxt tb) exhaust
  1654                               (flat disc_thmss) (flat sel_thmss) rel_inject_thms distincts
  1655                               rel_distinct_thms)
  1656                         |> Conjunction.elim_balanced (length goals)
  1657                         |> Proof_Context.export names_lthy lthy
  1658                         |> map Thm.close_derivation
  1659                     end;
  1660 
  1661                   val (rel_cases_thm, rel_cases_attrs) =
  1662                     let
  1663                       val rel_Rs_a_b = list_comb (rel, Rs) $ ta $ tb;
  1664                       val ctrBs = map (mk_ctr Bs) ctrs;
  1665 
  1666                       fun mk_assms ctrA ctrB ctxt =
  1667                         let
  1668                           val argA_Ts = binder_types (fastype_of ctrA);
  1669                           val argB_Ts = binder_types (fastype_of ctrB);
  1670                           val ((argAs, argBs), names_ctxt) =  ctxt
  1671                             |> mk_Frees "x" argA_Ts
  1672                             ||>> mk_Frees "y" argB_Ts;
  1673                           val ctrA_args = list_comb (ctrA, argAs);
  1674                           val ctrB_args = list_comb (ctrB, argBs);
  1675                         in
  1676                           (fold_rev Logic.all (argAs @ argBs) (Logic.list_implies
  1677                              (mk_Trueprop_eq (ta, ctrA_args) ::
  1678                                 mk_Trueprop_eq (tb, ctrB_args) ::
  1679                                   map2 (HOLogic.mk_Trueprop oo build_rel_app lthy Rs [])
  1680                                     argAs argBs,
  1681                               thesis)),
  1682                            names_ctxt)
  1683                         end;
  1684 
  1685                       val (assms, names_lthy) = fold_map2 mk_assms ctrAs ctrBs names_lthy;
  1686                       val goal =
  1687                         Logic.list_implies (HOLogic.mk_Trueprop rel_Rs_a_b :: assms, thesis);
  1688                       val thm =
  1689                         Goal.prove_sorry lthy [] [] goal
  1690                           (fn {context = ctxt, prems = _} =>
  1691                             mk_rel_cases_tac ctxt (certify ctxt ta) (certify ctxt tb) exhaust
  1692                               injects rel_inject_thms distincts rel_distinct_thms
  1693                               (map rel_eq_of_bnf live_nesting_bnfs))
  1694                         |> singleton (Proof_Context.export names_lthy lthy)
  1695                         |> Thm.close_derivation;
  1696 
  1697                       val ctr_names = quasi_unambiguous_case_names ((map name_of_ctr) ctrAs);
  1698                       val case_names_attr = Attrib.internal (K (Rule_Cases.case_names ctr_names));
  1699                       val consumes_attr = Attrib.internal (K (Rule_Cases.consumes 1));
  1700                       val cases_pred_attr = Attrib.internal o K o Induct.cases_pred;
  1701                     in
  1702                       (thm, [consumes_attr, case_names_attr, cases_pred_attr ""])
  1703                     end;
  1704 
  1705                   val map_disc_iff_thms =
  1706                     let
  1707                       val discsB = map (mk_disc_or_sel Bs) discs;
  1708                       val discsA_t = map (fn disc1 => Term.betapply (disc1, ta)) discAs;
  1709 
  1710                       fun mk_goal (discA_t, discB) =
  1711                         if head_of discA_t aconv HOLogic.Not orelse is_refl_bool discA_t then
  1712                           NONE
  1713                         else
  1714                           SOME (mk_Trueprop_eq
  1715                             (betapply (discB, (Term.list_comb (map_term, fs) $ ta)), discA_t));
  1716 
  1717                       val goals = map_filter mk_goal (discsA_t ~~ discsB);
  1718                     in
  1719                       if null goals then
  1720                         []
  1721                       else
  1722                         Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
  1723                           (fn {context = ctxt, prems = _} =>
  1724                             mk_map_disc_iff_tac ctxt (certify ctxt ta) exhaust (flat disc_thmss)
  1725                               map_thms)
  1726                         |> Conjunction.elim_balanced (length goals)
  1727                         |> Proof_Context.export names_lthy lthy
  1728                         |> map Thm.close_derivation
  1729                     end;
  1730 
  1731                   val map_sel_thms =
  1732                     let
  1733                       fun mk_goal (discA, selA) =
  1734                         let
  1735                           val prem = Term.betapply (discA, ta);
  1736                           val selB = mk_disc_or_sel Bs selA;
  1737                           val lhs = selB $ (Term.list_comb (map_term, fs) $ ta);
  1738                           val lhsT = fastype_of lhs;
  1739                           val map_rhsT =
  1740                             map_atyps (perhaps (AList.lookup (op =) (map swap live_AsBs))) lhsT;
  1741                           val map_rhs = build_map lthy []
  1742                             (the o (AList.lookup (op =) (live_AsBs ~~ fs))) (map_rhsT, lhsT);
  1743                           val rhs = (case map_rhs of
  1744                               Const (@{const_name id}, _) => selA $ ta
  1745                             | _ => map_rhs $ (selA $ ta));
  1746                           val concl = mk_Trueprop_eq (lhs, rhs);
  1747                         in
  1748                           if is_refl_bool prem then concl
  1749                           else Logic.mk_implies (HOLogic.mk_Trueprop prem, concl)
  1750                         end;
  1751                       val goals = map mk_goal discAs_selAss;
  1752                     in
  1753                       if null goals then
  1754                         []
  1755                       else
  1756                         Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
  1757                           (fn {context = ctxt, prems = _} =>
  1758                             mk_map_sel_tac ctxt (certify ctxt ta) exhaust (flat disc_thmss)
  1759                               map_thms (flat sel_thmss))
  1760                         |> Conjunction.elim_balanced (length goals)
  1761                         |> Proof_Context.export names_lthy lthy
  1762                         |> map Thm.close_derivation
  1763                     end;
  1764 
  1765                   val set_sel_thms =
  1766                     let
  1767                       fun mk_goal discA selA setA ctxt =
  1768                         let
  1769                           val prem = Term.betapply (discA, ta);
  1770                           val sel_rangeT = range_type (fastype_of selA);
  1771                           val A = HOLogic.dest_setT (range_type (fastype_of setA));
  1772 
  1773                           fun travese_nested_types t ctxt =
  1774                             (case fastype_of t of
  1775                               Type (type_name, innerTs) =>
  1776                               (case bnf_of ctxt type_name of
  1777                                 NONE => ([], ctxt)
  1778                               | SOME bnf =>
  1779                                 let
  1780                                   fun seq_assm a set ctxt =
  1781                                     let
  1782                                       val X = HOLogic.dest_setT (range_type (fastype_of set));
  1783                                       val (x, ctxt') = yield_singleton (mk_Frees "x") X ctxt;
  1784                                       val assm = mk_Trueprop_mem (x, set $ a);
  1785                                     in
  1786                                       travese_nested_types x ctxt'
  1787                                       |>> map (Logic.mk_implies o pair assm)
  1788                                     end;
  1789                                 in
  1790                                   fold_map (seq_assm t o mk_set innerTs) (sets_of_bnf bnf) ctxt
  1791                                   |>> flat
  1792                                 end)
  1793                             | T =>
  1794                               if T = A then
  1795                                 ([mk_Trueprop_mem (t, setA $ ta)], ctxt)
  1796                               else
  1797                                 ([], ctxt));
  1798 
  1799                           val (concls, ctxt') =
  1800                             if sel_rangeT = A then
  1801                               ([mk_Trueprop_mem (selA $ ta, setA $ ta)], ctxt)
  1802                             else
  1803                               travese_nested_types (selA $ ta) ctxt;
  1804                         in
  1805                           if exists_subtype_in [A] sel_rangeT then
  1806                             if is_refl_bool prem then
  1807                               (concls, ctxt')
  1808                             else
  1809                               (map (Logic.mk_implies o pair (HOLogic.mk_Trueprop prem)) concls,
  1810                                ctxt')
  1811                           else
  1812                             ([], ctxt)
  1813                         end;
  1814                       val (goals, names_lthy) = apfst (flat o flat) (fold_map (fn (disc, sel) =>
  1815                         fold_map (mk_goal disc sel) setAs) discAs_selAss names_lthy);
  1816                     in
  1817                       if null goals then
  1818                         []
  1819                       else
  1820                         Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced goals)
  1821                           (fn {context = ctxt, prems = _} =>
  1822                              mk_set_sel_tac ctxt (certify ctxt ta) exhaust (flat disc_thmss)
  1823                                (flat sel_thmss) set0_thms)
  1824                         |> Conjunction.elim_balanced (length goals)
  1825                         |> Proof_Context.export names_lthy lthy
  1826                         |> map Thm.close_derivation
  1827                     end;
  1828                 in
  1829                   (map_disc_iff_thms, map_sel_thms, set_sel_thms, rel_sel_thms, set_intros_thms,
  1830                     (set_cases_thms, set_cases_attrss), (rel_cases_thm, rel_cases_attrs))
  1831                 end;
  1832 
  1833               val anonymous_notes =
  1834                 [([case_cong], fundefcong_attrs),
  1835                  (rel_eq_thms, code_nitpicksimp_attrs)]
  1836                 |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
  1837 
  1838               val notes =
  1839                 [(mapN, map_thms, K (code_nitpicksimp_attrs @ simp_attrs)),
  1840                  (map_disc_iffN, map_disc_iff_thms, K simp_attrs),
  1841                  (map_selN, map_sel_thms, K []),
  1842                  (rel_casesN, [rel_cases_thm], K rel_cases_attrs),
  1843                  (rel_distinctN, rel_distinct_thms, K simp_attrs),
  1844                  (rel_injectN, rel_inject_thms, K simp_attrs),
  1845                  (rel_introsN, rel_intro_thms, K []),
  1846                  (rel_selN, rel_sel_thms, K []),
  1847                  (setN, set_thms, K (code_nitpicksimp_attrs @ simp_attrs)),
  1848                  (set_casesN, set_cases_thms, nth set_cases_attrss),
  1849                  (set_emptyN, set_empty_thms, K []),
  1850                  (set_introsN, set_intros_thms, K []),
  1851                  (set_selN, set_sel_thms, K [])]
  1852                 |> massage_simple_notes fp_b_name;
  1853 
  1854               val (noted, lthy') =
  1855                 lthy
  1856                 |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) map_thms)
  1857                 |> fp = Least_FP
  1858                   ? Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) rel_eq_thms)
  1859                 |> Spec_Rules.add Spec_Rules.Equational (`(single o lhs_head_of o hd) set0_thms)
  1860                 |> Local_Theory.notes (anonymous_notes @ notes);
  1861 
  1862               val subst = Morphism.thm (substitute_noted_thm noted);
  1863             in
  1864               (((map subst map_thms, map subst rel_inject_thms, map subst rel_distinct_thms,
  1865                  map (map subst) set0_thmss), ctr_sugar), lthy')
  1866             end;
  1867 
  1868         fun mk_binding pre = Binding.qualify false fp_b_name (Binding.prefix_name (pre ^ "_") fp_b);
  1869 
  1870         fun massage_res (((maps_sets_rels, ctr_sugar), co_rec_res), lthy) =
  1871           (((maps_sets_rels, (ctrs, xss, ctr_defs, ctr_sugar)), co_rec_res), lthy);
  1872       in
  1873         (wrap_ctrs
  1874          #> derive_maps_sets_rels
  1875          ##>>
  1876            (if fp = Least_FP then define_rec (the recs_args_types) mk_binding fpTs Cs reps
  1877            else define_corec (the corecs_args_types) mk_binding fpTs Cs abss) xtor_co_rec
  1878          #> massage_res, lthy')
  1879       end;
  1880 
  1881     fun wrap_types_etc (wrap_types_etcs, lthy) =
  1882       fold_map I wrap_types_etcs lthy
  1883       |>> apsnd split_list o apfst (apsnd split_list4 o apfst split_list4 o split_list)
  1884         o split_list;
  1885 
  1886     fun mk_simp_thms ({injects, distincts, case_thms, ...} : ctr_sugar) co_recs mapsx rel_injects
  1887         rel_distincts setss =
  1888       injects @ distincts @ case_thms @ co_recs @ mapsx @ rel_injects @ rel_distincts @ flat setss;
  1889 
  1890     fun derive_note_induct_recs_thms_for_types
  1891         ((((mapss, rel_injectss, rel_distinctss, setss), (ctrss, _, ctr_defss, ctr_sugars)),
  1892           (recs, rec_defs)), lthy) =
  1893       let
  1894         val ((induct_thms, induct_thm, induct_attrs), (rec_thmss, rec_attrs)) =
  1895           derive_induct_recs_thms_for_types pre_bnfs recs_args_types xtor_co_induct xtor_co_rec_thms
  1896             live_nesting_bnfs fp_nesting_bnfs fpTs Cs Xs ctrXs_Tsss abs_inverses type_definitions
  1897             abs_inverses ctrss ctr_defss recs rec_defs lthy;
  1898 
  1899         val induct_type_attr = Attrib.internal o K o Induct.induct_type;
  1900         val induct_pred_attr = Attrib.internal o K o Induct.induct_pred;
  1901 
  1902         val ((rel_induct_thmss, common_rel_induct_thms),
  1903              (rel_induct_attrs, common_rel_induct_attrs)) =
  1904           if live = 0 then
  1905             ((replicate nn [], []), ([], []))
  1906           else
  1907             let
  1908               val ((rel_induct_thms, common_rel_induct_thm), rel_induct_attrs) =
  1909                 derive_rel_induct_thms_for_types lthy fpTs As Bs ctrss ctr_Tsss
  1910                   (map #exhaust ctr_sugars) rel_xtor_co_induct_thm ctr_defss ctor_injects
  1911                   pre_rel_defs abs_inverses (map rel_eq_of_bnf live_nesting_bnfs);
  1912             in
  1913               ((map single rel_induct_thms, single common_rel_induct_thm),
  1914                (rel_induct_attrs, rel_induct_attrs))
  1915             end;
  1916 
  1917         val simp_thmss =
  1918           map6 mk_simp_thms ctr_sugars rec_thmss mapss rel_injectss rel_distinctss setss;
  1919 
  1920         val common_notes =
  1921           (if nn > 1 then
  1922              [(inductN, [induct_thm], K induct_attrs),
  1923               (rel_inductN, common_rel_induct_thms, K common_rel_induct_attrs)]
  1924            else
  1925              [])
  1926           |> massage_simple_notes fp_common_name;
  1927 
  1928         val notes =
  1929           [(inductN, map single induct_thms, fn T_name => induct_attrs @ [induct_type_attr T_name]),
  1930            (recN, rec_thmss, K rec_attrs),
  1931            (rel_inductN, rel_induct_thmss, K (rel_induct_attrs @ [induct_pred_attr ""])),
  1932            (simpsN, simp_thmss, K [])]
  1933           |> massage_multi_notes;
  1934       in
  1935         lthy
  1936         |> Spec_Rules.add Spec_Rules.Equational (recs, flat rec_thmss)
  1937         |> Local_Theory.notes (common_notes @ notes)
  1938         (* for "datatype_realizer.ML": *)
  1939         |>> name_noted_thms
  1940           (fst (dest_Type (hd fpTs)) ^ (implode (map (prefix "_") (tl fp_b_names)))) inductN
  1941         |-> register_as_fp_sugars fpTs fpBTs Xs Least_FP pre_bnfs absT_infos fp_nesting_bnfs
  1942           live_nesting_bnfs fp_res ctrXs_Tsss ctr_defss ctr_sugars recs rec_defs mapss [induct_thm]
  1943           (map single induct_thms) rec_thmss (replicate nn []) (replicate nn []) rel_injectss
  1944           rel_distinctss
  1945       end;
  1946 
  1947     fun derive_note_coinduct_corecs_thms_for_types
  1948         ((((mapss, rel_injectss, rel_distinctss, setss), (_, _, ctr_defss, ctr_sugars)),
  1949           (corecs, corec_defs)), lthy) =
  1950       let
  1951         val (([(coinduct_thms, coinduct_thm), (coinduct_strong_thms, coinduct_strong_thm)],
  1952               (coinduct_attrs, common_coinduct_attrs)),
  1953              corec_thmss, corec_disc_thmss,
  1954              (corec_disc_iff_thmss, corec_disc_iff_attrs), (corec_sel_thmsss, corec_sel_attrs)) =
  1955           derive_coinduct_corecs_thms_for_types pre_bnfs (the corecs_args_types) xtor_co_induct
  1956             dtor_injects dtor_ctors xtor_co_rec_thms live_nesting_bnfs fpTs Cs Xs ctrXs_Tsss kss mss
  1957             ns abs_inverses abs_inverses I ctr_defss ctr_sugars corecs corec_defs
  1958             (Proof_Context.export lthy' no_defs_lthy) lthy;
  1959 
  1960         fun distinct_prems ctxt th =
  1961           Goal.prove (*no sorry*) ctxt [] []
  1962             (th |> Thm.prop_of |> Logic.strip_horn |>> distinct (op aconv) |> Logic.list_implies)
  1963             (fn _ => HEADGOAL (cut_tac th THEN' atac) THEN ALLGOALS eq_assume_tac);
  1964 
  1965         fun eq_ifIN _ [thm] = thm
  1966           | eq_ifIN ctxt (thm :: thms) =
  1967               distinct_prems ctxt (@{thm eq_ifI} OF
  1968                 (map (unfold_thms ctxt @{thms atomize_imp[of _ "t = u" for t u]})
  1969                   [thm, eq_ifIN ctxt thms]));
  1970 
  1971         val corec_code_thms = map (eq_ifIN lthy) corec_thmss;
  1972         val corec_sel_thmss = map flat corec_sel_thmsss;
  1973 
  1974         val coinduct_type_attr = Attrib.internal o K o Induct.coinduct_type;
  1975         val coinduct_pred_attr = Attrib.internal o K o Induct.coinduct_pred;
  1976 
  1977         val flat_corec_thms = append oo append;
  1978 
  1979         val ((rel_coinduct_thmss, common_rel_coinduct_thms),
  1980              (rel_coinduct_attrs, common_rel_coinduct_attrs)) =
  1981           if live = 0 then
  1982             ((replicate nn [], []), ([], []))
  1983           else
  1984             let
  1985               val ((rel_coinduct_thms, common_rel_coinduct_thm),
  1986                    (rel_coinduct_attrs, common_rel_coinduct_attrs)) =
  1987                 derive_rel_coinduct_thm_for_types lthy fpTs ns As Bs mss ctr_sugars abs_inverses
  1988                   abs_injects ctor_injects dtor_ctors pre_rel_defs ctr_defss rel_xtor_co_induct_thm
  1989                   (map rel_eq_of_bnf live_nesting_bnfs)
  1990             in
  1991               ((map single rel_coinduct_thms, single common_rel_coinduct_thm),
  1992                (rel_coinduct_attrs, common_rel_coinduct_attrs))
  1993             end;
  1994 
  1995         val (set_induct_thms, set_induct_attrss) =
  1996           derive_set_induct_thms_for_types lthy nn fpTs (map #ctrs ctr_sugars)
  1997             (map (map (mk_set As)) (map sets_of_bnf fp_bnfs)) dtor_set_induct_thms
  1998             (map #exhaust ctr_sugars) (flat pre_set_defss) (flat ctr_defss)
  1999             dtor_ctors abs_inverses
  2000           |> split_list;
  2001 
  2002         val simp_thmss =
  2003           map6 mk_simp_thms ctr_sugars
  2004             (map3 flat_corec_thms corec_disc_thmss corec_disc_iff_thmss corec_sel_thmss)
  2005             mapss rel_injectss rel_distinctss setss;
  2006 
  2007         val common_notes =
  2008           (set_inductN, set_induct_thms, nth set_induct_attrss) ::
  2009           (if nn > 1 then
  2010             [(coinductN, [coinduct_thm], K common_coinduct_attrs),
  2011              (coinduct_strongN, [coinduct_strong_thm], K common_coinduct_attrs),
  2012              (rel_coinductN, common_rel_coinduct_thms, K common_rel_coinduct_attrs)]
  2013            else [])
  2014           |> massage_simple_notes fp_common_name;
  2015 
  2016         val notes =
  2017           [(coinductN, map single coinduct_thms,
  2018             fn T_name => coinduct_attrs @ [coinduct_type_attr T_name]),
  2019            (coinduct_strongN, map single coinduct_strong_thms, K coinduct_attrs),
  2020            (corecN, corec_thmss, K []),
  2021            (corec_codeN, map single corec_code_thms, K code_nitpicksimp_attrs),
  2022            (corec_discN, corec_disc_thmss, K []),
  2023            (corec_disc_iffN, corec_disc_iff_thmss, K corec_disc_iff_attrs),
  2024            (corec_selN, corec_sel_thmss, K corec_sel_attrs),
  2025            (rel_coinductN, rel_coinduct_thmss, K (rel_coinduct_attrs @ [coinduct_pred_attr ""])),
  2026            (simpsN, simp_thmss, K [])]
  2027           |> massage_multi_notes;
  2028       in
  2029         lthy
  2030         |> fold (curry (Spec_Rules.add Spec_Rules.Equational) corecs)
  2031           [flat corec_sel_thmss, flat corec_thmss]
  2032         |> Local_Theory.notes (common_notes @ notes)
  2033         |-> register_as_fp_sugars fpTs fpBTs Xs Greatest_FP pre_bnfs absT_infos fp_nesting_bnfs
  2034           live_nesting_bnfs fp_res ctrXs_Tsss ctr_defss ctr_sugars corecs corec_defs mapss
  2035           [coinduct_thm, coinduct_strong_thm] (transpose [coinduct_thms, coinduct_strong_thms])
  2036           corec_thmss corec_disc_thmss corec_sel_thmsss rel_injectss rel_distinctss
  2037       end;
  2038 
  2039     val lthy'' = lthy'
  2040       |> fold_map define_ctrs_dtrs_for_type (fp_bnfs ~~ fp_bs ~~ fpTs ~~ ctors ~~ dtors ~~
  2041         xtor_co_recs ~~ ctor_dtors ~~ dtor_ctors ~~ ctor_injects ~~ pre_map_defs ~~ pre_set_defss ~~
  2042         pre_rel_defs ~~ xtor_map_thms ~~ xtor_set_thmss ~~ xtor_rel_thms ~~ ns ~~ kss ~~ mss ~~
  2043         abss ~~ abs_injects ~~ abs_inverses ~~ type_definitions ~~ ctr_bindingss ~~ ctr_mixfixess ~~
  2044         ctr_Tsss ~~ disc_bindingss ~~ sel_bindingsss ~~ raw_sel_default_eqss)
  2045       |> wrap_types_etc
  2046       |> case_fp fp derive_note_induct_recs_thms_for_types
  2047            derive_note_coinduct_corecs_thms_for_types;
  2048 
  2049     val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
  2050       co_prefix fp ^ "datatype"));
  2051   in
  2052     timer; lthy''
  2053   end;
  2054 
  2055 fun co_datatypes x = define_co_datatypes (K I) (K I) (K I) x;
  2056 
  2057 fun co_datatype_cmd x =
  2058   define_co_datatypes Typedecl.read_constraint Syntax.parse_typ Syntax.parse_term x;
  2059 
  2060 val parse_ctr_arg =
  2061   @{keyword "("} |-- parse_binding_colon -- Parse.typ --| @{keyword ")"}
  2062   || Parse.typ >> pair Binding.empty;
  2063 
  2064 val parse_ctr_specs =
  2065   Parse.enum1 "|" (parse_ctr_spec Parse.binding parse_ctr_arg -- Parse.opt_mixfix);
  2066 
  2067 val parse_spec =
  2068   parse_type_args_named_constrained -- Parse.binding -- Parse.opt_mixfix --
  2069   (@{keyword "="} |-- parse_ctr_specs) -- parse_map_rel_bindings -- parse_sel_default_eqs;
  2070 
  2071 val parse_co_datatype = parse_ctr_options -- Parse.and_list1 parse_spec;
  2072 
  2073 fun parse_co_datatype_cmd fp construct_fp = parse_co_datatype >> co_datatype_cmd fp construct_fp;
  2074 
  2075 val _ = Context.>> (Context.map_theory FP_Sugar_Interpretation.init);
  2076 
  2077 end;