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