src/HOL/Tools/BNF/bnf_def.ML
author desharna
Mon Aug 18 15:03:22 2014 +0200 (2014-08-18)
changeset 57981 81baacfd56e8
parent 57970 eaa986cd285a
child 58093 6f37a300c82b
permissions -rw-r--r--
generate 'map_cong_simp' for BNFs
     1 (*  Title:      HOL/Tools/BNF/bnf_def.ML
     2     Author:     Dmitriy Traytel, TU Muenchen
     3     Author:     Jasmin Blanchette, TU Muenchen
     4     Author:     Martin Desharnais, TU Muenchen
     5     Copyright   2012, 2013, 2014
     6 
     7 Definition of bounded natural functors.
     8 *)
     9 
    10 signature BNF_DEF =
    11 sig
    12   type bnf
    13   type nonemptiness_witness = {I: int list, wit: term, prop: thm list}
    14 
    15   val morph_bnf: morphism -> bnf -> bnf
    16   val morph_bnf_defs: morphism -> bnf -> bnf
    17   val bnf_of: Proof.context -> string -> bnf option
    18   val bnf_interpretation: (bnf -> theory -> theory) -> theory -> theory
    19   val register_bnf: string -> bnf -> local_theory -> local_theory
    20 
    21   val name_of_bnf: bnf -> binding
    22   val T_of_bnf: bnf -> typ
    23   val live_of_bnf: bnf -> int
    24   val lives_of_bnf: bnf -> typ list
    25   val dead_of_bnf: bnf -> int
    26   val deads_of_bnf: bnf -> typ list
    27   val bd_of_bnf: bnf -> term
    28   val nwits_of_bnf: bnf -> int
    29 
    30   val mapN: string
    31   val relN: string
    32   val setN: string
    33   val mk_setN: int -> string
    34   val mk_witN: int -> string
    35 
    36   val map_of_bnf: bnf -> term
    37   val sets_of_bnf: bnf -> term list
    38   val rel_of_bnf: bnf -> term
    39 
    40   val mk_T_of_bnf: typ list -> typ list -> bnf -> typ
    41   val mk_bd_of_bnf: typ list -> typ list -> bnf -> term
    42   val mk_map_of_bnf: typ list -> typ list -> typ list -> bnf -> term
    43   val mk_rel_of_bnf: typ list -> typ list -> typ list -> bnf -> term
    44   val mk_sets_of_bnf: typ list list -> typ list list -> bnf -> term list
    45   val mk_wits_of_bnf: typ list list -> typ list list -> bnf -> (int list * term) list
    46 
    47   val bd_Card_order_of_bnf: bnf -> thm
    48   val bd_Cinfinite_of_bnf: bnf -> thm
    49   val bd_Cnotzero_of_bnf: bnf -> thm
    50   val bd_card_order_of_bnf: bnf -> thm
    51   val bd_cinfinite_of_bnf: bnf -> thm
    52   val collect_set_map_of_bnf: bnf -> thm
    53   val in_bd_of_bnf: bnf -> thm
    54   val in_cong_of_bnf: bnf -> thm
    55   val in_mono_of_bnf: bnf -> thm
    56   val in_rel_of_bnf: bnf -> thm
    57   val inj_map_of_bnf: bnf -> thm
    58   val inj_map_strong_of_bnf: bnf -> thm
    59   val map_comp0_of_bnf: bnf -> thm
    60   val map_comp_of_bnf: bnf -> thm
    61   val map_cong0_of_bnf: bnf -> thm
    62   val map_cong_of_bnf: bnf -> thm
    63   val map_cong_simp_of_bnf: bnf -> thm
    64   val map_def_of_bnf: bnf -> thm
    65   val map_id0_of_bnf: bnf -> thm
    66   val map_id_of_bnf: bnf -> thm
    67   val map_ident0_of_bnf: bnf -> thm
    68   val map_ident_of_bnf: bnf -> thm
    69   val map_transfer_of_bnf: bnf -> thm
    70   val le_rel_OO_of_bnf: bnf -> thm
    71   val rel_def_of_bnf: bnf -> thm
    72   val rel_Grp_of_bnf: bnf -> thm
    73   val rel_OO_of_bnf: bnf -> thm
    74   val rel_OO_Grp_of_bnf: bnf -> thm
    75   val rel_cong_of_bnf: bnf -> thm
    76   val rel_conversep_of_bnf: bnf -> thm
    77   val rel_mono_of_bnf: bnf -> thm
    78   val rel_mono_strong0_of_bnf: bnf -> thm
    79   val rel_mono_strong_of_bnf: bnf -> thm
    80   val rel_eq_of_bnf: bnf -> thm
    81   val rel_flip_of_bnf: bnf -> thm
    82   val set_bd_of_bnf: bnf -> thm list
    83   val set_defs_of_bnf: bnf -> thm list
    84   val set_map0_of_bnf: bnf -> thm list
    85   val set_map_of_bnf: bnf -> thm list
    86   val wit_thms_of_bnf: bnf -> thm list
    87   val wit_thmss_of_bnf: bnf -> thm list list
    88 
    89   val mk_map: int -> typ list -> typ list -> term -> term
    90   val mk_rel: int -> typ list -> typ list -> term -> term
    91   val build_map: Proof.context -> typ list -> (typ * typ -> term) -> typ * typ -> term
    92   val build_rel: Proof.context -> typ list -> (typ * typ -> term) -> typ * typ -> term
    93   val flatten_type_args_of_bnf: bnf -> 'a -> 'a list -> 'a list
    94   val map_flattened_map_args: Proof.context -> string -> (term list -> 'a list) -> term list ->
    95     'a list
    96 
    97   val mk_witness: int list * term -> thm list -> nonemptiness_witness
    98   val minimize_wits: (''a list * 'b) list -> (''a list * 'b) list
    99   val wits_of_bnf: bnf -> nonemptiness_witness list
   100 
   101   val zip_axioms: 'a -> 'a -> 'a -> 'a list -> 'a -> 'a -> 'a list -> 'a -> 'a -> 'a list
   102 
   103   datatype inline_policy = Dont_Inline | Hardly_Inline | Smart_Inline | Do_Inline
   104   datatype fact_policy = Dont_Note | Note_Some | Note_All
   105 
   106   val bnf_note_all: bool Config.T
   107   val bnf_timing: bool Config.T
   108   val user_policy: fact_policy -> Proof.context -> fact_policy
   109   val note_bnf_thms: fact_policy -> (binding -> binding) -> binding -> bnf -> Proof.context ->
   110     bnf * Proof.context
   111 
   112   val print_bnfs: Proof.context -> unit
   113   val prepare_def: inline_policy -> (Proof.context -> fact_policy) -> bool ->
   114     (binding -> binding) -> (Proof.context -> 'a -> typ) -> (Proof.context -> 'b -> term) ->
   115     typ list option -> binding -> binding -> binding list ->
   116     (((((binding * 'a) * 'b) * 'b list) * 'b) * 'b list) * 'b option -> Proof.context ->
   117     string * term list *
   118     ((Proof.context -> thm list -> tactic) option * term list list) *
   119     ((thm list -> thm list list) -> thm list list -> Proof.context -> bnf * local_theory) *
   120     local_theory * thm list
   121 
   122   val define_bnf_consts: inline_policy -> fact_policy -> bool -> typ list option ->
   123     binding -> binding -> binding list ->
   124     (((((binding * typ) * term) * term list) * term) * term list) * term option -> local_theory ->
   125       ((typ list * typ list * typ list * typ) *
   126        (term * term list * term * (int list * term) list * term) *
   127        (thm * thm list * thm * thm list * thm) *
   128        ((typ list -> typ list -> typ list -> term) *
   129         (typ list -> typ list -> term -> term) *
   130         (typ list -> typ list -> typ -> typ) *
   131         (typ list -> typ list -> typ list -> term) *
   132         (typ list -> typ list -> typ list -> term))) * local_theory
   133 
   134   val bnf_def: inline_policy -> (Proof.context -> fact_policy) -> bool -> (binding -> binding) ->
   135     (Proof.context -> tactic) list ->
   136     (Proof.context -> tactic) -> typ list option -> binding ->
   137     binding -> binding list ->
   138     (((((binding * typ) * term) * term list) * term) * term list) * term option ->
   139     local_theory -> bnf * local_theory
   140 end;
   141 
   142 structure BNF_Def : BNF_DEF =
   143 struct
   144 
   145 open BNF_Util
   146 open BNF_Tactics
   147 open BNF_Def_Tactics
   148 
   149 val fundefcong_attrs = @{attributes [fundef_cong]};
   150 
   151 type axioms = {
   152   map_id0: thm,
   153   map_comp0: thm,
   154   map_cong0: thm,
   155   set_map0: thm list,
   156   bd_card_order: thm,
   157   bd_cinfinite: thm,
   158   set_bd: thm list,
   159   le_rel_OO: thm,
   160   rel_OO_Grp: thm
   161 };
   162 
   163 fun mk_axioms' ((((((((id, comp), cong), map), c_o), cinf), set_bd), le_rel_OO), rel) =
   164   {map_id0 = id, map_comp0 = comp, map_cong0 = cong, set_map0 = map, bd_card_order = c_o,
   165    bd_cinfinite = cinf, set_bd = set_bd, le_rel_OO = le_rel_OO, rel_OO_Grp = rel};
   166 
   167 fun dest_cons [] = raise List.Empty
   168   | dest_cons (x :: xs) = (x, xs);
   169 
   170 fun mk_axioms n thms = thms
   171   |> map the_single
   172   |> dest_cons
   173   ||>> dest_cons
   174   ||>> dest_cons
   175   ||>> chop n
   176   ||>> dest_cons
   177   ||>> dest_cons
   178   ||>> chop n
   179   ||>> dest_cons
   180   ||> the_single
   181   |> mk_axioms';
   182 
   183 fun zip_axioms mid mcomp mcong smap bdco bdinf sbd le_rel_OO rel =
   184   [mid, mcomp, mcong] @ smap @ [bdco, bdinf] @ sbd @ [le_rel_OO, rel];
   185 
   186 fun dest_axioms {map_id0, map_comp0, map_cong0, set_map0, bd_card_order, bd_cinfinite, set_bd,
   187   le_rel_OO, rel_OO_Grp} =
   188   zip_axioms map_id0 map_comp0 map_cong0 set_map0 bd_card_order bd_cinfinite set_bd le_rel_OO
   189     rel_OO_Grp;
   190 
   191 fun map_axioms f {map_id0, map_comp0, map_cong0, set_map0, bd_card_order, bd_cinfinite, set_bd,
   192   le_rel_OO, rel_OO_Grp} =
   193   {map_id0 = f map_id0,
   194     map_comp0 = f map_comp0,
   195     map_cong0 = f map_cong0,
   196     set_map0 = map f set_map0,
   197     bd_card_order = f bd_card_order,
   198     bd_cinfinite = f bd_cinfinite,
   199     set_bd = map f set_bd,
   200     le_rel_OO = f le_rel_OO,
   201     rel_OO_Grp = f rel_OO_Grp};
   202 
   203 val morph_axioms = map_axioms o Morphism.thm;
   204 
   205 type defs = {
   206   map_def: thm,
   207   set_defs: thm list,
   208   rel_def: thm
   209 }
   210 
   211 fun mk_defs map sets rel = {map_def = map, set_defs = sets, rel_def = rel};
   212 
   213 fun map_defs f {map_def, set_defs, rel_def} =
   214   {map_def = f map_def, set_defs = map f set_defs, rel_def = f rel_def};
   215 
   216 val morph_defs = map_defs o Morphism.thm;
   217 
   218 type facts = {
   219   bd_Card_order: thm,
   220   bd_Cinfinite: thm,
   221   bd_Cnotzero: thm,
   222   collect_set_map: thm lazy,
   223   in_bd: thm lazy,
   224   in_cong: thm lazy,
   225   in_mono: thm lazy,
   226   in_rel: thm lazy,
   227   inj_map: thm lazy,
   228   inj_map_strong: thm lazy,
   229   map_comp: thm lazy,
   230   map_cong: thm lazy,
   231   map_cong_simp: thm lazy,
   232   map_id: thm lazy,
   233   map_ident0: thm lazy,
   234   map_ident: thm lazy,
   235   map_transfer: thm lazy,
   236   rel_eq: thm lazy,
   237   rel_flip: thm lazy,
   238   set_map: thm lazy list,
   239   rel_cong: thm lazy,
   240   rel_map: thm list lazy,
   241   rel_mono: thm lazy,
   242   rel_mono_strong0: thm lazy,
   243   rel_mono_strong: thm lazy,
   244   rel_Grp: thm lazy,
   245   rel_conversep: thm lazy,
   246   rel_OO: thm lazy
   247 };
   248 
   249 fun mk_facts bd_Card_order bd_Cinfinite bd_Cnotzero collect_set_map in_bd in_cong in_mono in_rel
   250     inj_map inj_map_strong map_comp map_cong map_cong_simp map_id map_ident0 map_ident
   251     map_transfer rel_eq rel_flip set_map rel_cong rel_map rel_mono rel_mono_strong0 rel_mono_strong
   252     rel_Grp rel_conversep rel_OO = {
   253   bd_Card_order = bd_Card_order,
   254   bd_Cinfinite = bd_Cinfinite,
   255   bd_Cnotzero = bd_Cnotzero,
   256   collect_set_map = collect_set_map,
   257   in_bd = in_bd,
   258   in_cong = in_cong,
   259   in_mono = in_mono,
   260   in_rel = in_rel,
   261   inj_map = inj_map,
   262   inj_map_strong = inj_map_strong,
   263   map_comp = map_comp,
   264   map_cong = map_cong,
   265   map_cong_simp = map_cong_simp,
   266   map_id = map_id,
   267   map_ident0 = map_ident0,
   268   map_ident = map_ident,
   269   map_transfer = map_transfer,
   270   rel_eq = rel_eq,
   271   rel_flip = rel_flip,
   272   set_map = set_map,
   273   rel_cong = rel_cong,
   274   rel_map = rel_map,
   275   rel_mono = rel_mono,
   276   rel_mono_strong0 = rel_mono_strong0,
   277   rel_mono_strong = rel_mono_strong,
   278   rel_Grp = rel_Grp,
   279   rel_conversep = rel_conversep,
   280   rel_OO = rel_OO};
   281 
   282 fun map_facts f {
   283   bd_Card_order,
   284   bd_Cinfinite,
   285   bd_Cnotzero,
   286   collect_set_map,
   287   in_bd,
   288   in_cong,
   289   in_mono,
   290   in_rel,
   291   inj_map,
   292   inj_map_strong,
   293   map_comp,
   294   map_cong,
   295   map_cong_simp,
   296   map_id,
   297   map_ident0,
   298   map_ident,
   299   map_transfer,
   300   rel_eq,
   301   rel_flip,
   302   set_map,
   303   rel_cong,
   304   rel_map,
   305   rel_mono,
   306   rel_mono_strong0,
   307   rel_mono_strong,
   308   rel_Grp,
   309   rel_conversep,
   310   rel_OO} =
   311   {bd_Card_order = f bd_Card_order,
   312     bd_Cinfinite = f bd_Cinfinite,
   313     bd_Cnotzero = f bd_Cnotzero,
   314     collect_set_map = Lazy.map f collect_set_map,
   315     in_bd = Lazy.map f in_bd,
   316     in_cong = Lazy.map f in_cong,
   317     in_mono = Lazy.map f in_mono,
   318     in_rel = Lazy.map f in_rel,
   319     inj_map = Lazy.map f inj_map,
   320     inj_map_strong = Lazy.map f inj_map_strong,
   321     map_comp = Lazy.map f map_comp,
   322     map_cong = Lazy.map f map_cong,
   323     map_cong_simp = Lazy.map f map_cong_simp,
   324     map_id = Lazy.map f map_id,
   325     map_ident0 = Lazy.map f map_ident0,
   326     map_ident = Lazy.map f map_ident,
   327     map_transfer = Lazy.map f map_transfer,
   328     rel_eq = Lazy.map f rel_eq,
   329     rel_flip = Lazy.map f rel_flip,
   330     set_map = map (Lazy.map f) set_map,
   331     rel_cong = Lazy.map f rel_cong,
   332     rel_map = Lazy.map (map f) rel_map,
   333     rel_mono = Lazy.map f rel_mono,
   334     rel_mono_strong0 = Lazy.map f rel_mono_strong0,
   335     rel_mono_strong = Lazy.map f rel_mono_strong,
   336     rel_Grp = Lazy.map f rel_Grp,
   337     rel_conversep = Lazy.map f rel_conversep,
   338     rel_OO = Lazy.map f rel_OO};
   339 
   340 val morph_facts = map_facts o Morphism.thm;
   341 
   342 type nonemptiness_witness = {
   343   I: int list,
   344   wit: term,
   345   prop: thm list
   346 };
   347 
   348 fun mk_witness (I, wit) prop = {I = I, wit = wit, prop = prop};
   349 fun map_witness f g {I, wit, prop} = {I = I, wit = f wit, prop = map g prop};
   350 fun morph_witness phi = map_witness (Morphism.term phi) (Morphism.thm phi);
   351 
   352 datatype bnf = BNF of {
   353   name: binding,
   354   T: typ,
   355   live: int,
   356   lives: typ list, (*source type variables of map*)
   357   lives': typ list, (*target type variables of map*)
   358   dead: int,
   359   deads: typ list,
   360   map: term,
   361   sets: term list,
   362   bd: term,
   363   axioms: axioms,
   364   defs: defs,
   365   facts: facts,
   366   nwits: int,
   367   wits: nonemptiness_witness list,
   368   rel: term
   369 };
   370 
   371 (* getters *)
   372 
   373 fun rep_bnf (BNF bnf) = bnf;
   374 val name_of_bnf = #name o rep_bnf;
   375 val T_of_bnf = #T o rep_bnf;
   376 fun mk_T_of_bnf Ds Ts bnf =
   377   let val bnf_rep = rep_bnf bnf
   378   in Term.typ_subst_atomic ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts)) (#T bnf_rep) end;
   379 val live_of_bnf = #live o rep_bnf;
   380 val lives_of_bnf = #lives o rep_bnf;
   381 val dead_of_bnf = #dead o rep_bnf;
   382 val deads_of_bnf = #deads o rep_bnf;
   383 val axioms_of_bnf = #axioms o rep_bnf;
   384 val facts_of_bnf = #facts o rep_bnf;
   385 val nwits_of_bnf = #nwits o rep_bnf;
   386 val wits_of_bnf = #wits o rep_bnf;
   387 
   388 fun flatten_type_args_of_bnf bnf dead_x xs =
   389   let
   390     val Type (_, Ts) = T_of_bnf bnf;
   391     val lives = lives_of_bnf bnf;
   392     val deads = deads_of_bnf bnf;
   393   in
   394     permute_like_unique (op =) (deads @ lives) Ts (replicate (length deads) dead_x @ xs)
   395   end;
   396 
   397 (*terms*)
   398 val map_of_bnf = #map o rep_bnf;
   399 val sets_of_bnf = #sets o rep_bnf;
   400 fun mk_map_of_bnf Ds Ts Us bnf =
   401   let val bnf_rep = rep_bnf bnf;
   402   in
   403     Term.subst_atomic_types
   404       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts) @ (#lives' bnf_rep ~~ Us)) (#map bnf_rep)
   405   end;
   406 fun mk_sets_of_bnf Dss Tss bnf =
   407   let val bnf_rep = rep_bnf bnf;
   408   in
   409     map2 (fn (Ds, Ts) => Term.subst_atomic_types
   410       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts))) (Dss ~~ Tss) (#sets bnf_rep)
   411   end;
   412 val bd_of_bnf = #bd o rep_bnf;
   413 fun mk_bd_of_bnf Ds Ts bnf =
   414   let val bnf_rep = rep_bnf bnf;
   415   in Term.subst_atomic_types ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts)) (#bd bnf_rep) end;
   416 fun mk_wits_of_bnf Dss Tss bnf =
   417   let
   418     val bnf_rep = rep_bnf bnf;
   419     val wits = map (fn x => (#I x, #wit x)) (#wits bnf_rep);
   420   in
   421     map2 (fn (Ds, Ts) => apsnd (Term.subst_atomic_types
   422       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts)))) (Dss ~~ Tss) wits
   423   end;
   424 val rel_of_bnf = #rel o rep_bnf;
   425 fun mk_rel_of_bnf Ds Ts Us bnf =
   426   let val bnf_rep = rep_bnf bnf;
   427   in
   428     Term.subst_atomic_types
   429       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts) @ (#lives' bnf_rep ~~ Us)) (#rel bnf_rep)
   430   end;
   431 
   432 (*thms*)
   433 val bd_card_order_of_bnf = #bd_card_order o #axioms o rep_bnf;
   434 val bd_cinfinite_of_bnf = #bd_cinfinite o #axioms o rep_bnf;
   435 val bd_Card_order_of_bnf = #bd_Card_order o #facts o rep_bnf;
   436 val bd_Cinfinite_of_bnf = #bd_Cinfinite o #facts o rep_bnf;
   437 val bd_Cnotzero_of_bnf = #bd_Cnotzero o #facts o rep_bnf;
   438 val collect_set_map_of_bnf = Lazy.force o #collect_set_map o #facts o rep_bnf;
   439 val in_bd_of_bnf = Lazy.force o #in_bd o #facts o rep_bnf;
   440 val in_cong_of_bnf = Lazy.force o #in_cong o #facts o rep_bnf;
   441 val in_mono_of_bnf = Lazy.force o #in_mono o #facts o rep_bnf;
   442 val in_rel_of_bnf = Lazy.force o #in_rel o #facts o rep_bnf;
   443 val inj_map_of_bnf = Lazy.force o #inj_map o #facts o rep_bnf;
   444 val inj_map_strong_of_bnf = Lazy.force o #inj_map_strong o #facts o rep_bnf;
   445 val map_def_of_bnf = #map_def o #defs o rep_bnf;
   446 val map_id0_of_bnf = #map_id0 o #axioms o rep_bnf;
   447 val map_id_of_bnf = Lazy.force o #map_id o #facts o rep_bnf;
   448 val map_ident0_of_bnf = Lazy.force o #map_ident0 o #facts o rep_bnf;
   449 val map_ident_of_bnf = Lazy.force o #map_ident o #facts o rep_bnf;
   450 val map_comp0_of_bnf = #map_comp0 o #axioms o rep_bnf;
   451 val map_comp_of_bnf = Lazy.force o #map_comp o #facts o rep_bnf;
   452 val map_cong0_of_bnf = #map_cong0 o #axioms o rep_bnf;
   453 val map_cong_of_bnf = Lazy.force o #map_cong o #facts o rep_bnf;
   454 val map_cong_simp_of_bnf = Lazy.force o #map_cong_simp o #facts o rep_bnf;
   455 val map_transfer_of_bnf = Lazy.force o #map_transfer o #facts o rep_bnf;
   456 val le_rel_OO_of_bnf = #le_rel_OO o #axioms o rep_bnf;
   457 val rel_def_of_bnf = #rel_def o #defs o rep_bnf;
   458 val rel_eq_of_bnf = Lazy.force o #rel_eq o #facts o rep_bnf;
   459 val rel_flip_of_bnf = Lazy.force o #rel_flip o #facts o rep_bnf;
   460 val set_bd_of_bnf = #set_bd o #axioms o rep_bnf;
   461 val set_defs_of_bnf = #set_defs o #defs o rep_bnf;
   462 val set_map0_of_bnf = #set_map0 o #axioms o rep_bnf;
   463 val set_map_of_bnf = map Lazy.force o #set_map o #facts o rep_bnf;
   464 val rel_cong_of_bnf = Lazy.force o #rel_cong o #facts o rep_bnf;
   465 val rel_mono_of_bnf = Lazy.force o #rel_mono o #facts o rep_bnf;
   466 val rel_mono_strong0_of_bnf = Lazy.force o #rel_mono_strong0 o #facts o rep_bnf;
   467 val rel_mono_strong_of_bnf = Lazy.force o #rel_mono_strong o #facts o rep_bnf;
   468 val rel_Grp_of_bnf = Lazy.force o #rel_Grp o #facts o rep_bnf;
   469 val rel_conversep_of_bnf = Lazy.force o #rel_conversep o #facts o rep_bnf;
   470 val rel_OO_of_bnf = Lazy.force o #rel_OO o #facts o rep_bnf;
   471 val rel_OO_Grp_of_bnf = #rel_OO_Grp o #axioms o rep_bnf;
   472 val wit_thms_of_bnf = maps #prop o wits_of_bnf;
   473 val wit_thmss_of_bnf = map #prop o wits_of_bnf;
   474 
   475 fun mk_bnf name T live lives lives' dead deads map sets bd axioms defs facts wits rel =
   476   BNF {name = name, T = T,
   477        live = live, lives = lives, lives' = lives', dead = dead, deads = deads,
   478        map = map, sets = sets, bd = bd,
   479        axioms = axioms, defs = defs, facts = facts,
   480        nwits = length wits, wits = wits, rel = rel};
   481 
   482 fun map_bnf f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16
   483   (BNF {name = name, T = T, live = live, lives = lives, lives' = lives',
   484   dead = dead, deads = deads, map = map, sets = sets, bd = bd,
   485   axioms = axioms, defs = defs, facts = facts,
   486   nwits = nwits, wits = wits, rel = rel}) =
   487   BNF {name = f1 name, T = f2 T,
   488        live = f3 live, lives = f4 lives, lives' = f5 lives', dead = f6 dead, deads = f7 deads,
   489        map = f8 map, sets = f9 sets, bd = f10 bd,
   490        axioms = f11 axioms, defs = f12 defs, facts = f13 facts,
   491        nwits = f14 nwits, wits = f15 wits, rel = f16 rel};
   492 
   493 fun morph_bnf phi =
   494   let
   495     val Tphi = Morphism.typ phi;
   496     val tphi = Morphism.term phi;
   497   in
   498     map_bnf (Morphism.binding phi) Tphi I (map Tphi) (map Tphi) I (map Tphi) tphi (map tphi) tphi
   499       (morph_axioms phi) (morph_defs phi) (morph_facts phi) I (map (morph_witness phi)) tphi
   500   end;
   501 
   502 fun morph_bnf_defs phi = map_bnf I I I I I I I I I I I (morph_defs phi) I I I I;
   503 
   504 structure Data = Generic_Data
   505 (
   506   type T = bnf Symtab.table;
   507   val empty = Symtab.empty;
   508   val extend = I;
   509   fun merge data : T = Symtab.merge (K true) data;
   510 );
   511 
   512 fun bnf_of ctxt =
   513   Symtab.lookup (Data.get (Context.Proof ctxt))
   514   #> Option.map (morph_bnf (Morphism.transfer_morphism (Proof_Context.theory_of ctxt)));
   515 
   516 
   517 (* Utilities *)
   518 
   519 fun normalize_set insts instA set =
   520   let
   521     val (T, T') = dest_funT (fastype_of set);
   522     val A = fst (Term.dest_TVar (HOLogic.dest_setT T'));
   523     val params = Term.add_tvar_namesT T [];
   524   in Term.subst_TVars ((A :: params) ~~ (instA :: insts)) set end;
   525 
   526 fun normalize_rel ctxt instTs instA instB rel =
   527   let
   528     val thy = Proof_Context.theory_of ctxt;
   529     val tyenv =
   530       Sign.typ_match thy (fastype_of rel, Library.foldr (op -->) (instTs, mk_pred2T instA instB))
   531         Vartab.empty;
   532   in Envir.subst_term (tyenv, Vartab.empty) rel end
   533   handle Type.TYPE_MATCH => error "Bad relator";
   534 
   535 fun normalize_wit insts CA As wit =
   536   let
   537     fun strip_param (Ts, T as Type (@{type_name fun}, [T1, T2])) =
   538         if Type.raw_instance (CA, T) then (Ts, T) else strip_param (T1 :: Ts, T2)
   539       | strip_param x = x;
   540     val (Ts, T) = strip_param ([], fastype_of wit);
   541     val subst = Term.add_tvar_namesT T [] ~~ insts;
   542     fun find y = find_index (fn x => x = y) As;
   543   in
   544     (map (find o Term.typ_subst_TVars subst) (rev Ts), Term.subst_TVars subst wit)
   545   end;
   546 
   547 fun minimize_wits wits =
   548  let
   549    fun minimize done [] = done
   550      | minimize done ((I, wit) :: todo) =
   551        if exists (fn (J, _) => subset (op =) (J, I)) (done @ todo)
   552        then minimize done todo
   553        else minimize ((I, wit) :: done) todo;
   554  in minimize [] wits end;
   555 
   556 fun mk_map live Ts Us t =
   557   let val (Type (_, Ts0), Type (_, Us0)) = strip_typeN (live + 1) (fastype_of t) |>> List.last in
   558     Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
   559   end;
   560 
   561 fun mk_rel live Ts Us t =
   562   let val [Type (_, Ts0), Type (_, Us0)] = binder_types (snd (strip_typeN live (fastype_of t))) in
   563     Term.subst_atomic_types (Ts0 @ Us0 ~~ Ts @ Us) t
   564   end;
   565 
   566 fun build_map_or_rel mk const of_bnf dest ctxt simpleTs build_simple =
   567   let
   568     fun build (TU as (T, U)) =
   569       if exists (curry (op =) T) simpleTs then
   570         build_simple TU
   571       else if T = U andalso not (exists_subtype_in simpleTs T) then
   572         const T
   573       else
   574         (case TU of
   575           (Type (s, Ts), Type (s', Us)) =>
   576           if s = s' then
   577             let
   578               val bnf = the (bnf_of ctxt s);
   579               val live = live_of_bnf bnf;
   580               val mapx = mk live Ts Us (of_bnf bnf);
   581               val TUs' = map dest (fst (strip_typeN live (fastype_of mapx)));
   582             in Term.list_comb (mapx, map build TUs') end
   583           else
   584             build_simple TU
   585         | _ => build_simple TU);
   586   in build end;
   587 
   588 val build_map = build_map_or_rel mk_map HOLogic.id_const map_of_bnf dest_funT;
   589 val build_rel = build_map_or_rel mk_rel HOLogic.eq_const rel_of_bnf dest_pred2T;
   590 
   591 fun map_flattened_map_args ctxt s map_args fs =
   592   let
   593     val flat_fs = flatten_type_args_of_bnf (the (bnf_of ctxt s)) Term.dummy fs;
   594     val flat_fs' = map_args flat_fs;
   595   in
   596     permute_like_unique (op aconv) flat_fs fs flat_fs'
   597   end;
   598 
   599 
   600 (* Names *)
   601 
   602 val mapN = "map";
   603 val setN = "set";
   604 fun mk_setN i = setN ^ nonzero_string_of_int i;
   605 val bdN = "bd";
   606 val witN = "wit";
   607 fun mk_witN i = witN ^ nonzero_string_of_int i;
   608 val relN = "rel";
   609 
   610 val bd_card_orderN = "bd_card_order";
   611 val bd_cinfiniteN = "bd_cinfinite";
   612 val bd_Card_orderN = "bd_Card_order";
   613 val bd_CinfiniteN = "bd_Cinfinite";
   614 val bd_CnotzeroN = "bd_Cnotzero";
   615 val collect_set_mapN = "collect_set_map";
   616 val in_bdN = "in_bd";
   617 val in_monoN = "in_mono";
   618 val in_relN = "in_rel";
   619 val inj_mapN = "inj_map";
   620 val inj_map_strongN = "inj_map_strong";
   621 val map_id0N = "map_id0";
   622 val map_idN = "map_id";
   623 val map_identN = "map_ident";
   624 val map_comp0N = "map_comp0";
   625 val map_compN = "map_comp";
   626 val map_cong0N = "map_cong0";
   627 val map_congN = "map_cong";
   628 val map_cong_simpN = "map_cong_simp";
   629 val map_transferN = "map_transfer";
   630 val rel_eqN = "rel_eq";
   631 val rel_flipN = "rel_flip";
   632 val set_map0N = "set_map0";
   633 val set_mapN = "set_map";
   634 val set_bdN = "set_bd";
   635 val rel_GrpN = "rel_Grp";
   636 val rel_conversepN = "rel_conversep";
   637 val rel_mapN = "rel_map"
   638 val rel_monoN = "rel_mono"
   639 val rel_mono_strong0N = "rel_mono_strong0"
   640 val rel_mono_strongN = "rel_mono_strong"
   641 val rel_comppN = "rel_compp";
   642 val rel_compp_GrpN = "rel_compp_Grp";
   643 
   644 datatype inline_policy = Dont_Inline | Hardly_Inline | Smart_Inline | Do_Inline;
   645 
   646 datatype fact_policy = Dont_Note | Note_Some | Note_All;
   647 
   648 val bnf_note_all = Attrib.setup_config_bool @{binding bnf_note_all} (K false);
   649 val bnf_timing = Attrib.setup_config_bool @{binding bnf_timing} (K false);
   650 
   651 fun user_policy policy ctxt = if Config.get ctxt bnf_note_all then Note_All else policy;
   652 
   653 val smart_max_inline_term_size = 25; (*FUDGE*)
   654 
   655 fun note_bnf_thms fact_policy qualify0 bnf_b bnf lthy =
   656   let
   657     val axioms = axioms_of_bnf bnf;
   658     val facts = facts_of_bnf bnf;
   659     val wits = wits_of_bnf bnf;
   660     val qualify =
   661       let val (_, qs, _) = Binding.dest bnf_b;
   662       in fold_rev (fn (s, mand) => Binding.qualify mand s) qs #> qualify0 end;
   663 
   664     fun note_if_note_all (noted0, lthy0) =
   665       let
   666         val witNs = if length wits = 1 then [witN] else map mk_witN (1 upto length wits);
   667         val notes =
   668           [(bd_card_orderN, [#bd_card_order axioms]),
   669            (bd_cinfiniteN, [#bd_cinfinite axioms]),
   670            (bd_Card_orderN, [#bd_Card_order facts]),
   671            (bd_CinfiniteN, [#bd_Cinfinite facts]),
   672            (bd_CnotzeroN, [#bd_Cnotzero facts]),
   673            (collect_set_mapN, [Lazy.force (#collect_set_map facts)]),
   674            (in_bdN, [Lazy.force (#in_bd facts)]),
   675            (in_monoN, [Lazy.force (#in_mono facts)]),
   676            (in_relN, [Lazy.force (#in_rel facts)]),
   677            (map_comp0N, [#map_comp0 axioms]),
   678            (map_transferN, [Lazy.force (#map_transfer facts)]),
   679            (rel_mono_strong0N, [Lazy.force (#rel_mono_strong0 facts)]),
   680            (rel_mono_strongN, [Lazy.force (#rel_mono_strong facts)]),
   681            (set_map0N, #set_map0 axioms),
   682            (set_bdN, #set_bd axioms)] @
   683           (witNs ~~ wit_thmss_of_bnf bnf)
   684           |> map (fn (thmN, thms) =>
   685             ((qualify (Binding.qualify true (Binding.name_of bnf_b) (Binding.name thmN)), []),
   686              [(thms, [])]));
   687       in
   688         Local_Theory.notes notes lthy0 |>> append noted0
   689       end
   690 
   691     fun note_unless_dont_note (noted0, lthy0) =
   692       let
   693         val notes =
   694           [(inj_mapN, [Lazy.force (#inj_map facts)], []),
   695            (inj_map_strongN, [Lazy.force (#inj_map_strong facts)], []),
   696            (map_compN, [Lazy.force (#map_comp facts)], []),
   697            (map_cong0N, [#map_cong0 axioms], []),
   698            (map_congN, [Lazy.force (#map_cong facts)], fundefcong_attrs),
   699            (map_cong_simpN, [Lazy.force (#map_cong_simp facts)], []),
   700            (map_idN, [Lazy.force (#map_id facts)], []),
   701            (map_id0N, [#map_id0 axioms], []),
   702            (map_identN, [Lazy.force (#map_ident facts)], []),
   703            (rel_comppN, [Lazy.force (#rel_OO facts)], []),
   704            (rel_compp_GrpN, no_refl [#rel_OO_Grp axioms], []),
   705            (rel_conversepN, [Lazy.force (#rel_conversep facts)], []),
   706            (rel_eqN, [Lazy.force (#rel_eq facts)], []),
   707            (rel_flipN, [Lazy.force (#rel_flip facts)], []),
   708            (rel_GrpN, [Lazy.force (#rel_Grp facts)], []),
   709            (rel_mapN, Lazy.force (#rel_map facts), []),
   710            (rel_monoN, [Lazy.force (#rel_mono facts)], []),
   711            (set_mapN, map Lazy.force (#set_map facts), [])]
   712           |> filter_out (null o #2)
   713           |> map (fn (thmN, thms, attrs) =>
   714             ((qualify (Binding.qualify true (Binding.name_of bnf_b) (Binding.name thmN)), attrs),
   715              [(thms, [])]));
   716       in
   717         Local_Theory.notes notes lthy0 |>> append noted0
   718       end
   719   in
   720     ([], lthy)
   721     |> fact_policy = Note_All ? note_if_note_all
   722     |> fact_policy <> Dont_Note ? note_unless_dont_note
   723     |>> (fn [] => bnf | noted => morph_bnf (substitute_noted_thm noted) bnf)
   724   end;
   725 
   726 
   727 (* Define new BNFs *)
   728 
   729 fun define_bnf_consts const_policy fact_policy internal Ds_opt map_b rel_b set_bs
   730   ((((((bnf_b, T_rhs), map_rhs), set_rhss), bd_rhs), wit_rhss), rel_rhs_opt) no_defs_lthy =
   731   let
   732     val live = length set_rhss;
   733 
   734     val def_qualify = Binding.conceal o Binding.qualify false (Binding.name_of bnf_b);
   735 
   736     fun mk_prefix_binding pre = Binding.prefix_name (pre ^ "_") bnf_b;
   737 
   738     fun maybe_define user_specified (b, rhs) lthy =
   739       let
   740         val inline =
   741           (user_specified orelse fact_policy = Dont_Note) andalso
   742           (case const_policy of
   743             Dont_Inline => false
   744           | Hardly_Inline => Term.is_Free rhs orelse Term.is_Const rhs
   745           | Smart_Inline => Term.size_of_term rhs <= smart_max_inline_term_size
   746           | Do_Inline => true)
   747       in
   748         if inline then
   749           ((rhs, Drule.reflexive_thm), lthy)
   750         else
   751           let val b = b () in
   752             apfst (apsnd snd)
   753               ((if internal then Local_Theory.define_internal else Local_Theory.define)
   754                 ((b, NoSyn), ((Thm.def_binding b, []), rhs)) lthy)
   755           end
   756       end;
   757 
   758     fun maybe_restore lthy_old lthy =
   759       lthy |> not (Theory.eq_thy (pairself Proof_Context.theory_of (lthy_old, lthy)))
   760         ? Local_Theory.restore;
   761 
   762     val map_bind_def =
   763       (fn () => def_qualify (if Binding.is_empty map_b then mk_prefix_binding mapN else map_b),
   764          map_rhs);
   765     val set_binds_defs =
   766       let
   767         fun set_name i get_b =
   768           (case try (nth set_bs) (i - 1) of
   769             SOME b => if Binding.is_empty b then get_b else K b
   770           | NONE => get_b) #> def_qualify;
   771         val bs = if live = 1 then [set_name 1 (fn () => mk_prefix_binding setN)]
   772           else map (fn i => set_name i (fn () => mk_prefix_binding (mk_setN i))) (1 upto live);
   773       in bs ~~ set_rhss end;
   774     val bd_bind_def = (fn () => def_qualify (mk_prefix_binding bdN), bd_rhs);
   775 
   776     val ((((bnf_map_term, raw_map_def),
   777       (bnf_set_terms, raw_set_defs)),
   778       (bnf_bd_term, raw_bd_def)), (lthy, lthy_old)) =
   779         no_defs_lthy
   780         |> maybe_define true map_bind_def
   781         ||>> apfst split_list o fold_map (maybe_define true) set_binds_defs
   782         ||>> maybe_define true bd_bind_def
   783         ||> `(maybe_restore no_defs_lthy);
   784 
   785     val phi = Proof_Context.export_morphism lthy_old lthy;
   786 
   787     val bnf_map_def = Morphism.thm phi raw_map_def;
   788     val bnf_set_defs = map (Morphism.thm phi) raw_set_defs;
   789     val bnf_bd_def = Morphism.thm phi raw_bd_def;
   790 
   791     val bnf_map = Morphism.term phi bnf_map_term;
   792 
   793     (*TODO: handle errors*)
   794     (*simple shape analysis of a map function*)
   795     val ((alphas, betas), (Calpha, _)) =
   796       fastype_of bnf_map
   797       |> strip_typeN live
   798       |>> map_split dest_funT
   799       ||> dest_funT
   800       handle TYPE _ => error "Bad map function";
   801 
   802     val Calpha_params = map TVar (Term.add_tvarsT Calpha []);
   803 
   804     val bnf_T = Morphism.typ phi T_rhs;
   805     val bad_args = Term.add_tfreesT bnf_T [];
   806     val _ = if null bad_args then () else error ("Locally fixed type arguments " ^
   807       commas_quote (map (Syntax.string_of_typ no_defs_lthy o TFree) bad_args));
   808 
   809     val bnf_sets =
   810       map2 (normalize_set Calpha_params) alphas (map (Morphism.term phi) bnf_set_terms);
   811     val bnf_bd =
   812       Term.subst_TVars (Term.add_tvar_namesT bnf_T [] ~~ Calpha_params)
   813         (Morphism.term phi bnf_bd_term);
   814 
   815     (*TODO: assert Ds = (TVars of bnf_map) \ (alphas @ betas) as sets*)
   816     val deads = (case Ds_opt of
   817       NONE => subtract (op =) (alphas @ betas) (map TVar (Term.add_tvars bnf_map []))
   818     | SOME Ds => map (Morphism.typ phi) Ds);
   819 
   820     (*TODO: further checks of type of bnf_map*)
   821     (*TODO: check types of bnf_sets*)
   822     (*TODO: check type of bnf_bd*)
   823     (*TODO: check type of bnf_rel*)
   824 
   825     fun mk_bnf_map Ds As' Bs' =
   826       Term.subst_atomic_types ((deads ~~ Ds) @ (alphas ~~ As') @ (betas ~~ Bs')) bnf_map;
   827     fun mk_bnf_t Ds As' = Term.subst_atomic_types ((deads ~~ Ds) @ (alphas ~~ As'));
   828     fun mk_bnf_T Ds As' = Term.typ_subst_atomic ((deads ~~ Ds) @ (alphas ~~ As'));
   829 
   830     val (((As, Bs), Ds), names_lthy) = lthy
   831       |> mk_TFrees live
   832       ||>> mk_TFrees live
   833       ||>> mk_TFrees (length deads);
   834     val RTs = map2 (curry HOLogic.mk_prodT) As Bs;
   835     val pred2RTs = map2 mk_pred2T As Bs;
   836     val (Rs, Rs') = names_lthy |> mk_Frees' "R" pred2RTs |> fst
   837     val CA = mk_bnf_T Ds As Calpha;
   838     val CR = mk_bnf_T Ds RTs Calpha;
   839     val setRs =
   840       map3 (fn R => fn T => fn U =>
   841           HOLogic.Collect_const (HOLogic.mk_prodT (T, U)) $ HOLogic.mk_split R) Rs As Bs;
   842 
   843     (*Grp (in (Collect (split R1) .. Collect (split Rn))) (map fst .. fst)^--1 OO
   844       Grp (in (Collect (split R1) .. Collect (split Rn))) (map snd .. snd)*)
   845     val OO_Grp =
   846       let
   847         val map1 = Term.list_comb (mk_bnf_map Ds RTs As, map fst_const RTs);
   848         val map2 = Term.list_comb (mk_bnf_map Ds RTs Bs, map snd_const RTs);
   849         val bnf_in = mk_in setRs (map (mk_bnf_t Ds RTs) bnf_sets) CR;
   850       in
   851         mk_rel_compp (mk_conversep (mk_Grp bnf_in map1), mk_Grp bnf_in map2)
   852         |> fold_rev Term.absfree Rs'
   853       end;
   854 
   855     val rel_rhs = the_default OO_Grp rel_rhs_opt;
   856 
   857     val rel_bind_def =
   858       (fn () => def_qualify (if Binding.is_empty rel_b then mk_prefix_binding relN else rel_b),
   859          rel_rhs);
   860 
   861     val wit_rhss =
   862       if null wit_rhss then
   863         [fold_rev Term.absdummy As (Term.list_comb (mk_bnf_map Ds As As,
   864           map2 (fn T => fn i => Term.absdummy T (Bound i)) As (live downto 1)) $
   865           Const (@{const_name undefined}, CA))]
   866       else wit_rhss;
   867     val nwits = length wit_rhss;
   868     val wit_binds_defs =
   869       let
   870         val bs = if nwits = 1 then [fn () => def_qualify (mk_prefix_binding witN)]
   871           else map (fn i => fn () => def_qualify (mk_prefix_binding (mk_witN i))) (1 upto nwits);
   872       in bs ~~ wit_rhss end;
   873 
   874     val (((bnf_rel_term, raw_rel_def), (bnf_wit_terms, raw_wit_defs)), (lthy, lthy_old)) =
   875       lthy
   876       |> maybe_define (is_some rel_rhs_opt) rel_bind_def
   877       ||>> apfst split_list o fold_map (maybe_define (not (null wit_rhss))) wit_binds_defs
   878       ||> `(maybe_restore lthy);
   879 
   880     val phi = Proof_Context.export_morphism lthy_old lthy;
   881     val bnf_rel_def = Morphism.thm phi raw_rel_def;
   882     val bnf_rel = Morphism.term phi bnf_rel_term;
   883     fun mk_bnf_rel Ds As' Bs' =
   884       normalize_rel lthy (map2 mk_pred2T As' Bs') (mk_bnf_T Ds As' Calpha) (mk_bnf_T Ds Bs' Calpha)
   885         bnf_rel;
   886 
   887     val bnf_wit_defs = map (Morphism.thm phi) raw_wit_defs;
   888     val bnf_wits =
   889       map (normalize_wit Calpha_params Calpha alphas o Morphism.term phi) bnf_wit_terms;
   890 
   891     fun mk_OO_Grp Ds' As' Bs' =
   892       Term.subst_atomic_types ((Ds ~~ Ds') @ (As ~~ As') @ (Bs ~~ Bs')) OO_Grp;
   893   in
   894     (((alphas, betas, deads, Calpha),
   895      (bnf_map, bnf_sets, bnf_bd, bnf_wits, bnf_rel),
   896      (bnf_map_def, bnf_set_defs, bnf_bd_def, bnf_wit_defs, bnf_rel_def),
   897      (mk_bnf_map, mk_bnf_t, mk_bnf_T, mk_bnf_rel, mk_OO_Grp)), lthy)
   898   end;
   899 
   900 fun prepare_def const_policy mk_fact_policy internal qualify prep_typ prep_term Ds_opt map_b rel_b
   901   set_bs ((((((raw_bnf_b, raw_bnf_T), raw_map), raw_sets), raw_bd), raw_wits), raw_rel_opt)
   902   no_defs_lthy =
   903   let
   904     val fact_policy = mk_fact_policy no_defs_lthy;
   905     val bnf_b = qualify raw_bnf_b;
   906     val live = length raw_sets;
   907 
   908     val T_rhs = prep_typ no_defs_lthy raw_bnf_T;
   909     val map_rhs = prep_term no_defs_lthy raw_map;
   910     val set_rhss = map (prep_term no_defs_lthy) raw_sets;
   911     val bd_rhs = prep_term no_defs_lthy raw_bd;
   912     val wit_rhss = map (prep_term no_defs_lthy) raw_wits;
   913     val rel_rhs_opt = Option.map (prep_term no_defs_lthy) raw_rel_opt;
   914 
   915     fun err T =
   916       error ("Trying to register the type " ^ quote (Syntax.string_of_typ no_defs_lthy T) ^
   917         " as unnamed BNF");
   918 
   919     val (bnf_b, key) =
   920       if Binding.eq_name (bnf_b, Binding.empty) then
   921         (case T_rhs of
   922           Type (C, Ts) => if forall (can dest_TFree) Ts
   923             then (Binding.qualified_name C, C) else err T_rhs
   924         | T => err T)
   925       else (bnf_b, Local_Theory.full_name no_defs_lthy bnf_b);
   926 
   927     val (((alphas, betas, deads, Calpha),
   928      (bnf_map, bnf_sets, bnf_bd, bnf_wits, bnf_rel),
   929      (bnf_map_def, bnf_set_defs, bnf_bd_def, bnf_wit_defs, bnf_rel_def),
   930      (mk_bnf_map_Ds, mk_bnf_t_Ds, mk_bnf_T_Ds, _, mk_OO_Grp)), lthy) =
   931        define_bnf_consts const_policy fact_policy internal Ds_opt map_b rel_b set_bs
   932          ((((((bnf_b, T_rhs), map_rhs), set_rhss), bd_rhs), wit_rhss), rel_rhs_opt) no_defs_lthy;
   933 
   934     val dead = length deads;
   935 
   936     val ((((((As', Bs'), Cs), Ds), B1Ts), B2Ts), (Ts, T)) = lthy
   937       |> mk_TFrees live
   938       ||>> mk_TFrees live
   939       ||>> mk_TFrees live
   940       ||>> mk_TFrees dead
   941       ||>> mk_TFrees live
   942       ||>> mk_TFrees live
   943       ||> fst o mk_TFrees 1
   944       ||> the_single
   945       ||> `(replicate live);
   946 
   947     val mk_bnf_map = mk_bnf_map_Ds Ds;
   948     val mk_bnf_t = mk_bnf_t_Ds Ds;
   949     val mk_bnf_T = mk_bnf_T_Ds Ds;
   950 
   951     val pred2RTs = map2 mk_pred2T As' Bs';
   952     val pred2RTsAsCs = map2 mk_pred2T As' Cs;
   953     val pred2RTsBsCs = map2 mk_pred2T Bs' Cs;
   954     val pred2RTsCsBs = map2 mk_pred2T Cs Bs';
   955     val pred2RT's = map2 mk_pred2T Bs' As';
   956     val self_pred2RTs = map2 mk_pred2T As' As';
   957     val transfer_domRTs = map2 mk_pred2T As' B1Ts;
   958     val transfer_ranRTs = map2 mk_pred2T Bs' B2Ts;
   959 
   960     val CA' = mk_bnf_T As' Calpha;
   961     val CB' = mk_bnf_T Bs' Calpha;
   962     val CC' = mk_bnf_T Cs Calpha;
   963     val CB1 = mk_bnf_T B1Ts Calpha;
   964     val CB2 = mk_bnf_T B2Ts Calpha;
   965 
   966     val bnf_map_AsAs = mk_bnf_map As' As';
   967     val bnf_map_AsBs = mk_bnf_map As' Bs';
   968     val bnf_map_AsCs = mk_bnf_map As' Cs;
   969     val bnf_map_BsCs = mk_bnf_map Bs' Cs;
   970     val bnf_sets_As = map (mk_bnf_t As') bnf_sets;
   971     val bnf_sets_Bs = map (mk_bnf_t Bs') bnf_sets;
   972     val bnf_bd_As = mk_bnf_t As' bnf_bd;
   973     fun mk_bnf_rel RTs CA CB = normalize_rel lthy RTs CA CB bnf_rel;
   974 
   975     val pre_names_lthy = lthy;
   976     val (((((((((((((((((((((fs, fs'), gs), hs), is), x), x'), y), zs), zs'), ys), As),
   977       As_copy), bs), Rs), Rs_copy), Ss), S_AsCs), S_CsBs),
   978       transfer_domRs), transfer_ranRs), names_lthy) = pre_names_lthy
   979       |> mk_Frees "f" (map2 (curry op -->) As' Bs')
   980       ||>> mk_Frees "f" (map2 (curry op -->) As' Bs')
   981       ||>> mk_Frees "g" (map2 (curry op -->) Bs' Cs)
   982       ||>> mk_Frees "h" (map2 (curry op -->) As' Ts)
   983       ||>> mk_Frees "i" (map2 (curry op -->) As' Cs)
   984       ||>> yield_singleton (mk_Frees "x") CA'
   985       ||>> yield_singleton (mk_Frees "x") CA'
   986       ||>> yield_singleton (mk_Frees "y") CB'
   987       ||>> mk_Frees "z" As'
   988       ||>> mk_Frees "z" As'
   989       ||>> mk_Frees "y" Bs'
   990       ||>> mk_Frees "A" (map HOLogic.mk_setT As')
   991       ||>> mk_Frees "A" (map HOLogic.mk_setT As')
   992       ||>> mk_Frees "b" As'
   993       ||>> mk_Frees "R" pred2RTs
   994       ||>> mk_Frees "R" pred2RTs
   995       ||>> mk_Frees "S" pred2RTsBsCs
   996       ||>> mk_Frees "S" pred2RTsAsCs
   997       ||>> mk_Frees "S" pred2RTsCsBs
   998       ||>> mk_Frees "R" transfer_domRTs
   999       ||>> mk_Frees "S" transfer_ranRTs;
  1000 
  1001     val fs_copy = map2 (retype_const_or_free o fastype_of) fs gs;
  1002     val x_copy = retype_const_or_free CA' y;
  1003 
  1004     val rel = mk_bnf_rel pred2RTs CA' CB';
  1005     val relAsAs = mk_bnf_rel self_pred2RTs CA' CA';
  1006     val bnf_wit_As = map (apsnd (mk_bnf_t As')) bnf_wits;
  1007 
  1008     val map_id0_goal =
  1009       let val bnf_map_app_id = Term.list_comb (bnf_map_AsAs, map HOLogic.id_const As') in
  1010         mk_Trueprop_eq (bnf_map_app_id, HOLogic.id_const CA')
  1011       end;
  1012 
  1013     val map_comp0_goal =
  1014       let
  1015         val bnf_map_app_comp = Term.list_comb (bnf_map_AsCs, map2 (curry HOLogic.mk_comp) gs fs);
  1016         val comp_bnf_map_app = HOLogic.mk_comp
  1017           (Term.list_comb (bnf_map_BsCs, gs), Term.list_comb (bnf_map_AsBs, fs));
  1018       in
  1019         fold_rev Logic.all (fs @ gs) (mk_Trueprop_eq (bnf_map_app_comp, comp_bnf_map_app))
  1020       end;
  1021 
  1022     fun mk_map_cong_prem mk_implies x z set f f_copy =
  1023       Logic.all z (mk_implies
  1024         (mk_Trueprop_mem (z, set $ x), mk_Trueprop_eq (f $ z, f_copy $ z)));
  1025 
  1026     val map_cong0_goal =
  1027       let
  1028         val prems = map4 (mk_map_cong_prem Logic.mk_implies x) zs bnf_sets_As fs fs_copy;
  1029         val eq = mk_Trueprop_eq (Term.list_comb (bnf_map_AsBs, fs) $ x,
  1030           Term.list_comb (bnf_map_AsBs, fs_copy) $ x);
  1031       in
  1032         fold_rev Logic.all (x :: fs @ fs_copy) (Logic.list_implies (prems, eq))
  1033       end;
  1034 
  1035     val set_map0s_goal =
  1036       let
  1037         fun mk_goal setA setB f =
  1038           let
  1039             val set_comp_map =
  1040               HOLogic.mk_comp (setB, Term.list_comb (bnf_map_AsBs, fs));
  1041             val image_comp_set = HOLogic.mk_comp (mk_image f, setA);
  1042           in
  1043             fold_rev Logic.all fs (mk_Trueprop_eq (set_comp_map, image_comp_set))
  1044           end;
  1045       in
  1046         map3 mk_goal bnf_sets_As bnf_sets_Bs fs
  1047       end;
  1048 
  1049     val card_order_bd_goal = HOLogic.mk_Trueprop (mk_card_order bnf_bd_As);
  1050 
  1051     val cinfinite_bd_goal = HOLogic.mk_Trueprop (mk_cinfinite bnf_bd_As);
  1052 
  1053     val set_bds_goal =
  1054       let
  1055         fun mk_goal set =
  1056           Logic.all x (HOLogic.mk_Trueprop (mk_ordLeq (mk_card_of (set $ x)) bnf_bd_As));
  1057       in
  1058         map mk_goal bnf_sets_As
  1059       end;
  1060 
  1061     val relAsCs = mk_bnf_rel pred2RTsAsCs CA' CC';
  1062     val relBsCs = mk_bnf_rel pred2RTsBsCs CB' CC';
  1063     val relCsBs = mk_bnf_rel pred2RTsCsBs CC' CB';
  1064     val rel_OO_lhs = Term.list_comb (relAsCs, map2 (curry mk_rel_compp) Rs Ss);
  1065     val rel_OO_rhs = mk_rel_compp (Term.list_comb (rel, Rs), Term.list_comb (relBsCs, Ss));
  1066     val le_rel_OO_goal =
  1067       fold_rev Logic.all (Rs @ Ss) (HOLogic.mk_Trueprop (mk_leq rel_OO_rhs rel_OO_lhs));
  1068 
  1069     val rel_OO_Grp_goal = fold_rev Logic.all Rs (mk_Trueprop_eq (Term.list_comb (rel, Rs),
  1070       Term.list_comb (mk_OO_Grp Ds As' Bs', Rs)));
  1071 
  1072     val goals = zip_axioms map_id0_goal map_comp0_goal map_cong0_goal set_map0s_goal
  1073       card_order_bd_goal cinfinite_bd_goal set_bds_goal le_rel_OO_goal rel_OO_Grp_goal;
  1074 
  1075     fun mk_wit_goals (I, wit) =
  1076       let
  1077         val xs = map (nth bs) I;
  1078         fun wit_goal i =
  1079           let
  1080             val z = nth zs i;
  1081             val set_wit = nth bnf_sets_As i $ Term.list_comb (wit, xs);
  1082             val concl = HOLogic.mk_Trueprop
  1083               (if member (op =) I i then HOLogic.mk_eq (z, nth bs i)
  1084               else @{term False});
  1085           in
  1086             fold_rev Logic.all (z :: xs)
  1087               (Logic.mk_implies (mk_Trueprop_mem (z, set_wit), concl))
  1088           end;
  1089       in
  1090         map wit_goal (0 upto live - 1)
  1091       end;
  1092 
  1093     fun triv_wit_tac ctxt = mk_trivial_wit_tac ctxt bnf_wit_defs;
  1094 
  1095     val wit_goalss =
  1096       (if null raw_wits then SOME triv_wit_tac else NONE, map mk_wit_goals bnf_wit_As);
  1097 
  1098     fun after_qed mk_wit_thms thms lthy =
  1099       let
  1100         val (axioms, nontriv_wit_thms) = apfst (mk_axioms live) (chop (length goals) thms);
  1101 
  1102         val bd_Card_order = #bd_card_order axioms RS @{thm conjunct2[OF card_order_on_Card_order]};
  1103         val bd_Cinfinite = @{thm conjI} OF [#bd_cinfinite axioms, bd_Card_order];
  1104         val bd_Cnotzero = bd_Cinfinite RS @{thm Cinfinite_Cnotzero};
  1105 
  1106         fun mk_collect_set_map () =
  1107           let
  1108             val defT = mk_bnf_T Ts Calpha --> HOLogic.mk_setT T;
  1109             val collect_map = HOLogic.mk_comp
  1110               (mk_collect (map (mk_bnf_t Ts) bnf_sets) defT,
  1111               Term.list_comb (mk_bnf_map As' Ts, hs));
  1112             val image_collect = mk_collect
  1113               (map2 (fn h => fn set => HOLogic.mk_comp (mk_image h, set)) hs bnf_sets_As)
  1114               defT;
  1115             (*collect {set1 ... setm} o map f1 ... fm = collect {f1` o set1 ... fm` o setm}*)
  1116             val goal = fold_rev Logic.all hs (mk_Trueprop_eq (collect_map, image_collect));
  1117           in
  1118             Goal.prove_sorry lthy [] [] goal (K (mk_collect_set_map_tac (#set_map0 axioms)))
  1119             |> Thm.close_derivation
  1120           end;
  1121 
  1122         val collect_set_map = Lazy.lazy mk_collect_set_map;
  1123 
  1124         fun mk_in_mono () =
  1125           let
  1126             val prems_mono = map2 (HOLogic.mk_Trueprop oo mk_leq) As As_copy;
  1127             val in_mono_goal =
  1128               fold_rev Logic.all (As @ As_copy)
  1129                 (Logic.list_implies (prems_mono, HOLogic.mk_Trueprop
  1130                   (mk_leq (mk_in As bnf_sets_As CA') (mk_in As_copy bnf_sets_As CA'))));
  1131           in
  1132             Goal.prove_sorry lthy [] [] in_mono_goal (K (mk_in_mono_tac live))
  1133             |> Thm.close_derivation
  1134           end;
  1135 
  1136         val in_mono = Lazy.lazy mk_in_mono;
  1137 
  1138         fun mk_in_cong () =
  1139           let
  1140             val prems_cong = map2 (curry mk_Trueprop_eq) As As_copy;
  1141             val in_cong_goal =
  1142               fold_rev Logic.all (As @ As_copy)
  1143                 (Logic.list_implies (prems_cong,
  1144                   mk_Trueprop_eq (mk_in As bnf_sets_As CA', mk_in As_copy bnf_sets_As CA')));
  1145           in
  1146             Goal.prove_sorry lthy [] [] in_cong_goal
  1147               (K ((TRY o hyp_subst_tac lthy THEN' rtac refl) 1))
  1148             |> Thm.close_derivation
  1149           end;
  1150 
  1151         val in_cong = Lazy.lazy mk_in_cong;
  1152 
  1153         val map_id = Lazy.lazy (fn () => mk_map_id (#map_id0 axioms));
  1154         val map_ident0 = Lazy.lazy (fn () => mk_map_ident lthy (#map_id0 axioms));
  1155         val map_ident = Lazy.lazy (fn () => mk_map_ident lthy (Lazy.force map_id));
  1156         val map_comp = Lazy.lazy (fn () => mk_map_comp (#map_comp0 axioms));
  1157 
  1158         fun mk_map_cong mk_implies () =
  1159           let
  1160             val prem0 = mk_Trueprop_eq (x, x_copy);
  1161             val prems = map4 (mk_map_cong_prem mk_implies x_copy) zs bnf_sets_As fs fs_copy;
  1162             val eq = mk_Trueprop_eq (Term.list_comb (bnf_map_AsBs, fs) $ x,
  1163               Term.list_comb (bnf_map_AsBs, fs_copy) $ x_copy);
  1164             val goal = fold_rev Logic.all (x :: x_copy :: fs @ fs_copy)
  1165               (Logic.list_implies (prem0 :: prems, eq));
  1166           in
  1167             Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, prems = _} =>
  1168               unfold_thms_tac lthy @{thms simp_implies_def} THEN
  1169               mk_map_cong_tac lthy (#map_cong0 axioms))
  1170             |> Thm.close_derivation
  1171           end;
  1172 
  1173         val map_cong = Lazy.lazy (mk_map_cong Logic.mk_implies);
  1174         val map_cong_simp = Lazy.lazy (mk_map_cong (fn (a, b) => @{term simp_implies} $ a $ b));
  1175 
  1176         fun mk_inj_map () =
  1177           let
  1178             val prems = map (HOLogic.mk_Trueprop o mk_inj) fs;
  1179             val concl = HOLogic.mk_Trueprop (mk_inj (Term.list_comb (bnf_map_AsBs, fs)));
  1180             val goal = fold_rev Logic.all fs (Logic.list_implies (prems, concl));
  1181           in
  1182             Goal.prove_sorry lthy [] [] goal (fn _ => mk_inj_map_tac live (Lazy.force map_id)
  1183               (Lazy.force map_comp) (#map_cong0 axioms) (Lazy.force map_cong))
  1184             |> Thm.close_derivation
  1185           end;
  1186 
  1187         val inj_map = Lazy.lazy mk_inj_map;
  1188 
  1189         val set_map = map (fn thm => Lazy.lazy (fn () => mk_set_map thm)) (#set_map0 axioms);
  1190 
  1191         val wit_thms =
  1192           if null nontriv_wit_thms then mk_wit_thms (map Lazy.force set_map) else nontriv_wit_thms;
  1193 
  1194         fun mk_in_bd () =
  1195           let
  1196             val bdT = fst (dest_relT (fastype_of bnf_bd_As));
  1197             val bdTs = replicate live bdT;
  1198             val bd_bnfT = mk_bnf_T bdTs Calpha;
  1199             val surj_imp_ordLeq_inst = (if live = 0 then TrueI else
  1200               let
  1201                 val ranTs = map (fn AT => mk_sumT (AT, HOLogic.unitT)) As';
  1202                 val funTs = map (fn T => bdT --> T) ranTs;
  1203                 val ran_bnfT = mk_bnf_T ranTs Calpha;
  1204                 val (revTs, Ts) = `rev (bd_bnfT :: funTs);
  1205                 val cTs = map (SOME o certifyT lthy) [ran_bnfT, Library.foldr1 HOLogic.mk_prodT Ts];
  1206                 val tinst = fold (fn T => fn t => HOLogic.mk_split (Term.absdummy T t)) (tl revTs)
  1207                   (Term.absdummy (hd revTs) (Term.list_comb (mk_bnf_map bdTs ranTs,
  1208                     map Bound (live - 1 downto 0)) $ Bound live));
  1209                 val cts = [NONE, SOME (certify lthy tinst)];
  1210               in
  1211                 Drule.instantiate' cTs cts @{thm surj_imp_ordLeq}
  1212               end);
  1213             val bd = mk_cexp
  1214               (if live = 0 then ctwo
  1215                 else mk_csum (Library.foldr1 (uncurry mk_csum) (map mk_card_of As)) ctwo)
  1216               (mk_csum bnf_bd_As (mk_card_of (HOLogic.mk_UNIV bd_bnfT)));
  1217             val in_bd_goal =
  1218               fold_rev Logic.all As
  1219                 (HOLogic.mk_Trueprop (mk_ordLeq (mk_card_of (mk_in As bnf_sets_As CA')) bd));
  1220           in
  1221             Goal.prove_sorry lthy [] [] in_bd_goal
  1222               (fn {context = ctxt, prems = _} => mk_in_bd_tac ctxt live surj_imp_ordLeq_inst
  1223                 (Lazy.force map_comp) (Lazy.force map_id) (#map_cong0 axioms)
  1224                 (map Lazy.force set_map) (#set_bd axioms) (#bd_card_order axioms)
  1225                 bd_Card_order bd_Cinfinite bd_Cnotzero)
  1226             |> Thm.close_derivation
  1227           end;
  1228 
  1229         val in_bd = Lazy.lazy mk_in_bd;
  1230 
  1231         val rel_OO_Grp = #rel_OO_Grp axioms;
  1232         val rel_OO_Grps = no_refl [rel_OO_Grp];
  1233 
  1234         fun mk_rel_Grp () =
  1235           let
  1236             val lhs = Term.list_comb (rel, map2 mk_Grp As fs);
  1237             val rhs = mk_Grp (mk_in As bnf_sets_As CA') (Term.list_comb (bnf_map_AsBs, fs));
  1238             val goal = fold_rev Logic.all (As @ fs) (mk_Trueprop_eq (lhs, rhs));
  1239           in
  1240             Goal.prove_sorry lthy [] [] goal
  1241               (fn {context = ctxt, prems = _} => mk_rel_Grp_tac ctxt rel_OO_Grps (#map_id0 axioms)
  1242                 (#map_cong0 axioms) (Lazy.force map_id) (Lazy.force map_comp)
  1243                 (map Lazy.force set_map))
  1244             |> Thm.close_derivation
  1245           end;
  1246 
  1247         val rel_Grp = Lazy.lazy mk_rel_Grp;
  1248 
  1249         fun mk_rel_prems f = map2 (HOLogic.mk_Trueprop oo f) Rs Rs_copy
  1250         fun mk_rel_concl f = HOLogic.mk_Trueprop
  1251           (f (Term.list_comb (rel, Rs), Term.list_comb (rel, Rs_copy)));
  1252 
  1253         fun mk_rel_mono () =
  1254           let
  1255             val mono_prems = mk_rel_prems mk_leq;
  1256             val mono_concl = mk_rel_concl (uncurry mk_leq);
  1257           in
  1258             Goal.prove_sorry lthy [] []
  1259               (fold_rev Logic.all (Rs @ Rs_copy) (Logic.list_implies (mono_prems, mono_concl)))
  1260               (K (mk_rel_mono_tac rel_OO_Grps (Lazy.force in_mono)))
  1261             |> Thm.close_derivation
  1262           end;
  1263 
  1264         fun mk_rel_cong () =
  1265           let
  1266             val cong_prems = mk_rel_prems (curry HOLogic.mk_eq);
  1267             val cong_concl = mk_rel_concl HOLogic.mk_eq;
  1268           in
  1269             Goal.prove_sorry lthy [] []
  1270               (fold_rev Logic.all (Rs @ Rs_copy) (Logic.list_implies (cong_prems, cong_concl)))
  1271               (fn _ => (TRY o hyp_subst_tac lthy THEN' rtac refl) 1)
  1272             |> Thm.close_derivation
  1273           end;
  1274 
  1275         val rel_mono = Lazy.lazy mk_rel_mono;
  1276         val rel_cong = Lazy.lazy mk_rel_cong;
  1277 
  1278         fun mk_rel_eq () =
  1279           Goal.prove_sorry lthy [] []
  1280             (mk_Trueprop_eq (Term.list_comb (relAsAs, map HOLogic.eq_const As'),
  1281               HOLogic.eq_const CA'))
  1282             (K (mk_rel_eq_tac live (Lazy.force rel_Grp) (Lazy.force rel_cong) (#map_id0 axioms)))
  1283           |> Thm.close_derivation;
  1284 
  1285         val rel_eq = Lazy.lazy mk_rel_eq;
  1286 
  1287         fun mk_rel_conversep () =
  1288           let
  1289             val relBsAs = mk_bnf_rel pred2RT's CB' CA';
  1290             val lhs = Term.list_comb (relBsAs, map mk_conversep Rs);
  1291             val rhs = mk_conversep (Term.list_comb (rel, Rs));
  1292             val le_goal = fold_rev Logic.all Rs (HOLogic.mk_Trueprop (mk_leq lhs rhs));
  1293             val le_thm = Goal.prove_sorry lthy [] [] le_goal
  1294               (fn {context = ctxt, prems = _} => mk_rel_conversep_le_tac ctxt rel_OO_Grps
  1295                 (Lazy.force rel_eq) (#map_cong0 axioms) (Lazy.force map_comp)
  1296                 (map Lazy.force set_map))
  1297               |> Thm.close_derivation
  1298             val goal = fold_rev Logic.all Rs (mk_Trueprop_eq (lhs, rhs));
  1299           in
  1300             Goal.prove_sorry lthy [] [] goal
  1301               (K (mk_rel_conversep_tac le_thm (Lazy.force rel_mono)))
  1302             |> Thm.close_derivation
  1303           end;
  1304 
  1305         val rel_conversep = Lazy.lazy mk_rel_conversep;
  1306 
  1307         fun mk_rel_OO () =
  1308           Goal.prove_sorry lthy [] []
  1309             (fold_rev Logic.all (Rs @ Ss) (HOLogic.mk_Trueprop (mk_leq rel_OO_lhs rel_OO_rhs)))
  1310             (fn {context = ctxt, prems = _} => mk_rel_OO_le_tac ctxt rel_OO_Grps (Lazy.force rel_eq)
  1311               (#map_cong0 axioms) (Lazy.force map_comp) (map Lazy.force set_map))
  1312           |> Thm.close_derivation
  1313           |> (fn thm => @{thm antisym} OF [thm, #le_rel_OO axioms]);
  1314 
  1315         val rel_OO = Lazy.lazy mk_rel_OO;
  1316 
  1317         fun mk_in_rel () = trans OF [rel_OO_Grp, @{thm OO_Grp_alt}] RS @{thm predicate2_eqD};
  1318 
  1319         val in_rel = Lazy.lazy mk_in_rel;
  1320 
  1321         fun mk_rel_flip () =
  1322           let
  1323             val rel_conversep_thm = Lazy.force rel_conversep;
  1324             val cts = map (SOME o certify lthy) Rs;
  1325             val rel_conversep_thm' = cterm_instantiate_pos cts rel_conversep_thm;
  1326           in
  1327             unfold_thms lthy @{thms conversep_iff} (rel_conversep_thm' RS @{thm predicate2_eqD})
  1328             |> singleton (Proof_Context.export names_lthy pre_names_lthy)
  1329           end;
  1330 
  1331         val rel_flip = Lazy.lazy mk_rel_flip;
  1332 
  1333         fun mk_rel_mono_strong0 () =
  1334           let
  1335             fun mk_prem setA setB R S a b =
  1336               HOLogic.mk_Trueprop
  1337                 (mk_Ball (setA $ x) (Term.absfree (dest_Free a)
  1338                   (mk_Ball (setB $ y) (Term.absfree (dest_Free b)
  1339                     (HOLogic.mk_imp (R $ a $ b, S $ a $ b))))));
  1340             val prems = HOLogic.mk_Trueprop (Term.list_comb (rel, Rs) $ x $ y) ::
  1341               map6 mk_prem bnf_sets_As bnf_sets_Bs Rs Rs_copy zs ys;
  1342             val concl = HOLogic.mk_Trueprop (Term.list_comb (rel, Rs_copy) $ x $ y);
  1343           in
  1344             Goal.prove_sorry lthy [] []
  1345               (fold_rev Logic.all (x :: y :: Rs @ Rs_copy) (Logic.list_implies (prems, concl)))
  1346               (fn {context = ctxt, prems = _} => mk_rel_mono_strong0_tac ctxt (Lazy.force in_rel)
  1347                 (map Lazy.force set_map))
  1348             |> Thm.close_derivation
  1349           end;
  1350 
  1351         val rel_mono_strong0 = Lazy.lazy mk_rel_mono_strong0;
  1352 
  1353         fun mk_rel_mono_strong () = Object_Logic.rulify lthy (Lazy.force rel_mono_strong0)
  1354 
  1355         val rel_mono_strong = Lazy.lazy mk_rel_mono_strong;
  1356 
  1357         fun mk_rel_map () =
  1358           let
  1359             fun mk_goal lhs rhs =
  1360               fold_rev Logic.all ([x, y] @ S_CsBs @ S_AsCs @ is @ gs) (mk_Trueprop_eq (lhs, rhs));
  1361 
  1362             val lhss =
  1363               [Term.list_comb (relCsBs, S_CsBs) $ (Term.list_comb (bnf_map_AsCs, is) $ x) $ y,
  1364                Term.list_comb (relAsCs, S_AsCs) $ x $ (Term.list_comb (bnf_map_BsCs, gs) $ y)];
  1365             val rhss =
  1366               [Term.list_comb (rel, map3 (fn f => fn P => fn T =>
  1367                  mk_vimage2p f (HOLogic.id_const T) $ P) is S_CsBs Bs') $ x $ y,
  1368                Term.list_comb (rel, map3 (fn f => fn P => fn T =>
  1369                  mk_vimage2p (HOLogic.id_const T) f $ P) gs S_AsCs As') $ x $ y];
  1370             val goals = map2 mk_goal lhss rhss;
  1371           in
  1372             goals
  1373             |> map (fn goal => Goal.prove_sorry lthy [] [] goal
  1374               (fn {context = ctxt, prems = _} =>
  1375                  mk_rel_map0_tac ctxt live (Lazy.force rel_OO) (Lazy.force rel_conversep)
  1376                   (Lazy.force rel_Grp) (Lazy.force map_id)))
  1377             |> map (unfold_thms lthy @{thms vimage2p_def[of id, unfolded id_apply]
  1378                  vimage2p_def[of _ id, unfolded id_apply]})
  1379             |> map Thm.close_derivation
  1380           end;
  1381 
  1382         val rel_map = Lazy.lazy mk_rel_map;
  1383 
  1384         fun mk_map_transfer () =
  1385           let
  1386             val rels = map2 mk_rel_fun transfer_domRs transfer_ranRs;
  1387             val rel = mk_rel_fun
  1388               (Term.list_comb (mk_bnf_rel transfer_domRTs CA' CB1, transfer_domRs))
  1389               (Term.list_comb (mk_bnf_rel transfer_ranRTs CB' CB2, transfer_ranRs));
  1390             val concl = HOLogic.mk_Trueprop
  1391               (fold_rev mk_rel_fun rels rel $ bnf_map_AsBs $ mk_bnf_map B1Ts B2Ts);
  1392           in
  1393             Goal.prove_sorry lthy [] []
  1394               (fold_rev Logic.all (transfer_domRs @ transfer_ranRs) concl)
  1395               (fn {context = ctxt, prems = _} => mk_map_transfer_tac ctxt (Lazy.force rel_mono)
  1396                 (Lazy.force in_rel) (map Lazy.force set_map) (#map_cong0 axioms)
  1397                 (Lazy.force map_comp))
  1398             |> Thm.close_derivation
  1399           end;
  1400 
  1401         val map_transfer = Lazy.lazy mk_map_transfer;
  1402 
  1403         fun mk_inj_map_strong () =
  1404           let
  1405             val assms = map5 (fn setA => fn z => fn f => fn z' => fn f' =>
  1406               fold_rev Logic.all [z, z']
  1407                 (Logic.mk_implies (mk_Trueprop_mem (z, setA $ x),
  1408                    Logic.mk_implies (mk_Trueprop_mem (z', setA $ x'),
  1409                      Logic.mk_implies (mk_Trueprop_eq (f $ z, f' $ z'),
  1410                        mk_Trueprop_eq (z, z')))))) bnf_sets_As zs fs zs' fs';
  1411             val concl = Logic.mk_implies
  1412               (mk_Trueprop_eq
  1413                  (Term.list_comb (bnf_map_AsBs, fs) $ x,
  1414                   Term.list_comb (bnf_map_AsBs, fs') $ x'),
  1415                mk_Trueprop_eq (x, x'));
  1416             val goal = fold_rev Logic.all (x :: x' :: fs @ fs')
  1417               (fold_rev (curry Logic.mk_implies) assms concl);
  1418           in
  1419             Goal.prove_sorry lthy [] [] goal (fn {context = ctxt, prems = _} =>
  1420               mk_inj_map_strong_tac ctxt (Lazy.force rel_eq) (Lazy.force rel_map)
  1421                 (Lazy.force rel_mono_strong))
  1422             |> Thm.close_derivation
  1423           end;
  1424 
  1425         val inj_map_strong = Lazy.lazy mk_inj_map_strong;
  1426 
  1427         val defs = mk_defs bnf_map_def bnf_set_defs bnf_rel_def;
  1428 
  1429         val facts = mk_facts bd_Card_order bd_Cinfinite bd_Cnotzero collect_set_map in_bd in_cong
  1430           in_mono in_rel inj_map inj_map_strong map_comp map_cong map_cong_simp map_id map_ident0
  1431           map_ident map_transfer rel_eq rel_flip set_map rel_cong rel_map rel_mono rel_mono_strong0
  1432           rel_mono_strong rel_Grp rel_conversep rel_OO;
  1433 
  1434         val wits = map2 mk_witness bnf_wits wit_thms;
  1435 
  1436         val bnf_rel =
  1437           Term.subst_atomic_types ((Ds ~~ deads) @ (As' ~~ alphas) @ (Bs' ~~ betas)) rel;
  1438 
  1439         val bnf = mk_bnf bnf_b Calpha live alphas betas dead deads bnf_map bnf_sets bnf_bd axioms
  1440           defs facts wits bnf_rel;
  1441       in
  1442         note_bnf_thms fact_policy qualify bnf_b bnf lthy
  1443       end;
  1444 
  1445     val one_step_defs =
  1446       no_reflexive (bnf_map_def :: bnf_bd_def :: bnf_set_defs @ bnf_wit_defs @ [bnf_rel_def]);
  1447   in
  1448     (key, goals, wit_goalss, after_qed, lthy, one_step_defs)
  1449   end;
  1450 
  1451 structure BNF_Interpretation = Interpretation
  1452 (
  1453   type T = bnf;
  1454   val eq: T * T -> bool = op = o pairself T_of_bnf;
  1455 );
  1456 
  1457 (* FIXME naming *)
  1458 fun with_repaired_path f bnf thy =
  1459   let
  1460     val qualifiers =
  1461       (case Binding.dest (name_of_bnf bnf) of
  1462         (* arbitrarily use "Fun" as prefix for "fun"*)
  1463         (_, [], @{type_name fun}) => [(Context.theory_name @{theory Fun}, false)]
  1464       | (_, qs, _) => qs)
  1465   in
  1466     thy
  1467     |> Sign.root_path
  1468     |> fold (uncurry (fn true => Sign.mandatory_path | false => Sign.add_path) o swap) qualifiers
  1469     |> (fn thy => f (morph_bnf (Morphism.transfer_morphism thy) bnf) thy)
  1470     |> Sign.restore_naming thy
  1471   end;
  1472 
  1473 fun bnf_interpretation f = BNF_Interpretation.interpretation (with_repaired_path f);
  1474 
  1475 fun register_bnf key bnf =
  1476   Local_Theory.declaration {syntax = false, pervasive = true}
  1477     (fn phi => Data.map (Symtab.update (key, morph_bnf phi bnf)))
  1478   #> Local_Theory.background_theory (BNF_Interpretation.data bnf);
  1479 
  1480 fun bnf_def const_policy fact_policy internal qualify tacs wit_tac Ds map_b rel_b set_bs =
  1481   (fn (_, goals, (triv_tac_opt, wit_goalss), after_qed, lthy, one_step_defs) =>
  1482   let
  1483     fun mk_wits_tac ctxt set_maps =
  1484       TRYALL Goal.conjunction_tac THEN
  1485       (case triv_tac_opt of
  1486         SOME tac => tac ctxt set_maps
  1487       | NONE => unfold_thms_tac ctxt one_step_defs THEN wit_tac ctxt);
  1488     val wit_goals = map Logic.mk_conjunction_balanced wit_goalss;
  1489     fun mk_wit_thms set_maps =
  1490       Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced wit_goals)
  1491         (fn {context = ctxt, prems = _} => mk_wits_tac ctxt set_maps)
  1492         |> Conjunction.elim_balanced (length wit_goals)
  1493         |> map2 (Conjunction.elim_balanced o length) wit_goalss
  1494         |> map (map (Thm.close_derivation o Thm.forall_elim_vars 0));
  1495   in
  1496     map2 (Thm.close_derivation oo Goal.prove_sorry lthy [] [])
  1497       goals (map (fn tac => fn {context = ctxt, prems = _} =>
  1498         unfold_thms_tac ctxt one_step_defs THEN tac ctxt) tacs)
  1499     |> (fn thms => after_qed mk_wit_thms (map single thms) lthy)
  1500   end) oo prepare_def const_policy fact_policy internal qualify (K I) (K I) Ds map_b rel_b set_bs;
  1501 
  1502 val bnf_cmd = (fn (key, goals, (triv_tac_opt, wit_goalss), after_qed, lthy, defs) =>
  1503   let
  1504     val wit_goals = map Logic.mk_conjunction_balanced wit_goalss;
  1505     fun mk_triv_wit_thms tac set_maps =
  1506       Goal.prove_sorry lthy [] [] (Logic.mk_conjunction_balanced wit_goals)
  1507         (fn {context = ctxt, prems = _} => TRYALL Goal.conjunction_tac THEN tac ctxt set_maps)
  1508         |> Conjunction.elim_balanced (length wit_goals)
  1509         |> map2 (Conjunction.elim_balanced o length) wit_goalss
  1510         |> map (map (Thm.close_derivation o Thm.forall_elim_vars 0));
  1511     val (mk_wit_thms, nontriv_wit_goals) =
  1512       (case triv_tac_opt of
  1513         NONE => (fn _ => [], map (map (rpair [])) wit_goalss)
  1514       | SOME tac => (mk_triv_wit_thms tac, []));
  1515   in
  1516     Proof.unfolding ([[(defs, [])]])
  1517       (Proof.theorem NONE (uncurry (register_bnf key) oo after_qed mk_wit_thms)
  1518         (map (single o rpair []) goals @ nontriv_wit_goals) lthy)
  1519   end) oo prepare_def Do_Inline (user_policy Note_Some) false I Syntax.read_typ Syntax.read_term
  1520     NONE Binding.empty Binding.empty [];
  1521 
  1522 fun print_bnfs ctxt =
  1523   let
  1524     fun pretty_set sets i = Pretty.block
  1525       [Pretty.str (mk_setN (i + 1) ^ ":"), Pretty.brk 1,
  1526           Pretty.quote (Syntax.pretty_term ctxt (nth sets i))];
  1527 
  1528     fun pretty_bnf (key, BNF {T, map, sets, bd, live, lives, dead, deads, ...}) =
  1529       Pretty.big_list
  1530         (Pretty.string_of (Pretty.block [Pretty.str key, Pretty.str ":", Pretty.brk 1,
  1531           Pretty.quote (Syntax.pretty_typ ctxt T)]))
  1532         ([Pretty.block [Pretty.str "live:", Pretty.brk 1, Pretty.str (string_of_int live),
  1533             Pretty.brk 3, Pretty.list "[" "]" (List.map (Syntax.pretty_typ ctxt) lives)],
  1534           Pretty.block [Pretty.str "dead:", Pretty.brk 1, Pretty.str (string_of_int dead),
  1535             Pretty.brk 3, Pretty.list "[" "]" (List.map (Syntax.pretty_typ ctxt) deads)],
  1536           Pretty.block [Pretty.str (mapN ^ ":"), Pretty.brk 1,
  1537             Pretty.quote (Syntax.pretty_term ctxt map)]] @
  1538           List.map (pretty_set sets) (0 upto length sets - 1) @
  1539           [Pretty.block [Pretty.str (bdN ^ ":"), Pretty.brk 1,
  1540             Pretty.quote (Syntax.pretty_term ctxt bd)]]);
  1541   in
  1542     Pretty.big_list "BNFs:" (map pretty_bnf (Symtab.dest (Data.get (Context.Proof ctxt))))
  1543     |> Pretty.writeln
  1544   end;
  1545 
  1546 val _ =
  1547   Outer_Syntax.improper_command @{command_spec "print_bnfs"}
  1548     "print all bounded natural functors"
  1549     (Scan.succeed (Toplevel.keep (print_bnfs o Toplevel.context_of)));
  1550 
  1551 val _ =
  1552   Outer_Syntax.local_theory_to_proof @{command_spec "bnf"}
  1553     "register a type as a bounded natural functor"
  1554     (parse_opt_binding_colon -- Parse.typ --|
  1555        (Parse.reserved "map" -- @{keyword ":"}) -- Parse.term --
  1556        (Scan.option ((Parse.reserved "sets" -- @{keyword ":"}) |--
  1557          Scan.repeat1 (Scan.unless (Parse.reserved "bd") Parse.term)) >> the_default []) --|
  1558        (Parse.reserved "bd" -- @{keyword ":"}) -- Parse.term --
  1559        (Scan.option ((Parse.reserved "wits" -- @{keyword ":"}) |--
  1560          Scan.repeat1 (Scan.unless (Parse.reserved "rel") Parse.term)) >> the_default []) --
  1561        Scan.option ((Parse.reserved "rel" -- @{keyword ":"}) |-- Parse.term)
  1562        >> bnf_cmd);
  1563 
  1564 val _ = Context.>> (Context.map_theory BNF_Interpretation.init);
  1565 
  1566 end;