src/HOL/BNF/Tools/bnf_def.ML
author blanchet
Wed Apr 24 18:49:52 2013 +0200 (2013-04-24)
changeset 51767 bbcdd8519253
parent 51766 f19a4d0ab1bf
child 51787 1267c28c7bdd
permissions -rw-r--r--
honor user-specified name for relator + generalize syntax
     1 (*  Title:      HOL/BNF/Tools/bnf_def.ML
     2     Author:     Dmitriy Traytel, TU Muenchen
     3     Author:     Jasmin Blanchette, TU Muenchen
     4     Copyright   2012
     5 
     6 Definition of bounded natural functors.
     7 *)
     8 
     9 signature BNF_DEF =
    10 sig
    11   type BNF
    12   type nonemptiness_witness = {I: int list, wit: term, prop: thm list}
    13 
    14   val bnf_of: Proof.context -> string -> BNF option
    15   val register_bnf: string -> (BNF * local_theory) -> (BNF * local_theory)
    16 
    17   val name_of_bnf: BNF -> binding
    18   val T_of_bnf: BNF -> typ
    19   val live_of_bnf: BNF -> int
    20   val lives_of_bnf: BNF -> typ list
    21   val dead_of_bnf: BNF -> int
    22   val deads_of_bnf: BNF -> typ list
    23   val nwits_of_bnf: BNF -> int
    24 
    25   val mapN: string
    26   val relN: string
    27   val setN: string
    28   val mk_setN: int -> string
    29   val srelN: string
    30 
    31   val map_of_bnf: BNF -> term
    32   val sets_of_bnf: BNF -> term list
    33   val rel_of_bnf: BNF -> term
    34 
    35   val mk_T_of_bnf: typ list -> typ list -> BNF -> typ
    36   val mk_bd_of_bnf: typ list -> typ list -> BNF -> term
    37   val mk_map_of_bnf: typ list -> typ list -> typ list -> BNF -> term
    38   val mk_rel_of_bnf: typ list -> typ list -> typ list -> BNF -> term
    39   val mk_sets_of_bnf: typ list list -> typ list list -> BNF -> term list
    40   val mk_srel_of_bnf: typ list -> typ list -> typ list -> BNF -> term
    41   val mk_wits_of_bnf: typ list list -> typ list list -> BNF -> (int list * term) list
    42 
    43   val bd_Card_order_of_bnf: BNF -> thm
    44   val bd_Cinfinite_of_bnf: BNF -> thm
    45   val bd_Cnotzero_of_bnf: BNF -> thm
    46   val bd_card_order_of_bnf: BNF -> thm
    47   val bd_cinfinite_of_bnf: BNF -> thm
    48   val collect_set_map_of_bnf: BNF -> thm
    49   val in_bd_of_bnf: BNF -> thm
    50   val in_cong_of_bnf: BNF -> thm
    51   val in_mono_of_bnf: BNF -> thm
    52   val in_srel_of_bnf: BNF -> thm
    53   val map_comp'_of_bnf: BNF -> thm
    54   val map_comp_of_bnf: BNF -> thm
    55   val map_cong0_of_bnf: BNF -> thm
    56   val map_cong_of_bnf: BNF -> thm
    57   val map_def_of_bnf: BNF -> thm
    58   val map_id'_of_bnf: BNF -> thm
    59   val map_id_of_bnf: BNF -> thm
    60   val map_wppull_of_bnf: BNF -> thm
    61   val map_wpull_of_bnf: BNF -> thm
    62   val rel_def_of_bnf: BNF -> thm
    63   val rel_eq_of_bnf: BNF -> thm
    64   val rel_flip_of_bnf: BNF -> thm
    65   val rel_srel_of_bnf: BNF -> thm
    66   val set_bd_of_bnf: BNF -> thm list
    67   val set_defs_of_bnf: BNF -> thm list
    68   val set_map'_of_bnf: BNF -> thm list
    69   val set_map_of_bnf: BNF -> thm list
    70   val srel_def_of_bnf: BNF -> thm
    71   val srel_Gr_of_bnf: BNF -> thm
    72   val srel_Id_of_bnf: BNF -> thm
    73   val srel_O_of_bnf: BNF -> thm
    74   val srel_O_Gr_of_bnf: BNF -> thm
    75   val srel_cong_of_bnf: BNF -> thm
    76   val srel_converse_of_bnf: BNF -> thm
    77   val srel_mono_of_bnf: BNF -> thm
    78   val wit_thms_of_bnf: BNF -> thm list
    79   val wit_thmss_of_bnf: BNF -> thm list list
    80 
    81   val mk_witness: int list * term -> thm list -> nonemptiness_witness
    82   val minimize_wits: (''a list * 'b) list -> (''a list * 'b) list
    83   val wits_of_bnf: BNF -> nonemptiness_witness list
    84 
    85   val zip_axioms: 'a -> 'a -> 'a -> 'a list -> 'a -> 'a -> 'a list -> 'a -> 'a -> 'a -> 'a list
    86 
    87   datatype const_policy = Dont_Inline | Hardly_Inline | Smart_Inline | Do_Inline
    88   datatype fact_policy = Dont_Note | Note_Some | Note_All
    89 
    90   val bnf_note_all: bool Config.T
    91   val user_policy: fact_policy -> Proof.context -> fact_policy
    92 
    93   val print_bnfs: Proof.context -> unit
    94   val bnf_def: const_policy -> (Proof.context -> fact_policy) -> (binding -> binding) ->
    95     ({prems: thm list, context: Proof.context} -> tactic) list ->
    96     ({prems: thm list, context: Proof.context} -> tactic) -> typ list option -> binding ->
    97     binding -> binding list ->
    98     ((((binding * term) * term list) * term) * term list) * term option ->
    99     local_theory -> BNF * local_theory
   100 end;
   101 
   102 structure BNF_Def : BNF_DEF =
   103 struct
   104 
   105 open BNF_Util
   106 open BNF_Tactics
   107 open BNF_Def_Tactics
   108 
   109 val fundef_cong_attrs = @{attributes [fundef_cong]};
   110 
   111 type axioms = {
   112   map_id: thm,
   113   map_comp: thm,
   114   map_cong0: thm,
   115   set_map: thm list,
   116   bd_card_order: thm,
   117   bd_cinfinite: thm,
   118   set_bd: thm list,
   119   in_bd: thm,
   120   map_wpull: thm,
   121   srel_O_Gr: thm
   122 };
   123 
   124 fun mk_axioms' (((((((((id, comp), cong), nat), c_o), cinf), set_bd), in_bd), wpull), srel) =
   125   {map_id = id, map_comp = comp, map_cong0 = cong, set_map = nat, bd_card_order = c_o,
   126    bd_cinfinite = cinf, set_bd = set_bd, in_bd = in_bd, map_wpull = wpull, srel_O_Gr = srel};
   127 
   128 fun dest_cons [] = raise Empty
   129   | dest_cons (x :: xs) = (x, xs);
   130 
   131 fun mk_axioms n thms = thms
   132   |> map the_single
   133   |> dest_cons
   134   ||>> dest_cons
   135   ||>> dest_cons
   136   ||>> chop n
   137   ||>> dest_cons
   138   ||>> dest_cons
   139   ||>> chop n
   140   ||>> dest_cons
   141   ||>> dest_cons
   142   ||> the_single
   143   |> mk_axioms';
   144 
   145 fun zip_axioms mid mcomp mcong snat bdco bdinf sbd inbd wpull srel =
   146   [mid, mcomp, mcong] @ snat @ [bdco, bdinf] @ sbd @ [inbd, wpull, srel];
   147 
   148 fun dest_axioms {map_id, map_comp, map_cong0, set_map, bd_card_order, bd_cinfinite, set_bd, in_bd,
   149   map_wpull, srel_O_Gr} =
   150   zip_axioms map_id map_comp map_cong0 set_map bd_card_order bd_cinfinite set_bd in_bd map_wpull
   151     srel_O_Gr;
   152 
   153 fun map_axioms f {map_id, map_comp, map_cong0, set_map, bd_card_order, bd_cinfinite, set_bd,
   154   in_bd, map_wpull, srel_O_Gr} =
   155   {map_id = f map_id,
   156     map_comp = f map_comp,
   157     map_cong0 = f map_cong0,
   158     set_map = map f set_map,
   159     bd_card_order = f bd_card_order,
   160     bd_cinfinite = f bd_cinfinite,
   161     set_bd = map f set_bd,
   162     in_bd = f in_bd,
   163     map_wpull = f map_wpull,
   164     srel_O_Gr = f srel_O_Gr};
   165 
   166 val morph_axioms = map_axioms o Morphism.thm;
   167 
   168 type defs = {
   169   map_def: thm,
   170   set_defs: thm list,
   171   rel_def: thm,
   172   srel_def: thm
   173 }
   174 
   175 fun mk_defs map sets rel srel = {map_def = map, set_defs = sets, rel_def = rel, srel_def = srel};
   176 
   177 fun map_defs f {map_def, set_defs, rel_def, srel_def} =
   178   {map_def = f map_def, set_defs = map f set_defs, rel_def = f rel_def, srel_def = f srel_def};
   179 
   180 val morph_defs = map_defs o Morphism.thm;
   181 
   182 type facts = {
   183   bd_Card_order: thm,
   184   bd_Cinfinite: thm,
   185   bd_Cnotzero: thm,
   186   collect_set_map: thm lazy,
   187   in_cong: thm lazy,
   188   in_mono: thm lazy,
   189   in_srel: thm lazy,
   190   map_comp': thm lazy,
   191   map_cong: thm lazy,
   192   map_id': thm lazy,
   193   map_wppull: thm lazy,
   194   rel_eq: thm lazy,
   195   rel_flip: thm lazy,
   196   rel_srel: thm lazy,
   197   set_map': thm lazy list,
   198   srel_cong: thm lazy,
   199   srel_mono: thm lazy,
   200   srel_Id: thm lazy,
   201   srel_Gr: thm lazy,
   202   srel_converse: thm lazy,
   203   srel_O: thm lazy
   204 };
   205 
   206 fun mk_facts bd_Card_order bd_Cinfinite bd_Cnotzero collect_set_map in_cong in_mono in_srel
   207     map_comp' map_cong map_id' map_wppull rel_eq rel_flip rel_srel set_map' srel_cong srel_mono
   208     srel_Id srel_Gr srel_converse srel_O = {
   209   bd_Card_order = bd_Card_order,
   210   bd_Cinfinite = bd_Cinfinite,
   211   bd_Cnotzero = bd_Cnotzero,
   212   collect_set_map = collect_set_map,
   213   in_cong = in_cong,
   214   in_mono = in_mono,
   215   in_srel = in_srel,
   216   map_comp' = map_comp',
   217   map_cong = map_cong,
   218   map_id' = map_id',
   219   map_wppull = map_wppull,
   220   rel_eq = rel_eq,
   221   rel_flip = rel_flip,
   222   rel_srel = rel_srel,
   223   set_map' = set_map',
   224   srel_cong = srel_cong,
   225   srel_mono = srel_mono,
   226   srel_Id = srel_Id,
   227   srel_Gr = srel_Gr,
   228   srel_converse = srel_converse,
   229   srel_O = srel_O};
   230 
   231 fun map_facts f {
   232   bd_Card_order,
   233   bd_Cinfinite,
   234   bd_Cnotzero,
   235   collect_set_map,
   236   in_cong,
   237   in_mono,
   238   in_srel,
   239   map_comp',
   240   map_cong,
   241   map_id',
   242   map_wppull,
   243   rel_eq,
   244   rel_flip,
   245   rel_srel,
   246   set_map',
   247   srel_cong,
   248   srel_mono,
   249   srel_Id,
   250   srel_Gr,
   251   srel_converse,
   252   srel_O} =
   253   {bd_Card_order = f bd_Card_order,
   254     bd_Cinfinite = f bd_Cinfinite,
   255     bd_Cnotzero = f bd_Cnotzero,
   256     collect_set_map = Lazy.map f collect_set_map,
   257     in_cong = Lazy.map f in_cong,
   258     in_mono = Lazy.map f in_mono,
   259     in_srel = Lazy.map f in_srel,
   260     map_comp' = Lazy.map f map_comp',
   261     map_cong = Lazy.map f map_cong,
   262     map_id' = Lazy.map f map_id',
   263     map_wppull = Lazy.map f map_wppull,
   264     rel_eq = Lazy.map f rel_eq,
   265     rel_flip = Lazy.map f rel_flip,
   266     rel_srel = Lazy.map f rel_srel,
   267     set_map' = map (Lazy.map f) set_map',
   268     srel_cong = Lazy.map f srel_cong,
   269     srel_mono = Lazy.map f srel_mono,
   270     srel_Id = Lazy.map f srel_Id,
   271     srel_Gr = Lazy.map f srel_Gr,
   272     srel_converse = Lazy.map f srel_converse,
   273     srel_O = Lazy.map f srel_O};
   274 
   275 val morph_facts = map_facts o Morphism.thm;
   276 
   277 type nonemptiness_witness = {
   278   I: int list,
   279   wit: term,
   280   prop: thm list
   281 };
   282 
   283 fun mk_witness (I, wit) prop = {I = I, wit = wit, prop = prop};
   284 fun map_witness f g {I, wit, prop} = {I = I, wit = f wit, prop = map g prop};
   285 fun morph_witness phi = map_witness (Morphism.term phi) (Morphism.thm phi);
   286 
   287 datatype BNF = BNF of {
   288   name: binding,
   289   T: typ,
   290   live: int,
   291   lives: typ list, (*source type variables of map, only for composition*)
   292   lives': typ list, (*target type variables of map, only for composition*)
   293   dead: int,
   294   deads: typ list, (*only for composition*)
   295   map: term,
   296   sets: term list,
   297   bd: term,
   298   axioms: axioms,
   299   defs: defs,
   300   facts: facts,
   301   nwits: int,
   302   wits: nonemptiness_witness list,
   303   rel: term,
   304   srel: term
   305 };
   306 
   307 (* getters *)
   308 
   309 fun rep_bnf (BNF bnf) = bnf;
   310 val name_of_bnf = #name o rep_bnf;
   311 val T_of_bnf = #T o rep_bnf;
   312 fun mk_T_of_bnf Ds Ts bnf =
   313   let val bnf_rep = rep_bnf bnf
   314   in Term.typ_subst_atomic ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts)) (#T bnf_rep) end;
   315 val live_of_bnf = #live o rep_bnf;
   316 val lives_of_bnf = #lives o rep_bnf;
   317 val dead_of_bnf = #dead o rep_bnf;
   318 val deads_of_bnf = #deads o rep_bnf;
   319 val axioms_of_bnf = #axioms o rep_bnf;
   320 val facts_of_bnf = #facts o rep_bnf;
   321 val nwits_of_bnf = #nwits o rep_bnf;
   322 val wits_of_bnf = #wits o rep_bnf;
   323 
   324 (*terms*)
   325 val map_of_bnf = #map o rep_bnf;
   326 val sets_of_bnf = #sets o rep_bnf;
   327 fun mk_map_of_bnf Ds Ts Us bnf =
   328   let val bnf_rep = rep_bnf bnf;
   329   in
   330     Term.subst_atomic_types
   331       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts) @ (#lives' bnf_rep ~~ Us)) (#map bnf_rep)
   332   end;
   333 fun mk_sets_of_bnf Dss Tss bnf =
   334   let val bnf_rep = rep_bnf bnf;
   335   in
   336     map2 (fn (Ds, Ts) => Term.subst_atomic_types
   337       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts))) (Dss ~~ Tss) (#sets bnf_rep)
   338   end;
   339 val bd_of_bnf = #bd o rep_bnf;
   340 fun mk_bd_of_bnf Ds Ts bnf =
   341   let val bnf_rep = rep_bnf bnf;
   342   in Term.subst_atomic_types ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts)) (#bd bnf_rep) end;
   343 fun mk_wits_of_bnf Dss Tss bnf =
   344   let
   345     val bnf_rep = rep_bnf bnf;
   346     val wits = map (fn x => (#I x, #wit x)) (#wits bnf_rep);
   347   in
   348     map2 (fn (Ds, Ts) => apsnd (Term.subst_atomic_types
   349       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts)))) (Dss ~~ Tss) wits
   350   end;
   351 val rel_of_bnf = #rel o rep_bnf;
   352 fun mk_rel_of_bnf Ds Ts Us bnf =
   353   let val bnf_rep = rep_bnf bnf;
   354   in
   355     Term.subst_atomic_types
   356       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts) @ (#lives' bnf_rep ~~ Us)) (#rel bnf_rep)
   357   end;
   358 val srel_of_bnf = #srel o rep_bnf;
   359 fun mk_srel_of_bnf Ds Ts Us bnf =
   360   let val bnf_rep = rep_bnf bnf;
   361   in
   362     Term.subst_atomic_types
   363       ((#deads bnf_rep ~~ Ds) @ (#lives bnf_rep ~~ Ts) @ (#lives' bnf_rep ~~ Us)) (#srel bnf_rep)
   364   end;
   365 
   366 (*thms*)
   367 val bd_card_order_of_bnf = #bd_card_order o #axioms o rep_bnf;
   368 val bd_cinfinite_of_bnf = #bd_cinfinite o #axioms o rep_bnf;
   369 val bd_Card_order_of_bnf = #bd_Card_order o #facts o rep_bnf;
   370 val bd_Cinfinite_of_bnf = #bd_Cinfinite o #facts o rep_bnf;
   371 val bd_Cnotzero_of_bnf = #bd_Cnotzero o #facts o rep_bnf;
   372 val collect_set_map_of_bnf = Lazy.force o #collect_set_map o #facts o rep_bnf;
   373 val in_bd_of_bnf = #in_bd o #axioms o rep_bnf;
   374 val in_cong_of_bnf = Lazy.force o #in_cong o #facts o rep_bnf;
   375 val in_mono_of_bnf = Lazy.force o #in_mono o #facts o rep_bnf;
   376 val in_srel_of_bnf = Lazy.force o #in_srel o #facts o rep_bnf;
   377 val map_def_of_bnf = #map_def o #defs o rep_bnf;
   378 val map_id_of_bnf = #map_id o #axioms o rep_bnf;
   379 val map_id'_of_bnf = Lazy.force o #map_id' o #facts o rep_bnf;
   380 val map_comp_of_bnf = #map_comp o #axioms o rep_bnf;
   381 val map_comp'_of_bnf = Lazy.force o #map_comp' o #facts o rep_bnf;
   382 val map_cong0_of_bnf = #map_cong0 o #axioms o rep_bnf;
   383 val map_cong_of_bnf = Lazy.force o #map_cong o #facts o rep_bnf;
   384 val map_wppull_of_bnf = Lazy.force o #map_wppull o #facts o rep_bnf;
   385 val map_wpull_of_bnf = #map_wpull o #axioms o rep_bnf;
   386 val rel_def_of_bnf = #rel_def o #defs o rep_bnf;
   387 val rel_eq_of_bnf = Lazy.force o #rel_eq o #facts o rep_bnf;
   388 val rel_flip_of_bnf = Lazy.force o #rel_flip o #facts o rep_bnf;
   389 val rel_srel_of_bnf = Lazy.force o #rel_srel o #facts o rep_bnf;
   390 val set_bd_of_bnf = #set_bd o #axioms o rep_bnf;
   391 val set_defs_of_bnf = #set_defs o #defs o rep_bnf;
   392 val set_map_of_bnf = #set_map o #axioms o rep_bnf;
   393 val set_map'_of_bnf = map Lazy.force o #set_map' o #facts o rep_bnf;
   394 val srel_cong_of_bnf = Lazy.force o #srel_cong o #facts o rep_bnf;
   395 val srel_mono_of_bnf = Lazy.force o #srel_mono o #facts o rep_bnf;
   396 val srel_def_of_bnf = #srel_def o #defs o rep_bnf;
   397 val srel_Id_of_bnf = Lazy.force o #srel_Id o #facts o rep_bnf;
   398 val srel_Gr_of_bnf = Lazy.force o #srel_Gr o #facts o rep_bnf;
   399 val srel_converse_of_bnf = Lazy.force o #srel_converse o #facts o rep_bnf;
   400 val srel_O_of_bnf = Lazy.force o #srel_O o #facts o rep_bnf;
   401 val srel_O_Gr_of_bnf = #srel_O_Gr o #axioms o rep_bnf;
   402 val wit_thms_of_bnf = maps #prop o wits_of_bnf;
   403 val wit_thmss_of_bnf = map #prop o wits_of_bnf;
   404 
   405 fun mk_bnf name T live lives lives' dead deads map sets bd axioms defs facts wits rel srel =
   406   BNF {name = name, T = T,
   407        live = live, lives = lives, lives' = lives', dead = dead, deads = deads,
   408        map = map, sets = sets, bd = bd,
   409        axioms = axioms, defs = defs, facts = facts,
   410        nwits = length wits, wits = wits, rel = rel, srel = srel};
   411 
   412 fun morph_bnf phi (BNF {name = name, T = T, live = live, lives = lives, lives' = lives',
   413   dead = dead, deads = deads, map = map, sets = sets, bd = bd,
   414   axioms = axioms, defs = defs, facts = facts,
   415   nwits = nwits, wits = wits, rel = rel, srel = srel}) =
   416   BNF {name = Morphism.binding phi name, T = Morphism.typ phi T,
   417     live = live, lives = List.map (Morphism.typ phi) lives,
   418     lives' = List.map (Morphism.typ phi) lives',
   419     dead = dead, deads = List.map (Morphism.typ phi) deads,
   420     map = Morphism.term phi map, sets = List.map (Morphism.term phi) sets,
   421     bd = Morphism.term phi bd,
   422     axioms = morph_axioms phi axioms,
   423     defs = morph_defs phi defs,
   424     facts = morph_facts phi facts,
   425     nwits = nwits,
   426     wits = List.map (morph_witness phi) wits,
   427     rel = Morphism.term phi rel, srel = Morphism.term phi srel};
   428 
   429 fun eq_bnf (BNF {T = T1, live = live1, dead = dead1, ...},
   430   BNF {T = T2, live = live2, dead = dead2, ...}) =
   431   Type.could_unify (T1, T2) andalso live1 = live2 andalso dead1 = dead2;
   432 
   433 structure Data = Generic_Data
   434 (
   435   type T = BNF Symtab.table;
   436   val empty = Symtab.empty;
   437   val extend = I;
   438   val merge = Symtab.merge eq_bnf;
   439 );
   440 
   441 val bnf_of = Symtab.lookup o Data.get o Context.Proof;
   442 
   443 
   444 
   445 (* Utilities *)
   446 
   447 fun normalize_set insts instA set =
   448   let
   449     val (T, T') = dest_funT (fastype_of set);
   450     val A = fst (Term.dest_TVar (HOLogic.dest_setT T'));
   451     val params = Term.add_tvar_namesT T [];
   452   in Term.subst_TVars ((A :: params) ~~ (instA :: insts)) set end;
   453 
   454 fun normalize_rel ctxt instTs instA instB rel =
   455   let
   456     val thy = Proof_Context.theory_of ctxt;
   457     val tyenv =
   458       Sign.typ_match thy (fastype_of rel, Library.foldr (op -->) (instTs, mk_pred2T instA instB))
   459         Vartab.empty;
   460   in Envir.subst_term (tyenv, Vartab.empty) rel end
   461   handle Type.TYPE_MATCH => error "Bad predicator";
   462 
   463 fun normalize_srel ctxt instTs instA instB srel =
   464   let
   465     val thy = Proof_Context.theory_of ctxt;
   466     val tyenv =
   467       Sign.typ_match thy (fastype_of srel, Library.foldr (op -->) (instTs, mk_relT (instA, instB)))
   468         Vartab.empty;
   469   in Envir.subst_term (tyenv, Vartab.empty) srel end
   470   handle Type.TYPE_MATCH => error "Bad relator";
   471 
   472 fun normalize_wit insts CA As wit =
   473   let
   474     fun strip_param (Ts, T as Type (@{type_name fun}, [T1, T2])) =
   475         if Type.raw_instance (CA, T) then (Ts, T) else strip_param (T1 :: Ts, T2)
   476       | strip_param x = x;
   477     val (Ts, T) = strip_param ([], fastype_of wit);
   478     val subst = Term.add_tvar_namesT T [] ~~ insts;
   479     fun find y = find_index (fn x => x = y) As;
   480   in
   481     (map (find o Term.typ_subst_TVars subst) (rev Ts), Term.subst_TVars subst wit)
   482   end;
   483 
   484 fun minimize_wits wits =
   485  let
   486    fun minimize done [] = done
   487      | minimize done ((I, wit) :: todo) =
   488        if exists (fn (J, _) => subset (op =) (J, I)) (done @ todo)
   489        then minimize done todo
   490        else minimize ((I, wit) :: done) todo;
   491  in minimize [] wits end;
   492 
   493 
   494 
   495 (* Names *)
   496 
   497 val mapN = "map";
   498 val setN = "set";
   499 fun mk_setN i = setN ^ nonzero_string_of_int i;
   500 val bdN = "bd";
   501 val witN = "wit";
   502 fun mk_witN i = witN ^ nonzero_string_of_int i;
   503 val relN = "rel";
   504 val srelN = "srel";
   505 
   506 val bd_card_orderN = "bd_card_order";
   507 val bd_cinfiniteN = "bd_cinfinite";
   508 val bd_Card_orderN = "bd_Card_order";
   509 val bd_CinfiniteN = "bd_Cinfinite";
   510 val bd_CnotzeroN = "bd_Cnotzero";
   511 val collect_set_mapN = "collect_set_map";
   512 val in_bdN = "in_bd";
   513 val in_monoN = "in_mono";
   514 val in_srelN = "in_srel";
   515 val map_idN = "map_id";
   516 val map_id'N = "map_id'";
   517 val map_compN = "map_comp";
   518 val map_comp'N = "map_comp'";
   519 val map_cong0N = "map_cong0";
   520 val map_congN = "map_cong";
   521 val map_wpullN = "map_wpull";
   522 val rel_eqN = "rel_eq";
   523 val rel_flipN = "rel_flip";
   524 val rel_srelN = "rel_srel";
   525 val set_mapN = "set_map";
   526 val set_map'N = "set_map'";
   527 val set_bdN = "set_bd";
   528 val srel_IdN = "srel_Id";
   529 val srel_GrN = "srel_Gr";
   530 val srel_converseN = "srel_converse";
   531 val srel_monoN = "srel_mono"
   532 val srel_ON = "srel_comp";
   533 val srel_O_GrN = "srel_comp_Gr";
   534 
   535 datatype const_policy = Dont_Inline | Hardly_Inline | Smart_Inline | Do_Inline;
   536 
   537 datatype fact_policy = Dont_Note | Note_Some | Note_All;
   538 
   539 val bnf_note_all = Attrib.setup_config_bool @{binding bnf_note_all} (K false);
   540 
   541 fun user_policy policy ctxt = if Config.get ctxt bnf_note_all then Note_All else policy;
   542 
   543 val smart_max_inline_size = 25; (*FUDGE*)
   544 
   545 
   546 (* Define new BNFs *)
   547 
   548 fun prepare_def const_policy mk_fact_policy qualify prep_term Ds_opt map_b rel_b set_bs
   549   (((((raw_b, raw_map), raw_sets), raw_bd_Abs), raw_wits), raw_rel_opt) no_defs_lthy =
   550   let
   551     val fact_policy = mk_fact_policy no_defs_lthy;
   552     val b = qualify raw_b;
   553     val live = length raw_sets;
   554     val nwits = length raw_wits;
   555 
   556     val map_rhs = prep_term no_defs_lthy raw_map;
   557     val set_rhss = map (prep_term no_defs_lthy) raw_sets;
   558     val (bd_rhsT, bd_rhs) = (case prep_term no_defs_lthy raw_bd_Abs of
   559       Abs (_, T, t) => (T, t)
   560     | _ => error "Bad bound constant");
   561     val wit_rhss = map (prep_term no_defs_lthy) raw_wits;
   562 
   563     fun err T =
   564       error ("Trying to register the type " ^ quote (Syntax.string_of_typ no_defs_lthy T) ^
   565         " as unnamed BNF");
   566 
   567     val (b, key) =
   568       if Binding.eq_name (b, Binding.empty) then
   569         (case bd_rhsT of
   570           Type (C, Ts) => if forall (is_some o try dest_TFree) Ts
   571             then (Binding.qualified_name C, C) else err bd_rhsT
   572         | T => err T)
   573       else (b, Local_Theory.full_name no_defs_lthy b);
   574 
   575     fun maybe_define user_specified (b, rhs) lthy =
   576       let
   577         val inline =
   578           (user_specified orelse fact_policy = Dont_Note) andalso
   579           (case const_policy of
   580             Dont_Inline => false
   581           | Hardly_Inline => Term.is_Free rhs orelse Term.is_Const rhs
   582           | Smart_Inline => Term.size_of_term rhs <= smart_max_inline_size
   583           | Do_Inline => true)
   584       in
   585         if inline then
   586           ((rhs, Drule.reflexive_thm), lthy)
   587         else
   588           let val b = b () in
   589             apfst (apsnd snd) (Local_Theory.define ((b, NoSyn), ((Thm.def_binding b, []), rhs))
   590               lthy)
   591           end
   592       end;
   593 
   594     fun maybe_restore lthy_old lthy =
   595       lthy |> not (pointer_eq (lthy_old, lthy)) ? Local_Theory.restore;
   596 
   597     val map_bind_def =
   598       (fn () => if Binding.is_empty map_b then Binding.suffix_name ("_" ^ mapN) b else map_b,
   599        map_rhs);
   600     val set_binds_defs =
   601       let
   602         fun set_name i get_b =
   603           (case try (nth set_bs) (i - 1) of
   604             SOME b => if Binding.is_empty b then get_b else K b
   605           | NONE => get_b);
   606         val bs =
   607           if live = 1 then
   608             [set_name 1 (fn () => Binding.suffix_name ("_" ^ setN) b)]
   609           else
   610             map (fn i => set_name i (fn () => Binding.suffix_name ("_" ^ mk_setN i) b))
   611               (1 upto live);
   612       in bs ~~ set_rhss end;
   613     val bd_bind_def = (fn () => Binding.suffix_name ("_" ^ bdN) b, bd_rhs);
   614     val wit_binds_defs =
   615       let
   616         val bs = if nwits = 1 then [fn () => Binding.suffix_name ("_" ^ witN) b]
   617           else map (fn i => fn () => Binding.suffix_name ("_" ^ mk_witN i) b) (1 upto nwits);
   618       in bs ~~ wit_rhss end;
   619 
   620     val (((((bnf_map_term, raw_map_def),
   621       (bnf_set_terms, raw_set_defs)),
   622       (bnf_bd_term, raw_bd_def)),
   623       (bnf_wit_terms, raw_wit_defs)), (lthy, lthy_old)) =
   624         no_defs_lthy
   625         |> maybe_define true map_bind_def
   626         ||>> apfst split_list o fold_map (maybe_define true) set_binds_defs
   627         ||>> maybe_define true bd_bind_def
   628         ||>> apfst split_list o fold_map (maybe_define true) wit_binds_defs
   629         ||> `(maybe_restore no_defs_lthy);
   630 
   631     val phi = Proof_Context.export_morphism lthy_old lthy;
   632 
   633     val bnf_map_def = Morphism.thm phi raw_map_def;
   634     val bnf_set_defs = map (Morphism.thm phi) raw_set_defs;
   635     val bnf_bd_def = Morphism.thm phi raw_bd_def;
   636     val bnf_wit_defs = map (Morphism.thm phi) raw_wit_defs;
   637 
   638     val bnf_map = Morphism.term phi bnf_map_term;
   639 
   640     (*TODO: handle errors*)
   641     (*simple shape analysis of a map function*)
   642     val ((alphas, betas), (CA, _)) =
   643       fastype_of bnf_map
   644       |> strip_typeN live
   645       |>> map_split dest_funT
   646       ||> dest_funT
   647       handle TYPE _ => error "Bad map function";
   648 
   649     val CA_params = map TVar (Term.add_tvarsT CA []);
   650 
   651     val bnf_sets = map2 (normalize_set CA_params) alphas (map (Morphism.term phi) bnf_set_terms);
   652     val bdT = Morphism.typ phi bd_rhsT;
   653     val bnf_bd =
   654       Term.subst_TVars (Term.add_tvar_namesT bdT [] ~~ CA_params) (Morphism.term phi bnf_bd_term);
   655     val bnf_wits = map (normalize_wit CA_params CA alphas o Morphism.term phi) bnf_wit_terms;
   656 
   657     (*TODO: assert Ds = (TVars of bnf_map) \ (alphas @ betas) as sets*)
   658     val deads = (case Ds_opt of
   659       NONE => subtract (op =) (alphas @ betas) (map TVar (Term.add_tvars bnf_map []))
   660     | SOME Ds => map (Morphism.typ phi) Ds);
   661     val dead = length deads;
   662 
   663     (*TODO: further checks of type of bnf_map*)
   664     (*TODO: check types of bnf_sets*)
   665     (*TODO: check type of bnf_bd*)
   666     (*TODO: check type of bnf_rel*)
   667 
   668     val ((((((((((As', Bs'), Cs), Ds), B1Ts), B2Ts), domTs), ranTs), ranTs'), ranTs''),
   669       (Ts, T)) = lthy
   670       |> mk_TFrees live
   671       ||>> mk_TFrees live
   672       ||>> mk_TFrees live
   673       ||>> mk_TFrees dead
   674       ||>> mk_TFrees live
   675       ||>> mk_TFrees live
   676       ||>> mk_TFrees live
   677       ||>> mk_TFrees live
   678       ||>> mk_TFrees live
   679       ||>> mk_TFrees live
   680       ||> fst o mk_TFrees 1
   681       ||> the_single
   682       ||> `(replicate live);
   683 
   684     fun mk_bnf_map As' Bs' =
   685       Term.subst_atomic_types ((deads ~~ Ds) @ (alphas ~~ As') @ (betas ~~ Bs')) bnf_map;
   686     fun mk_bnf_t As' = Term.subst_atomic_types ((deads ~~ Ds) @ (alphas ~~ As'));
   687     fun mk_bnf_T As' = Term.typ_subst_atomic ((deads ~~ Ds) @ (alphas ~~ As'));
   688 
   689     val (setRTs, RTs) = map_split (`HOLogic.mk_setT o HOLogic.mk_prodT) (As' ~~ Bs');
   690     val setRTsAsCs = map (HOLogic.mk_setT o HOLogic.mk_prodT) (As' ~~ Cs);
   691     val setRTsBsCs = map (HOLogic.mk_setT o HOLogic.mk_prodT) (Bs' ~~ Cs);
   692     val setRT's = map (HOLogic.mk_setT o HOLogic.mk_prodT) (Bs' ~~ As');
   693     val self_setRTs = map (HOLogic.mk_setT o HOLogic.mk_prodT) (As' ~~ As');
   694     val QTs = map2 mk_pred2T As' Bs';
   695 
   696     val CA' = mk_bnf_T As' CA;
   697     val CB' = mk_bnf_T Bs' CA;
   698     val CC' = mk_bnf_T Cs CA;
   699     val CRs' = mk_bnf_T RTs CA;
   700     val CA'CB' = HOLogic.mk_prodT (CA', CB');
   701 
   702     val bnf_map_AsAs = mk_bnf_map As' As';
   703     val bnf_map_AsBs = mk_bnf_map As' Bs';
   704     val bnf_map_AsCs = mk_bnf_map As' Cs;
   705     val bnf_map_BsCs = mk_bnf_map Bs' Cs;
   706     val bnf_sets_As = map (mk_bnf_t As') bnf_sets;
   707     val bnf_sets_Bs = map (mk_bnf_t Bs') bnf_sets;
   708     val bnf_bd_As = mk_bnf_t As' bnf_bd;
   709     val bnf_wit_As = map (apsnd (mk_bnf_t As')) bnf_wits;
   710 
   711     val pre_names_lthy = lthy;
   712     val ((((((((((((((((((((((((fs, gs), hs), p), (x, x')), (y, y')), (z, z')), zs), As),
   713       As_copy), Xs), B1s), B2s), f1s), f2s), e1s), e2s), p1s), p2s), bs), (Rs, Rs')), Rs_copy), Ss),
   714       (Qs, Qs')), names_lthy) = pre_names_lthy
   715       |> mk_Frees "f" (map2 (curry (op -->)) As' Bs')
   716       ||>> mk_Frees "g" (map2 (curry (op -->)) Bs' Cs)
   717       ||>> mk_Frees "h" (map2 (curry (op -->)) As' Ts)
   718       ||>> yield_singleton (mk_Frees "p") CA'CB'
   719       ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "x") CA'
   720       ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "y") CB'
   721       ||>> yield_singleton (apfst (op ~~) oo mk_Frees' "z") CRs'
   722       ||>> mk_Frees "z" As'
   723       ||>> mk_Frees "A" (map HOLogic.mk_setT As')
   724       ||>> mk_Frees "A" (map HOLogic.mk_setT As')
   725       ||>> mk_Frees "A" (map HOLogic.mk_setT domTs)
   726       ||>> mk_Frees "B1" (map HOLogic.mk_setT B1Ts)
   727       ||>> mk_Frees "B2" (map HOLogic.mk_setT B2Ts)
   728       ||>> mk_Frees "f1" (map2 (curry (op -->)) B1Ts ranTs)
   729       ||>> mk_Frees "f2" (map2 (curry (op -->)) B2Ts ranTs)
   730       ||>> mk_Frees "e1" (map2 (curry (op -->)) B1Ts ranTs')
   731       ||>> mk_Frees "e2" (map2 (curry (op -->)) B2Ts ranTs'')
   732       ||>> mk_Frees "p1" (map2 (curry (op -->)) domTs B1Ts)
   733       ||>> mk_Frees "p2" (map2 (curry (op -->)) domTs B2Ts)
   734       ||>> mk_Frees "b" As'
   735       ||>> mk_Frees' "r" setRTs
   736       ||>> mk_Frees "r" setRTs
   737       ||>> mk_Frees "s" setRTsBsCs
   738       ||>> mk_Frees' "P" QTs;
   739 
   740     val fs_copy = map2 (retype_free o fastype_of) fs gs;
   741     val x_copy = retype_free CA' y;
   742 
   743     (*Gr (in R1 .. Rn) (map fst .. fst)^-1 O Gr (in R1 .. Rn) (map snd .. snd)*)
   744     val O_Gr =
   745       let
   746         val map1 = Term.list_comb (mk_bnf_map RTs As', map fst_const RTs);
   747         val map2 = Term.list_comb (mk_bnf_map RTs Bs', map snd_const RTs);
   748         val bnf_in = mk_in (map Free Rs') (map (mk_bnf_t RTs) bnf_sets) CRs';
   749       in
   750         mk_rel_comp (mk_converse (mk_Gr bnf_in map1), mk_Gr bnf_in map2)
   751       end;
   752 
   753     fun mk_predicate_of_set x_name y_name t =
   754       let
   755         val (T, U) = HOLogic.dest_prodT (HOLogic.dest_setT (fastype_of t));
   756         val x = Free (x_name, T);
   757         val y = Free (y_name, U);
   758       in fold_rev Term.lambda [x, y] (HOLogic.mk_mem (HOLogic.mk_prod (x, y), t)) end;
   759 
   760     val sQs =
   761       map3 (fn Q => fn T => fn U =>
   762           HOLogic.Collect_const (HOLogic.mk_prodT (T, U)) $ HOLogic.mk_split Q) Qs As' Bs';
   763 
   764     val rel_rhs = (case raw_rel_opt of
   765         NONE =>
   766         fold_rev absfree Qs' (mk_predicate_of_set (fst x') (fst y')
   767           (Term.list_comb (fold_rev Term.absfree Rs' O_Gr, sQs)))
   768       | SOME raw_rel => prep_term no_defs_lthy raw_rel);
   769 
   770     val rel_bind_def =
   771       (fn () => if Binding.is_empty rel_b then Binding.suffix_name ("_" ^ relN) b else rel_b,
   772        rel_rhs);
   773 
   774     val ((bnf_rel_term, raw_rel_def), (lthy, lthy_old)) =
   775       lthy
   776       |> maybe_define (is_some raw_rel_opt) rel_bind_def
   777       ||> `(maybe_restore lthy);
   778 
   779     val phi = Proof_Context.export_morphism lthy_old lthy;
   780     val bnf_rel_def = Morphism.thm phi raw_rel_def;
   781     val bnf_rel = Morphism.term phi bnf_rel_term;
   782 
   783     fun mk_bnf_rel QTs CA' CB' = normalize_rel lthy QTs CA' CB' bnf_rel;
   784 
   785     val rel = mk_bnf_rel QTs CA' CB';
   786 
   787     val srel_rhs =
   788       fold_rev Term.absfree Rs' (HOLogic.Collect_const CA'CB' $
   789         Term.lambda p (Term.list_comb (rel, map (mk_predicate_of_set (fst x') (fst y')) Rs) $
   790         HOLogic.mk_fst p $ HOLogic.mk_snd p));
   791 
   792     val srel_bind_def = (fn () => Binding.suffix_name ("_" ^ srelN) b, srel_rhs);
   793 
   794     val ((bnf_srel_term, raw_srel_def), (lthy, lthy_old)) =
   795       lthy
   796       |> maybe_define false srel_bind_def
   797       ||> `(maybe_restore lthy);
   798 
   799     val phi = Proof_Context.export_morphism lthy_old lthy;
   800     val bnf_srel_def = Morphism.thm phi raw_srel_def;
   801     val bnf_srel = Morphism.term phi bnf_srel_term;
   802 
   803     fun mk_bnf_srel setRTs CA' CB' = normalize_srel lthy setRTs CA' CB' bnf_srel;
   804 
   805     val srel = mk_bnf_srel setRTs CA' CB';
   806 
   807     val _ = case no_reflexive (raw_map_def :: raw_set_defs @ [raw_bd_def] @
   808         raw_wit_defs @ [raw_rel_def, raw_srel_def]) of
   809         [] => ()
   810       | defs => Proof_Display.print_consts true lthy_old (K false)
   811           (map (dest_Free o fst o Logic.dest_equals o prop_of) defs);
   812 
   813     val map_id_goal =
   814       let val bnf_map_app_id = Term.list_comb (bnf_map_AsAs, map HOLogic.id_const As') in
   815         mk_Trueprop_eq (bnf_map_app_id, HOLogic.id_const CA')
   816       end;
   817 
   818     val map_comp_goal =
   819       let
   820         val bnf_map_app_comp = Term.list_comb (bnf_map_AsCs, map2 (curry HOLogic.mk_comp) gs fs);
   821         val comp_bnf_map_app = HOLogic.mk_comp
   822           (Term.list_comb (bnf_map_BsCs, gs), Term.list_comb (bnf_map_AsBs, fs));
   823       in
   824         fold_rev Logic.all (fs @ gs) (mk_Trueprop_eq (bnf_map_app_comp, comp_bnf_map_app))
   825       end;
   826 
   827     fun mk_map_cong_prem x z set f f_copy =
   828       Logic.all z (Logic.mk_implies
   829         (HOLogic.mk_Trueprop (HOLogic.mk_mem (z, set $ x)),
   830         mk_Trueprop_eq (f $ z, f_copy $ z)));
   831 
   832     val map_cong0_goal =
   833       let
   834         val prems = map4 (mk_map_cong_prem x) zs bnf_sets_As fs fs_copy;
   835         val eq = mk_Trueprop_eq (Term.list_comb (bnf_map_AsBs, fs) $ x,
   836           Term.list_comb (bnf_map_AsBs, fs_copy) $ x);
   837       in
   838         fold_rev Logic.all (x :: fs @ fs_copy) (Logic.list_implies (prems, eq))
   839       end;
   840 
   841     val set_maps_goal =
   842       let
   843         fun mk_goal setA setB f =
   844           let
   845             val set_comp_map =
   846               HOLogic.mk_comp (setB, Term.list_comb (bnf_map_AsBs, fs));
   847             val image_comp_set = HOLogic.mk_comp (mk_image f, setA);
   848           in
   849             fold_rev Logic.all fs (mk_Trueprop_eq (set_comp_map, image_comp_set))
   850           end;
   851       in
   852         map3 mk_goal bnf_sets_As bnf_sets_Bs fs
   853       end;
   854 
   855     val card_order_bd_goal = HOLogic.mk_Trueprop (mk_card_order bnf_bd_As);
   856 
   857     val cinfinite_bd_goal = HOLogic.mk_Trueprop (mk_cinfinite bnf_bd_As);
   858 
   859     val set_bds_goal =
   860       let
   861         fun mk_goal set =
   862           Logic.all x (HOLogic.mk_Trueprop (mk_ordLeq (mk_card_of (set $ x)) bnf_bd_As));
   863       in
   864         map mk_goal bnf_sets_As
   865       end;
   866 
   867     val in_bd_goal =
   868       let
   869         val bd = mk_cexp
   870           (if live = 0 then ctwo
   871             else mk_csum (Library.foldr1 (uncurry mk_csum) (map mk_card_of As)) ctwo)
   872           bnf_bd_As;
   873       in
   874         fold_rev Logic.all As
   875           (HOLogic.mk_Trueprop (mk_ordLeq (mk_card_of (mk_in As bnf_sets_As CA')) bd))
   876       end;
   877 
   878     val map_wpull_goal =
   879       let
   880         val prems = map HOLogic.mk_Trueprop
   881           (map8 mk_wpull Xs B1s B2s f1s f2s (replicate live NONE) p1s p2s);
   882         val CX = mk_bnf_T domTs CA;
   883         val CB1 = mk_bnf_T B1Ts CA;
   884         val CB2 = mk_bnf_T B2Ts CA;
   885         val bnf_sets_CX = map2 (normalize_set (map (mk_bnf_T domTs) CA_params)) domTs bnf_sets;
   886         val bnf_sets_CB1 = map2 (normalize_set (map (mk_bnf_T B1Ts) CA_params)) B1Ts bnf_sets;
   887         val bnf_sets_CB2 = map2 (normalize_set (map (mk_bnf_T B2Ts) CA_params)) B2Ts bnf_sets;
   888         val bnf_map_app_f1 = Term.list_comb (mk_bnf_map B1Ts ranTs, f1s);
   889         val bnf_map_app_f2 = Term.list_comb (mk_bnf_map B2Ts ranTs, f2s);
   890         val bnf_map_app_p1 = Term.list_comb (mk_bnf_map domTs B1Ts, p1s);
   891         val bnf_map_app_p2 = Term.list_comb (mk_bnf_map domTs B2Ts, p2s);
   892 
   893         val map_wpull = mk_wpull (mk_in Xs bnf_sets_CX CX)
   894           (mk_in B1s bnf_sets_CB1 CB1) (mk_in B2s bnf_sets_CB2 CB2)
   895           bnf_map_app_f1 bnf_map_app_f2 NONE bnf_map_app_p1 bnf_map_app_p2;
   896       in
   897         fold_rev Logic.all (Xs @ B1s @ B2s @ f1s @ f2s @ p1s @ p2s)
   898           (Logic.list_implies (prems, HOLogic.mk_Trueprop map_wpull))
   899       end;
   900 
   901     val srel_O_Gr_goal = fold_rev Logic.all Rs (mk_Trueprop_eq (Term.list_comb (srel, Rs), O_Gr));
   902 
   903     val goals = zip_axioms map_id_goal map_comp_goal map_cong0_goal set_maps_goal card_order_bd_goal
   904       cinfinite_bd_goal set_bds_goal in_bd_goal map_wpull_goal srel_O_Gr_goal;
   905 
   906     fun mk_wit_goals (I, wit) =
   907       let
   908         val xs = map (nth bs) I;
   909         fun wit_goal i =
   910           let
   911             val z = nth zs i;
   912             val set_wit = nth bnf_sets_As i $ Term.list_comb (wit, xs);
   913             val concl = HOLogic.mk_Trueprop
   914               (if member (op =) I i then HOLogic.mk_eq (z, nth bs i)
   915               else @{term False});
   916           in
   917             fold_rev Logic.all (z :: xs)
   918               (Logic.mk_implies (HOLogic.mk_Trueprop (HOLogic.mk_mem (z, set_wit)), concl))
   919           end;
   920       in
   921         map wit_goal (0 upto live - 1)
   922       end;
   923 
   924     val wit_goalss = map mk_wit_goals bnf_wit_As;
   925 
   926     fun after_qed thms lthy =
   927       let
   928         val (axioms, wit_thms) = apfst (mk_axioms live) (chop (length goals) thms);
   929 
   930         val bd_Card_order = #bd_card_order axioms RS @{thm conjunct2[OF card_order_on_Card_order]};
   931         val bd_Cinfinite = @{thm conjI} OF [#bd_cinfinite axioms, bd_Card_order];
   932         val bd_Cnotzero = bd_Cinfinite RS @{thm Cinfinite_Cnotzero};
   933 
   934         fun mk_collect_set_map () =
   935           let
   936             val defT = mk_bnf_T Ts CA --> HOLogic.mk_setT T;
   937             val collect_map = HOLogic.mk_comp
   938               (mk_collect (map (mk_bnf_t Ts) bnf_sets) defT,
   939               Term.list_comb (mk_bnf_map As' Ts, hs));
   940             val image_collect = mk_collect
   941               (map2 (fn h => fn set => HOLogic.mk_comp (mk_image h, set)) hs bnf_sets_As)
   942               defT;
   943             (*collect {set1 ... setm} o map f1 ... fm = collect {f1` o set1 ... fm` o setm}*)
   944             val goal = fold_rev Logic.all hs (mk_Trueprop_eq (collect_map, image_collect));
   945           in
   946             Goal.prove_sorry lthy [] [] goal (K (mk_collect_set_map_tac (#set_map axioms)))
   947             |> Thm.close_derivation
   948           end;
   949 
   950         val collect_set_map = Lazy.lazy mk_collect_set_map;
   951 
   952         fun mk_in_mono () =
   953           let
   954             val prems_mono = map2 (HOLogic.mk_Trueprop oo mk_subset) As As_copy;
   955             val in_mono_goal =
   956               fold_rev Logic.all (As @ As_copy)
   957                 (Logic.list_implies (prems_mono, HOLogic.mk_Trueprop
   958                   (mk_subset (mk_in As bnf_sets_As CA') (mk_in As_copy bnf_sets_As CA'))));
   959           in
   960             Goal.prove_sorry lthy [] [] in_mono_goal (K (mk_in_mono_tac live))
   961             |> Thm.close_derivation
   962           end;
   963 
   964         val in_mono = Lazy.lazy mk_in_mono;
   965 
   966         fun mk_in_cong () =
   967           let
   968             val prems_cong = map2 (curry mk_Trueprop_eq) As As_copy;
   969             val in_cong_goal =
   970               fold_rev Logic.all (As @ As_copy)
   971                 (Logic.list_implies (prems_cong,
   972                   mk_Trueprop_eq (mk_in As bnf_sets_As CA', mk_in As_copy bnf_sets_As CA')));
   973           in
   974             Goal.prove_sorry lthy [] [] in_cong_goal (K ((TRY o hyp_subst_tac THEN' rtac refl) 1))
   975             |> Thm.close_derivation
   976           end;
   977 
   978         val in_cong = Lazy.lazy mk_in_cong;
   979 
   980         val map_id' = Lazy.lazy (fn () => mk_map_id' (#map_id axioms));
   981         val map_comp' = Lazy.lazy (fn () => mk_map_comp' (#map_comp axioms));
   982 
   983         fun mk_map_cong () =
   984           let
   985             val prem0 = mk_Trueprop_eq (x, x_copy);
   986             val prems = map4 (mk_map_cong_prem x_copy) zs bnf_sets_As fs fs_copy;
   987             val eq = mk_Trueprop_eq (Term.list_comb (bnf_map_AsBs, fs) $ x,
   988               Term.list_comb (bnf_map_AsBs, fs_copy) $ x_copy);
   989             val goal = fold_rev Logic.all (x :: x_copy :: fs @ fs_copy)
   990               (Logic.list_implies (prem0 :: prems, eq));
   991           in
   992             Goal.prove_sorry lthy [] [] goal (fn _ => mk_map_cong_tac (#map_cong0 axioms))
   993             |> Thm.close_derivation
   994           end;
   995 
   996         val map_cong = Lazy.lazy mk_map_cong;
   997 
   998         val set_map' = map (fn thm => Lazy.lazy (fn () => mk_set_map' thm)) (#set_map axioms);
   999 
  1000         fun mk_map_wppull () =
  1001           let
  1002             val prems = if live = 0 then [] else
  1003               [HOLogic.mk_Trueprop (Library.foldr1 HOLogic.mk_conj
  1004                 (map8 mk_wpull Xs B1s B2s f1s f2s (map SOME (e1s ~~ e2s)) p1s p2s))];
  1005             val CX = mk_bnf_T domTs CA;
  1006             val CB1 = mk_bnf_T B1Ts CA;
  1007             val CB2 = mk_bnf_T B2Ts CA;
  1008             val bnf_sets_CX =
  1009               map2 (normalize_set (map (mk_bnf_T domTs) CA_params)) domTs bnf_sets;
  1010             val bnf_sets_CB1 =
  1011               map2 (normalize_set (map (mk_bnf_T B1Ts) CA_params)) B1Ts bnf_sets;
  1012             val bnf_sets_CB2 =
  1013               map2 (normalize_set (map (mk_bnf_T B2Ts) CA_params)) B2Ts bnf_sets;
  1014             val bnf_map_app_f1 = Term.list_comb (mk_bnf_map B1Ts ranTs, f1s);
  1015             val bnf_map_app_f2 = Term.list_comb (mk_bnf_map B2Ts ranTs, f2s);
  1016             val bnf_map_app_e1 = Term.list_comb (mk_bnf_map B1Ts ranTs', e1s);
  1017             val bnf_map_app_e2 = Term.list_comb (mk_bnf_map B2Ts ranTs'', e2s);
  1018             val bnf_map_app_p1 = Term.list_comb (mk_bnf_map domTs B1Ts, p1s);
  1019             val bnf_map_app_p2 = Term.list_comb (mk_bnf_map domTs B2Ts, p2s);
  1020 
  1021             val concl = mk_wpull (mk_in Xs bnf_sets_CX CX)
  1022               (mk_in B1s bnf_sets_CB1 CB1) (mk_in B2s bnf_sets_CB2 CB2)
  1023               bnf_map_app_f1 bnf_map_app_f2 (SOME (bnf_map_app_e1, bnf_map_app_e2))
  1024               bnf_map_app_p1 bnf_map_app_p2;
  1025 
  1026             val goal =
  1027               fold_rev Logic.all (Xs @ B1s @ B2s @ f1s @ f2s @ e1s @ e2s @ p1s @ p2s)
  1028                 (Logic.list_implies (prems, HOLogic.mk_Trueprop concl))
  1029           in
  1030             Goal.prove_sorry lthy [] [] goal
  1031               (fn _ => mk_map_wppull_tac (#map_id axioms) (#map_cong0 axioms)
  1032                 (#map_wpull axioms) (Lazy.force map_comp') (map Lazy.force set_map'))
  1033             |> Thm.close_derivation
  1034           end;
  1035 
  1036         val map_wppull = Lazy.lazy mk_map_wppull;
  1037 
  1038         val srel_O_Grs = no_refl [#srel_O_Gr axioms];
  1039 
  1040         fun mk_srel_Gr () =
  1041           let
  1042             val lhs = Term.list_comb (srel, map2 mk_Gr As fs);
  1043             val rhs = mk_Gr (mk_in As bnf_sets_As CA') (Term.list_comb (bnf_map_AsBs, fs));
  1044             val goal = fold_rev Logic.all (As @ fs) (mk_Trueprop_eq (lhs, rhs));
  1045           in
  1046             Goal.prove_sorry lthy [] [] goal
  1047               (mk_srel_Gr_tac srel_O_Grs (#map_id axioms) (#map_cong0 axioms) (Lazy.force map_id')
  1048                 (Lazy.force map_comp') (map Lazy.force set_map'))
  1049             |> Thm.close_derivation
  1050           end;
  1051 
  1052         val srel_Gr = Lazy.lazy mk_srel_Gr;
  1053 
  1054         fun mk_srel_prems f = map2 (HOLogic.mk_Trueprop oo f) Rs Rs_copy
  1055         fun mk_srel_concl f = HOLogic.mk_Trueprop
  1056           (f (Term.list_comb (srel, Rs), Term.list_comb (srel, Rs_copy)));
  1057 
  1058         fun mk_srel_mono () =
  1059           let
  1060             val mono_prems = mk_srel_prems mk_subset;
  1061             val mono_concl = mk_srel_concl (uncurry mk_subset);
  1062           in
  1063             Goal.prove_sorry lthy [] []
  1064               (fold_rev Logic.all (Rs @ Rs_copy) (Logic.list_implies (mono_prems, mono_concl)))
  1065               (mk_srel_mono_tac srel_O_Grs (Lazy.force in_mono))
  1066             |> Thm.close_derivation
  1067           end;
  1068 
  1069         fun mk_srel_cong () =
  1070           let
  1071             val cong_prems = mk_srel_prems (curry HOLogic.mk_eq);
  1072             val cong_concl = mk_srel_concl HOLogic.mk_eq;
  1073           in
  1074             Goal.prove_sorry lthy [] []
  1075               (fold_rev Logic.all (Rs @ Rs_copy) (Logic.list_implies (cong_prems, cong_concl)))
  1076               (fn _ => (TRY o hyp_subst_tac THEN' rtac refl) 1)
  1077             |> Thm.close_derivation
  1078           end;
  1079 
  1080         val srel_mono = Lazy.lazy mk_srel_mono;
  1081         val srel_cong = Lazy.lazy mk_srel_cong;
  1082 
  1083         fun mk_srel_Id () =
  1084           let val srelAsAs = mk_bnf_srel self_setRTs CA' CA' in
  1085             Goal.prove_sorry lthy [] []
  1086               (mk_Trueprop_eq (Term.list_comb (srelAsAs, map Id_const As'), Id_const CA'))
  1087               (mk_srel_Id_tac live (Lazy.force srel_Gr) (#map_id axioms))
  1088             |> Thm.close_derivation
  1089           end;
  1090 
  1091         val srel_Id = Lazy.lazy mk_srel_Id;
  1092 
  1093         fun mk_srel_converse () =
  1094           let
  1095             val srelBsAs = mk_bnf_srel setRT's CB' CA';
  1096             val lhs = Term.list_comb (srelBsAs, map mk_converse Rs);
  1097             val rhs = mk_converse (Term.list_comb (srel, Rs));
  1098             val le_goal = fold_rev Logic.all Rs (HOLogic.mk_Trueprop (mk_subset lhs rhs));
  1099             val le_thm = Goal.prove_sorry lthy [] [] le_goal
  1100               (mk_srel_converse_le_tac srel_O_Grs (Lazy.force srel_Id) (#map_cong0 axioms)
  1101                 (Lazy.force map_comp') (map Lazy.force set_map'))
  1102               |> Thm.close_derivation
  1103             val goal = fold_rev Logic.all Rs (mk_Trueprop_eq (lhs, rhs));
  1104           in
  1105             Goal.prove_sorry lthy [] [] goal (fn _ => mk_srel_converse_tac le_thm)
  1106             |> Thm.close_derivation
  1107           end;
  1108 
  1109         val srel_converse = Lazy.lazy mk_srel_converse;
  1110 
  1111         fun mk_srel_O () =
  1112           let
  1113             val srelAsCs = mk_bnf_srel setRTsAsCs CA' CC';
  1114             val srelBsCs = mk_bnf_srel setRTsBsCs CB' CC';
  1115             val lhs = Term.list_comb (srelAsCs, map2 (curry mk_rel_comp) Rs Ss);
  1116             val rhs = mk_rel_comp (Term.list_comb (srel, Rs), Term.list_comb (srelBsCs, Ss));
  1117             val goal = fold_rev Logic.all (Rs @ Ss) (mk_Trueprop_eq (lhs, rhs));
  1118           in
  1119             Goal.prove_sorry lthy [] [] goal
  1120               (mk_srel_O_tac srel_O_Grs (Lazy.force srel_Id) (#map_cong0 axioms)
  1121                 (Lazy.force map_wppull) (Lazy.force map_comp') (map Lazy.force set_map'))
  1122             |> Thm.close_derivation
  1123           end;
  1124 
  1125         val srel_O = Lazy.lazy mk_srel_O;
  1126 
  1127         fun mk_in_srel () =
  1128           let
  1129             val bnf_in = mk_in Rs (map (mk_bnf_t RTs) bnf_sets) CRs';
  1130             val map1 = Term.list_comb (mk_bnf_map RTs As', map fst_const RTs);
  1131             val map2 = Term.list_comb (mk_bnf_map RTs Bs', map snd_const RTs);
  1132             val map_fst_eq = HOLogic.mk_eq (map1 $ z, x);
  1133             val map_snd_eq = HOLogic.mk_eq (map2 $ z, y);
  1134             val lhs = HOLogic.mk_mem (HOLogic.mk_prod (x, y), Term.list_comb (srel, Rs));
  1135             val rhs =
  1136               HOLogic.mk_exists (fst z', snd z', HOLogic.mk_conj (HOLogic.mk_mem (z, bnf_in),
  1137                 HOLogic.mk_conj (map_fst_eq, map_snd_eq)));
  1138             val goal =
  1139               fold_rev Logic.all (x :: y :: Rs) (mk_Trueprop_eq (lhs, rhs));
  1140           in
  1141             Goal.prove_sorry lthy [] [] goal (mk_in_srel_tac srel_O_Grs (length bnf_sets))
  1142             |> Thm.close_derivation
  1143           end;
  1144 
  1145         val in_srel = Lazy.lazy mk_in_srel;
  1146 
  1147         val eqset_imp_iff_pair = @{thm eqset_imp_iff_pair};
  1148         val mem_Collect_etc = @{thms fst_conv mem_Collect_eq prod.cases snd_conv};
  1149         val mem_Collect_etc' = @{thms fst_conv mem_Collect_eq pair_in_Id_conv snd_conv};
  1150 
  1151         fun mk_rel_srel () =
  1152           unfold_thms lthy mem_Collect_etc
  1153             (funpow live (fn thm => thm RS @{thm fun_cong_pair}) (bnf_srel_def RS meta_eq_to_obj_eq)
  1154                RS eqset_imp_iff_pair RS sym)
  1155           |> Drule.zero_var_indexes;
  1156 
  1157         val rel_srel = Lazy.lazy mk_rel_srel;
  1158 
  1159         fun mk_rel_eq () =
  1160           unfold_thms lthy (bnf_srel_def :: mem_Collect_etc')
  1161             (Lazy.force srel_Id RS @{thm arg_cong[of _ _ "%A x y. (x, y) : A"]})
  1162           |> Drule.eta_contraction_rule;
  1163 
  1164         val rel_eq = Lazy.lazy mk_rel_eq;
  1165 
  1166         fun mk_rel_flip () =
  1167           let
  1168             val srel_converse_thm = Lazy.force srel_converse;
  1169             val cts = map (SOME o certify lthy) sQs;
  1170             val srel_converse_thm' = cterm_instantiate_pos cts srel_converse_thm;
  1171           in
  1172             unfold_thms lthy (bnf_srel_def :: @{thm converse_iff} :: mem_Collect_etc)
  1173               (srel_converse_thm' RS eqset_imp_iff_pair)
  1174             |> singleton (Proof_Context.export names_lthy pre_names_lthy)
  1175           end;
  1176 
  1177         val rel_flip = Lazy.lazy mk_rel_flip;
  1178 
  1179         val defs = mk_defs bnf_map_def bnf_set_defs bnf_rel_def bnf_srel_def;
  1180 
  1181         val facts = mk_facts bd_Card_order bd_Cinfinite bd_Cnotzero collect_set_map in_cong in_mono
  1182           in_srel map_comp' map_cong map_id' map_wppull rel_eq rel_flip rel_srel set_map'
  1183           srel_cong srel_mono srel_Id srel_Gr srel_converse srel_O;
  1184 
  1185         val wits = map2 mk_witness bnf_wits wit_thms;
  1186 
  1187         val bnf_rel =
  1188           Term.subst_atomic_types ((Ds ~~ deads) @ (As' ~~ alphas) @ (Bs' ~~ betas)) rel;
  1189         val bnf_srel =
  1190           Term.subst_atomic_types ((Ds ~~ deads) @ (As' ~~ alphas) @ (Bs' ~~ betas)) srel;
  1191 
  1192         val bnf = mk_bnf b CA live alphas betas dead deads bnf_map bnf_sets bnf_bd axioms defs facts
  1193           wits bnf_rel bnf_srel;
  1194       in
  1195         (bnf, lthy
  1196           |> (if fact_policy = Note_All then
  1197                 let
  1198                   val witNs = if length wits = 1 then [witN] else map mk_witN (1 upto length wits);
  1199                   val notes =
  1200                     [(bd_card_orderN, [#bd_card_order axioms]),
  1201                     (bd_cinfiniteN, [#bd_cinfinite axioms]),
  1202                     (bd_Card_orderN, [#bd_Card_order facts]),
  1203                     (bd_CinfiniteN, [#bd_Cinfinite facts]),
  1204                     (bd_CnotzeroN, [#bd_Cnotzero facts]),
  1205                     (collect_set_mapN, [Lazy.force (#collect_set_map facts)]),
  1206                     (in_bdN, [#in_bd axioms]),
  1207                     (in_monoN, [Lazy.force (#in_mono facts)]),
  1208                     (in_srelN, [Lazy.force (#in_srel facts)]),
  1209                     (map_compN, [#map_comp axioms]),
  1210                     (map_idN, [#map_id axioms]),
  1211                     (map_wpullN, [#map_wpull axioms]),
  1212                     (set_mapN, #set_map axioms),
  1213                     (set_bdN, #set_bd axioms)] @
  1214                     (witNs ~~ wit_thms)
  1215                     |> map (fn (thmN, thms) =>
  1216                       ((qualify (Binding.qualify true (Binding.name_of b) (Binding.name thmN)), []),
  1217                       [(thms, [])]));
  1218                 in
  1219                   Local_Theory.notes notes #> snd
  1220                 end
  1221               else
  1222                 I)
  1223           |> (if fact_policy <> Dont_Note then
  1224                 let
  1225                   val notes =
  1226                     [(map_comp'N, [Lazy.force (#map_comp' facts)], []),
  1227                     (map_cong0N, [#map_cong0 axioms], []),
  1228                     (map_congN, [Lazy.force (#map_cong facts)], fundef_cong_attrs),
  1229                     (map_id'N, [Lazy.force (#map_id' facts)], []),
  1230                     (rel_eqN, [Lazy.force (#rel_eq facts)], []),
  1231                     (rel_flipN, [Lazy.force (#rel_flip facts)], []),
  1232                     (rel_srelN, [Lazy.force (#rel_srel facts)], []),
  1233                     (set_map'N, map Lazy.force (#set_map' facts), []),
  1234                     (srel_O_GrN, srel_O_Grs, []),
  1235                     (srel_IdN, [Lazy.force (#srel_Id facts)], []),
  1236                     (srel_GrN, [Lazy.force (#srel_Gr facts)], []),
  1237                     (srel_converseN, [Lazy.force (#srel_converse facts)], []),
  1238                     (srel_monoN, [Lazy.force (#srel_mono facts)], []),
  1239                     (srel_ON, [Lazy.force (#srel_O facts)], [])]
  1240                     |> filter_out (null o #2)
  1241                     |> map (fn (thmN, thms, attrs) =>
  1242                       ((qualify (Binding.qualify true (Binding.name_of b) (Binding.name thmN)),
  1243                         attrs), [(thms, [])]));
  1244                 in
  1245                   Local_Theory.notes notes #> snd
  1246                 end
  1247               else
  1248                 I))
  1249       end;
  1250 
  1251     val one_step_defs =
  1252       no_reflexive (bnf_map_def :: bnf_bd_def :: bnf_set_defs @ bnf_wit_defs @ [bnf_rel_def,
  1253         bnf_srel_def]);
  1254   in
  1255     (key, goals, wit_goalss, after_qed, lthy, one_step_defs)
  1256   end;
  1257 
  1258 fun register_bnf key (bnf, lthy) =
  1259   (bnf, Local_Theory.declaration {syntax = false, pervasive = true}
  1260     (fn phi => Data.map (Symtab.update_new (key, morph_bnf phi bnf))) lthy);
  1261 
  1262 (* TODO: Once the invariant "nwits > 0" holds, remove "mk_conjunction_balanced'" and "rtac TrueI"
  1263    below *)
  1264 fun mk_conjunction_balanced' [] = @{prop True}
  1265   | mk_conjunction_balanced' ts = Logic.mk_conjunction_balanced ts;
  1266 
  1267 fun bnf_def const_policy fact_policy qualify tacs wit_tac Ds map_b rel_b set_bs =
  1268   (fn (_, goals, wit_goalss, after_qed, lthy, one_step_defs) =>
  1269   let
  1270     val wits_tac =
  1271       K (TRYALL Goal.conjunction_tac) THEN' K (TRYALL (rtac TrueI)) THEN'
  1272       mk_unfold_thms_then_tac lthy one_step_defs wit_tac;
  1273     val wit_goals = map mk_conjunction_balanced' wit_goalss;
  1274     val wit_thms =
  1275       Goal.prove_sorry lthy [] [] (mk_conjunction_balanced' wit_goals) wits_tac
  1276       |> Conjunction.elim_balanced (length wit_goals)
  1277       |> map2 (Conjunction.elim_balanced o length) wit_goalss
  1278       |> map (map (Thm.close_derivation o Thm.forall_elim_vars 0));
  1279   in
  1280     map2 (Thm.close_derivation oo Goal.prove_sorry lthy [] [])
  1281       goals (map (mk_unfold_thms_then_tac lthy one_step_defs) tacs)
  1282     |> (fn thms => after_qed (map single thms @ wit_thms) lthy)
  1283   end) oo prepare_def const_policy fact_policy qualify (K I) Ds map_b rel_b set_bs;
  1284 
  1285 val bnf_def_cmd = (fn (key, goals, wit_goals, after_qed, lthy, defs) =>
  1286   Proof.unfolding ([[(defs, [])]])
  1287     (Proof.theorem NONE (snd o register_bnf key oo after_qed)
  1288       (map (single o rpair []) goals @ map (map (rpair [])) wit_goals) lthy)) oo
  1289   prepare_def Do_Inline (user_policy Note_Some) I Syntax.read_term NONE Binding.empty Binding.empty
  1290     [];
  1291 
  1292 fun print_bnfs ctxt =
  1293   let
  1294     fun pretty_set sets i = Pretty.block
  1295       [Pretty.str (mk_setN (i + 1) ^ ":"), Pretty.brk 1,
  1296           Pretty.quote (Syntax.pretty_term ctxt (nth sets i))];
  1297 
  1298     fun pretty_bnf (key, BNF {T = T, map = map, sets = sets, bd = bd,
  1299       live = live, lives = lives, dead = dead, deads = deads, ...}) =
  1300       Pretty.big_list
  1301         (Pretty.string_of (Pretty.block [Pretty.str key, Pretty.str ":", Pretty.brk 1,
  1302           Pretty.quote (Syntax.pretty_typ ctxt T)]))
  1303         ([Pretty.block [Pretty.str "live:", Pretty.brk 1, Pretty.str (string_of_int live),
  1304             Pretty.brk 3, Pretty.list "[" "]" (List.map (Syntax.pretty_typ ctxt) lives)],
  1305           Pretty.block [Pretty.str "dead:", Pretty.brk 1, Pretty.str (string_of_int dead),
  1306             Pretty.brk 3, Pretty.list "[" "]" (List.map (Syntax.pretty_typ ctxt) deads)],
  1307           Pretty.block [Pretty.str (mapN ^ ":"), Pretty.brk 1,
  1308             Pretty.quote (Syntax.pretty_term ctxt map)]] @
  1309           List.map (pretty_set sets) (0 upto length sets - 1) @
  1310           [Pretty.block [Pretty.str (bdN ^ ":"), Pretty.brk 1,
  1311             Pretty.quote (Syntax.pretty_term ctxt bd)]]);
  1312   in
  1313     Pretty.big_list "BNFs:" (map pretty_bnf (Symtab.dest (Data.get (Context.Proof ctxt))))
  1314     |> Pretty.writeln
  1315   end;
  1316 
  1317 val _ =
  1318   Outer_Syntax.improper_command @{command_spec "print_bnfs"} "print all BNFs"
  1319     (Scan.succeed (Toplevel.keep (print_bnfs o Toplevel.context_of)));
  1320 
  1321 val _ =
  1322   Outer_Syntax.local_theory_to_proof @{command_spec "bnf_def"} "define a BNF for an existing type"
  1323     ((parse_opt_binding_colon -- Parse.term --
  1324        (@{keyword "["} |-- Parse.list Parse.term --| @{keyword "]"}) -- Parse.term --
  1325        (@{keyword "["} |-- Parse.list Parse.term --| @{keyword "]"}) -- Scan.option Parse.term)
  1326        >> bnf_def_cmd);
  1327 
  1328 end;