src/HOL/Tools/BNF/bnf_fp_util.ML
author wenzelm
Tue Jan 09 15:40:12 2018 +0100 (15 months ago)
changeset 67386 998e01d6f8fd
parent 67091 1393c2340eec
child 67463 a5ca98950a91
permissions -rw-r--r--
clarified modules;
     1 (*  Title:      HOL/Tools/BNF/bnf_fp_util.ML
     2     Author:     Dmitriy Traytel, TU Muenchen
     3     Author:     Jasmin Blanchette, TU Muenchen
     4     Author:     Martin Desharnais, TU Muenchen
     5     Author:     Stefan Berghofer, TU Muenchen
     6     Copyright   2012, 2013, 2014
     7 
     8 Shared library for the datatype and codatatype constructions.
     9 *)
    10 
    11 signature BNF_FP_UTIL =
    12 sig
    13   exception EMPTY_DATATYPE of string
    14 
    15   type fp_result =
    16     {Ts: typ list,
    17      bnfs: BNF_Def.bnf list,
    18      pre_bnfs: BNF_Def.bnf list,
    19      absT_infos: BNF_Comp.absT_info list,
    20      ctors: term list,
    21      dtors: term list,
    22      xtor_un_folds: term list,
    23      xtor_co_recs: term list,
    24      xtor_co_induct: thm,
    25      dtor_ctors: thm list,
    26      ctor_dtors: thm list,
    27      ctor_injects: thm list,
    28      dtor_injects: thm list,
    29      xtor_maps: thm list,
    30      xtor_map_unique: thm,
    31      xtor_setss: thm list list,
    32      xtor_rels: thm list,
    33      xtor_un_fold_thms: thm list,
    34      xtor_co_rec_thms: thm list,
    35      xtor_un_fold_unique: thm,
    36      xtor_co_rec_unique: thm,
    37      xtor_un_fold_o_maps: thm list,
    38      xtor_co_rec_o_maps: thm list,
    39      xtor_un_fold_transfers: thm list,
    40      xtor_co_rec_transfers: thm list,
    41      xtor_rel_co_induct: thm,
    42      dtor_set_inducts: thm list}
    43 
    44   val morph_fp_result: morphism -> fp_result -> fp_result
    45 
    46   val time: Proof.context -> Timer.real_timer -> string -> Timer.real_timer
    47 
    48   val fixpoint: ('a * 'a -> bool) -> ('a list -> 'a list) -> 'a list -> 'a list
    49 
    50   val IITN: string
    51   val LevN: string
    52   val algN: string
    53   val behN: string
    54   val bisN: string
    55   val carTN: string
    56   val caseN: string
    57   val coN: string
    58   val coinductN: string
    59   val coinduct_strongN: string
    60   val corecN: string
    61   val corec_discN: string
    62   val corec_disc_iffN: string
    63   val ctorN: string
    64   val ctor_dtorN: string
    65   val ctor_exhaustN: string
    66   val ctor_induct2N: string
    67   val ctor_inductN: string
    68   val ctor_injectN: string
    69   val ctor_foldN: string
    70   val ctor_fold_o_mapN: string
    71   val ctor_fold_transferN: string
    72   val ctor_fold_uniqueN: string
    73   val ctor_mapN: string
    74   val ctor_map_uniqueN: string
    75   val ctor_recN: string
    76   val ctor_rec_o_mapN: string
    77   val ctor_rec_transferN: string
    78   val ctor_rec_uniqueN: string
    79   val ctor_relN: string
    80   val ctor_rel_inductN: string
    81   val ctor_set_inclN: string
    82   val ctor_set_set_inclN: string
    83   val dtorN: string
    84   val dtor_coinductN: string
    85   val dtor_corecN: string
    86   val dtor_corec_o_mapN: string
    87   val dtor_corec_transferN: string
    88   val dtor_corec_uniqueN: string
    89   val dtor_ctorN: string
    90   val dtor_exhaustN: string
    91   val dtor_injectN: string
    92   val dtor_mapN: string
    93   val dtor_map_coinductN: string
    94   val dtor_map_coinduct_strongN: string
    95   val dtor_map_uniqueN: string
    96   val dtor_relN: string
    97   val dtor_rel_coinductN: string
    98   val dtor_set_inclN: string
    99   val dtor_set_set_inclN: string
   100   val dtor_coinduct_strongN: string
   101   val dtor_unfoldN: string
   102   val dtor_unfold_o_mapN: string
   103   val dtor_unfold_transferN: string
   104   val dtor_unfold_uniqueN: string
   105   val exhaustN: string
   106   val colN: string
   107   val inductN: string
   108   val injectN: string
   109   val isNodeN: string
   110   val lsbisN: string
   111   val mapN: string
   112   val map_uniqueN: string
   113   val min_algN: string
   114   val morN: string
   115   val nchotomyN: string
   116   val recN: string
   117   val rel_casesN: string
   118   val rel_coinductN: string
   119   val rel_inductN: string
   120   val rel_injectN: string
   121   val rel_introsN: string
   122   val rel_distinctN: string
   123   val rel_selN: string
   124   val rvN: string
   125   val corec_selN: string
   126   val set_inclN: string
   127   val set_set_inclN: string
   128   val setN: string
   129   val simpsN: string
   130   val strTN: string
   131   val str_initN: string
   132   val sum_bdN: string
   133   val sum_bdTN: string
   134   val uniqueN: string
   135 
   136   (* TODO: Don't index set facts. Isabelle packages traditionally generate uniform names. *)
   137   val mk_ctor_setN: int -> string
   138   val mk_dtor_setN: int -> string
   139   val mk_dtor_set_inductN: int -> string
   140   val mk_set_inductN: int -> string
   141 
   142   val co_prefix: BNF_Util.fp_kind -> string
   143 
   144   val split_conj_thm: thm -> thm list
   145   val split_conj_prems: int -> thm -> thm
   146 
   147   val mk_sumTN: typ list -> typ
   148   val mk_sumTN_balanced: typ list -> typ
   149   val mk_tupleT_balanced: typ list -> typ
   150   val mk_sumprodT_balanced: typ list list -> typ
   151 
   152   val mk_proj: typ -> int -> int -> term
   153 
   154   val mk_convol: term * term -> term
   155   val mk_rel_prod: term -> term -> term
   156   val mk_rel_sum: term -> term -> term
   157 
   158   val Inl_const: typ -> typ -> term
   159   val Inr_const: typ -> typ -> term
   160   val mk_tuple_balanced: term list -> term
   161   val mk_tuple1_balanced: typ list -> term list -> term
   162   val abs_curried_balanced: typ list -> term -> term
   163   val mk_tupled_fun: term -> term -> term list -> term
   164 
   165   val mk_case_sum: term * term -> term
   166   val mk_case_sumN: term list -> term
   167   val mk_case_absumprod: typ -> term -> term list -> term list list -> term list list -> term
   168 
   169   val mk_Inl: typ -> term -> term
   170   val mk_Inr: typ -> term -> term
   171   val mk_sumprod_balanced: typ -> int -> int -> term list -> term
   172   val mk_absumprod: typ -> term -> int -> int -> term list -> term
   173 
   174   val dest_sumT: typ -> typ * typ
   175   val dest_sumTN_balanced: int -> typ -> typ list
   176   val dest_tupleT_balanced: int -> typ -> typ list
   177   val dest_absumprodT: typ -> typ -> int -> int list -> typ -> typ list list
   178 
   179   val If_const: typ -> term
   180 
   181   val mk_Field: term -> term
   182   val mk_If: term -> term -> term -> term
   183 
   184   val mk_absumprodE: thm -> int list -> thm
   185 
   186   val mk_sum_caseN: int -> int -> thm
   187   val mk_sum_caseN_balanced: int -> int -> thm
   188 
   189   val mk_sum_Cinfinite: thm list -> thm
   190   val mk_sum_card_order: thm list -> thm
   191 
   192   val force_typ: Proof.context -> typ -> term -> term
   193 
   194   val mk_xtor_rel_co_induct_thm: BNF_Util.fp_kind -> term list -> term list -> term list ->
   195     term list -> term list -> term list -> term list -> term list ->
   196     ({prems: thm list, context: Proof.context} -> tactic) -> Proof.context -> thm
   197   val mk_xtor_co_iter_transfer_thms: BNF_Util.fp_kind -> term list -> term list -> term list ->
   198     term list -> term list -> term list -> term list ->
   199     ({prems: thm list, context: Proof.context} -> tactic) -> Proof.context -> thm list
   200   val mk_xtor_co_iter_o_map_thms: BNF_Util.fp_kind -> bool -> int -> thm -> thm list -> thm list ->
   201     thm list -> thm list -> thm list
   202   val derive_xtor_co_recs: BNF_Util.fp_kind -> binding list -> (typ list -> typ list) ->
   203     (typ list list * typ list) -> BNF_Def.bnf list -> term list -> term list ->
   204     thm -> thm list -> thm list -> thm list -> thm list ->
   205     (BNF_Comp.absT_info * BNF_Comp.absT_info) option list ->
   206     local_theory ->
   207     (term list * (thm list * thm * thm list * thm list)) * local_theory
   208   val raw_qualify: (binding -> binding) -> binding -> binding -> binding
   209 
   210   val fixpoint_bnf: bool -> (binding -> binding) ->
   211       (binding list -> (string * sort) list -> typ list * typ list list -> BNF_Def.bnf list ->
   212       BNF_Comp.absT_info list -> local_theory -> 'a) ->
   213     binding list -> (string * sort) list -> (string * sort) list -> (string * sort) list ->
   214     typ list -> BNF_Comp.comp_cache -> local_theory ->
   215     ((BNF_Def.bnf list * BNF_Comp.absT_info list) * BNF_Comp.comp_cache) * 'a
   216   val fp_antiquote_setup: binding -> theory -> theory
   217 end;
   218 
   219 structure BNF_FP_Util : BNF_FP_UTIL =
   220 struct
   221 
   222 open Ctr_Sugar
   223 open BNF_Comp
   224 open BNF_Def
   225 open BNF_Util
   226 open BNF_FP_Util_Tactics
   227 
   228 exception EMPTY_DATATYPE of string;
   229 
   230 type fp_result =
   231   {Ts: typ list,
   232    bnfs: bnf list,
   233    pre_bnfs: BNF_Def.bnf list,
   234    absT_infos: BNF_Comp.absT_info list,
   235    ctors: term list,
   236    dtors: term list,
   237    xtor_un_folds: term list,
   238    xtor_co_recs: term list,
   239    xtor_co_induct: thm,
   240    dtor_ctors: thm list,
   241    ctor_dtors: thm list,
   242    ctor_injects: thm list,
   243    dtor_injects: thm list,
   244    xtor_maps: thm list,
   245    xtor_map_unique: thm,
   246    xtor_setss: thm list list,
   247    xtor_rels: thm list,
   248    xtor_un_fold_thms: thm list,
   249    xtor_co_rec_thms: thm list,
   250    xtor_un_fold_unique: thm,
   251    xtor_co_rec_unique: thm,
   252    xtor_un_fold_o_maps: thm list,
   253    xtor_co_rec_o_maps: thm list,
   254    xtor_un_fold_transfers: thm list,
   255    xtor_co_rec_transfers: thm list,
   256    xtor_rel_co_induct: thm,
   257    dtor_set_inducts: thm list};
   258 
   259 fun morph_fp_result phi {Ts, bnfs, pre_bnfs, absT_infos, ctors, dtors, xtor_un_folds,
   260     xtor_co_recs, xtor_co_induct, dtor_ctors, ctor_dtors, ctor_injects, dtor_injects, xtor_maps,
   261     xtor_map_unique, xtor_setss, xtor_rels, xtor_un_fold_thms, xtor_co_rec_thms,
   262     xtor_un_fold_unique, xtor_co_rec_unique, xtor_un_fold_o_maps,
   263     xtor_co_rec_o_maps, xtor_un_fold_transfers, xtor_co_rec_transfers, xtor_rel_co_induct,
   264     dtor_set_inducts} =
   265   {Ts = map (Morphism.typ phi) Ts,
   266    bnfs = map (morph_bnf phi) bnfs,
   267    pre_bnfs = map (morph_bnf phi) pre_bnfs,
   268    absT_infos = map (morph_absT_info phi) absT_infos,
   269    ctors = map (Morphism.term phi) ctors,
   270    dtors = map (Morphism.term phi) dtors,
   271    xtor_un_folds = map (Morphism.term phi) xtor_un_folds,
   272    xtor_co_recs = map (Morphism.term phi) xtor_co_recs,
   273    xtor_co_induct = Morphism.thm phi xtor_co_induct,
   274    dtor_ctors = map (Morphism.thm phi) dtor_ctors,
   275    ctor_dtors = map (Morphism.thm phi) ctor_dtors,
   276    ctor_injects = map (Morphism.thm phi) ctor_injects,
   277    dtor_injects = map (Morphism.thm phi) dtor_injects,
   278    xtor_maps = map (Morphism.thm phi) xtor_maps,
   279    xtor_map_unique = Morphism.thm phi xtor_map_unique,
   280    xtor_setss = map (map (Morphism.thm phi)) xtor_setss,
   281    xtor_rels = map (Morphism.thm phi) xtor_rels,
   282    xtor_un_fold_thms = map (Morphism.thm phi) xtor_un_fold_thms,
   283    xtor_co_rec_thms = map (Morphism.thm phi) xtor_co_rec_thms,
   284    xtor_un_fold_unique = Morphism.thm phi xtor_un_fold_unique,
   285    xtor_co_rec_unique = Morphism.thm phi xtor_co_rec_unique,
   286    xtor_un_fold_o_maps = map (Morphism.thm phi) xtor_un_fold_o_maps,
   287    xtor_co_rec_o_maps = map (Morphism.thm phi) xtor_co_rec_o_maps,
   288    xtor_un_fold_transfers = map (Morphism.thm phi) xtor_un_fold_transfers,
   289    xtor_co_rec_transfers = map (Morphism.thm phi) xtor_co_rec_transfers,
   290    xtor_rel_co_induct = Morphism.thm phi xtor_rel_co_induct,
   291    dtor_set_inducts = map (Morphism.thm phi) dtor_set_inducts};
   292 
   293 fun time ctxt timer msg = (if Config.get ctxt bnf_timing
   294   then warning (msg ^ ": " ^ string_of_int (Time.toMilliseconds (Timer.checkRealTimer timer)) ^
   295     " ms")
   296   else (); Timer.startRealTimer ());
   297 
   298 val preN = "pre_"
   299 val rawN = "raw_"
   300 
   301 val coN = "co"
   302 val unN = "un"
   303 val algN = "alg"
   304 val IITN = "IITN"
   305 val foldN = "fold"
   306 val unfoldN = unN ^ foldN
   307 val uniqueN = "unique"
   308 val transferN = "transfer"
   309 val simpsN = "simps"
   310 val ctorN = "ctor"
   311 val dtorN = "dtor"
   312 val ctor_foldN = ctorN ^ "_" ^ foldN
   313 val dtor_unfoldN = dtorN ^ "_" ^ unfoldN
   314 val ctor_fold_uniqueN = ctor_foldN ^ "_" ^ uniqueN
   315 val ctor_fold_o_mapN = ctor_foldN ^ "_o_" ^ mapN
   316 val dtor_unfold_uniqueN = dtor_unfoldN ^ "_" ^ uniqueN
   317 val dtor_unfold_o_mapN = dtor_unfoldN ^ "_o_" ^ mapN
   318 val ctor_fold_transferN = ctor_foldN ^ "_" ^ transferN
   319 val dtor_unfold_transferN = dtor_unfoldN ^ "_" ^ transferN
   320 val ctor_mapN = ctorN ^ "_" ^ mapN
   321 val dtor_mapN = dtorN ^ "_" ^ mapN
   322 val map_uniqueN = mapN ^ "_" ^ uniqueN
   323 val ctor_map_uniqueN = ctorN ^ "_" ^ map_uniqueN
   324 val dtor_map_uniqueN = dtorN ^ "_" ^ map_uniqueN
   325 val min_algN = "min_alg"
   326 val morN = "mor"
   327 val bisN = "bis"
   328 val lsbisN = "lsbis"
   329 val sum_bdTN = "sbdT"
   330 val sum_bdN = "sbd"
   331 val carTN = "carT"
   332 val strTN = "strT"
   333 val isNodeN = "isNode"
   334 val LevN = "Lev"
   335 val rvN = "recover"
   336 val behN = "beh"
   337 val setN = "set"
   338 val mk_ctor_setN = prefix (ctorN ^ "_") o mk_setN
   339 val mk_dtor_setN = prefix (dtorN ^ "_") o mk_setN
   340 fun mk_set_inductN i = mk_setN i ^ "_induct"
   341 val mk_dtor_set_inductN = prefix (dtorN ^ "_") o mk_set_inductN
   342 
   343 val str_initN = "str_init"
   344 val recN = "rec"
   345 val corecN = coN ^ recN
   346 val ctor_recN = ctorN ^ "_" ^ recN
   347 val ctor_rec_o_mapN = ctor_recN ^ "_o_" ^ mapN
   348 val ctor_rec_transferN = ctor_recN ^ "_" ^ transferN
   349 val ctor_rec_uniqueN = ctor_recN ^ "_" ^ uniqueN
   350 val dtor_corecN = dtorN ^ "_" ^ corecN
   351 val dtor_corec_o_mapN = dtor_corecN ^ "_o_" ^ mapN
   352 val dtor_corec_transferN = dtor_corecN ^ "_" ^ transferN
   353 val dtor_corec_uniqueN = dtor_corecN ^ "_" ^ uniqueN
   354 
   355 val ctor_dtorN = ctorN ^ "_" ^ dtorN
   356 val dtor_ctorN = dtorN ^ "_" ^ ctorN
   357 val nchotomyN = "nchotomy"
   358 val injectN = "inject"
   359 val exhaustN = "exhaust"
   360 val ctor_injectN = ctorN ^ "_" ^ injectN
   361 val ctor_exhaustN = ctorN ^ "_" ^ exhaustN
   362 val dtor_injectN = dtorN ^ "_" ^ injectN
   363 val dtor_exhaustN = dtorN ^ "_" ^ exhaustN
   364 val ctor_relN = ctorN ^ "_" ^ relN
   365 val dtor_relN = dtorN ^ "_" ^ relN
   366 val inductN = "induct"
   367 val coinductN = coN ^ inductN
   368 val ctor_inductN = ctorN ^ "_" ^ inductN
   369 val ctor_induct2N = ctor_inductN ^ "2"
   370 val dtor_map_coinductN = dtor_mapN ^ "_" ^ coinductN
   371 val dtor_coinductN = dtorN ^ "_" ^ coinductN
   372 val coinduct_strongN = coinductN ^ "_strong"
   373 val dtor_map_coinduct_strongN = dtor_mapN ^ "_" ^ coinduct_strongN
   374 val dtor_coinduct_strongN = dtorN ^ "_" ^ coinduct_strongN
   375 val colN = "col"
   376 val set_inclN = "set_incl"
   377 val ctor_set_inclN = ctorN ^ "_" ^ set_inclN
   378 val dtor_set_inclN = dtorN ^ "_" ^ set_inclN
   379 val set_set_inclN = "set_set_incl"
   380 val ctor_set_set_inclN = ctorN ^ "_" ^ set_set_inclN
   381 val dtor_set_set_inclN = dtorN ^ "_" ^ set_set_inclN
   382 
   383 val caseN = "case"
   384 val discN = "disc"
   385 val corec_discN = corecN ^ "_" ^ discN
   386 val iffN = "_iff"
   387 val corec_disc_iffN = corec_discN ^ iffN
   388 val distinctN = "distinct"
   389 val rel_distinctN = relN ^ "_" ^ distinctN
   390 val injectN = "inject"
   391 val rel_casesN = relN ^ "_cases"
   392 val rel_injectN = relN ^ "_" ^ injectN
   393 val rel_introsN = relN ^ "_intros"
   394 val rel_coinductN = relN ^ "_" ^ coinductN
   395 val rel_selN = relN ^ "_sel"
   396 val dtor_rel_coinductN = dtorN ^ "_" ^ rel_coinductN
   397 val rel_inductN = relN ^ "_" ^ inductN
   398 val ctor_rel_inductN = ctorN ^ "_" ^ rel_inductN
   399 val selN = "sel"
   400 val corec_selN = corecN ^ "_" ^ selN
   401 
   402 fun co_prefix fp = case_fp fp "" "co";
   403 
   404 fun dest_sumT (Type (@{type_name sum}, [T, T'])) = (T, T');
   405 
   406 val dest_sumTN_balanced = Balanced_Tree.dest dest_sumT;
   407 
   408 fun dest_tupleT_balanced 0 @{typ unit} = []
   409   | dest_tupleT_balanced n T = Balanced_Tree.dest HOLogic.dest_prodT n T;
   410 
   411 fun dest_absumprodT absT repT n ms =
   412   map2 dest_tupleT_balanced ms o dest_sumTN_balanced n o mk_repT absT repT;
   413 
   414 val mk_sumTN = Library.foldr1 mk_sumT;
   415 val mk_sumTN_balanced = Balanced_Tree.make mk_sumT;
   416 
   417 fun mk_tupleT_balanced [] = HOLogic.unitT
   418   | mk_tupleT_balanced Ts = Balanced_Tree.make HOLogic.mk_prodT Ts;
   419 
   420 val mk_sumprodT_balanced = mk_sumTN_balanced o map mk_tupleT_balanced;
   421 
   422 fun mk_proj T n k =
   423   let val (binders, _) = strip_typeN n T in
   424     fold_rev (fn T => fn t => Abs (Name.uu, T, t)) binders (Bound (n - k - 1))
   425   end;
   426 
   427 fun mk_convol (f, g) =
   428   let
   429     val (fU, fTU) = `range_type (fastype_of f);
   430     val ((gT, gU), gTU) = `dest_funT (fastype_of g);
   431     val convolT = fTU --> gTU --> gT --> HOLogic.mk_prodT (fU, gU);
   432   in Const (@{const_name convol}, convolT) $ f $ g end;
   433 
   434 fun mk_rel_prod R S =
   435   let
   436     val ((A1, A2), RT) = `dest_pred2T (fastype_of R);
   437     val ((B1, B2), ST) = `dest_pred2T (fastype_of S);
   438     val rel_prodT = RT --> ST --> mk_pred2T (HOLogic.mk_prodT (A1, B1)) (HOLogic.mk_prodT (A2, B2));
   439   in Const (@{const_name rel_prod}, rel_prodT) $ R $ S end;
   440 
   441 fun mk_rel_sum R S =
   442   let
   443     val ((A1, A2), RT) = `dest_pred2T (fastype_of R);
   444     val ((B1, B2), ST) = `dest_pred2T (fastype_of S);
   445     val rel_sumT = RT --> ST --> mk_pred2T (mk_sumT (A1, B1)) (mk_sumT (A2, B2));
   446   in Const (@{const_name rel_sum}, rel_sumT) $ R $ S end;
   447 
   448 fun Inl_const LT RT = Const (@{const_name Inl}, LT --> mk_sumT (LT, RT));
   449 fun mk_Inl RT t = Inl_const (fastype_of t) RT $ t;
   450 
   451 fun Inr_const LT RT = Const (@{const_name Inr}, RT --> mk_sumT (LT, RT));
   452 fun mk_Inr LT t = Inr_const LT (fastype_of t) $ t;
   453 
   454 fun mk_prod1 bound_Ts (t, u) =
   455   HOLogic.pair_const (fastype_of1 (bound_Ts, t)) (fastype_of1 (bound_Ts, u)) $ t $ u;
   456 
   457 fun mk_tuple1_balanced _ [] = HOLogic.unit
   458   | mk_tuple1_balanced bound_Ts ts = Balanced_Tree.make (mk_prod1 bound_Ts) ts;
   459 
   460 val mk_tuple_balanced = mk_tuple1_balanced [];
   461 
   462 fun abs_curried_balanced Ts t =
   463   t $ mk_tuple1_balanced (List.rev Ts) (map Bound (length Ts - 1 downto 0))
   464   |> fold_rev (Term.abs o pair Name.uu) Ts;
   465 
   466 fun mk_sumprod_balanced T n k ts = Sum_Tree.mk_inj T n k (mk_tuple_balanced ts);
   467 
   468 fun mk_absumprod absT abs0 n k ts =
   469   let val abs = mk_abs absT abs0;
   470   in abs $ mk_sumprod_balanced (domain_type (fastype_of abs)) n k ts end;
   471 
   472 fun mk_case_sum (f, g) =
   473   let
   474     val (fT, T') = dest_funT (fastype_of f);
   475     val (gT, _) = dest_funT (fastype_of g);
   476   in
   477     Sum_Tree.mk_sumcase fT gT T' f g
   478   end;
   479 
   480 val mk_case_sumN = Library.foldr1 mk_case_sum;
   481 val mk_case_sumN_balanced = Balanced_Tree.make mk_case_sum;
   482 
   483 fun mk_tupled_fun f x xs =
   484   if xs = [x] then f else HOLogic.tupled_lambda x (Term.list_comb (f, xs));
   485 
   486 fun mk_case_absumprod absT rep fs xss xss' =
   487   HOLogic.mk_comp (mk_case_sumN_balanced
   488     (@{map 3} mk_tupled_fun fs (map mk_tuple_balanced xss) xss'), mk_rep absT rep);
   489 
   490 fun If_const T = Const (@{const_name If}, HOLogic.boolT --> T --> T --> T);
   491 fun mk_If p t f = let val T = fastype_of t in If_const T $ p $ t $ f end;
   492 
   493 fun mk_Field r =
   494   let val T = fst (dest_relT (fastype_of r));
   495   in Const (@{const_name Field}, mk_relT (T, T) --> HOLogic.mk_setT T) $ r end;
   496 
   497 (*dangerous; use with monotonic, converging functions only!*)
   498 fun fixpoint eq f X = if subset eq (f X, X) then X else fixpoint eq f (f X);
   499 
   500 (* stolen from "~~/src/HOL/Tools/Datatype/datatype_aux.ML" *)
   501 fun split_conj_thm th =
   502   ((th RS conjunct1) :: split_conj_thm (th RS conjunct2)) handle THM _ => [th];
   503 
   504 fun split_conj_prems limit th =
   505   let
   506     fun split n i th =
   507       if i = n then th else split n (i + 1) (conjI RSN (i, th)) handle THM _ => th;
   508   in split limit 1 th end;
   509 
   510 fun mk_obj_sumEN_balanced n =
   511   Balanced_Tree.make (fn (thm1, thm2) => thm1 RSN (1, thm2 RSN (2, @{thm obj_sumE_f})))
   512     (replicate n asm_rl);
   513 
   514 fun mk_tupled_allIN_balanced 0 = @{thm unit_all_impI}
   515   | mk_tupled_allIN_balanced n =
   516     let
   517       val (tfrees, _) = BNF_Util.mk_TFrees n @{context};
   518       val T = mk_tupleT_balanced tfrees;
   519     in
   520       @{thm asm_rl[of "\<forall>x. P x \<longrightarrow> Q x" for P Q]}
   521       |> Thm.instantiate' [SOME (Thm.ctyp_of @{context} T)] []
   522       |> Raw_Simplifier.rewrite_goals_rule @{context} @{thms split_paired_All[THEN eq_reflection]}
   523       |> (fn thm => impI RS funpow n (fn th => allI RS th) thm)
   524       |> Thm.varifyT_global
   525     end;
   526 
   527 fun mk_absumprodE type_definition ms =
   528   let val n = length ms in
   529     mk_obj_sumEN_balanced n OF map mk_tupled_allIN_balanced ms RS
   530       (type_definition RS @{thm type_copy_obj_one_point_absE})
   531   end;
   532 
   533 fun mk_sum_caseN 1 1 = refl
   534   | mk_sum_caseN _ 1 = @{thm sum.case(1)}
   535   | mk_sum_caseN 2 2 = @{thm sum.case(2)}
   536   | mk_sum_caseN n k = trans OF [@{thm case_sum_step(2)}, mk_sum_caseN (n - 1) (k - 1)];
   537 
   538 fun mk_sum_step base step thm =
   539   if Thm.eq_thm_prop (thm, refl) then base else trans OF [step, thm];
   540 
   541 fun mk_sum_caseN_balanced 1 1 = refl
   542   | mk_sum_caseN_balanced n k =
   543     Balanced_Tree.access {left = mk_sum_step @{thm sum.case(1)} @{thm case_sum_step(1)},
   544       right = mk_sum_step @{thm sum.case(2)} @{thm case_sum_step(2)}, init = refl} n k;
   545 
   546 fun mk_sum_Cinfinite [thm] = thm
   547   | mk_sum_Cinfinite (thm :: thms) = @{thm Cinfinite_csum_weak} OF [thm, mk_sum_Cinfinite thms];
   548 
   549 fun mk_sum_card_order [thm] = thm
   550   | mk_sum_card_order (thm :: thms) = @{thm card_order_csum} OF [thm, mk_sum_card_order thms];
   551 
   552 fun mk_xtor_rel_co_induct_thm fp pre_rels pre_phis rels phis xs ys xtors xtor's tac lthy =
   553   let
   554     val pre_relphis = map (fn rel => Term.list_comb (rel, phis @ pre_phis)) pre_rels;
   555     val relphis = map (fn rel => Term.list_comb (rel, phis)) rels;
   556     fun mk_xtor fp' xtor x = if fp = fp' then xtor $ x else x;
   557     val dtor = mk_xtor Greatest_FP;
   558     val ctor = mk_xtor Least_FP;
   559     fun flip f x y = if fp = Greatest_FP then f y x else f x y;
   560 
   561     fun mk_prem pre_relphi phi x y xtor xtor' =
   562       HOLogic.mk_Trueprop (list_all_free [x, y] (flip (curry HOLogic.mk_imp)
   563         (pre_relphi $ (dtor xtor x) $ (dtor xtor' y)) (phi $ (ctor xtor x) $ (ctor xtor' y))));
   564     val prems = @{map 6} mk_prem pre_relphis pre_phis xs ys xtors xtor's;
   565 
   566     val concl = HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
   567       (map2 (flip mk_leq) relphis pre_phis));
   568   in
   569     Goal.prove_sorry lthy (map (fst o dest_Free) (phis @ pre_phis)) prems concl tac
   570     |> Thm.close_derivation
   571     |> (fn thm => thm OF (replicate (length pre_rels) @{thm allI[OF allI[OF impI]]}))
   572   end;
   573 
   574 fun mk_xtor_co_iter_transfer_thms fp pre_rels pre_iphis pre_ophis rels phis un_folds un_folds' tac lthy =
   575   let
   576     val pre_relphis = map (fn rel => Term.list_comb (rel, phis @ pre_iphis)) pre_rels;
   577     val relphis = map (fn rel => Term.list_comb (rel, phis)) rels;
   578     fun flip f x y = if fp = Greatest_FP then f y x else f x y;
   579 
   580     val arg_rels = map2 (flip mk_rel_fun) pre_relphis pre_ophis;
   581     fun mk_transfer relphi pre_phi un_fold un_fold' =
   582       fold_rev mk_rel_fun arg_rels (flip mk_rel_fun relphi pre_phi) $ un_fold $ un_fold';
   583     val transfers = @{map 4} mk_transfer relphis pre_ophis un_folds un_folds';
   584 
   585     val goal = fold_rev Logic.all (phis @ pre_ophis)
   586       (HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj transfers));
   587   in
   588     Goal.prove_sorry lthy [] [] goal tac
   589     |> Thm.close_derivation
   590     |> split_conj_thm
   591   end;
   592 
   593 fun mk_xtor_co_iter_o_map_thms fp is_rec m un_fold_unique xtor_maps xtor_un_folds sym_map_comps
   594     map_cong0s =
   595   let
   596     val n = length sym_map_comps;
   597     val rewrite_comp_comp2 = case_fp fp @{thm rewriteR_comp_comp2} @{thm rewriteL_comp_comp2};
   598     val rewrite_comp_comp = case_fp fp @{thm rewriteR_comp_comp} @{thm rewriteL_comp_comp};
   599     val map_cong_passive_args1 = replicate m (case_fp fp @{thm id_comp} @{thm comp_id} RS fun_cong);
   600     val map_cong_active_args1 = replicate n (if is_rec
   601       then case_fp fp @{thm convol_o} @{thm o_case_sum} RS fun_cong
   602       else refl);
   603     val map_cong_passive_args2 = replicate m (case_fp fp @{thm comp_id} @{thm id_comp} RS fun_cong);
   604     val map_cong_active_args2 = replicate n (if is_rec
   605       then case_fp fp @{thm map_prod_o_convol_id} @{thm case_sum_o_map_sum_id}
   606       else case_fp fp @{thm id_comp} @{thm comp_id} RS fun_cong);
   607     fun mk_map_congs passive active =
   608       map (fn thm => thm OF (passive @ active) RS @{thm ext}) map_cong0s;
   609     val map_cong1s = mk_map_congs map_cong_passive_args1 map_cong_active_args1;
   610     val map_cong2s = mk_map_congs map_cong_passive_args2 map_cong_active_args2;
   611 
   612     fun mk_rewrites map_congs = map2 (fn sym_map_comp => fn map_cong =>
   613       mk_trans sym_map_comp map_cong RS rewrite_comp_comp) sym_map_comps map_congs;
   614     val rewrite1s = mk_rewrites map_cong1s;
   615     val rewrite2s = mk_rewrites map_cong2s;
   616     val unique_prems =
   617       @{map 4} (fn xtor_map => fn un_fold => fn rewrite1 => fn rewrite2 =>
   618         mk_trans (rewrite_comp_comp2 OF [xtor_map, un_fold])
   619           (mk_trans rewrite1 (mk_sym rewrite2)))
   620       xtor_maps xtor_un_folds rewrite1s rewrite2s;
   621   in
   622     split_conj_thm (un_fold_unique OF map (case_fp fp I mk_sym) unique_prems)
   623   end;
   624 
   625 fun force_typ ctxt T =
   626   Term.map_types Type_Infer.paramify_vars
   627   #> Type.constraint T
   628   #> Syntax.check_term ctxt
   629   #> singleton (Variable.polymorphic ctxt);
   630 
   631 fun absT_info_encodeT thy (SOME (src : absT_info, dst : absT_info)) src_absT =
   632     let
   633       val src_repT = mk_repT (#absT src) (#repT src) src_absT;
   634       val dst_absT = mk_absT thy (#repT dst) (#absT dst) src_repT;
   635     in
   636       dst_absT
   637     end
   638   | absT_info_encodeT _ NONE T = T;
   639 
   640 fun absT_info_decodeT thy = absT_info_encodeT thy o Option.map swap;
   641 
   642 fun absT_info_encode thy fp (opt as SOME (src : absT_info, dst : absT_info)) t =
   643     let
   644       val co_alg_funT = case_fp fp domain_type range_type;
   645       fun co_swap pair = case_fp fp I swap pair;
   646       val mk_co_comp = curry (HOLogic.mk_comp o co_swap);
   647       val mk_co_abs = case_fp fp mk_abs mk_rep;
   648       val mk_co_rep = case_fp fp mk_rep mk_abs;
   649       val co_abs = case_fp fp #abs #rep;
   650       val co_rep = case_fp fp #rep #abs;
   651       val src_absT = co_alg_funT (fastype_of t);
   652       val dst_absT = absT_info_encodeT thy opt src_absT;
   653       val co_src_abs = mk_co_abs src_absT (co_abs src);
   654       val co_dst_rep = mk_co_rep dst_absT (co_rep dst);
   655     in
   656       mk_co_comp (mk_co_comp t co_src_abs) co_dst_rep
   657     end
   658   | absT_info_encode _ _ NONE t = t;
   659 
   660 fun absT_info_decode thy fp = absT_info_encode thy fp o Option.map swap;
   661 
   662 fun mk_xtor_un_fold_xtor_thms ctxt fp un_folds xtors xtor_un_fold_unique map_id0s
   663     absT_info_opts =
   664   let
   665     val thy = Proof_Context.theory_of ctxt;
   666     fun mk_goal un_fold =
   667       let
   668         val rhs = list_comb (un_fold, @{map 2} (absT_info_encode thy fp) absT_info_opts xtors);
   669         val T = range_type (fastype_of rhs);
   670       in
   671         HOLogic.mk_eq (HOLogic.id_const T, rhs)
   672       end;
   673     val goal = HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj (map mk_goal un_folds));
   674     fun mk_inverses NONE = []
   675       | mk_inverses (SOME (src, dst)) =
   676         [#type_definition dst RS @{thm type_definition.Abs_inverse[OF _ UNIV_I]},
   677          #type_definition src RS @{thm type_definition.Rep_inverse}];
   678     val inverses = maps mk_inverses absT_info_opts;
   679   in
   680     Goal.prove_sorry ctxt [] [] goal (fn {context = ctxt, prems = _} =>
   681       mk_xtor_un_fold_xtor_tac ctxt xtor_un_fold_unique map_id0s inverses)
   682     |> split_conj_thm |> map mk_sym
   683   end;
   684 
   685 fun derive_xtor_co_recs fp bs mk_Ts (Dss, resDs) pre_bnfs xtors0 un_folds0
   686     xtor_un_fold_unique xtor_un_folds xtor_un_fold_transfers xtor_maps xtor_rels
   687     absT_info_opts lthy =
   688   let
   689     val thy = Proof_Context.theory_of lthy;
   690     fun co_swap pair = case_fp fp I swap pair;
   691     val mk_co_comp = curry (HOLogic.mk_comp o co_swap);
   692     fun mk_co_algT T U = case_fp fp (T --> U) (U --> T);
   693     val co_alg_funT = case_fp fp domain_type range_type;
   694     val mk_co_product = curry (case_fp fp mk_convol mk_case_sum);
   695     val co_proj1_const = case_fp fp fst_const (uncurry Inl_const o dest_sumT) o co_alg_funT;
   696     val co_proj2_const = case_fp fp snd_const (uncurry Inr_const o dest_sumT) o co_alg_funT;
   697     val mk_co_productT = curry (case_fp fp HOLogic.mk_prodT mk_sumT);
   698     val rewrite_comp_comp = case_fp fp @{thm rewriteL_comp_comp} @{thm rewriteR_comp_comp};
   699 
   700     val n = length pre_bnfs;
   701     val live = live_of_bnf (hd pre_bnfs);
   702     val m = live - n;
   703     val ks = 1 upto n;
   704 
   705     val map_id0s = map map_id0_of_bnf pre_bnfs;
   706     val map_comps = map map_comp_of_bnf pre_bnfs;
   707     val map_cong0s = map map_cong0_of_bnf pre_bnfs;
   708     val map_transfers = map map_transfer_of_bnf pre_bnfs;
   709     val sym_map_comp0s = map (mk_sym o map_comp0_of_bnf) pre_bnfs;
   710 
   711     val deads = fold (union (op =)) Dss resDs;
   712     val ((((As, Bs), Xs), Ys), names_lthy) = lthy
   713       |> fold Variable.declare_typ deads
   714       |> mk_TFrees m
   715       ||>> mk_TFrees m
   716       ||>> mk_TFrees n
   717       ||>> mk_TFrees n;
   718 
   719     val XFTs = @{map 2} (fn Ds => mk_T_of_bnf Ds (As @ Xs)) Dss pre_bnfs;
   720     val co_algXFTs = @{map 2} mk_co_algT XFTs Xs;
   721     val Ts = mk_Ts As;
   722     val un_foldTs = @{map 2} (fn T => fn X => co_algXFTs ---> mk_co_algT T X) Ts Xs;
   723     val un_folds = @{map 2} (force_typ names_lthy) un_foldTs un_folds0;
   724     val ABs = As ~~ Bs;
   725     val XYs = Xs ~~ Ys;
   726 
   727     val Us = map (typ_subst_atomic ABs) Ts;
   728 
   729     val TFTs = @{map 2} (fn Ds => mk_T_of_bnf Ds (As @ Ts)) Dss pre_bnfs;
   730 
   731     val TFTs' = @{map 2} (absT_info_decodeT thy) absT_info_opts TFTs;
   732     val xtors = @{map 3} (force_typ names_lthy oo mk_co_algT) TFTs' Ts xtors0;
   733 
   734     val ids = map HOLogic.id_const As;
   735     val co_rec_Xs = @{map 2} mk_co_productT Ts Xs;
   736     val co_rec_Ys = @{map 2} mk_co_productT Us Ys;
   737     val co_rec_algXs = @{map 2} mk_co_algT co_rec_Xs Xs;
   738     val co_proj1s = map co_proj1_const co_rec_algXs;
   739     val co_rec_maps = @{map 2} (fn Ds =>
   740       mk_map_of_bnf Ds (As @ case_fp fp co_rec_Xs Ts) (As @ case_fp fp Ts co_rec_Xs)) Dss pre_bnfs;
   741     val co_rec_Ts = @{map 2} (fn Ds => mk_T_of_bnf Ds (As @ co_rec_Xs)) Dss pre_bnfs
   742     val co_rec_argTs = @{map 2} mk_co_algT co_rec_Ts Xs;
   743     val co_rec_resTs = @{map 2} mk_co_algT Ts Xs;
   744 
   745     val (((co_rec_ss, fs), xs), names_lthy) = names_lthy
   746       |> mk_Frees "s" co_rec_argTs
   747       ||>> mk_Frees "f" co_rec_resTs
   748       ||>> mk_Frees "x" (case_fp fp TFTs' Xs);
   749 
   750     val co_rec_strs =
   751       @{map 4} (fn xtor => fn s => fn mapx => fn absT_info_opt =>
   752         mk_co_product (mk_co_comp (absT_info_encode thy fp absT_info_opt xtor)
   753           (list_comb (mapx, ids @ co_proj1s))) s)
   754       xtors co_rec_ss co_rec_maps absT_info_opts;
   755 
   756     val theta = Xs ~~ co_rec_Xs;
   757     val co_rec_un_folds = map (subst_atomic_types theta) un_folds;
   758 
   759     val co_rec_spec0s = map (fn un_fold => list_comb (un_fold, co_rec_strs)) co_rec_un_folds;
   760 
   761     val co_rec_ids = @{map 2} (mk_co_comp o co_proj1_const) co_rec_algXs co_rec_spec0s;
   762     val co_rec_specs = @{map 2} (mk_co_comp o co_proj2_const) co_rec_algXs co_rec_spec0s;
   763 
   764     val co_recN = case_fp fp ctor_recN dtor_corecN;
   765     fun co_rec_bind i = nth bs (i - 1) |> Binding.prefix_name (co_recN ^ "_");
   766     val co_rec_def_bind = rpair [] o Binding.concealed o Thm.def_binding o co_rec_bind;
   767 
   768     fun co_rec_spec i =
   769       fold_rev (Term.absfree o Term.dest_Free) co_rec_ss (nth co_rec_specs (i - 1));
   770 
   771     val ((co_rec_frees, (_, co_rec_def_frees)), (lthy, lthy_old)) =
   772       lthy
   773       |> Local_Theory.open_target |> snd
   774       |> fold_map (fn i =>
   775         Local_Theory.define ((co_rec_bind i, NoSyn), (co_rec_def_bind i, co_rec_spec i))) ks
   776       |>> apsnd split_list o split_list
   777       ||> `Local_Theory.close_target;
   778 
   779     val phi = Proof_Context.export_morphism lthy_old lthy;
   780     val co_rec_names = map (fst o dest_Const o Morphism.term phi) co_rec_frees;
   781     val co_recs = @{map 2} (fn name => fn resT =>
   782       Const (name, co_rec_argTs ---> resT)) co_rec_names co_rec_resTs;
   783     val co_rec_defs = map (fn def =>
   784       mk_unabs_def n (Morphism.thm phi def RS meta_eq_to_obj_eq)) co_rec_def_frees;
   785 
   786     val xtor_un_fold_xtor_thms =
   787       mk_xtor_un_fold_xtor_thms lthy fp (map (Term.subst_atomic_types (Xs ~~ Ts)) un_folds)
   788         xtors xtor_un_fold_unique map_id0s absT_info_opts;
   789 
   790     val co_rec_id_thms =
   791       let
   792         val goal = @{map 2} (fn T => fn t => HOLogic.mk_eq (t, HOLogic.id_const T)) Ts co_rec_ids
   793           |> Library.foldr1 HOLogic.mk_conj |> HOLogic.mk_Trueprop;
   794         val vars = Variable.add_free_names lthy goal [];
   795       in
   796         Goal.prove_sorry lthy vars [] goal
   797           (fn {context = ctxt, prems = _} => mk_xtor_co_rec_id_tac ctxt xtor_un_fold_xtor_thms
   798             xtor_un_fold_unique xtor_un_folds map_comps)
   799         |> Thm.close_derivation
   800         |> split_conj_thm
   801       end;
   802 
   803     val co_rec_app_ss = map (fn co_rec => list_comb (co_rec, co_rec_ss)) co_recs;
   804     val co_products = @{map 2} (fn T => mk_co_product (HOLogic.id_const T)) Ts co_rec_app_ss;
   805     val co_rec_maps_rev = @{map 2} (fn Ds =>
   806       mk_map_of_bnf Ds (As @ case_fp fp Ts co_rec_Xs) (As @ case_fp fp co_rec_Xs Ts)) Dss pre_bnfs;
   807     fun mk_co_app f g x = case_fp fp (f $ (g $ x)) (g $ (f $ x));
   808     val co_rec_expand_thms = map (fn thm => thm RS
   809       case_fp fp @{thm convol_expand_snd} @{thm case_sum_expand_Inr_pointfree}) co_rec_id_thms;
   810     val xtor_co_rec_thms =
   811       let
   812         fun mk_goal co_rec s mapx xtor x absT_info_opt =
   813           let
   814             val lhs = mk_co_app co_rec xtor x;
   815             val rhs = mk_co_app s
   816               (list_comb (mapx, ids @ co_products) |> absT_info_decode thy fp absT_info_opt) x;
   817           in
   818             mk_Trueprop_eq (lhs, rhs)
   819           end;
   820         val goals =
   821           @{map 6} mk_goal co_rec_app_ss co_rec_ss co_rec_maps_rev xtors xs absT_info_opts;
   822       in
   823         map2 (fn goal => fn un_fold =>
   824           Variable.add_free_names lthy goal []
   825           |> (fn vars => Goal.prove_sorry lthy vars [] goal
   826             (fn {context = ctxt, prems = _} =>
   827               mk_xtor_co_rec_tac ctxt un_fold co_rec_defs co_rec_expand_thms))
   828           |> Thm.close_derivation)
   829         goals xtor_un_folds
   830       end;
   831 
   832     val co_product_fs = @{map 2} (fn T => mk_co_product (HOLogic.id_const T)) Ts fs;
   833     val co_rec_expand'_thms = map (fn thm =>
   834       thm RS case_fp fp @{thm convol_expand_snd'} @{thm case_sum_expand_Inr'}) co_rec_id_thms;
   835     val xtor_co_rec_unique_thm =
   836       let
   837         fun mk_prem f s mapx xtor absT_info_opt =
   838           let
   839             val lhs = mk_co_comp f xtor;
   840             val rhs = mk_co_comp s (list_comb (mapx, ids @ co_product_fs))
   841               |> absT_info_decode thy fp absT_info_opt;
   842           in
   843             mk_Trueprop_eq (co_swap (lhs, rhs))
   844           end;
   845         val prems = @{map 5} mk_prem fs co_rec_ss co_rec_maps_rev xtors absT_info_opts;
   846         val concl = @{map 2} (curry HOLogic.mk_eq) fs co_rec_app_ss
   847           |> Library.foldr1 HOLogic.mk_conj |> HOLogic.mk_Trueprop;
   848         val goal = Logic.list_implies (prems, concl);
   849         val vars = Variable.add_free_names lthy goal [];
   850         fun mk_inverses NONE = []
   851           | mk_inverses (SOME (src, dst)) =
   852             [#type_definition dst RS @{thm type_copy_Rep_o_Abs} RS rewrite_comp_comp,
   853              #type_definition src RS @{thm type_copy_Abs_o_Rep}];
   854         val inverses = maps mk_inverses absT_info_opts;
   855       in
   856         Goal.prove_sorry lthy vars [] goal
   857           (fn {context = ctxt, prems = _} => mk_xtor_co_rec_unique_tac ctxt fp co_rec_defs
   858             co_rec_expand'_thms xtor_un_fold_unique map_id0s sym_map_comp0s inverses)
   859         |> Thm.close_derivation
   860       end;
   861 
   862     val xtor_co_rec_o_map_thms = if forall is_none absT_info_opts
   863       then
   864         mk_xtor_co_iter_o_map_thms fp true m xtor_co_rec_unique_thm
   865           (map (mk_pointfree2 lthy) xtor_maps) (map (mk_pointfree2 lthy) xtor_co_rec_thms)
   866           sym_map_comp0s map_cong0s
   867       else
   868         replicate n refl (* FIXME *);
   869 
   870     val ABphiTs = @{map 2} mk_pred2T As Bs;
   871     val XYphiTs = @{map 2} mk_pred2T Xs Ys;
   872 
   873     val ((ABphis, XYphis), names_lthy) = names_lthy
   874       |> mk_Frees "R" ABphiTs
   875       ||>> mk_Frees "S" XYphiTs;
   876 
   877     val xtor_co_rec_transfer_thms = if forall is_none absT_info_opts
   878       then
   879         let
   880           val pre_rels =
   881             @{map 2} (fn Ds => mk_rel_of_bnf Ds (As @ co_rec_Xs) (Bs @ co_rec_Ys)) Dss pre_bnfs;
   882           val rels = @{map 3} (fn T => fn T' => Thm.prop_of #> HOLogic.dest_Trueprop
   883               #> fst o dest_comb #> fst o dest_comb #> funpow n (snd o dest_comb)
   884               #> case_fp fp (fst o dest_comb #> snd o dest_comb) (snd o dest_comb) #> head_of
   885               #> force_typ names_lthy (ABphiTs ---> mk_pred2T T T'))
   886             Ts Us xtor_un_fold_transfers;
   887 
   888           fun tac {context = ctxt, prems = _} = mk_xtor_co_rec_transfer_tac ctxt fp n m co_rec_defs
   889             xtor_un_fold_transfers map_transfers xtor_rels;
   890 
   891           val mk_rel_co_product = case_fp fp mk_rel_prod mk_rel_sum;
   892           val rec_phis =
   893             map2 (fn rel => mk_rel_co_product (Term.list_comb (rel, ABphis))) rels XYphis;
   894         in
   895           mk_xtor_co_iter_transfer_thms fp pre_rels rec_phis XYphis rels ABphis
   896             co_recs (map (subst_atomic_types (ABs @ XYs)) co_recs) tac lthy
   897         end
   898       else
   899         replicate n TrueI (* FIXME *);
   900 
   901     val notes =
   902       [(case_fp fp ctor_recN dtor_corecN, xtor_co_rec_thms),
   903        (case_fp fp ctor_rec_uniqueN dtor_corec_uniqueN, split_conj_thm xtor_co_rec_unique_thm),
   904        (case_fp fp ctor_rec_o_mapN dtor_corec_o_mapN, xtor_co_rec_o_map_thms),
   905        (case_fp fp ctor_rec_transferN dtor_corec_transferN, xtor_co_rec_transfer_thms)]
   906       |> map (apsnd (map single))
   907       |> maps (fn (thmN, thmss) =>
   908         map2 (fn b => fn thms =>
   909           ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), []), [(thms, [])]))
   910         bs thmss);
   911 
   912      val lthy = lthy |> Config.get lthy bnf_internals ? snd o Local_Theory.notes notes;
   913   in
   914     ((co_recs,
   915      (xtor_co_rec_thms, xtor_co_rec_unique_thm, xtor_co_rec_o_map_thms, xtor_co_rec_transfer_thms)),
   916       lthy)
   917   end;
   918 
   919 fun raw_qualify extra_qualify base_b =
   920   let
   921     val qs = Binding.path_of base_b;
   922     val n = Binding.name_of base_b;
   923   in
   924     Binding.prefix_name rawN
   925     #> fold_rev (fn (s, mand) => Binding.qualify mand s) (qs @ [(n, true)])
   926     #> extra_qualify #> Binding.concealed
   927   end;
   928 
   929 fun fixpoint_bnf force_out_of_line extra_qualify construct_fp bs resBs Ds0 Xs rhsXs comp_cache0
   930     lthy =
   931   let
   932     val time = time lthy;
   933     val timer = time (Timer.startRealTimer ());
   934 
   935     fun flatten_tyargs Ass =
   936       subtract (op =) Xs (filter (fn T => exists (fn Ts => member (op =) Ts T) Ass) resBs) @ Xs;
   937 
   938     val ((bnfs, (deadss, livess)), (comp_cache_unfold_set, lthy')) =
   939       apfst (apsnd split_list o split_list)
   940         (@{fold_map 2}
   941           (fn b => bnf_of_typ true Smart_Inline (raw_qualify extra_qualify b) flatten_tyargs Xs Ds0)
   942           bs rhsXs ((comp_cache0, empty_unfolds), lthy));
   943 
   944     fun norm_qualify i =
   945       Binding.qualify true (Binding.name_of (nth bs (Int.max (0, i - 1))))
   946       #> extra_qualify #> Binding.concealed;
   947 
   948     val Ass = map (map dest_TFree) livess;
   949     val Ds' = fold (fold Term.add_tfreesT) deadss [];
   950     val Ds = union (op =) Ds' Ds0;
   951     val missing = resBs |> fold (subtract (op =)) (Ds' :: Ass);
   952     val (dead_phantoms, live_phantoms) = List.partition (member (op =) Ds0) missing;
   953     val resBs' = resBs |> fold (subtract (op =)) [dead_phantoms, Ds];
   954 
   955     val timer = time (timer "Construction of BNFs");
   956 
   957     val ((kill_posss, _), (bnfs', ((comp_cache', unfold_set'), lthy''))) =
   958       normalize_bnfs norm_qualify Ass Ds (K (resBs' @ Xs)) bnfs (comp_cache_unfold_set, lthy');
   959 
   960     val Dss = @{map 3} (fn lives => fn kill_posss => fn deads => deads @ map (nth lives) kill_posss)
   961       livess kill_posss deadss;
   962     val all_Dss = Dss |> force_out_of_line ? map (fn Ds' => union (op =) Ds' (map TFree Ds0));
   963 
   964     fun pre_qualify b =
   965       Binding.qualify false (Binding.name_of b)
   966       #> extra_qualify
   967       #> not (Config.get lthy'' bnf_internals) ? Binding.concealed;
   968 
   969     val ((pre_bnfs, (deadss, absT_infos)), lthy''') = lthy''
   970       |> @{fold_map 5} (fn b => seal_bnf (pre_qualify b) unfold_set' (Binding.prefix_name preN b))
   971         bs (replicate (length rhsXs) (force_out_of_line orelse not (null live_phantoms))) Dss
   972         all_Dss bnfs'
   973       |>> split_list
   974       |>> apsnd split_list;
   975 
   976     val timer = time (timer "Normalization & sealing of BNFs");
   977 
   978     val res = construct_fp bs resBs (map TFree dead_phantoms, deadss) pre_bnfs absT_infos lthy''';
   979 
   980     val timer = time (timer "FP construction in total");
   981   in
   982     (((pre_bnfs, absT_infos), comp_cache'), res)
   983   end;
   984 
   985 fun fp_antiquote_setup binding =
   986   Document_Antiquotation.setup binding (Args.type_name {proper = true, strict = true})
   987     (fn {source = src, context = ctxt, ...} => fn fcT_name =>
   988        (case Ctr_Sugar.ctr_sugar_of ctxt fcT_name of
   989          NONE => error ("Not a known freely generated type name: " ^ quote fcT_name)
   990        | SOME {T = T0, ctrs = ctrs0, ...} =>
   991          let
   992            val freezeT = Term.map_atyps (fn TVar ((s, _), S) => TFree (s, S) | T => T);
   993 
   994            val T = freezeT T0;
   995            val ctrs = map (Term.map_types freezeT) ctrs0;
   996 
   997            val pretty_typ_bracket = Syntax.pretty_typ (Config.put pretty_priority 1001 ctxt);
   998            fun pretty_ctr ctr =
   999              Pretty.block (Pretty.breaks (Syntax.pretty_term ctxt ctr ::
  1000                map pretty_typ_bracket (binder_types (fastype_of ctr))));
  1001            val pretty_co_datatype =
  1002              Pretty.block (Pretty.keyword1 (Binding.name_of binding) :: Pretty.brk 1 ::
  1003                Syntax.pretty_typ ctxt T :: Pretty.str " =" :: Pretty.brk 1 ::
  1004                flat (separate [Pretty.brk 1, Pretty.str "| "] (map (single o pretty_ctr) ctrs)));
  1005          in
  1006            Thy_Output.output ctxt
  1007              (Thy_Output.maybe_pretty_source (K (K pretty_co_datatype)) ctxt src [()])
  1008          end));
  1009 
  1010 end;