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