src/HOL/BNF/Tools/bnf_comp.ML
author blanchet
Wed Sep 26 10:00:59 2012 +0200 (2012-09-26)
changeset 49585 5c4a12550491
parent 49538 c90818b63599
child 49586 d5e342ffe91e
permissions -rw-r--r--
generate high-level "maps", "sets", and "rels" properties
     1 (*  Title:      HOL/BNF/Tools/bnf_comp.ML
     2     Author:     Dmitriy Traytel, TU Muenchen
     3     Author:     Jasmin Blanchette, TU Muenchen
     4     Copyright   2012
     5 
     6 Composition of bounded natural functors.
     7 *)
     8 
     9 signature BNF_COMP =
    10 sig
    11   val ID_bnf: BNF_Def.BNF
    12   val DEADID_bnf: BNF_Def.BNF
    13 
    14   type unfold_set
    15   val empty_unfolds: unfold_set
    16   val map_unfolds_of: unfold_set -> thm list
    17   val rel_unfolds_of: unfold_set -> thm list
    18   val set_unfoldss_of: unfold_set -> thm list list
    19   val srel_unfolds_of: unfold_set -> thm list
    20 
    21   val bnf_of_typ: BNF_Def.const_policy -> (binding -> binding) ->
    22     ((string * sort) list list -> (string * sort) list) -> typ -> unfold_set * Proof.context ->
    23     (BNF_Def.BNF * (typ list * typ list)) * (unfold_set * Proof.context)
    24   val default_comp_sort: (string * sort) list list -> (string * sort) list
    25   val normalize_bnfs: (int -> binding -> binding) -> ''a list list -> ''a list ->
    26     (''a list list -> ''a list) -> BNF_Def.BNF list -> unfold_set -> Proof.context ->
    27     (int list list * ''a list) * (BNF_Def.BNF list * (unfold_set * Proof.context))
    28   val seal_bnf: unfold_set -> binding -> typ list -> BNF_Def.BNF -> Proof.context ->
    29     (BNF_Def.BNF * typ list) * local_theory
    30 end;
    31 
    32 structure BNF_Comp : BNF_COMP =
    33 struct
    34 
    35 open BNF_Def
    36 open BNF_Util
    37 open BNF_Tactics
    38 open BNF_Comp_Tactics
    39 
    40 val ID_bnf = the (bnf_of @{context} "Basic_BNFs.ID");
    41 val DEADID_bnf = the (bnf_of @{context} "Basic_BNFs.DEADID");
    42 
    43 (* TODO: Replace by "BNF_Defs.defs list" *)
    44 type unfold_set = {
    45   map_unfolds: thm list,
    46   set_unfoldss: thm list list,
    47   rel_unfolds: thm list,
    48   srel_unfolds: thm list
    49 };
    50 
    51 val empty_unfolds = {map_unfolds = [], set_unfoldss = [], rel_unfolds = [], srel_unfolds = []};
    52 
    53 fun add_to_thms thms new = thms |> not (Thm.is_reflexive new) ? insert Thm.eq_thm new;
    54 fun adds_to_thms thms news = insert (eq_set Thm.eq_thm) (no_reflexive news) thms;
    55 
    56 fun add_to_unfolds map sets rel srel
    57   {map_unfolds, set_unfoldss, rel_unfolds, srel_unfolds} =
    58   {map_unfolds = add_to_thms map_unfolds map,
    59     set_unfoldss = adds_to_thms set_unfoldss sets,
    60     rel_unfolds = add_to_thms rel_unfolds rel,
    61     srel_unfolds = add_to_thms srel_unfolds srel};
    62 
    63 fun add_bnf_to_unfolds bnf =
    64   add_to_unfolds (map_def_of_bnf bnf) (set_defs_of_bnf bnf) (rel_def_of_bnf bnf)
    65     (srel_def_of_bnf bnf);
    66 
    67 val map_unfolds_of = #map_unfolds;
    68 val set_unfoldss_of = #set_unfoldss;
    69 val rel_unfolds_of = #rel_unfolds;
    70 val srel_unfolds_of = #srel_unfolds;
    71 
    72 val bdTN = "bdT";
    73 
    74 fun mk_killN n = "_kill" ^ string_of_int n;
    75 fun mk_liftN n = "_lift" ^ string_of_int n;
    76 fun mk_permuteN src dest =
    77   "_permute_" ^ implode (map string_of_int src) ^ "_" ^ implode (map string_of_int dest);
    78 
    79 (*copied from Envir.expand_term_free*)
    80 fun expand_term_const defs =
    81   let
    82     val eqs = map ((fn ((x, U), u) => (x, (U, u))) o apfst dest_Const) defs;
    83     val get = fn Const (x, _) => AList.lookup (op =) eqs x | _ => NONE;
    84   in Envir.expand_term get end;
    85 
    86 fun clean_compose_bnf const_policy qualify b outer inners (unfold_set, lthy) =
    87   let
    88     val olive = live_of_bnf outer;
    89     val onwits = nwits_of_bnf outer;
    90     val odead = dead_of_bnf outer;
    91     val inner = hd inners;
    92     val ilive = live_of_bnf inner;
    93     val ideads = map dead_of_bnf inners;
    94     val inwitss = map nwits_of_bnf inners;
    95 
    96     (* TODO: check olive = length inners > 0,
    97                    forall inner from inners. ilive = live,
    98                    forall inner from inners. idead = dead  *)
    99 
   100     val (oDs, lthy1) = apfst (map TFree)
   101       (Variable.invent_types (replicate odead HOLogic.typeS) lthy);
   102     val (Dss, lthy2) = apfst (map (map TFree))
   103         (fold_map Variable.invent_types (map (fn n => replicate n HOLogic.typeS) ideads) lthy1);
   104     val (Ass, lthy3) = apfst (replicate ilive o map TFree)
   105       (Variable.invent_types (replicate ilive HOLogic.typeS) lthy2);
   106     val As = if ilive > 0 then hd Ass else [];
   107     val Ass_repl = replicate olive As;
   108     val (Bs, _(*lthy4*)) = apfst (map TFree)
   109       (Variable.invent_types (replicate ilive HOLogic.typeS) lthy3);
   110     val Bss_repl = replicate olive Bs;
   111 
   112     val ((((fs', Qs'), Asets), xs), _(*names_lthy*)) = lthy
   113       |> apfst snd o mk_Frees' "f" (map2 (curry (op -->)) As Bs)
   114       ||>> apfst snd o mk_Frees' "Q" (map2 mk_pred2T As Bs)
   115       ||>> mk_Frees "A" (map HOLogic.mk_setT As)
   116       ||>> mk_Frees "x" As;
   117 
   118     val CAs = map3 mk_T_of_bnf Dss Ass_repl inners;
   119     val CCA = mk_T_of_bnf oDs CAs outer;
   120     val CBs = map3 mk_T_of_bnf Dss Bss_repl inners;
   121     val outer_sets = mk_sets_of_bnf (replicate olive oDs) (replicate olive CAs) outer;
   122     val inner_setss = map3 mk_sets_of_bnf (map (replicate ilive) Dss) (replicate olive Ass) inners;
   123     val inner_bds = map3 mk_bd_of_bnf Dss Ass_repl inners;
   124     val outer_bd = mk_bd_of_bnf oDs CAs outer;
   125 
   126     (*%f1 ... fn. outer.map (inner_1.map f1 ... fn) ... (inner_m.map f1 ... fn)*)
   127     val mapx = fold_rev Term.abs fs'
   128       (Term.list_comb (mk_map_of_bnf oDs CAs CBs outer,
   129         map2 (fn Ds => (fn f => Term.list_comb (f, map Bound (ilive - 1 downto 0))) o
   130           mk_map_of_bnf Ds As Bs) Dss inners));
   131     (*%Q1 ... Qn. outer.rel (inner_1.rel Q1 ... Qn) ... (inner_m.rel Q1 ... Qn)*)
   132     val rel = fold_rev Term.abs Qs'
   133       (Term.list_comb (mk_rel_of_bnf oDs CAs CBs outer,
   134         map2 (fn Ds => (fn f => Term.list_comb (f, map Bound (ilive - 1 downto 0))) o
   135           mk_rel_of_bnf Ds As Bs) Dss inners));
   136 
   137     (*Union o collect {outer.set_1 ... outer.set_m} o outer.map inner_1.set_i ... inner_m.set_i*)
   138     (*Union o collect {image inner_1.set_i o outer.set_1 ... image inner_m.set_i o outer.set_m}*)
   139     fun mk_set i =
   140       let
   141         val (setTs, T) = `(replicate olive o HOLogic.mk_setT) (nth As i);
   142         val outer_set = mk_collect
   143           (mk_sets_of_bnf (replicate olive oDs) (replicate olive setTs) outer)
   144           (mk_T_of_bnf oDs setTs outer --> HOLogic.mk_setT T);
   145         val inner_sets = map (fn sets => nth sets i) inner_setss;
   146         val outer_map = mk_map_of_bnf oDs CAs setTs outer;
   147         val map_inner_sets = Term.list_comb (outer_map, inner_sets);
   148         val collect_image = mk_collect
   149           (map2 (fn f => fn set => HOLogic.mk_comp (mk_image f, set)) inner_sets outer_sets)
   150           (CCA --> HOLogic.mk_setT T);
   151       in
   152         (Library.foldl1 HOLogic.mk_comp [mk_Union T, outer_set, map_inner_sets],
   153         HOLogic.mk_comp (mk_Union T, collect_image))
   154       end;
   155 
   156     val (sets, sets_alt) = map_split mk_set (0 upto ilive - 1);
   157 
   158     (*(inner_1.bd +c ... +c inner_m.bd) *c outer.bd*)
   159     val bd = Term.absdummy CCA (mk_cprod (Library.foldr1 (uncurry mk_csum) inner_bds) outer_bd);
   160 
   161     fun map_id_tac {context = ctxt, ...} =
   162       let
   163         (*order the theorems by reverse size to prevent bad interaction with nonconfluent rewrite
   164           rules*)
   165         val thms = (map map_id_of_bnf inners
   166           |> map (`(Term.size_of_term o Thm.prop_of))
   167           |> sort (rev_order o int_ord o pairself fst)
   168           |> map snd) @ [map_id_of_bnf outer];
   169       in
   170         (EVERY' (map (fn thm => subst_tac ctxt [thm]) thms) THEN' rtac refl) 1
   171       end;
   172 
   173     fun map_comp_tac _ =
   174       mk_comp_map_comp_tac (map_comp_of_bnf outer) (map_cong_of_bnf outer)
   175         (map map_comp_of_bnf inners);
   176 
   177     fun mk_single_set_natural_tac i _ =
   178       mk_comp_set_natural_tac (map_comp_of_bnf outer) (map_cong_of_bnf outer)
   179         (collect_set_natural_of_bnf outer)
   180         (map ((fn thms => nth thms i) o set_natural_of_bnf) inners);
   181 
   182     val set_natural_tacs = map mk_single_set_natural_tac (0 upto ilive - 1);
   183 
   184     fun bd_card_order_tac _ =
   185       mk_comp_bd_card_order_tac (map bd_card_order_of_bnf inners) (bd_card_order_of_bnf outer);
   186 
   187     fun bd_cinfinite_tac _ =
   188       mk_comp_bd_cinfinite_tac (bd_cinfinite_of_bnf inner) (bd_cinfinite_of_bnf outer);
   189 
   190     val set_alt_thms =
   191       if ! quick_and_dirty then
   192         []
   193       else
   194         map (fn goal =>
   195           Skip_Proof.prove lthy [] [] goal
   196             (fn {context, ...} => (mk_comp_set_alt_tac context (collect_set_natural_of_bnf outer)))
   197           |> Thm.close_derivation)
   198         (map2 (curry (HOLogic.mk_Trueprop o HOLogic.mk_eq)) sets sets_alt);
   199 
   200     fun map_cong_tac _ =
   201       mk_comp_map_cong_tac set_alt_thms (map_cong_of_bnf outer) (map map_cong_of_bnf inners);
   202 
   203     val set_bd_tacs =
   204       if ! quick_and_dirty then
   205         replicate (length set_alt_thms) (K all_tac)
   206       else
   207         let
   208           val outer_set_bds = set_bd_of_bnf outer;
   209           val inner_set_bdss = map set_bd_of_bnf inners;
   210           val inner_bd_Card_orders = map bd_Card_order_of_bnf inners;
   211           fun single_set_bd_thm i j =
   212             @{thm comp_single_set_bd} OF [nth inner_bd_Card_orders j, nth (nth inner_set_bdss j) i,
   213               nth outer_set_bds j]
   214           val single_set_bd_thmss =
   215             map ((fn f => map f (0 upto olive - 1)) o single_set_bd_thm) (0 upto ilive - 1);
   216         in
   217           map2 (fn set_alt => fn single_set_bds => fn {context, ...} =>
   218             mk_comp_set_bd_tac context set_alt single_set_bds)
   219           set_alt_thms single_set_bd_thmss
   220         end;
   221 
   222     val in_alt_thm =
   223       let
   224         val inx = mk_in Asets sets CCA;
   225         val in_alt = mk_in (map2 (mk_in Asets) inner_setss CAs) outer_sets CCA;
   226         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   227       in
   228         Skip_Proof.prove lthy [] [] goal
   229           (fn {context, ...} => mk_comp_in_alt_tac context set_alt_thms)
   230         |> Thm.close_derivation
   231       end;
   232 
   233     fun in_bd_tac _ =
   234       mk_comp_in_bd_tac in_alt_thm (map in_bd_of_bnf inners) (in_bd_of_bnf outer)
   235         (map bd_Cinfinite_of_bnf inners) (bd_Card_order_of_bnf outer);
   236 
   237     fun map_wpull_tac _ =
   238       mk_map_wpull_tac in_alt_thm (map map_wpull_of_bnf inners) (map_wpull_of_bnf outer);
   239 
   240     fun srel_O_Gr_tac _ =
   241       let
   242         val basic_thms = @{thms mem_Collect_eq fst_conv snd_conv}; (*TODO: tune*)
   243         val outer_srel_Gr = srel_Gr_of_bnf outer RS sym;
   244         val outer_srel_cong = srel_cong_of_bnf outer;
   245         val thm =
   246           (trans OF [in_alt_thm RS @{thm O_Gr_cong},
   247              trans OF [@{thm arg_cong2[of _ _ _ _ relcomp]} OF
   248                [trans OF [outer_srel_Gr RS @{thm arg_cong[of _ _ converse]},
   249                  srel_converse_of_bnf outer RS sym], outer_srel_Gr],
   250                trans OF [srel_O_of_bnf outer RS sym, outer_srel_cong OF
   251                  (map (fn bnf => srel_O_Gr_of_bnf bnf RS sym) inners)]]] RS sym)
   252           |> unfold_thms lthy (basic_thms @ srel_def_of_bnf outer :: map srel_def_of_bnf inners);
   253       in
   254         unfold_thms_tac lthy basic_thms THEN rtac thm 1
   255       end;
   256 
   257     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   258       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   259 
   260     val outer_wits = mk_wits_of_bnf (replicate onwits oDs) (replicate onwits CAs) outer;
   261 
   262     val inner_witss = map (map (fn (I, wit) => Term.list_comb (wit, map (nth xs) I)))
   263       (map3 (fn Ds => fn n => mk_wits_of_bnf (replicate n Ds) (replicate n As))
   264         Dss inwitss inners);
   265 
   266     val inner_witsss = map (map (nth inner_witss) o fst) outer_wits;
   267 
   268     val wits = (inner_witsss, (map (single o snd) outer_wits))
   269       |-> map2 (fold (map_product (fn iwit => fn owit => owit $ iwit)))
   270       |> flat
   271       |> map (`(fn t => Term.add_frees t []))
   272       |> minimize_wits
   273       |> map (fn (frees, t) => fold absfree frees t);
   274 
   275     fun wit_tac {context = ctxt, ...} =
   276       mk_comp_wit_tac ctxt (wit_thms_of_bnf outer) (collect_set_natural_of_bnf outer)
   277         (maps wit_thms_of_bnf inners);
   278 
   279     val (bnf', lthy') =
   280       bnf_def const_policy (K Dont_Note) qualify tacs wit_tac (SOME (oDs @ flat Dss))
   281         (((((b, mapx), sets), bd), wits), SOME rel) lthy;
   282   in
   283     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   284   end;
   285 
   286 (* Killing live variables *)
   287 
   288 fun kill_bnf qualify n bnf (unfold_set, lthy) = if n = 0 then (bnf, (unfold_set, lthy)) else
   289   let
   290     val b = Binding.suffix_name (mk_killN n) (name_of_bnf bnf);
   291     val live = live_of_bnf bnf;
   292     val dead = dead_of_bnf bnf;
   293     val nwits = nwits_of_bnf bnf;
   294 
   295     (* TODO: check 0 < n <= live *)
   296 
   297     val (Ds, lthy1) = apfst (map TFree)
   298       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   299     val ((killedAs, As), lthy2) = apfst (`(take n) o map TFree)
   300       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   301     val (Bs, _(*lthy3*)) = apfst (append killedAs o map TFree)
   302       (Variable.invent_types (replicate (live - n) HOLogic.typeS) lthy2);
   303 
   304     val ((Asets, lives), _(*names_lthy*)) = lthy
   305       |> mk_Frees "A" (map HOLogic.mk_setT (drop n As))
   306       ||>> mk_Frees "x" (drop n As);
   307     val xs = map (fn T => HOLogic.choice_const T $ absdummy T @{term True}) killedAs @ lives;
   308 
   309     val T = mk_T_of_bnf Ds As bnf;
   310 
   311     (*bnf.map id ... id*)
   312     val mapx = Term.list_comb (mk_map_of_bnf Ds As Bs bnf, map HOLogic.id_const killedAs);
   313     (*bnf.rel (op =) ... (op =)*)
   314     val rel = Term.list_comb (mk_rel_of_bnf Ds As Bs bnf, map HOLogic.eq_const killedAs);
   315 
   316     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   317     val sets = drop n bnf_sets;
   318 
   319     (*(|UNIV :: A1 set| +c ... +c |UNIV :: An set|) *c bnf.bd*)
   320     val bnf_bd = mk_bd_of_bnf Ds As bnf;
   321     val bd = mk_cprod
   322       (Library.foldr1 (uncurry mk_csum) (map (mk_card_of o HOLogic.mk_UNIV) killedAs)) bnf_bd;
   323 
   324     fun map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   325     fun map_comp_tac {context, ...} =
   326       unfold_thms_tac context ((map_comp_of_bnf bnf RS sym) :: @{thms o_assoc id_o o_id}) THEN
   327       rtac refl 1;
   328     fun map_cong_tac {context, ...} =
   329       mk_kill_map_cong_tac context n (live - n) (map_cong_of_bnf bnf);
   330     val set_natural_tacs = map (fn thm => fn _ => rtac thm 1) (drop n (set_natural_of_bnf bnf));
   331     fun bd_card_order_tac _ = mk_kill_bd_card_order_tac n (bd_card_order_of_bnf bnf);
   332     fun bd_cinfinite_tac _ = mk_kill_bd_cinfinite_tac (bd_Cinfinite_of_bnf bnf);
   333     val set_bd_tacs =
   334       map (fn thm => fn _ => mk_kill_set_bd_tac (bd_Card_order_of_bnf bnf) thm)
   335         (drop n (set_bd_of_bnf bnf));
   336 
   337     val in_alt_thm =
   338       let
   339         val inx = mk_in Asets sets T;
   340         val in_alt = mk_in (map HOLogic.mk_UNIV killedAs @ Asets) bnf_sets T;
   341         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   342       in
   343         Skip_Proof.prove lthy [] [] goal (K kill_in_alt_tac) |> Thm.close_derivation
   344       end;
   345 
   346     fun in_bd_tac _ =
   347       mk_kill_in_bd_tac n (live > n) in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf)
   348         (bd_Cinfinite_of_bnf bnf) (bd_Cnotzero_of_bnf bnf);
   349     fun map_wpull_tac _ = mk_map_wpull_tac in_alt_thm [] (map_wpull_of_bnf bnf);
   350 
   351     fun srel_O_Gr_tac _ =
   352       let
   353         val srel_Gr = srel_Gr_of_bnf bnf RS sym
   354         val thm =
   355           (trans OF [in_alt_thm RS @{thm O_Gr_cong},
   356             trans OF [@{thm arg_cong2[of _ _ _ _ relcomp]} OF
   357               [trans OF [srel_Gr RS @{thm arg_cong[of _ _ converse]},
   358                 srel_converse_of_bnf bnf RS sym], srel_Gr],
   359               trans OF [srel_O_of_bnf bnf RS sym, srel_cong_of_bnf bnf OF
   360                 (replicate n @{thm trans[OF Gr_UNIV_id[OF refl] Id_alt[symmetric]]} @
   361                  replicate (live - n) @{thm Gr_fst_snd})]]] RS sym)
   362           |> unfold_thms lthy (srel_def_of_bnf bnf :: @{thms Id_def' mem_Collect_eq split_conv});
   363       in
   364         rtac thm 1
   365       end;
   366 
   367     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   368       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   369 
   370     val bnf_wits = mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf;
   371 
   372     val wits = map (fn t => fold absfree (Term.add_frees t []) t)
   373       (map (fn (I, wit) => Term.list_comb (wit, map (nth xs) I)) bnf_wits);
   374 
   375     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   376 
   377     val (bnf', lthy') =
   378       bnf_def Smart_Inline (K Dont_Note) qualify tacs wit_tac (SOME (killedAs @ Ds))
   379         (((((b, mapx), sets), Term.absdummy T bd), wits), SOME rel) lthy;
   380   in
   381     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   382   end;
   383 
   384 (* Adding dummy live variables *)
   385 
   386 fun lift_bnf qualify n bnf (unfold_set, lthy) = if n = 0 then (bnf, (unfold_set, lthy)) else
   387   let
   388     val b = Binding.suffix_name (mk_liftN n) (name_of_bnf bnf);
   389     val live = live_of_bnf bnf;
   390     val dead = dead_of_bnf bnf;
   391     val nwits = nwits_of_bnf bnf;
   392 
   393     (* TODO: check 0 < n *)
   394 
   395     val (Ds, lthy1) = apfst (map TFree)
   396       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   397     val ((newAs, As), lthy2) = apfst (chop n o map TFree)
   398       (Variable.invent_types (replicate (n + live) HOLogic.typeS) lthy1);
   399     val ((newBs, Bs), _(*lthy3*)) = apfst (chop n o map TFree)
   400       (Variable.invent_types (replicate (n + live) HOLogic.typeS) lthy2);
   401 
   402     val (Asets, _(*names_lthy*)) = lthy
   403       |> mk_Frees "A" (map HOLogic.mk_setT (newAs @ As));
   404 
   405     val T = mk_T_of_bnf Ds As bnf;
   406 
   407     (*%f1 ... fn. bnf.map*)
   408     val mapx =
   409       fold_rev Term.absdummy (map2 (curry (op -->)) newAs newBs) (mk_map_of_bnf Ds As Bs bnf);
   410     (*%Q1 ... Qn. bnf.rel*)
   411     val rel = fold_rev Term.absdummy (map2 mk_pred2T newAs newBs) (mk_rel_of_bnf Ds As Bs bnf);
   412 
   413     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   414     val sets = map (fn A => absdummy T (HOLogic.mk_set A [])) newAs @ bnf_sets;
   415 
   416     val bd = mk_bd_of_bnf Ds As bnf;
   417 
   418     fun map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   419     fun map_comp_tac {context, ...} =
   420       unfold_thms_tac context ((map_comp_of_bnf bnf RS sym) :: @{thms o_assoc id_o o_id}) THEN
   421       rtac refl 1;
   422     fun map_cong_tac {context, ...} =
   423       rtac (map_cong_of_bnf bnf) 1 THEN REPEAT_DETERM_N live (Goal.assume_rule_tac context 1);
   424     val set_natural_tacs =
   425       if ! quick_and_dirty then
   426         replicate (n + live) (K all_tac)
   427       else
   428         replicate n (K empty_natural_tac) @
   429         map (fn thm => fn _ => rtac thm 1) (set_natural_of_bnf bnf);
   430     fun bd_card_order_tac _ = rtac (bd_card_order_of_bnf bnf) 1;
   431     fun bd_cinfinite_tac _ = rtac (bd_cinfinite_of_bnf bnf) 1;
   432     val set_bd_tacs =
   433       if ! quick_and_dirty then
   434         replicate (n + live) (K all_tac)
   435       else
   436         replicate n (K (mk_lift_set_bd_tac (bd_Card_order_of_bnf bnf))) @
   437         (map (fn thm => fn _ => rtac thm 1) (set_bd_of_bnf bnf));
   438 
   439     val in_alt_thm =
   440       let
   441         val inx = mk_in Asets sets T;
   442         val in_alt = mk_in (drop n Asets) bnf_sets T;
   443         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   444       in
   445         Skip_Proof.prove lthy [] [] goal (K lift_in_alt_tac) |> Thm.close_derivation
   446       end;
   447 
   448     fun in_bd_tac _ = mk_lift_in_bd_tac n in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf);
   449     fun map_wpull_tac _ = mk_map_wpull_tac in_alt_thm [] (map_wpull_of_bnf bnf);
   450 
   451     fun srel_O_Gr_tac _ =
   452       mk_simple_srel_O_Gr_tac lthy (srel_def_of_bnf bnf) (srel_O_Gr_of_bnf bnf) in_alt_thm;
   453 
   454     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   455       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   456 
   457     val wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   458 
   459     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   460 
   461     val (bnf', lthy') =
   462       bnf_def Smart_Inline (K Dont_Note) qualify tacs wit_tac (SOME Ds)
   463         (((((b, mapx), sets), Term.absdummy T bd), wits), SOME rel) lthy;
   464 
   465   in
   466     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   467   end;
   468 
   469 (* Changing the order of live variables *)
   470 
   471 fun permute_bnf qualify src dest bnf (unfold_set, lthy) =
   472   if src = dest then (bnf, (unfold_set, lthy)) else
   473   let
   474     val b = Binding.suffix_name (mk_permuteN src dest) (name_of_bnf bnf);
   475     val live = live_of_bnf bnf;
   476     val dead = dead_of_bnf bnf;
   477     val nwits = nwits_of_bnf bnf;
   478     fun permute xs = mk_permute src dest xs;
   479     fun permute_rev xs = mk_permute dest src xs;
   480 
   481     val (Ds, lthy1) = apfst (map TFree)
   482       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   483     val (As, lthy2) = apfst (map TFree)
   484       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   485     val (Bs, _(*lthy3*)) = apfst (map TFree)
   486       (Variable.invent_types (replicate live HOLogic.typeS) lthy2);
   487 
   488     val (Asets, _(*names_lthy*)) = lthy
   489       |> mk_Frees "A" (map HOLogic.mk_setT (permute As));
   490 
   491     val T = mk_T_of_bnf Ds As bnf;
   492 
   493     (*%f(1) ... f(n). bnf.map f\<sigma>(1) ... f\<sigma>(n)*)
   494     val mapx = fold_rev Term.absdummy (permute (map2 (curry op -->) As Bs))
   495       (Term.list_comb (mk_map_of_bnf Ds As Bs bnf, permute_rev (map Bound (live - 1 downto 0))));
   496     (*%Q(1) ... Q(n). bnf.rel Q\<sigma>(1) ... Q\<sigma>(n)*)
   497     val rel = fold_rev Term.absdummy (permute (map2 mk_pred2T As Bs))
   498       (Term.list_comb (mk_rel_of_bnf Ds As Bs bnf, permute_rev (map Bound (live - 1 downto 0))));
   499 
   500     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   501     val sets = permute bnf_sets;
   502 
   503     val bd = mk_bd_of_bnf Ds As bnf;
   504 
   505     fun map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   506     fun map_comp_tac _ = rtac (map_comp_of_bnf bnf) 1;
   507     fun map_cong_tac {context, ...} =
   508       rtac (map_cong_of_bnf bnf) 1 THEN REPEAT_DETERM_N live (Goal.assume_rule_tac context 1);
   509     val set_natural_tacs = permute (map (fn thm => fn _ => rtac thm 1) (set_natural_of_bnf bnf));
   510     fun bd_card_order_tac _ = rtac (bd_card_order_of_bnf bnf) 1;
   511     fun bd_cinfinite_tac _ = rtac (bd_cinfinite_of_bnf bnf) 1;
   512     val set_bd_tacs = permute (map (fn thm => fn _ => rtac thm 1) (set_bd_of_bnf bnf));
   513 
   514     val in_alt_thm =
   515       let
   516         val inx = mk_in Asets sets T;
   517         val in_alt = mk_in (permute_rev Asets) bnf_sets T;
   518         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   519       in
   520         Skip_Proof.prove lthy [] [] goal (K (mk_permute_in_alt_tac src dest))
   521         |> Thm.close_derivation
   522       end;
   523 
   524     fun in_bd_tac _ =
   525       mk_permute_in_bd_tac src dest in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf);
   526     fun map_wpull_tac _ = mk_map_wpull_tac in_alt_thm [] (map_wpull_of_bnf bnf);
   527 
   528     fun srel_O_Gr_tac _ =
   529       mk_simple_srel_O_Gr_tac lthy (srel_def_of_bnf bnf) (srel_O_Gr_of_bnf bnf) in_alt_thm;
   530 
   531     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   532       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   533 
   534     val wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   535 
   536     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   537 
   538     val (bnf', lthy') =
   539       bnf_def Smart_Inline (K Dont_Note) qualify tacs wit_tac (SOME Ds)
   540         (((((b, mapx), sets), Term.absdummy T bd), wits), SOME rel) lthy;
   541   in
   542     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   543   end;
   544 
   545 (* Composition pipeline *)
   546 
   547 fun permute_and_kill qualify n src dest bnf =
   548   bnf
   549   |> permute_bnf qualify src dest
   550   #> uncurry (kill_bnf qualify n);
   551 
   552 fun lift_and_permute qualify n src dest bnf =
   553   bnf
   554   |> lift_bnf qualify n
   555   #> uncurry (permute_bnf qualify src dest);
   556 
   557 fun normalize_bnfs qualify Ass Ds sort bnfs unfold_set lthy =
   558   let
   559     val before_kill_src = map (fn As => 0 upto (length As - 1)) Ass;
   560     val kill_poss = map (find_indices Ds) Ass;
   561     val live_poss = map2 (subtract (op =)) kill_poss before_kill_src;
   562     val before_kill_dest = map2 append kill_poss live_poss;
   563     val kill_ns = map length kill_poss;
   564     val (inners', (unfold_set', lthy')) =
   565       fold_map5 (fn i => permute_and_kill (qualify i))
   566         (if length bnfs = 1 then [0] else (1 upto length bnfs))
   567         kill_ns before_kill_src before_kill_dest bnfs (unfold_set, lthy);
   568 
   569     val Ass' = map2 (map o nth) Ass live_poss;
   570     val As = sort Ass';
   571     val after_lift_dest = replicate (length Ass') (0 upto (length As - 1));
   572     val old_poss = map (map (fn x => find_index (fn y => x = y) As)) Ass';
   573     val new_poss = map2 (subtract (op =)) old_poss after_lift_dest;
   574     val after_lift_src = map2 append new_poss old_poss;
   575     val lift_ns = map (fn xs => length As - length xs) Ass';
   576   in
   577     ((kill_poss, As), fold_map5 (fn i => lift_and_permute (qualify i))
   578       (if length bnfs = 1 then [0] else (1 upto length bnfs))
   579       lift_ns after_lift_src after_lift_dest inners' (unfold_set', lthy'))
   580   end;
   581 
   582 fun default_comp_sort Ass =
   583   Library.sort (Term_Ord.typ_ord o pairself TFree) (fold (fold (insert (op =))) Ass []);
   584 
   585 fun compose_bnf const_policy qualify sort outer inners oDs Dss tfreess (unfold_set, lthy) =
   586   let
   587     val b = name_of_bnf outer;
   588 
   589     val Ass = map (map Term.dest_TFree) tfreess;
   590     val Ds = fold (fold Term.add_tfreesT) (oDs :: Dss) [];
   591 
   592     val ((kill_poss, As), (inners', (unfold_set', lthy'))) =
   593       normalize_bnfs qualify Ass Ds sort inners unfold_set lthy;
   594 
   595     val Ds = oDs @ flat (map3 (append oo map o nth) tfreess kill_poss Dss);
   596     val As = map TFree As;
   597   in
   598     apfst (rpair (Ds, As))
   599       (clean_compose_bnf const_policy (qualify 0) b outer inners' (unfold_set', lthy'))
   600   end;
   601 
   602 (* Hide the type of the bound (optimization) and unfold the definitions (nicer to the user) *)
   603 
   604 fun seal_bnf unfold_set b Ds bnf lthy =
   605   let
   606     val live = live_of_bnf bnf;
   607     val nwits = nwits_of_bnf bnf;
   608 
   609     val (As, lthy1) = apfst (map TFree)
   610       (Variable.invent_types (replicate live HOLogic.typeS) (fold Variable.declare_typ Ds lthy));
   611     val (Bs, _) = apfst (map TFree)
   612       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   613 
   614     val map_unfolds = map_unfolds_of unfold_set;
   615     val set_unfoldss = set_unfoldss_of unfold_set;
   616     val rel_unfolds = rel_unfolds_of unfold_set;
   617     val srel_unfolds = srel_unfolds_of unfold_set;
   618 
   619     val expand_maps =
   620       fold expand_term_const (map (single o Logic.dest_equals o Thm.prop_of) map_unfolds);
   621     val expand_sets =
   622       fold expand_term_const (map (map (Logic.dest_equals o Thm.prop_of)) set_unfoldss);
   623     val expand_rels =
   624       fold expand_term_const (map (single o Logic.dest_equals o Thm.prop_of) rel_unfolds);
   625     val unfold_maps = fold (unfold_thms lthy o single) map_unfolds;
   626     val unfold_sets = fold (unfold_thms lthy) set_unfoldss;
   627     val unfold_rels = unfold_thms lthy rel_unfolds;
   628     val unfold_srels = unfold_thms lthy srel_unfolds;
   629     val unfold_all = unfold_sets o unfold_maps o unfold_rels o unfold_srels;
   630     val bnf_map = expand_maps (mk_map_of_bnf Ds As Bs bnf);
   631     val bnf_sets = map (expand_maps o expand_sets)
   632       (mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf);
   633     val bnf_bd = mk_bd_of_bnf Ds As bnf;
   634     val bnf_rel = expand_rels (mk_rel_of_bnf Ds As Bs bnf);
   635     val T = mk_T_of_bnf Ds As bnf;
   636 
   637     (*bd should only depend on dead type variables!*)
   638     val bd_repT = fst (dest_relT (fastype_of bnf_bd));
   639     val bdT_bind = Binding.suffix_name ("_" ^ bdTN) b;
   640     val params = fold Term.add_tfreesT Ds [];
   641     val deads = map TFree params;
   642 
   643     val ((bdT_name, (bdT_glob_info, bdT_loc_info)), lthy) =
   644       typedef false NONE (bdT_bind, params, NoSyn)
   645         (HOLogic.mk_UNIV bd_repT) NONE (EVERY' [rtac exI, rtac UNIV_I] 1) lthy;
   646 
   647     val bnf_bd' = mk_dir_image bnf_bd
   648       (Const (#Abs_name bdT_glob_info, bd_repT --> Type (bdT_name, deads)))
   649 
   650     val Abs_bdT_inj = mk_Abs_inj_thm (#Abs_inject bdT_loc_info);
   651     val Abs_bdT_bij = mk_Abs_bij_thm lthy Abs_bdT_inj (#Abs_cases bdT_loc_info);
   652 
   653     val bd_ordIso = @{thm dir_image} OF [Abs_bdT_inj, bd_Card_order_of_bnf bnf];
   654     val bd_card_order =
   655       @{thm card_order_dir_image} OF [Abs_bdT_bij, bd_card_order_of_bnf bnf];
   656     val bd_cinfinite =
   657       (@{thm Cinfinite_cong} OF [bd_ordIso, bd_Cinfinite_of_bnf bnf]) RS conjunct1;
   658 
   659     val set_bds =
   660       map (fn thm => @{thm ordLeq_ordIso_trans} OF [thm, bd_ordIso]) (set_bd_of_bnf bnf);
   661     val in_bd =
   662       @{thm ordLeq_ordIso_trans} OF [in_bd_of_bnf bnf,
   663         @{thm cexp_cong2_Cnotzero} OF [bd_ordIso, if live = 0 then
   664           @{thm ctwo_Cnotzero} else @{thm ctwo_Cnotzero} RS @{thm csum_Cnotzero2},
   665             bd_Card_order_of_bnf bnf]];
   666 
   667     fun mk_tac thm {context = ctxt, prems = _} =
   668       (rtac (unfold_all thm) THEN'
   669       SOLVE o REPEAT_DETERM o (atac ORELSE' Goal.assume_rule_tac ctxt)) 1;
   670 
   671     val tacs = zip_axioms (mk_tac (map_id_of_bnf bnf)) (mk_tac (map_comp_of_bnf bnf))
   672       (mk_tac (map_cong_of_bnf bnf)) (map mk_tac (set_natural_of_bnf bnf))
   673       (K (rtac bd_card_order 1)) (K (rtac bd_cinfinite 1)) (map mk_tac set_bds) (mk_tac in_bd)
   674       (mk_tac (map_wpull_of_bnf bnf))
   675       (mk_tac (unfold_thms lthy [srel_def_of_bnf bnf] (srel_O_Gr_of_bnf bnf)));
   676 
   677     val bnf_wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   678 
   679     fun wit_tac _ = mk_simple_wit_tac (map unfold_all (wit_thms_of_bnf bnf));
   680 
   681     val (bnf', lthy') = bnf_def Hardly_Inline (user_policy Dont_Note) I tacs wit_tac (SOME deads)
   682       (((((b, bnf_map), bnf_sets), Term.absdummy T bnf_bd'), bnf_wits), SOME bnf_rel) lthy;
   683   in
   684     ((bnf', deads), lthy')
   685   end;
   686 
   687 fun bnf_of_typ _ _ _ (T as TFree _) accum = ((ID_bnf, ([], [T])), accum)
   688   | bnf_of_typ _ _ _ (TVar _) _ = error "Unexpected schematic variable"
   689   | bnf_of_typ const_policy qualify' sort (T as Type (C, Ts)) (unfold_set, lthy) =
   690     let
   691       val tfrees = Term.add_tfreesT T [];
   692       val bnf_opt = if null tfrees then NONE else bnf_of lthy C;
   693     in
   694       (case bnf_opt of
   695         NONE => ((DEADID_bnf, ([T], [])), (unfold_set, lthy))
   696       | SOME bnf =>
   697         if forall (can Term.dest_TFree) Ts andalso length Ts = length tfrees then
   698           let
   699             val T' = T_of_bnf bnf;
   700             val deads = deads_of_bnf bnf;
   701             val lives = lives_of_bnf bnf;
   702             val tvars' = Term.add_tvarsT T' [];
   703             val deads_lives =
   704               pairself (map (Term.typ_subst_TVars (map fst tvars' ~~ map TFree tfrees)))
   705                 (deads, lives);
   706           in ((bnf, deads_lives), (unfold_set, lthy)) end
   707         else
   708           let
   709             val name = Long_Name.base_name C;
   710             fun qualify i =
   711               let val namei = name ^ nonzero_string_of_int i;
   712               in qualify' o Binding.qualify true namei end;
   713             val odead = dead_of_bnf bnf;
   714             val olive = live_of_bnf bnf;
   715             val oDs_pos = find_indices [TFree ("dead", [])] (snd (Term.dest_Type
   716               (mk_T_of_bnf (replicate odead (TFree ("dead", []))) (replicate olive dummyT) bnf)));
   717             val oDs = map (nth Ts) oDs_pos;
   718             val Ts' = map (nth Ts) (subtract (op =) oDs_pos (0 upto length Ts - 1));
   719             val ((inners, (Dss, Ass)), (unfold_set', lthy')) =
   720               apfst (apsnd split_list o split_list)
   721                 (fold_map2 (fn i => bnf_of_typ Smart_Inline (qualify i) sort)
   722                 (if length Ts' = 1 then [0] else (1 upto length Ts')) Ts' (unfold_set, lthy));
   723           in
   724             compose_bnf const_policy qualify sort bnf inners oDs Dss Ass (unfold_set', lthy')
   725           end)
   726     end;
   727 
   728 end;