src/HOL/BNF/Tools/bnf_fp_def_sugar.ML
author blanchet
Thu May 02 11:19:05 2013 +0200 (2013-05-02)
changeset 51857 17e7f00563fb
parent 51856 b3368771c3cc
child 51858 7a08fe1e19b1
permissions -rw-r--r--
tuned names -- co_ and un_ with underscore are to be understood as (co) and (un)
     1 (*  Title:      HOL/BNF/Tools/bnf_fp_def_sugar.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2012
     4 
     5 Sugared datatype and codatatype constructions.
     6 *)
     7 
     8 signature BNF_FP_DEF_SUGAR =
     9 sig
    10   type fp_sugar =
    11     {lfp: bool,
    12      index: int,
    13      pre_bnfs: BNF_Def.bnf list,
    14      fp_res: BNF_FP_Util.fp_result,
    15      ctr_sugars: BNF_Ctr_Sugar.ctr_sugar list,
    16      un_folds: term list,
    17      co_recs: term list,
    18      un_fold_thmss: thm list list,
    19      co_rec_thmss: thm list list};
    20 
    21   val fp_sugar_of: local_theory -> string -> fp_sugar option
    22 
    23   val indexify_fst: ''a list -> (int -> ''a * 'b -> 'c) -> ''a * 'b -> 'c
    24   val build_map: local_theory -> (typ * typ -> term) -> typ * typ -> term
    25 
    26   val mk_fp_iter_fun_types: term -> typ list
    27   val mk_fun_arg_typess: int -> int list -> typ -> typ list list
    28   val unzip_recT: typ list -> typ -> typ list * typ list
    29   val mk_fold_fun_typess: typ list list list -> typ list list -> typ list list
    30   val mk_rec_fun_typess: typ list -> typ list list list -> typ list list -> typ list list
    31 
    32   val derive_induct_fold_rec_thms_for_types: BNF_Def.bnf list -> term list -> term list -> thm ->
    33     thm list -> thm list -> BNF_Def.bnf list -> BNF_Def.bnf list -> typ list -> typ list ->
    34     typ list -> term list list -> thm list list -> term list -> term list -> thm list -> thm list ->
    35     local_theory ->
    36     (thm * thm list * Args.src list) * (thm list list * Args.src list)
    37     * (thm list list * Args.src list)
    38   val derive_coinduct_unfold_corec_thms_for_types: BNF_Def.bnf list -> term list -> term list ->
    39     thm -> thm -> thm list -> thm list -> thm list -> BNF_Def.bnf list -> BNF_Def.bnf list ->
    40     typ list -> typ list -> typ list -> int list list -> int list list -> int list ->
    41     thm list list -> BNF_Ctr_Sugar.ctr_sugar list -> term list -> term list -> thm list ->
    42     thm list -> local_theory ->
    43     (thm * thm list * thm * thm list * Args.src list)
    44     * (thm list list * thm list list * Args.src list)
    45     * (thm list list * thm list list) * (thm list list * thm list list * Args.src list)
    46     * (thm list list * thm list list * Args.src list)
    47     * (thm list list * thm list list * Args.src list)
    48 
    49   val datatypes: bool ->
    50     (mixfix list -> (string * sort) list option -> binding list -> binding list -> binding list ->
    51       binding list list -> typ list * typ list list -> BNF_Def.bnf list -> local_theory ->
    52       BNF_FP_Util.fp_result * local_theory) ->
    53     (bool * bool) * (((((binding * (typ * sort)) list * binding) * (binding * binding)) * mixfix) *
    54       ((((binding * binding) * (binding * typ) list) * (binding * term) list) *
    55         mixfix) list) list ->
    56     local_theory -> local_theory
    57   val parse_datatype_cmd: bool ->
    58     (mixfix list -> (string * sort) list option -> binding list -> binding list -> binding list ->
    59       binding list list -> typ list * typ list list -> BNF_Def.bnf list -> local_theory ->
    60       BNF_FP_Util.fp_result * local_theory) ->
    61     (local_theory -> local_theory) parser
    62 end;
    63 
    64 structure BNF_FP_Def_Sugar : BNF_FP_DEF_SUGAR =
    65 struct
    66 
    67 open BNF_Util
    68 open BNF_Ctr_Sugar
    69 open BNF_Def
    70 open BNF_FP_Util
    71 open BNF_FP_Def_Sugar_Tactics
    72 
    73 val EqN = "Eq_";
    74 
    75 type fp_sugar =
    76   {lfp: bool,
    77    index: int,
    78    pre_bnfs: bnf list,
    79    fp_res: fp_result,
    80    ctr_sugars: ctr_sugar list,
    81    un_folds: term list,
    82    co_recs: term list,
    83    un_fold_thmss: thm list list,
    84    co_rec_thmss: thm list list};
    85 
    86 fun eq_fp_sugar ({lfp = lfp1, index = index1, fp_res = fp_res1, ...} : fp_sugar,
    87     {lfp = lfp2, index = index2, fp_res = fp_res2, ...} : fp_sugar) =
    88   lfp1 = lfp2 andalso index1 = index2 andalso eq_fp_result (fp_res1, fp_res2);
    89 
    90 fun morph_fp_sugar phi {lfp, index, pre_bnfs, fp_res, ctr_sugars, un_folds, co_recs, un_fold_thmss,
    91     co_rec_thmss} =
    92   {lfp = lfp, index = index, pre_bnfs = map (morph_bnf phi) pre_bnfs,
    93    fp_res = morph_fp_result phi fp_res, ctr_sugars = map (morph_ctr_sugar phi) ctr_sugars,
    94    un_folds = map (Morphism.term phi) un_folds, co_recs = map (Morphism.term phi) co_recs,
    95    un_fold_thmss = map (map (Morphism.thm phi)) un_fold_thmss,
    96    co_rec_thmss = map (map (Morphism.thm phi)) co_rec_thmss};
    97 
    98 structure Data = Generic_Data
    99 (
   100   type T = fp_sugar Symtab.table;
   101   val empty = Symtab.empty;
   102   val extend = I;
   103   val merge = Symtab.merge eq_fp_sugar;
   104 );
   105 
   106 val fp_sugar_of = Symtab.lookup o Data.get o Context.Proof;
   107 
   108 fun register_fp_sugar key fp_sugar =
   109   Local_Theory.declaration {syntax = false, pervasive = true}
   110     (fn phi => Data.map (Symtab.update_new (key, morph_fp_sugar phi fp_sugar)));
   111 
   112 fun register_fp_sugars lfp pre_bnfs (fp_res as {ctors, ...}) ctr_sugars un_folds co_recs
   113     un_fold_thmss co_rec_thmss lthy =
   114   (0, lthy)
   115   |> fold (fn ctor => fn (kk, lthy) => (kk + 1,
   116     register_fp_sugar (fp_name_of_ctor ctor) {lfp = lfp, index = kk,
   117       pre_bnfs = pre_bnfs, fp_res = fp_res, ctr_sugars = ctr_sugars, un_folds = un_folds,
   118       co_recs = co_recs, un_fold_thmss = un_fold_thmss, co_rec_thmss = co_rec_thmss} lthy)) ctors
   119   |> snd;
   120 
   121 (* This function could produce clashes in contrived examples (e.g., "x.A", "x.x_A", "y.A"). *)
   122 fun quasi_unambiguous_case_names names =
   123   let
   124     val ps = map (`Long_Name.base_name) names;
   125     val dups = Library.duplicates (op =) (map fst ps);
   126     fun underscore s =
   127       let val ss = space_explode Long_Name.separator s in
   128         space_implode "_" (drop (length ss - 2) ss)
   129       end;
   130   in
   131     map (fn (base, full) => if member (op =) dups base then underscore full else base) ps
   132   end;
   133 
   134 val mp_conj = @{thm mp_conj};
   135 
   136 val simp_attrs = @{attributes [simp]};
   137 val code_simp_attrs = Code.add_default_eqn_attrib :: simp_attrs;
   138 
   139 fun split_list4 [] = ([], [], [], [])
   140   | split_list4 ((x1, x2, x3, x4) :: xs) =
   141     let val (xs1, xs2, xs3, xs4) = split_list4 xs;
   142     in (x1 :: xs1, x2 :: xs2, x3 :: xs3, x4 :: xs4) end;
   143 
   144 fun add_components_of_typ (Type (s, Ts)) =
   145     fold add_components_of_typ Ts #> cons (Long_Name.base_name s)
   146   | add_components_of_typ _ = I;
   147 
   148 fun base_name_of_typ T = space_implode "_" (add_components_of_typ T []);
   149 
   150 fun exists_subtype_in Ts = exists_subtype (member (op =) Ts);
   151 
   152 fun resort_tfree S (TFree (s, _)) = TFree (s, S);
   153 
   154 fun typ_subst_nonatomic inst (T as Type (s, Ts)) =
   155     (case AList.lookup (op =) inst T of
   156       NONE => Type (s, map (typ_subst_nonatomic inst) Ts)
   157     | SOME T' => T')
   158   | typ_subst_nonatomic inst T = the_default T (AList.lookup (op =) inst T);
   159 
   160 fun variant_types ss Ss ctxt =
   161   let
   162     val (tfrees, _) =
   163       fold_map2 (fn s => fn S => Name.variant s #> apfst (rpair S)) ss Ss (Variable.names_of ctxt);
   164     val ctxt' = fold (Variable.declare_constraints o Logic.mk_type o TFree) tfrees ctxt;
   165   in (tfrees, ctxt') end;
   166 
   167 val lists_bmoc = fold (fn xs => fn t => Term.list_comb (t, xs));
   168 
   169 fun mk_tupled_fun x f xs = HOLogic.tupled_lambda x (Term.list_comb (f, xs));
   170 fun mk_uncurried_fun f xs = mk_tupled_fun (HOLogic.mk_tuple xs) f xs;
   171 
   172 fun flat_rec unzipf xs =
   173   let val ps = map unzipf xs in
   174     (* The first line below gives the preferred order. The second line is for compatibility with the
   175        old datatype package: *)
   176 (*
   177     maps (op @) ps
   178 *)
   179     maps fst ps @ maps snd ps
   180   end;
   181 
   182 fun flat_predss_getterss qss fss = maps (op @) (qss ~~ fss);
   183 
   184 fun flat_preds_predsss_gettersss [] [qss] [fss] = flat_predss_getterss qss fss
   185   | flat_preds_predsss_gettersss (p :: ps) (qss :: qsss) (fss :: fsss) =
   186     p :: flat_predss_getterss qss fss @ flat_preds_predsss_gettersss ps qsss fsss;
   187 
   188 fun mk_flip (x, Type (_, [T1, Type (_, [T2, T3])])) =
   189   Abs ("x", T1, Abs ("y", T2, Var (x, T2 --> T1 --> T3) $ Bound 0 $ Bound 1));
   190 
   191 fun flip_rels lthy n thm =
   192   let
   193     val Rs = Term.add_vars (prop_of thm) [];
   194     val Rs' = rev (drop (length Rs - n) Rs);
   195     val cRs = map (fn f => (certify lthy (Var f), certify lthy (mk_flip f))) Rs';
   196   in
   197     Drule.cterm_instantiate cRs thm
   198   end;
   199 
   200 fun mk_ctor_or_dtor get_T Ts t =
   201   let val Type (_, Ts0) = get_T (fastype_of t) in
   202     Term.subst_atomic_types (Ts0 ~~ Ts) t
   203   end;
   204 
   205 val mk_ctor = mk_ctor_or_dtor range_type;
   206 val mk_dtor = mk_ctor_or_dtor domain_type;
   207 
   208 fun mk_xxiter lfp Ts Us t =
   209   let
   210     val (bindings, body) = strip_type (fastype_of t);
   211     val (f_Us, prebody) = split_last bindings;
   212     val Type (_, Ts0) = if lfp then prebody else body;
   213     val Us0 = distinct (op =) (map (if lfp then body_type else domain_type) f_Us);
   214   in
   215     Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
   216   end;
   217 
   218 val mk_fp_iter_fun_types = fst o split_last o binder_types o fastype_of;
   219 
   220 fun mk_fp_iter lfp As Cs fp_iters0 =
   221   map (mk_xxiter lfp As Cs) fp_iters0
   222   |> (fn ts => (ts, mk_fp_iter_fun_types (hd ts)));
   223 
   224 fun unzip_recT fpTs T =
   225   let
   226     fun project_recT proj =
   227       let
   228         fun project (Type (s as @{type_name prod}, Ts as [T, U])) =
   229             if member (op =) fpTs T then proj (T, U) else Type (s, map project Ts)
   230           | project (Type (s, Ts)) = Type (s, map project Ts)
   231           | project T = T;
   232       in project end;
   233   in
   234     if exists_subtype_in fpTs T then ([project_recT fst T], [project_recT snd T]) else ([T], [])
   235   end;
   236 
   237 val massage_rec_fun_arg_typesss = map o map o flat_rec o unzip_recT;
   238 
   239 val mk_fold_fun_typess = map2 (map2 (curry (op --->)));
   240 val mk_rec_fun_typess = mk_fold_fun_typess oo massage_rec_fun_arg_typesss;
   241 
   242 fun mk_fun_arg_typess n ms = map2 dest_tupleT ms o dest_sumTN_balanced n o domain_type;
   243 
   244 fun mk_fold_rec_terms_types fpTs Css ns mss ctor_fold_fun_Ts ctor_rec_fun_Ts lthy =
   245   let
   246     val y_Tsss = map3 mk_fun_arg_typess ns mss ctor_fold_fun_Ts;
   247     val g_Tss = mk_fold_fun_typess y_Tsss Css;
   248 
   249     val ((gss, ysss), lthy) =
   250       lthy
   251       |> mk_Freess "f" g_Tss
   252       ||>> mk_Freesss "x" y_Tsss;
   253 
   254     val z_Tsss = map3 mk_fun_arg_typess ns mss ctor_rec_fun_Ts;
   255     val h_Tss = mk_rec_fun_typess fpTs z_Tsss Css;
   256 
   257     val hss = map2 (map2 retype_free) h_Tss gss;
   258     val zsss = map2 (map2 (map2 retype_free)) z_Tsss ysss;
   259   in
   260     (((gss, g_Tss, ysss), (hss, h_Tss, zsss)), lthy)
   261   end;
   262 
   263 fun mk_unfold_corec_terms_types fpTs Cs ns mss dtor_unfold_fun_Ts dtor_corec_fun_Ts lthy =
   264   let
   265     (*avoid "'a itself" arguments in coiterators and corecursors*)
   266     fun repair_arity [0] = [1]
   267       | repair_arity ms = ms;
   268 
   269     fun project_corecT proj =
   270       let
   271         fun project (Type (s as @{type_name sum}, Ts as [T, U])) =
   272             if member (op =) fpTs T then proj (T, U) else Type (s, map project Ts)
   273           | project (Type (s, Ts)) = Type (s, map project Ts)
   274           | project T = T;
   275       in project end;
   276 
   277     fun unzip_corecT T =
   278       if exists_subtype_in fpTs T then [project_corecT fst T, project_corecT snd T] else [T];
   279 
   280     val p_Tss = map2 (fn n => replicate (Int.max (0, n - 1)) o mk_pred1T) ns Cs;
   281 
   282     fun mk_types maybe_unzipT fun_Ts =
   283       let
   284         val f_sum_prod_Ts = map range_type fun_Ts;
   285         val f_prod_Tss = map2 dest_sumTN_balanced ns f_sum_prod_Ts;
   286         val f_Tsss = map2 (map2 dest_tupleT o repair_arity) mss f_prod_Tss;
   287         val f_Tssss =
   288           map2 (fn C => map (map (map (curry (op -->) C) o maybe_unzipT))) Cs f_Tsss;
   289         val q_Tssss =
   290           map (map (map (fn [_] => [] | [_, C] => [mk_pred1T (domain_type C)]))) f_Tssss;
   291         val pf_Tss = map3 flat_preds_predsss_gettersss p_Tss q_Tssss f_Tssss;
   292       in (q_Tssss, f_sum_prod_Ts, f_Tsss, f_Tssss, pf_Tss) end;
   293 
   294     val (r_Tssss, g_sum_prod_Ts, g_Tsss, g_Tssss, pg_Tss) = mk_types single dtor_unfold_fun_Ts;
   295     val (s_Tssss, h_sum_prod_Ts, h_Tsss, h_Tssss, ph_Tss) = mk_types unzip_corecT dtor_corec_fun_Ts;
   296 
   297     val (((cs, pss), gssss), lthy) =
   298       lthy
   299       |> mk_Frees "a" Cs
   300       ||>> mk_Freess "p" p_Tss
   301       ||>> mk_Freessss "g" g_Tssss;
   302     val rssss = map (map (map (fn [] => []))) r_Tssss;
   303 
   304     val hssss_hd = map2 (map2 (map2 (fn T :: _ => fn [g] => retype_free T g))) h_Tssss gssss;
   305     val ((sssss, hssss_tl), lthy) =
   306       lthy
   307       |> mk_Freessss "q" s_Tssss
   308       ||>> mk_Freessss "h" (map (map (map tl)) h_Tssss);
   309     val hssss = map2 (map2 (map2 cons)) hssss_hd hssss_tl;
   310 
   311     val cpss = map2 (map o rapp) cs pss;
   312 
   313     fun mk_terms qssss fssss =
   314       let
   315         val pfss = map3 flat_preds_predsss_gettersss pss qssss fssss;
   316         val cqssss = map2 (map o map o map o rapp) cs qssss;
   317         val cfssss = map2 (map o map o map o rapp) cs fssss;
   318       in (pfss, cqssss, cfssss) end;
   319 
   320     val unfold_terms = mk_terms rssss gssss;
   321     val corec_terms = mk_terms sssss hssss;
   322   in
   323     ((cs, cpss, (unfold_terms, (g_sum_prod_Ts, g_Tsss, pg_Tss)),
   324       (corec_terms, (h_sum_prod_Ts, h_Tsss, ph_Tss))), lthy)
   325   end;
   326 
   327 fun mk_map live Ts Us t =
   328   let val (Type (_, Ts0), Type (_, Us0)) = strip_typeN (live + 1) (fastype_of t) |>> List.last in
   329     Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
   330   end;
   331 
   332 fun mk_rel live Ts Us t =
   333   let val [Type (_, Ts0), Type (_, Us0)] = binder_types (snd (strip_typeN live (fastype_of t))) in
   334     Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
   335   end;
   336 
   337 fun liveness_of_fp_bnf n bnf =
   338   (case T_of_bnf bnf of
   339     Type (_, Ts) => map (not o member (op =) (deads_of_bnf bnf)) Ts
   340   | _ => replicate n false);
   341 
   342 fun cannot_merge_types () = error "Mutually recursive types must have the same type parameters";
   343 
   344 fun merge_type_arg T T' = if T = T' then T else cannot_merge_types ();
   345 
   346 fun merge_type_args (As, As') =
   347   if length As = length As' then map2 merge_type_arg As As' else cannot_merge_types ();
   348 
   349 fun reassoc_conjs thm =
   350   reassoc_conjs (thm RS @{thm conj_assoc[THEN iffD1]})
   351   handle THM _ => thm;
   352 
   353 fun type_args_named_constrained_of ((((ncAs, _), _), _), _) = ncAs;
   354 fun type_binding_of ((((_, b), _), _), _) = b;
   355 fun map_binding_of (((_, (b, _)), _), _) = b;
   356 fun rel_binding_of (((_, (_, b)), _), _) = b;
   357 fun mixfix_of ((_, mx), _) = mx;
   358 fun ctr_specs_of (_, ctr_specs) = ctr_specs;
   359 
   360 fun disc_of ((((disc, _), _), _), _) = disc;
   361 fun ctr_of ((((_, ctr), _), _), _) = ctr;
   362 fun args_of (((_, args), _), _) = args;
   363 fun defaults_of ((_, ds), _) = ds;
   364 fun ctr_mixfix_of (_, mx) = mx;
   365 
   366 fun indexify_fst xs f (x, y) = f (find_index (curry (op =) x) xs) (x, y);
   367 
   368 fun build_map lthy build_simple =
   369   let
   370     fun build (TU as (T, U)) =
   371       if T = U then
   372         id_const T
   373       else
   374         (case TU of
   375           (Type (s, Ts), Type (s', Us)) =>
   376           if s = s' then
   377             let
   378               val bnf = the (bnf_of lthy s);
   379               val live = live_of_bnf bnf;
   380               val mapx = mk_map live Ts Us (map_of_bnf bnf);
   381               val TUs' = map dest_funT (fst (strip_typeN live (fastype_of mapx)));
   382             in Term.list_comb (mapx, map build TUs') end
   383           else
   384             build_simple TU
   385         | _ => build_simple TU);
   386   in build end;
   387 
   388 fun derive_induct_fold_rec_thms_for_types pre_bnfs ctor_folds0 ctor_recs0 ctor_induct ctor_fold_thms
   389     ctor_rec_thms nesting_bnfs nested_bnfs fpTs Cs As ctrss ctr_defss folds recs fold_defs rec_defs
   390     lthy =
   391   let
   392     val ctr_Tsss = map (map (binder_types o fastype_of)) ctrss;
   393 
   394     val nn = length pre_bnfs;
   395     val ns = map length ctr_Tsss;
   396     val mss = map (map length) ctr_Tsss;
   397     val Css = map2 replicate ns Cs;
   398 
   399     val pre_map_defs = map map_def_of_bnf pre_bnfs;
   400     val pre_set_defss = map set_defs_of_bnf pre_bnfs;
   401     val nesting_map_ids'' = map (unfold_thms lthy @{thms id_def} o map_id_of_bnf) nesting_bnfs;
   402     val nested_map_comp's = map map_comp'_of_bnf nested_bnfs;
   403     val nested_map_ids'' = map (unfold_thms lthy @{thms id_def} o map_id_of_bnf) nested_bnfs;
   404     val nested_set_map's = maps set_map'_of_bnf nested_bnfs;
   405 
   406     val fp_b_names = map base_name_of_typ fpTs;
   407 
   408     val (_, ctor_fold_fun_Ts) = mk_fp_iter true As Cs ctor_folds0;
   409     val (_, ctor_rec_fun_Ts) = mk_fp_iter true As Cs ctor_recs0;
   410 
   411     val (((gss, _, _), (hss, _, _)), names_lthy0) =
   412       mk_fold_rec_terms_types fpTs Css ns mss ctor_fold_fun_Ts ctor_rec_fun_Ts lthy;
   413 
   414     val ((((ps, ps'), xsss), us'), names_lthy) =
   415       names_lthy0
   416       |> mk_Frees' "P" (map mk_pred1T fpTs)
   417       ||>> mk_Freesss "x" ctr_Tsss
   418       ||>> Variable.variant_fixes fp_b_names;
   419 
   420     val us = map2 (curry Free) us' fpTs;
   421 
   422     fun mk_sets_nested bnf =
   423       let
   424         val Type (T_name, Us) = T_of_bnf bnf;
   425         val lives = lives_of_bnf bnf;
   426         val sets = sets_of_bnf bnf;
   427         fun mk_set U =
   428           (case find_index (curry (op =) U) lives of
   429             ~1 => Term.dummy
   430           | i => nth sets i);
   431       in
   432         (T_name, map mk_set Us)
   433       end;
   434 
   435     val setss_nested = map mk_sets_nested nested_bnfs;
   436 
   437     val (induct_thms, induct_thm) =
   438       let
   439         fun mk_set Ts t =
   440           let val Type (_, Ts0) = domain_type (fastype_of t) in
   441             Term.subst_atomic_types (Ts0 ~~ Ts) t
   442           end;
   443 
   444         fun mk_raw_prem_prems names_lthy (x as Free (s, T as Type (T_name, Ts0))) =
   445             (case find_index (curry (op =) T) fpTs of
   446               ~1 =>
   447               (case AList.lookup (op =) setss_nested T_name of
   448                 NONE => []
   449               | SOME raw_sets0 =>
   450                 let
   451                   val (Ts, raw_sets) =
   452                     split_list (filter (exists_subtype_in fpTs o fst) (Ts0 ~~ raw_sets0));
   453                   val sets = map (mk_set Ts0) raw_sets;
   454                   val (ys, names_lthy') = names_lthy |> mk_Frees s Ts;
   455                   val xysets = map (pair x) (ys ~~ sets);
   456                   val ppremss = map (mk_raw_prem_prems names_lthy') ys;
   457                 in
   458                   flat (map2 (map o apfst o cons) xysets ppremss)
   459                 end)
   460             | kk => [([], (kk + 1, x))])
   461           | mk_raw_prem_prems _ _ = [];
   462 
   463         fun close_prem_prem xs t =
   464           fold_rev Logic.all (map Free (drop (nn + length xs)
   465             (rev (Term.add_frees t (map dest_Free xs @ ps'))))) t;
   466 
   467         fun mk_prem_prem xs (xysets, (j, x)) =
   468           close_prem_prem xs (Logic.list_implies (map (fn (x', (y, set)) =>
   469               HOLogic.mk_Trueprop (HOLogic.mk_mem (y, set $ x'))) xysets,
   470             HOLogic.mk_Trueprop (nth ps (j - 1) $ x)));
   471 
   472         fun mk_raw_prem phi ctr ctr_Ts =
   473           let
   474             val (xs, names_lthy') = names_lthy |> mk_Frees "x" ctr_Ts;
   475             val pprems = maps (mk_raw_prem_prems names_lthy') xs;
   476           in (xs, pprems, HOLogic.mk_Trueprop (phi $ Term.list_comb (ctr, xs))) end;
   477 
   478         fun mk_prem (xs, raw_pprems, concl) =
   479           fold_rev Logic.all xs (Logic.list_implies (map (mk_prem_prem xs) raw_pprems, concl));
   480 
   481         val raw_premss = map3 (map2 o mk_raw_prem) ps ctrss ctr_Tsss;
   482 
   483         val goal =
   484           Library.foldr (Logic.list_implies o apfst (map mk_prem)) (raw_premss,
   485             HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map2 (curry (op $)) ps us)));
   486 
   487         val kksss = map (map (map (fst o snd) o #2)) raw_premss;
   488 
   489         val ctor_induct' = ctor_induct OF (map mk_sumEN_tupled_balanced mss);
   490 
   491         val thm =
   492           Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   493             mk_induct_tac ctxt nn ns mss kksss (flat ctr_defss) ctor_induct' nested_set_map's
   494               pre_set_defss)
   495           |> singleton (Proof_Context.export names_lthy lthy)
   496           |> Thm.close_derivation;
   497       in
   498         `(conj_dests nn) thm
   499       end;
   500 
   501     val induct_cases = quasi_unambiguous_case_names (maps (map name_of_ctr) ctrss);
   502 
   503     val (fold_thmss, rec_thmss) =
   504       let
   505         val xctrss = map2 (map2 (curry Term.list_comb)) ctrss xsss;
   506         val gfolds = map (lists_bmoc gss) folds;
   507         val hrecs = map (lists_bmoc hss) recs;
   508 
   509         fun mk_goal fss fiter xctr f xs fxs =
   510           fold_rev (fold_rev Logic.all) (xs :: fss)
   511             (mk_Trueprop_eq (fiter $ xctr, Term.list_comb (f, fxs)));
   512 
   513         val mk_U = typ_subst_nonatomic (map2 pair fpTs Cs);
   514 
   515         fun unzip_iters fiters combine (x as Free (_, T)) =
   516           if exists_subtype_in fpTs T then
   517             combine (x, build_map lthy (indexify_fst fpTs (K o nth fiters)) (T, mk_U T) $ x)
   518           else
   519             ([x], []);
   520 
   521         val gxsss = map (map (flat_rec (unzip_iters gfolds (fn (_, t) => ([t], []))))) xsss;
   522         val hxsss = map (map (flat_rec (unzip_iters hrecs (pairself single)))) xsss;
   523 
   524         val fold_goalss = map5 (map4 o mk_goal gss) gfolds xctrss gss xsss gxsss;
   525         val rec_goalss = map5 (map4 o mk_goal hss) hrecs xctrss hss xsss hxsss;
   526 
   527         val fold_tacss =
   528           map2 (map o mk_iter_tac pre_map_defs [] nesting_map_ids'' fold_defs) ctor_fold_thms
   529             ctr_defss;
   530         val rec_tacss =
   531           map2 (map o mk_iter_tac pre_map_defs nested_map_comp's
   532             (nested_map_ids'' @ nesting_map_ids'') rec_defs) ctor_rec_thms ctr_defss;
   533 
   534         fun prove goal tac =
   535           Goal.prove_sorry lthy [] [] goal (tac o #context)
   536           |> Thm.close_derivation;
   537       in
   538         (map2 (map2 prove) fold_goalss fold_tacss, map2 (map2 prove) rec_goalss rec_tacss)
   539       end;
   540 
   541     val induct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names induct_cases));
   542   in
   543     ((induct_thm, induct_thms, [induct_case_names_attr]),
   544      (fold_thmss, code_simp_attrs), (rec_thmss, code_simp_attrs))
   545   end;
   546 
   547 fun derive_coinduct_unfold_corec_thms_for_types pre_bnfs dtor_unfolds0 dtor_corecs0 dtor_coinduct
   548     dtor_strong_induct dtor_ctors dtor_unfold_thms dtor_corec_thms nesting_bnfs nested_bnfs fpTs Cs
   549     As kss mss ns ctr_defss ctr_sugars unfolds corecs unfold_defs corec_defs lthy =
   550   let
   551     val nn = length pre_bnfs;
   552 
   553     val pre_map_defs = map map_def_of_bnf pre_bnfs;
   554     val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
   555     val nesting_map_ids'' = map (unfold_thms lthy @{thms id_def} o map_id_of_bnf) nesting_bnfs;
   556     val nesting_rel_eqs = map rel_eq_of_bnf nesting_bnfs;
   557     val nested_map_comp's = map map_comp'_of_bnf nested_bnfs;
   558     val nested_map_comps'' = map ((fn thm => thm RS sym) o map_comp_of_bnf) nested_bnfs;
   559     val nested_map_ids'' = map (unfold_thms lthy @{thms id_def} o map_id_of_bnf) nested_bnfs;
   560 
   561     val fp_b_names = map base_name_of_typ fpTs;
   562 
   563     val (_, dtor_unfold_fun_Ts) = mk_fp_iter false As Cs dtor_unfolds0;
   564     val (_, dtor_corec_fun_Ts) = mk_fp_iter false As Cs dtor_corecs0;
   565 
   566     val ctrss = map (map (mk_ctr As) o #ctrs) ctr_sugars;
   567     val discss = map (map (mk_disc_or_sel As) o #discs) ctr_sugars;
   568     val selsss = map (map (map (mk_disc_or_sel As)) o #selss) ctr_sugars;
   569     val exhausts = map #exhaust ctr_sugars;
   570     val disc_thmsss = map #disc_thmss ctr_sugars;
   571     val discIss = map #discIs ctr_sugars;
   572     val sel_thmsss = map #sel_thmss ctr_sugars;
   573 
   574     val ((cs, cpss, ((pgss, crssss, cgssss), _), ((phss, csssss, chssss), _)), names_lthy0) =
   575       mk_unfold_corec_terms_types fpTs Cs ns mss dtor_unfold_fun_Ts dtor_corec_fun_Ts lthy;
   576 
   577     val (((rs, us'), vs'), names_lthy) =
   578       names_lthy0
   579       |> mk_Frees "R" (map (fn T => mk_pred2T T T) fpTs)
   580       ||>> Variable.variant_fixes fp_b_names
   581       ||>> Variable.variant_fixes (map (suffix "'") fp_b_names);
   582 
   583     val us = map2 (curry Free) us' fpTs;
   584     val udiscss = map2 (map o rapp) us discss;
   585     val uselsss = map2 (map o map o rapp) us selsss;
   586 
   587     val vs = map2 (curry Free) vs' fpTs;
   588     val vdiscss = map2 (map o rapp) vs discss;
   589     val vselsss = map2 (map o map o rapp) vs selsss;
   590 
   591     val ((coinduct_thms, coinduct_thm), (strong_coinduct_thms, strong_coinduct_thm)) =
   592       let
   593         val uvrs = map3 (fn r => fn u => fn v => r $ u $ v) rs us vs;
   594         val uv_eqs = map2 (curry HOLogic.mk_eq) us vs;
   595         val strong_rs =
   596           map4 (fn u => fn v => fn uvr => fn uv_eq =>
   597             fold_rev Term.lambda [u, v] (HOLogic.mk_disj (uvr, uv_eq))) us vs uvrs uv_eqs;
   598 
   599         fun build_rel rs' T =
   600           (case find_index (curry (op =) T) fpTs of
   601             ~1 =>
   602             if exists_subtype_in fpTs T then
   603               let
   604                 val Type (s, Ts) = T
   605                 val bnf = the (bnf_of lthy s);
   606                 val live = live_of_bnf bnf;
   607                 val rel = mk_rel live Ts Ts (rel_of_bnf bnf);
   608                 val Ts' = map domain_type (fst (strip_typeN live (fastype_of rel)));
   609               in Term.list_comb (rel, map (build_rel rs') Ts') end
   610             else
   611               HOLogic.eq_const T
   612           | kk => nth rs' kk);
   613 
   614         fun build_rel_app rs' usel vsel = fold rapp [usel, vsel] (build_rel rs' (fastype_of usel));
   615 
   616         fun mk_prem_ctr_concls rs' n k udisc usels vdisc vsels =
   617           (if k = n then [] else [HOLogic.mk_eq (udisc, vdisc)]) @
   618           (if null usels then
   619              []
   620            else
   621              [Library.foldr HOLogic.mk_imp (if n = 1 then [] else [udisc, vdisc],
   622                 Library.foldr1 HOLogic.mk_conj (map2 (build_rel_app rs') usels vsels))]);
   623 
   624         fun mk_prem_concl rs' n udiscs uselss vdiscs vselss =
   625           Library.foldr1 HOLogic.mk_conj
   626             (flat (map5 (mk_prem_ctr_concls rs' n) (1 upto n) udiscs uselss vdiscs vselss))
   627           handle List.Empty => @{term True};
   628 
   629         fun mk_prem rs' uvr u v n udiscs uselss vdiscs vselss =
   630           fold_rev Logic.all [u, v] (Logic.mk_implies (HOLogic.mk_Trueprop uvr,
   631             HOLogic.mk_Trueprop (mk_prem_concl rs' n udiscs uselss vdiscs vselss)));
   632 
   633         val concl =
   634           HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
   635             (map3 (fn uvr => fn u => fn v => HOLogic.mk_imp (uvr, HOLogic.mk_eq (u, v)))
   636                uvrs us vs));
   637 
   638         fun mk_goal rs' =
   639           Logic.list_implies (map8 (mk_prem rs') uvrs us vs ns udiscss uselsss vdiscss vselsss,
   640             concl);
   641 
   642         val goal = mk_goal rs;
   643         val strong_goal = mk_goal strong_rs;
   644 
   645         fun prove dtor_coinduct' goal =
   646           Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
   647             mk_coinduct_tac ctxt nesting_rel_eqs nn ns dtor_coinduct' pre_rel_defs dtor_ctors
   648               exhausts ctr_defss disc_thmsss sel_thmsss)
   649           |> singleton (Proof_Context.export names_lthy lthy)
   650           |> Thm.close_derivation;
   651 
   652         fun postproc nn thm =
   653           Thm.permute_prems 0 nn
   654             (if nn = 1 then thm RS mp else funpow nn (fn thm => reassoc_conjs (thm RS mp_conj)) thm)
   655           |> Drule.zero_var_indexes
   656           |> `(conj_dests nn);
   657       in
   658         (postproc nn (prove dtor_coinduct goal), postproc nn (prove dtor_strong_induct strong_goal))
   659       end;
   660 
   661     fun mk_coinduct_concls ms discs ctrs =
   662       let
   663         fun mk_disc_concl disc = [name_of_disc disc];
   664         fun mk_ctr_concl 0 _ = []
   665           | mk_ctr_concl _ ctor = [name_of_ctr ctor];
   666         val disc_concls = map mk_disc_concl (fst (split_last discs)) @ [[]];
   667         val ctr_concls = map2 mk_ctr_concl ms ctrs;
   668       in
   669         flat (map2 append disc_concls ctr_concls)
   670       end;
   671 
   672     val coinduct_cases = quasi_unambiguous_case_names (map (prefix EqN) fp_b_names);
   673     val coinduct_conclss =
   674       map3 (quasi_unambiguous_case_names ooo mk_coinduct_concls) mss discss ctrss;
   675 
   676     fun mk_maybe_not pos = not pos ? HOLogic.mk_not;
   677 
   678     val gunfolds = map (lists_bmoc pgss) unfolds;
   679     val hcorecs = map (lists_bmoc phss) corecs;
   680 
   681     val (unfold_thmss, corec_thmss, safe_unfold_thmss, safe_corec_thmss) =
   682       let
   683         fun mk_goal pfss c cps fcoiter n k ctr m cfs' =
   684           fold_rev (fold_rev Logic.all) ([c] :: pfss)
   685             (Logic.list_implies (seq_conds (HOLogic.mk_Trueprop oo mk_maybe_not) n k cps,
   686                mk_Trueprop_eq (fcoiter $ c, Term.list_comb (ctr, take m cfs'))));
   687 
   688         val mk_U = typ_subst_nonatomic (map2 pair Cs fpTs);
   689 
   690         fun intr_coiters fcoiters [] [cf] =
   691             let val T = fastype_of cf in
   692               if exists_subtype_in Cs T then
   693                 build_map lthy (indexify_fst Cs (K o nth fcoiters)) (T, mk_U T) $ cf
   694               else
   695                 cf
   696             end
   697           | intr_coiters fcoiters [cq] [cf, cf'] =
   698             mk_If cq (intr_coiters fcoiters [] [cf]) (intr_coiters fcoiters [] [cf']);
   699 
   700         val crgsss = map2 (map2 (map2 (intr_coiters gunfolds))) crssss cgssss;
   701         val cshsss = map2 (map2 (map2 (intr_coiters hcorecs))) csssss chssss;
   702 
   703         val unfold_goalss = map8 (map4 oooo mk_goal pgss) cs cpss gunfolds ns kss ctrss mss crgsss;
   704         val corec_goalss = map8 (map4 oooo mk_goal phss) cs cpss hcorecs ns kss ctrss mss cshsss;
   705 
   706         fun mk_map_if_distrib bnf =
   707           let
   708             val mapx = map_of_bnf bnf;
   709             val live = live_of_bnf bnf;
   710             val ((Ts, T), U) = strip_typeN (live + 1) (fastype_of mapx) |>> split_last;
   711             val fs = Variable.variant_frees lthy [mapx] (map (pair "f") Ts);
   712             val t = Term.list_comb (mapx, map (Var o apfst (rpair 0)) fs);
   713           in
   714             Drule.instantiate' (map (SOME o certifyT lthy) [U, T]) [SOME (certify lthy t)]
   715               @{thm if_distrib}
   716           end;
   717 
   718         val nested_map_if_distribs = map mk_map_if_distrib nested_bnfs;
   719 
   720         val unfold_tacss =
   721           map3 (map oo mk_coiter_tac unfold_defs [] [] nesting_map_ids'' [])
   722             dtor_unfold_thms pre_map_defs ctr_defss;
   723         val corec_tacss =
   724           map3 (map oo mk_coiter_tac corec_defs nested_map_comps'' nested_map_comp's
   725               (nested_map_ids'' @ nesting_map_ids'') nested_map_if_distribs)
   726             dtor_corec_thms pre_map_defs ctr_defss;
   727 
   728         fun prove goal tac =
   729           Goal.prove_sorry lthy [] [] goal (tac o #context)
   730           |> Thm.close_derivation;
   731 
   732         val unfold_thmss = map2 (map2 prove) unfold_goalss unfold_tacss;
   733         val corec_thmss = map2 (map2 prove) corec_goalss corec_tacss;
   734 
   735         val filter_safesss =
   736           map2 (map_filter (fn (safes, thm) => if forall I safes then SOME thm else NONE) oo
   737             curry (op ~~)) (map2 (map2 (map2 (member (op =)))) cgssss crgsss);
   738 
   739         val safe_unfold_thmss = filter_safesss unfold_thmss;
   740         val safe_corec_thmss = filter_safesss corec_thmss;
   741       in
   742         (unfold_thmss, corec_thmss, safe_unfold_thmss, safe_corec_thmss)
   743       end;
   744 
   745     val (disc_unfold_iff_thmss, disc_corec_iff_thmss) =
   746       let
   747         fun mk_goal c cps fcoiter n k disc =
   748           mk_Trueprop_eq (disc $ (fcoiter $ c),
   749             if n = 1 then @{const True}
   750             else Library.foldr1 HOLogic.mk_conj (seq_conds mk_maybe_not n k cps));
   751 
   752         val unfold_goalss = map6 (map2 oooo mk_goal) cs cpss gunfolds ns kss discss;
   753         val corec_goalss = map6 (map2 oooo mk_goal) cs cpss hcorecs ns kss discss;
   754 
   755         fun mk_case_split' cp = Drule.instantiate' [] [SOME (certify lthy cp)] @{thm case_split};
   756 
   757         val case_splitss' = map (map mk_case_split') cpss;
   758 
   759         val unfold_tacss =
   760           map3 (map oo mk_disc_coiter_iff_tac) case_splitss' unfold_thmss disc_thmsss;
   761         val corec_tacss =
   762           map3 (map oo mk_disc_coiter_iff_tac) case_splitss' corec_thmss disc_thmsss;
   763 
   764         fun prove goal tac =
   765           Goal.prove_sorry lthy [] [] goal (tac o #context)
   766           |> singleton (Proof_Context.export names_lthy lthy)
   767           |> Thm.close_derivation;
   768 
   769         fun proves [_] [_] = []
   770           | proves goals tacs = map2 prove goals tacs;
   771       in
   772         (map2 proves unfold_goalss unfold_tacss, map2 proves corec_goalss corec_tacss)
   773       end;
   774 
   775     val is_triv_discI = is_triv_implies orf is_concl_refl;
   776 
   777     fun mk_disc_coiter_thms coiters discIs =
   778       map (op RS) (filter_out (is_triv_discI o snd) (coiters ~~ discIs));
   779 
   780     val disc_unfold_thmss = map2 mk_disc_coiter_thms unfold_thmss discIss;
   781     val disc_corec_thmss = map2 mk_disc_coiter_thms corec_thmss discIss;
   782 
   783     fun mk_sel_coiter_thm coiter_thm sel sel_thm =
   784       let
   785         val (domT, ranT) = dest_funT (fastype_of sel);
   786         val arg_cong' =
   787           Drule.instantiate' (map (SOME o certifyT lthy) [domT, ranT])
   788             [NONE, NONE, SOME (certify lthy sel)] arg_cong
   789           |> Thm.varifyT_global;
   790         val sel_thm' = sel_thm RSN (2, trans);
   791       in
   792         coiter_thm RS arg_cong' RS sel_thm'
   793       end;
   794 
   795     fun mk_sel_coiter_thms coiterss =
   796       map3 (map3 (map2 o mk_sel_coiter_thm)) coiterss selsss sel_thmsss |> map flat;
   797 
   798     val sel_unfold_thmss = mk_sel_coiter_thms unfold_thmss;
   799     val sel_corec_thmss = mk_sel_coiter_thms corec_thmss;
   800 
   801     val coinduct_consumes_attr = Attrib.internal (K (Rule_Cases.consumes nn));
   802     val coinduct_case_names_attr = Attrib.internal (K (Rule_Cases.case_names coinduct_cases));
   803     val coinduct_case_concl_attrs =
   804       map2 (fn casex => fn concls =>
   805           Attrib.internal (K (Rule_Cases.case_conclusion (casex, concls))))
   806         coinduct_cases coinduct_conclss;
   807     val coinduct_case_attrs =
   808       coinduct_consumes_attr :: coinduct_case_names_attr :: coinduct_case_concl_attrs;
   809   in
   810     ((coinduct_thm, coinduct_thms, strong_coinduct_thm, strong_coinduct_thms, coinduct_case_attrs),
   811      (unfold_thmss, corec_thmss, []),
   812      (safe_unfold_thmss, safe_corec_thmss),
   813      (disc_unfold_thmss, disc_corec_thmss, simp_attrs),
   814      (disc_unfold_iff_thmss, disc_corec_iff_thmss, simp_attrs),
   815      (sel_unfold_thmss, sel_corec_thmss, simp_attrs))
   816   end;
   817 
   818 fun define_datatypes prepare_constraint prepare_typ prepare_term lfp construct_fp
   819     (wrap_opts as (no_dests, rep_compat), specs) no_defs_lthy0 =
   820   let
   821     (* TODO: sanity checks on arguments *)
   822 
   823     val _ = if not lfp andalso no_dests then error "Cannot define destructor-less codatatypes"
   824       else ();
   825 
   826     fun qualify mandatory fp_b_name =
   827       Binding.qualify mandatory fp_b_name o (rep_compat ? Binding.qualify false rep_compat_prefix);
   828 
   829     val nn = length specs;
   830     val fp_bs = map type_binding_of specs;
   831     val fp_b_names = map Binding.name_of fp_bs;
   832     val fp_common_name = mk_common_name fp_b_names;
   833     val map_bs = map map_binding_of specs;
   834     val rel_bs = map rel_binding_of specs;
   835 
   836     fun prepare_type_arg (_, (ty, c)) =
   837       let val TFree (s, _) = prepare_typ no_defs_lthy0 ty in
   838         TFree (s, prepare_constraint no_defs_lthy0 c)
   839       end;
   840 
   841     val Ass0 = map (map prepare_type_arg o type_args_named_constrained_of) specs;
   842     val unsorted_Ass0 = map (map (resort_tfree HOLogic.typeS)) Ass0;
   843     val unsorted_As = Library.foldr1 merge_type_args unsorted_Ass0;
   844     val set_bss = map (map fst o type_args_named_constrained_of) specs;
   845 
   846     val (((Bs0, Cs), Xs), no_defs_lthy) =
   847       no_defs_lthy0
   848       |> fold (Variable.declare_typ o resort_tfree dummyS) unsorted_As
   849       |> mk_TFrees (length unsorted_As)
   850       ||>> mk_TFrees nn
   851       ||>> apfst (map TFree) o
   852         variant_types (map (prefix "'") fp_b_names) (replicate nn HOLogic.typeS);
   853 
   854     (* TODO: cleaner handling of fake contexts, without "background_theory" *)
   855     (*the "perhaps o try" below helps gracefully handles the case where the new type is defined in a
   856       locale and shadows an existing global type*)
   857 
   858     fun add_fake_type spec =
   859       Sign.add_type no_defs_lthy (type_binding_of spec,
   860         length (type_args_named_constrained_of spec), mixfix_of spec);
   861 
   862     val fake_thy = Theory.copy #> fold add_fake_type specs;
   863     val fake_lthy = Proof_Context.background_theory fake_thy no_defs_lthy;
   864 
   865     fun mk_fake_T b =
   866       Type (fst (Term.dest_Type (Proof_Context.read_type_name fake_lthy true (Binding.name_of b))),
   867         unsorted_As);
   868 
   869     val fake_Ts = map mk_fake_T fp_bs;
   870 
   871     val mixfixes = map mixfix_of specs;
   872 
   873     val _ = (case duplicates Binding.eq_name fp_bs of [] => ()
   874       | b :: _ => error ("Duplicate type name declaration " ^ quote (Binding.name_of b)));
   875 
   876     val ctr_specss = map ctr_specs_of specs;
   877 
   878     val disc_bindingss = map (map disc_of) ctr_specss;
   879     val ctr_bindingss =
   880       map2 (fn fp_b_name => map (qualify false fp_b_name o ctr_of)) fp_b_names ctr_specss;
   881     val ctr_argsss = map (map args_of) ctr_specss;
   882     val ctr_mixfixess = map (map ctr_mixfix_of) ctr_specss;
   883 
   884     val sel_bindingsss = map (map (map fst)) ctr_argsss;
   885     val fake_ctr_Tsss0 = map (map (map (prepare_typ fake_lthy o snd))) ctr_argsss;
   886     val raw_sel_defaultsss = map (map defaults_of) ctr_specss;
   887 
   888     val (As :: _) :: fake_ctr_Tsss =
   889       burrow (burrow (Syntax.check_typs fake_lthy)) (Ass0 :: fake_ctr_Tsss0);
   890 
   891     val _ = (case duplicates (op =) unsorted_As of [] => ()
   892       | A :: _ => error ("Duplicate type parameter " ^
   893           quote (Syntax.string_of_typ no_defs_lthy A)));
   894 
   895     val rhs_As' = fold (fold (fold Term.add_tfreesT)) fake_ctr_Tsss [];
   896     val _ = (case subtract (op =) (map dest_TFree As) rhs_As' of
   897         [] => ()
   898       | A' :: _ => error ("Extra type variable on right-hand side: " ^
   899           quote (Syntax.string_of_typ no_defs_lthy (TFree A'))));
   900 
   901     fun eq_fpT_check (T as Type (s, Us)) (Type (s', Us')) =
   902         s = s' andalso (Us = Us' orelse error ("Illegal occurrence of recursive type " ^
   903           quote (Syntax.string_of_typ fake_lthy T)))
   904       | eq_fpT_check _ _ = false;
   905 
   906     fun freeze_fp (T as Type (s, Us)) =
   907         (case find_index (eq_fpT_check T) fake_Ts of
   908           ~1 => Type (s, map freeze_fp Us)
   909         | kk => nth Xs kk)
   910       | freeze_fp T = T;
   911 
   912     val ctr_TsssXs = map (map (map freeze_fp)) fake_ctr_Tsss;
   913     val ctr_sum_prod_TsXs = map (mk_sumTN_balanced o map HOLogic.mk_tupleT) ctr_TsssXs;
   914 
   915     val fp_eqs =
   916       map dest_TFree Xs ~~ map (Term.typ_subst_atomic (As ~~ unsorted_As)) ctr_sum_prod_TsXs;
   917 
   918     val (pre_bnfs, (fp_res as {bnfs = fp_bnfs as any_fp_bnf :: _, ctors = ctors0, dtors = dtors0,
   919            folds = fp_folds0, recs = fp_recs0, induct = fp_induct, strong_induct = fp_strong_induct,
   920            dtor_ctors, ctor_dtors, ctor_injects, map_thms = fp_map_thms, set_thmss = fp_set_thmss,
   921            rel_thms = fp_rel_thms, fold_thms = fp_fold_thms, rec_thms = fp_rec_thms}, lthy)) =
   922       fp_bnf construct_fp fp_bs mixfixes map_bs rel_bs set_bss (map dest_TFree unsorted_As) fp_eqs
   923         no_defs_lthy0;
   924 
   925     val timer = time (Timer.startRealTimer ());
   926 
   927     fun add_nesty_bnf_names Us =
   928       let
   929         fun add (Type (s, Ts)) ss =
   930             let val (needs, ss') = fold_map add Ts ss in
   931               if exists I needs then (true, insert (op =) s ss') else (false, ss')
   932             end
   933           | add T ss = (member (op =) Us T, ss);
   934       in snd oo add end;
   935 
   936     fun nesty_bnfs Us =
   937       map_filter (bnf_of lthy) (fold (fold (fold (add_nesty_bnf_names Us))) ctr_TsssXs []);
   938 
   939     val nesting_bnfs = nesty_bnfs As;
   940     val nested_bnfs = nesty_bnfs Xs;
   941 
   942     val pre_map_defs = map map_def_of_bnf pre_bnfs;
   943     val pre_set_defss = map set_defs_of_bnf pre_bnfs;
   944     val pre_rel_defs = map rel_def_of_bnf pre_bnfs;
   945     val nesting_set_map's = maps set_map'_of_bnf nesting_bnfs;
   946     val nested_set_map's = maps set_map'_of_bnf nested_bnfs;
   947 
   948     val live = live_of_bnf any_fp_bnf;
   949 
   950     val Bs =
   951       map3 (fn alive => fn A as TFree (_, S) => fn B => if alive then resort_tfree S B else A)
   952         (liveness_of_fp_bnf (length As) any_fp_bnf) As Bs0;
   953 
   954     val B_ify = Term.typ_subst_atomic (As ~~ Bs);
   955 
   956     val ctors = map (mk_ctor As) ctors0;
   957     val dtors = map (mk_dtor As) dtors0;
   958 
   959     val fpTs = map (domain_type o fastype_of) dtors;
   960 
   961     fun massage_simple_notes base =
   962       filter_out (null o #2)
   963       #> map (fn (thmN, thms, attrs) =>
   964         ((qualify true base (Binding.name thmN), attrs), [(thms, [])]));
   965 
   966     val massage_multi_notes =
   967       maps (fn (thmN, thmss, attrs) =>
   968         if forall null thmss then
   969           []
   970         else
   971           map3 (fn fp_b_name => fn Type (T_name, _) => fn thms =>
   972             ((qualify true fp_b_name (Binding.name thmN), attrs T_name),
   973              [(thms, [])])) fp_b_names fpTs thmss);
   974 
   975     val ctr_Tsss = map (map (map (Term.typ_subst_atomic (Xs ~~ fpTs)))) ctr_TsssXs;
   976     val ns = map length ctr_Tsss;
   977     val kss = map (fn n => 1 upto n) ns;
   978     val mss = map (map length) ctr_Tsss;
   979     val Css = map2 replicate ns Cs;
   980 
   981     val (fp_folds, fp_fold_fun_Ts) = mk_fp_iter lfp As Cs fp_folds0;
   982     val (fp_recs, fp_rec_fun_Ts) = mk_fp_iter lfp As Cs fp_recs0;
   983 
   984     val (((fold_only, rec_only),
   985           (cs, cpss, unfold_only as ((_, crssss, cgssss), (_, g_Tsss, _)),
   986            corec_only as ((_, csssss, chssss), (_, h_Tsss, _)))), _) =
   987       if lfp then
   988         mk_fold_rec_terms_types fpTs Css ns mss fp_fold_fun_Ts fp_rec_fun_Ts lthy
   989         |>> rpair ([], [], (([], [], []), ([], [], [])), (([], [], []), ([], [], [])))
   990       else
   991         mk_unfold_corec_terms_types fpTs Cs ns mss fp_fold_fun_Ts fp_rec_fun_Ts lthy
   992         |>> pair (([], [], []), ([], [], []));
   993 
   994     fun define_ctrs_case_for_type (((((((((((((((((((((((((fp_bnf, fp_b), fpT), C), ctor), dtor),
   995             fp_fold), fp_rec), ctor_dtor), dtor_ctor), ctor_inject), pre_map_def), pre_set_defs),
   996           pre_rel_def), fp_map_thm), fp_set_thms), fp_rel_thm), n), ks), ms), ctr_bindings),
   997         ctr_mixfixes), ctr_Tss), disc_bindings), sel_bindingss), raw_sel_defaultss) no_defs_lthy =
   998       let
   999         val fp_b_name = Binding.name_of fp_b;
  1000 
  1001         val dtorT = domain_type (fastype_of ctor);
  1002         val ctr_prod_Ts = map HOLogic.mk_tupleT ctr_Tss;
  1003         val ctr_sum_prod_T = mk_sumTN_balanced ctr_prod_Ts;
  1004         val case_Ts = map (fn Ts => Ts ---> C) ctr_Tss;
  1005 
  1006         val (((((w, fs), xss), yss), u'), names_lthy) =
  1007           no_defs_lthy
  1008           |> yield_singleton (mk_Frees "w") dtorT
  1009           ||>> mk_Frees "f" case_Ts
  1010           ||>> mk_Freess "x" ctr_Tss
  1011           ||>> mk_Freess "y" (map (map B_ify) ctr_Tss)
  1012           ||>> yield_singleton Variable.variant_fixes fp_b_name;
  1013 
  1014         val u = Free (u', fpT);
  1015 
  1016         val tuple_xs = map HOLogic.mk_tuple xss;
  1017         val tuple_ys = map HOLogic.mk_tuple yss;
  1018 
  1019         val ctr_rhss =
  1020           map3 (fn k => fn xs => fn tuple_x => fold_rev Term.lambda xs (ctor $
  1021             mk_InN_balanced ctr_sum_prod_T n tuple_x k)) ks xss tuple_xs;
  1022 
  1023         val case_binding = qualify false fp_b_name (Binding.suffix_name ("_" ^ caseN) fp_b);
  1024 
  1025         val case_rhs =
  1026           fold_rev Term.lambda (fs @ [u])
  1027             (mk_sum_caseN_balanced (map2 mk_uncurried_fun fs xss) $ (dtor $ u));
  1028 
  1029         val ((raw_case :: raw_ctrs, raw_case_def :: raw_ctr_defs), (lthy', lthy)) = no_defs_lthy
  1030           |> apfst split_list o fold_map3 (fn b => fn mx => fn rhs =>
  1031               Local_Theory.define ((b, mx), ((Thm.def_binding b, []), rhs)) #>> apsnd snd)
  1032             (case_binding :: ctr_bindings) (NoSyn :: ctr_mixfixes) (case_rhs :: ctr_rhss)
  1033           ||> `Local_Theory.restore;
  1034 
  1035         val phi = Proof_Context.export_morphism lthy lthy';
  1036 
  1037         val ctr_defs = map (Morphism.thm phi) raw_ctr_defs;
  1038         val ctr_defs' =
  1039           map2 (fn m => fn def => mk_unabs_def m (def RS meta_eq_to_obj_eq)) ms ctr_defs;
  1040         val case_def = Morphism.thm phi raw_case_def;
  1041 
  1042         val ctrs0 = map (Morphism.term phi) raw_ctrs;
  1043         val casex0 = Morphism.term phi raw_case;
  1044 
  1045         val ctrs = map (mk_ctr As) ctrs0;
  1046 
  1047         fun wrap lthy =
  1048           let
  1049             fun exhaust_tac {context = ctxt, prems = _} =
  1050               let
  1051                 val ctor_iff_dtor_thm =
  1052                   let
  1053                     val goal =
  1054                       fold_rev Logic.all [w, u]
  1055                         (mk_Trueprop_eq (HOLogic.mk_eq (u, ctor $ w), HOLogic.mk_eq (dtor $ u, w)));
  1056                   in
  1057                     Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, ...} =>
  1058                       mk_ctor_iff_dtor_tac ctxt (map (SOME o certifyT lthy) [dtorT, fpT])
  1059                         (certify lthy ctor) (certify lthy dtor) ctor_dtor dtor_ctor)
  1060                     |> Thm.close_derivation
  1061                     |> Morphism.thm phi
  1062                   end;
  1063 
  1064                 val sumEN_thm' =
  1065                   unfold_thms lthy @{thms all_unit_eq}
  1066                     (Drule.instantiate' (map (SOME o certifyT lthy) ctr_prod_Ts) []
  1067                        (mk_sumEN_balanced n))
  1068                   |> Morphism.thm phi;
  1069               in
  1070                 mk_exhaust_tac ctxt n ctr_defs ctor_iff_dtor_thm sumEN_thm'
  1071               end;
  1072 
  1073             val inject_tacss =
  1074               map2 (fn 0 => K [] | _ => fn ctr_def => [fn {context = ctxt, ...} =>
  1075                   mk_inject_tac ctxt ctr_def ctor_inject]) ms ctr_defs;
  1076 
  1077             val half_distinct_tacss =
  1078               map (map (fn (def, def') => fn {context = ctxt, ...} =>
  1079                 mk_half_distinct_tac ctxt ctor_inject [def, def'])) (mk_half_pairss (`I ctr_defs));
  1080 
  1081             val case_tacs =
  1082               map3 (fn k => fn m => fn ctr_def => fn {context = ctxt, ...} =>
  1083                 mk_case_tac ctxt n k m case_def ctr_def dtor_ctor) ks ms ctr_defs;
  1084 
  1085             val tacss = [exhaust_tac] :: inject_tacss @ half_distinct_tacss @ [case_tacs];
  1086 
  1087             val sel_defaultss = map (map (apsnd (prepare_term lthy))) raw_sel_defaultss
  1088           in
  1089             wrap_free_constructors tacss (((wrap_opts, ctrs0), casex0), (disc_bindings,
  1090               (sel_bindingss, sel_defaultss))) lthy
  1091           end;
  1092 
  1093         fun derive_maps_sets_rels (ctr_sugar, lthy) =
  1094           if live = 0 then
  1095             ((([], [], [], []), ctr_sugar), lthy)
  1096           else
  1097             let
  1098               val rel_flip = rel_flip_of_bnf fp_bnf;
  1099               val nones = replicate live NONE;
  1100 
  1101               val ctor_cong =
  1102                 if lfp then
  1103                   Drule.dummy_thm
  1104                 else
  1105                   let val ctor' = mk_ctor Bs ctor in
  1106                     cterm_instantiate_pos [NONE, NONE, SOME (certify lthy ctor')] arg_cong
  1107                   end;
  1108 
  1109               fun mk_cIn ify =
  1110                 certify lthy o (not lfp ? curry (op $) (map_types ify ctor)) oo
  1111                 mk_InN_balanced (ify ctr_sum_prod_T) n;
  1112 
  1113               val cxIns = map2 (mk_cIn I) tuple_xs ks;
  1114               val cyIns = map2 (mk_cIn B_ify) tuple_ys ks;
  1115 
  1116               fun mk_map_thm ctr_def' cxIn =
  1117                 fold_thms lthy [ctr_def']
  1118                   (unfold_thms lthy (pre_map_def ::
  1119                        (if lfp then [] else [ctor_dtor, dtor_ctor]) @ sum_prod_thms_map)
  1120                      (cterm_instantiate_pos (nones @ [SOME cxIn])
  1121                         (if lfp then fp_map_thm else fp_map_thm RS ctor_cong)))
  1122                 |> singleton (Proof_Context.export names_lthy no_defs_lthy);
  1123 
  1124               fun mk_set_thm fp_set_thm ctr_def' cxIn =
  1125                 fold_thms lthy [ctr_def']
  1126                   (unfold_thms lthy (pre_set_defs @ nested_set_map's @ nesting_set_map's @
  1127                        (if lfp then [] else [dtor_ctor]) @ sum_prod_thms_set)
  1128                      (cterm_instantiate_pos [SOME cxIn] fp_set_thm))
  1129                 |> singleton (Proof_Context.export names_lthy no_defs_lthy);
  1130 
  1131               fun mk_set_thms fp_set_thm = map2 (mk_set_thm fp_set_thm) ctr_defs' cxIns;
  1132 
  1133               val map_thms = map2 mk_map_thm ctr_defs' cxIns;
  1134               val set_thmss = map mk_set_thms fp_set_thms;
  1135 
  1136               val rel_infos = (ctr_defs' ~~ cxIns, ctr_defs' ~~ cyIns);
  1137 
  1138               fun mk_rel_thm postproc ctr_defs' cxIn cyIn =
  1139                 fold_thms lthy ctr_defs'
  1140                    (unfold_thms lthy (@{thm Inl_Inr_False} :: pre_rel_def ::
  1141                         (if lfp then [] else [dtor_ctor]) @ sum_prod_thms_rel)
  1142                       (cterm_instantiate_pos (nones @ [SOME cxIn, SOME cyIn]) fp_rel_thm))
  1143                 |> postproc
  1144                 |> singleton (Proof_Context.export names_lthy no_defs_lthy);
  1145 
  1146               fun mk_rel_inject_thm ((ctr_def', cxIn), (_, cyIn)) =
  1147                 mk_rel_thm (unfold_thms lthy @{thms eq_sym_Unity_conv}) [ctr_def'] cxIn cyIn;
  1148 
  1149               val rel_inject_thms = map mk_rel_inject_thm (op ~~ rel_infos);
  1150 
  1151               fun mk_half_rel_distinct_thm ((xctr_def', cxIn), (yctr_def', cyIn)) =
  1152                 mk_rel_thm (fn thm => thm RS @{thm eq_False[THEN iffD1]}) [xctr_def', yctr_def']
  1153                   cxIn cyIn;
  1154 
  1155               fun mk_other_half_rel_distinct_thm thm =
  1156                 flip_rels lthy live thm
  1157                 RS (rel_flip RS sym RS @{thm arg_cong[of _ _ Not]} RS iffD2);
  1158 
  1159               val half_rel_distinct_thmss =
  1160                 map (map mk_half_rel_distinct_thm) (mk_half_pairss rel_infos);
  1161               val other_half_rel_distinct_thmss =
  1162                 map (map mk_other_half_rel_distinct_thm) half_rel_distinct_thmss;
  1163               val (rel_distinct_thms, _) =
  1164                 join_halves n half_rel_distinct_thmss other_half_rel_distinct_thmss;
  1165 
  1166               val notes =
  1167                 [(mapN, map_thms, code_simp_attrs),
  1168                  (rel_distinctN, rel_distinct_thms, code_simp_attrs),
  1169                  (rel_injectN, rel_inject_thms, code_simp_attrs),
  1170                  (setsN, flat set_thmss, code_simp_attrs)]
  1171                 |> massage_simple_notes fp_b_name;
  1172             in
  1173               (((map_thms, rel_inject_thms, rel_distinct_thms, set_thmss), ctr_sugar),
  1174                lthy |> Local_Theory.notes notes |> snd)
  1175             end;
  1176 
  1177         fun define_fold_rec no_defs_lthy =
  1178           let
  1179             val fpT_to_C = fpT --> C;
  1180 
  1181             fun build_prod_proj mk_proj = build_map lthy (mk_proj o fst);
  1182 
  1183             (* TODO: Avoid these complications; cf. corec case *)
  1184             fun mk_U proj (Type (s as @{type_name prod}, Ts as [T', U])) =
  1185                 if member (op =) fpTs T' then proj (T', U) else Type (s, map (mk_U proj) Ts)
  1186               | mk_U proj (Type (s, Ts)) = Type (s, map (mk_U proj) Ts)
  1187               | mk_U _ T = T;
  1188 
  1189             fun unzip_rec (x as Free (_, T)) =
  1190               if exists_subtype_in fpTs T then
  1191                 ([build_prod_proj fst_const (T, mk_U fst T) $ x],
  1192                  [build_prod_proj snd_const (T, mk_U snd T) $ x])
  1193               else
  1194                 ([x], []);
  1195 
  1196             fun mk_iter_arg f xs =
  1197               mk_tupled_fun (HOLogic.mk_tuple xs) f (flat_rec unzip_rec xs);
  1198 
  1199             fun generate_iter (suf, ctor_iter, (fss, f_Tss, xsss)) =
  1200               let
  1201                 val res_T = fold_rev (curry (op --->)) f_Tss fpT_to_C;
  1202                 val binding = qualify false fp_b_name (Binding.suffix_name ("_" ^ suf) fp_b);
  1203                 val spec =
  1204                   mk_Trueprop_eq (lists_bmoc fss (Free (Binding.name_of binding, res_T)),
  1205                     Term.list_comb (ctor_iter,
  1206                       map2 (mk_sum_caseN_balanced oo map2 mk_iter_arg) fss xsss));
  1207               in (binding, spec) end;
  1208 
  1209             val iter_infos =
  1210               [(foldN, fp_fold, fold_only),
  1211                (recN, fp_rec, rec_only)];
  1212 
  1213             val (bindings, specs) = map generate_iter iter_infos |> split_list;
  1214 
  1215             val ((csts, defs), (lthy', lthy)) = no_defs_lthy
  1216               |> apfst split_list o fold_map2 (fn b => fn spec =>
  1217                 Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
  1218                 #>> apsnd snd) bindings specs
  1219               ||> `Local_Theory.restore;
  1220 
  1221             val phi = Proof_Context.export_morphism lthy lthy';
  1222 
  1223             val [fold_def, rec_def] = map (Morphism.thm phi) defs;
  1224 
  1225             val [foldx, recx] = map (mk_xxiter lfp As Cs o Morphism.term phi) csts;
  1226           in
  1227             ((foldx, recx, fold_def, rec_def), lthy')
  1228           end;
  1229 
  1230         fun define_unfold_corec no_defs_lthy =
  1231           let
  1232             val B_to_fpT = C --> fpT;
  1233 
  1234             fun build_sum_inj mk_inj = build_map lthy (uncurry mk_inj o dest_sumT o snd);
  1235 
  1236             fun build_dtor_coiter_arg _ [] [cf] = cf
  1237               | build_dtor_coiter_arg T [cq] [cf, cf'] =
  1238                 mk_If cq (build_sum_inj Inl_const (fastype_of cf, T) $ cf)
  1239                   (build_sum_inj Inr_const (fastype_of cf', T) $ cf')
  1240 
  1241             val crgsss = map3 (map3 (map3 build_dtor_coiter_arg)) g_Tsss crssss cgssss;
  1242             val cshsss = map3 (map3 (map3 build_dtor_coiter_arg)) h_Tsss csssss chssss;
  1243 
  1244             fun mk_preds_getterss_join c n cps sum_prod_T cqfss =
  1245               Term.lambda c (mk_IfN sum_prod_T cps
  1246                 (map2 (mk_InN_balanced sum_prod_T n) (map HOLogic.mk_tuple cqfss) (1 upto n)));
  1247 
  1248             fun generate_coiter (suf, dtor_coiter, (cqfsss, ((pfss, _, _),
  1249                 (f_sum_prod_Ts, _, pf_Tss)))) =
  1250               let
  1251                 val res_T = fold_rev (curry (op --->)) pf_Tss B_to_fpT;
  1252                 val binding = qualify false fp_b_name (Binding.suffix_name ("_" ^ suf) fp_b);
  1253                 val spec =
  1254                   mk_Trueprop_eq (lists_bmoc pfss (Free (Binding.name_of binding, res_T)),
  1255                     Term.list_comb (dtor_coiter,
  1256                       map5 mk_preds_getterss_join cs ns cpss f_sum_prod_Ts cqfsss));
  1257               in (binding, spec) end;
  1258 
  1259             val coiter_infos =
  1260               [(unfoldN, fp_fold, (crgsss, unfold_only)),
  1261                (corecN, fp_rec, (cshsss, corec_only))];
  1262 
  1263             val (bindings, specs) = map generate_coiter coiter_infos |> split_list;
  1264 
  1265             val ((csts, defs), (lthy', lthy)) = no_defs_lthy
  1266               |> apfst split_list o fold_map2 (fn b => fn spec =>
  1267                 Specification.definition (SOME (b, NONE, NoSyn), ((Thm.def_binding b, []), spec))
  1268                 #>> apsnd snd) bindings specs
  1269               ||> `Local_Theory.restore;
  1270 
  1271             val phi = Proof_Context.export_morphism lthy lthy';
  1272 
  1273             val [unfold_def, corec_def] = map (Morphism.thm phi) defs;
  1274 
  1275             val [unfold, corec] = map (mk_xxiter lfp As Cs o Morphism.term phi) csts;
  1276           in
  1277             ((unfold, corec, unfold_def, corec_def), lthy')
  1278           end;
  1279 
  1280         fun massage_res (((maps_sets_rels, ctr_sugar), xxiter_res), lthy) =
  1281           (((maps_sets_rels, (ctrs, xss, ctr_defs, ctr_sugar)), xxiter_res), lthy);
  1282       in
  1283         (wrap
  1284          #> derive_maps_sets_rels
  1285          ##>> (if lfp then define_fold_rec else define_unfold_corec)
  1286          #> massage_res, lthy')
  1287       end;
  1288 
  1289     fun wrap_types_etc (wrap_types_etcs, lthy) =
  1290       fold_map I wrap_types_etcs lthy
  1291       |>> apsnd split_list4 o apfst (apsnd split_list4 o apfst split_list4 o split_list)
  1292         o split_list;
  1293 
  1294     val mk_simp_thmss =
  1295       map7 (fn {injects, distincts, case_thms, ...} => fn un_folds => fn co_recs =>
  1296         fn mapsx => fn rel_injects => fn rel_distincts => fn setss =>
  1297           injects @ distincts @ case_thms @ co_recs @ un_folds @ mapsx @ rel_injects
  1298           @ rel_distincts @ flat setss);
  1299 
  1300     fun derive_and_note_induct_fold_rec_thms_for_types
  1301         ((((mapsx, rel_injects, rel_distincts, setss), (ctrss, _, ctr_defss, ctr_sugars)),
  1302           (folds, recs, fold_defs, rec_defs)), lthy) =
  1303       let
  1304         val ((induct_thm, induct_thms, induct_attrs), (fold_thmss, fold_attrs),
  1305              (rec_thmss, rec_attrs)) =
  1306           derive_induct_fold_rec_thms_for_types pre_bnfs fp_folds0 fp_recs0 fp_induct fp_fold_thms
  1307             fp_rec_thms nesting_bnfs nested_bnfs fpTs Cs As ctrss ctr_defss folds recs fold_defs
  1308             rec_defs lthy;
  1309 
  1310         val induct_type_attr = Attrib.internal o K o Induct.induct_type;
  1311 
  1312         val simp_thmss =
  1313           mk_simp_thmss ctr_sugars fold_thmss rec_thmss mapsx rel_injects rel_distincts setss;
  1314 
  1315         val common_notes =
  1316           (if nn > 1 then [(inductN, [induct_thm], induct_attrs)] else [])
  1317           |> massage_simple_notes fp_common_name;
  1318 
  1319         val notes =
  1320           [(foldN, fold_thmss, K fold_attrs),
  1321            (inductN, map single induct_thms, fn T_name => induct_attrs @ [induct_type_attr T_name]),
  1322            (recN, rec_thmss, K rec_attrs),
  1323            (simpsN, simp_thmss, K [])]
  1324           |> massage_multi_notes;
  1325       in
  1326         lthy
  1327         |> Local_Theory.notes (common_notes @ notes) |> snd
  1328         |> register_fp_sugars true pre_bnfs fp_res ctr_sugars folds recs fold_thmss rec_thmss
  1329       end;
  1330 
  1331     fun derive_and_note_coinduct_unfold_corec_thms_for_types
  1332         ((((mapsx, rel_injects, rel_distincts, setss), (ctrss, _, ctr_defss, ctr_sugars)),
  1333           (unfolds, corecs, unfold_defs, corec_defs)), lthy) =
  1334       let
  1335         val ((coinduct_thm, coinduct_thms, strong_coinduct_thm, strong_coinduct_thms,
  1336               coinduct_attrs),
  1337              (unfold_thmss, corec_thmss, coiter_attrs),
  1338              (safe_unfold_thmss, safe_corec_thmss),
  1339              (disc_unfold_thmss, disc_corec_thmss, disc_coiter_attrs),
  1340              (disc_unfold_iff_thmss, disc_corec_iff_thmss, disc_coiter_iff_attrs),
  1341              (sel_unfold_thmss, sel_corec_thmss, sel_coiter_attrs)) =
  1342           derive_coinduct_unfold_corec_thms_for_types pre_bnfs fp_folds0 fp_recs0 fp_induct
  1343             fp_strong_induct dtor_ctors fp_fold_thms fp_rec_thms nesting_bnfs nested_bnfs fpTs Cs As
  1344             kss mss ns ctr_defss ctr_sugars unfolds corecs unfold_defs corec_defs lthy;
  1345 
  1346         val coinduct_type_attr = Attrib.internal o K o Induct.coinduct_type;
  1347 
  1348         fun flat_coiter_thms coiters disc_coiters sel_coiters =
  1349           coiters @ disc_coiters @ sel_coiters;
  1350 
  1351         val simp_thmss =
  1352           mk_simp_thmss ctr_sugars
  1353             (map3 flat_coiter_thms safe_unfold_thmss disc_unfold_thmss sel_unfold_thmss)
  1354             (map3 flat_coiter_thms safe_corec_thmss disc_corec_thmss sel_corec_thmss)
  1355             mapsx rel_injects rel_distincts setss;
  1356 
  1357         val anonymous_notes =
  1358           [(flat safe_unfold_thmss @ flat safe_corec_thmss, simp_attrs)]
  1359           |> map (fn (thms, attrs) => ((Binding.empty, attrs), [(thms, [])]));
  1360 
  1361         val common_notes =
  1362           (if nn > 1 then
  1363              [(coinductN, [coinduct_thm], coinduct_attrs),
  1364               (strong_coinductN, [strong_coinduct_thm], coinduct_attrs)]
  1365            else
  1366              [])
  1367           |> massage_simple_notes fp_common_name;
  1368 
  1369         val notes =
  1370           [(coinductN, map single coinduct_thms,
  1371             fn T_name => coinduct_attrs @ [coinduct_type_attr T_name]),
  1372            (corecN, corec_thmss, K coiter_attrs),
  1373            (disc_corecN, disc_corec_thmss, K disc_coiter_attrs),
  1374            (disc_corec_iffN, disc_corec_iff_thmss, K disc_coiter_iff_attrs),
  1375            (disc_unfoldN, disc_unfold_thmss, K disc_coiter_attrs),
  1376            (disc_unfold_iffN, disc_unfold_iff_thmss, K disc_coiter_iff_attrs),
  1377            (sel_corecN, sel_corec_thmss, K sel_coiter_attrs),
  1378            (sel_unfoldN, sel_unfold_thmss, K sel_coiter_attrs),
  1379            (simpsN, simp_thmss, K []),
  1380            (strong_coinductN, map single strong_coinduct_thms, K coinduct_attrs),
  1381            (unfoldN, unfold_thmss, K coiter_attrs)]
  1382           |> massage_multi_notes;
  1383       in
  1384         lthy
  1385         |> Local_Theory.notes (anonymous_notes @ common_notes @ notes) |> snd
  1386         |> register_fp_sugars false pre_bnfs fp_res ctr_sugars unfolds corecs unfold_thmss
  1387           corec_thmss
  1388       end;
  1389 
  1390     val lthy' = lthy
  1391       |> fold_map define_ctrs_case_for_type (fp_bnfs ~~ fp_bs ~~ fpTs ~~ Cs ~~ ctors ~~ dtors ~~
  1392         fp_folds ~~ fp_recs ~~ ctor_dtors ~~ dtor_ctors ~~ ctor_injects ~~ pre_map_defs ~~
  1393         pre_set_defss ~~ pre_rel_defs ~~ fp_map_thms ~~ fp_set_thmss ~~ fp_rel_thms ~~ ns ~~ kss ~~
  1394         mss ~~ ctr_bindingss ~~ ctr_mixfixess ~~ ctr_Tsss ~~ disc_bindingss ~~ sel_bindingsss ~~
  1395         raw_sel_defaultsss)
  1396       |> wrap_types_etc
  1397       |> (if lfp then derive_and_note_induct_fold_rec_thms_for_types
  1398           else derive_and_note_coinduct_unfold_corec_thms_for_types);
  1399 
  1400     val timer = time (timer ("Constructors, discriminators, selectors, etc., for the new " ^
  1401       (if lfp then "" else "co") ^ "datatype"));
  1402   in
  1403     timer; lthy'
  1404   end;
  1405 
  1406 val datatypes = define_datatypes (K I) (K I) (K I);
  1407 
  1408 val datatype_cmd = define_datatypes Typedecl.read_constraint Syntax.parse_typ Syntax.parse_term;
  1409 
  1410 val parse_ctr_arg =
  1411   @{keyword "("} |-- parse_binding_colon -- Parse.typ --| @{keyword ")"} ||
  1412   (Parse.typ >> pair Binding.empty);
  1413 
  1414 val parse_defaults =
  1415   @{keyword "("} |-- @{keyword "defaults"} |-- Scan.repeat parse_bound_term --| @{keyword ")"};
  1416 
  1417 val parse_type_arg_constrained =
  1418   Parse.type_ident -- Scan.option (@{keyword "::"} |-- Parse.!!! Parse.sort);
  1419 
  1420 val parse_type_arg_named_constrained = parse_opt_binding_colon -- parse_type_arg_constrained;
  1421 
  1422 val parse_type_args_named_constrained =
  1423   parse_type_arg_constrained >> (single o pair Binding.empty) ||
  1424   @{keyword "("} |-- Parse.!!! (Parse.list1 parse_type_arg_named_constrained --| @{keyword ")"}) ||
  1425   Scan.succeed [];
  1426 
  1427 val parse_map_rel_binding = Parse.short_ident --| @{keyword ":"} -- parse_binding;
  1428 
  1429 val no_map_rel = (Binding.empty, Binding.empty);
  1430 
  1431 (* "map" and "rel" are purposedly not registered as keywords, because they are short and nice names
  1432    that we don't want them to be highlighted everywhere. *)
  1433 fun extract_map_rel ("map", b) = apfst (K b)
  1434   | extract_map_rel ("rel", b) = apsnd (K b)
  1435   | extract_map_rel (s, _) = error ("Expected \"map\" or \"rel\" instead of " ^ quote s);
  1436 
  1437 val parse_map_rel_bindings =
  1438   @{keyword "("} |-- Scan.repeat parse_map_rel_binding --| @{keyword ")"}
  1439     >> (fn ps => fold extract_map_rel ps no_map_rel) ||
  1440   Scan.succeed no_map_rel;
  1441 
  1442 val parse_ctr_spec =
  1443   parse_opt_binding_colon -- parse_binding -- Scan.repeat parse_ctr_arg --
  1444   Scan.optional parse_defaults [] -- Parse.opt_mixfix;
  1445 
  1446 val parse_spec =
  1447   parse_type_args_named_constrained -- parse_binding -- parse_map_rel_bindings --
  1448   Parse.opt_mixfix -- (@{keyword "="} |-- Parse.enum1 "|" parse_ctr_spec);
  1449 
  1450 val parse_datatype = parse_wrap_options -- Parse.and_list1 parse_spec;
  1451 
  1452 fun parse_datatype_cmd lfp construct_fp = parse_datatype >> datatype_cmd lfp construct_fp;
  1453 
  1454 end;