src/HOL/BNF/Tools/bnf_comp.ML
author blanchet
Sun Sep 30 23:45:03 2012 +0200 (2012-09-30)
changeset 49669 620fa6272c48
parent 49630 9f6ca87ab405
child 49713 3d07ddf70f8b
permissions -rw-r--r--
fixed quick-and-dirty mode
     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 _ =
   162       mk_comp_map_id_tac (map_id_of_bnf outer) (map_cong_of_bnf outer)
   163         (map map_id_of_bnf inners);
   164 
   165     fun map_comp_tac _ =
   166       mk_comp_map_comp_tac (map_comp_of_bnf outer) (map_cong_of_bnf outer)
   167         (map map_comp_of_bnf inners);
   168 
   169     fun mk_single_set_natural_tac i _ =
   170       mk_comp_set_natural_tac (map_comp_of_bnf outer) (map_cong_of_bnf outer)
   171         (collect_set_natural_of_bnf outer)
   172         (map ((fn thms => nth thms i) o set_natural_of_bnf) inners);
   173 
   174     val set_natural_tacs = map mk_single_set_natural_tac (0 upto ilive - 1);
   175 
   176     fun bd_card_order_tac _ =
   177       mk_comp_bd_card_order_tac (map bd_card_order_of_bnf inners) (bd_card_order_of_bnf outer);
   178 
   179     fun bd_cinfinite_tac _ =
   180       mk_comp_bd_cinfinite_tac (bd_cinfinite_of_bnf inner) (bd_cinfinite_of_bnf outer);
   181 
   182     val set_alt_thms =
   183       if ! quick_and_dirty then
   184         []
   185       else
   186         map (fn goal =>
   187           Skip_Proof.prove lthy [] [] goal
   188             (fn {context, ...} => (mk_comp_set_alt_tac context (collect_set_natural_of_bnf outer)))
   189           |> Thm.close_derivation)
   190         (map2 (curry (HOLogic.mk_Trueprop o HOLogic.mk_eq)) sets sets_alt);
   191 
   192     fun map_cong_tac _ =
   193       mk_comp_map_cong_tac set_alt_thms (map_cong_of_bnf outer) (map map_cong_of_bnf inners);
   194 
   195     val set_bd_tacs =
   196       if ! quick_and_dirty then
   197         replicate ilive (K all_tac)
   198       else
   199         let
   200           val outer_set_bds = set_bd_of_bnf outer;
   201           val inner_set_bdss = map set_bd_of_bnf inners;
   202           val inner_bd_Card_orders = map bd_Card_order_of_bnf inners;
   203           fun single_set_bd_thm i j =
   204             @{thm comp_single_set_bd} OF [nth inner_bd_Card_orders j, nth (nth inner_set_bdss j) i,
   205               nth outer_set_bds j]
   206           val single_set_bd_thmss =
   207             map ((fn f => map f (0 upto olive - 1)) o single_set_bd_thm) (0 upto ilive - 1);
   208         in
   209           map2 (fn set_alt => fn single_set_bds => fn {context, ...} =>
   210             mk_comp_set_bd_tac context set_alt single_set_bds)
   211           set_alt_thms single_set_bd_thmss
   212         end;
   213 
   214     val in_alt_thm =
   215       let
   216         val inx = mk_in Asets sets CCA;
   217         val in_alt = mk_in (map2 (mk_in Asets) inner_setss CAs) outer_sets CCA;
   218         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   219       in
   220         Skip_Proof.prove lthy [] [] goal
   221           (fn {context, ...} => mk_comp_in_alt_tac context set_alt_thms)
   222         |> Thm.close_derivation
   223       end;
   224 
   225     fun in_bd_tac _ =
   226       mk_comp_in_bd_tac in_alt_thm (map in_bd_of_bnf inners) (in_bd_of_bnf outer)
   227         (map bd_Cinfinite_of_bnf inners) (bd_Card_order_of_bnf outer);
   228 
   229     fun map_wpull_tac _ =
   230       mk_map_wpull_tac in_alt_thm (map map_wpull_of_bnf inners) (map_wpull_of_bnf outer);
   231 
   232     fun srel_O_Gr_tac _ =
   233       let
   234         val basic_thms = @{thms mem_Collect_eq fst_conv snd_conv}; (*TODO: tune*)
   235         val outer_srel_Gr = srel_Gr_of_bnf outer RS sym;
   236         val outer_srel_cong = srel_cong_of_bnf outer;
   237         val thm =
   238           (trans OF [in_alt_thm RS @{thm O_Gr_cong},
   239              trans OF [@{thm arg_cong2[of _ _ _ _ relcomp]} OF
   240                [trans OF [outer_srel_Gr RS @{thm arg_cong[of _ _ converse]},
   241                  srel_converse_of_bnf outer RS sym], outer_srel_Gr],
   242                trans OF [srel_O_of_bnf outer RS sym, outer_srel_cong OF
   243                  (map (fn bnf => srel_O_Gr_of_bnf bnf RS sym) inners)]]] RS sym)
   244           |> unfold_thms lthy (basic_thms @ srel_def_of_bnf outer :: map srel_def_of_bnf inners);
   245       in
   246         unfold_thms_tac lthy basic_thms THEN rtac thm 1
   247       end;
   248 
   249     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   250       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   251 
   252     val outer_wits = mk_wits_of_bnf (replicate onwits oDs) (replicate onwits CAs) outer;
   253 
   254     val inner_witss = map (map (fn (I, wit) => Term.list_comb (wit, map (nth xs) I)))
   255       (map3 (fn Ds => fn n => mk_wits_of_bnf (replicate n Ds) (replicate n As))
   256         Dss inwitss inners);
   257 
   258     val inner_witsss = map (map (nth inner_witss) o fst) outer_wits;
   259 
   260     val wits = (inner_witsss, (map (single o snd) outer_wits))
   261       |-> map2 (fold (map_product (fn iwit => fn owit => owit $ iwit)))
   262       |> flat
   263       |> map (`(fn t => Term.add_frees t []))
   264       |> minimize_wits
   265       |> map (fn (frees, t) => fold absfree frees t);
   266 
   267     fun wit_tac {context = ctxt, ...} =
   268       mk_comp_wit_tac ctxt (wit_thms_of_bnf outer) (collect_set_natural_of_bnf outer)
   269         (maps wit_thms_of_bnf inners);
   270 
   271     val (bnf', lthy') =
   272       bnf_def const_policy (K Dont_Note) qualify tacs wit_tac (SOME (oDs @ flat Dss))
   273         (((((b, mapx), sets), bd), wits), SOME rel) lthy;
   274   in
   275     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   276   end;
   277 
   278 (* Killing live variables *)
   279 
   280 fun kill_bnf qualify n bnf (unfold_set, lthy) = if n = 0 then (bnf, (unfold_set, lthy)) else
   281   let
   282     val b = Binding.suffix_name (mk_killN n) (name_of_bnf bnf);
   283     val live = live_of_bnf bnf;
   284     val dead = dead_of_bnf bnf;
   285     val nwits = nwits_of_bnf bnf;
   286 
   287     (* TODO: check 0 < n <= live *)
   288 
   289     val (Ds, lthy1) = apfst (map TFree)
   290       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   291     val ((killedAs, As), lthy2) = apfst (`(take n) o map TFree)
   292       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   293     val (Bs, _(*lthy3*)) = apfst (append killedAs o map TFree)
   294       (Variable.invent_types (replicate (live - n) HOLogic.typeS) lthy2);
   295 
   296     val ((Asets, lives), _(*names_lthy*)) = lthy
   297       |> mk_Frees "A" (map HOLogic.mk_setT (drop n As))
   298       ||>> mk_Frees "x" (drop n As);
   299     val xs = map (fn T => HOLogic.choice_const T $ absdummy T @{term True}) killedAs @ lives;
   300 
   301     val T = mk_T_of_bnf Ds As bnf;
   302 
   303     (*bnf.map id ... id*)
   304     val mapx = Term.list_comb (mk_map_of_bnf Ds As Bs bnf, map HOLogic.id_const killedAs);
   305     (*bnf.rel (op =) ... (op =)*)
   306     val rel = Term.list_comb (mk_rel_of_bnf Ds As Bs bnf, map HOLogic.eq_const killedAs);
   307 
   308     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   309     val sets = drop n bnf_sets;
   310 
   311     (*(|UNIV :: A1 set| +c ... +c |UNIV :: An set|) *c bnf.bd*)
   312     val bnf_bd = mk_bd_of_bnf Ds As bnf;
   313     val bd = mk_cprod
   314       (Library.foldr1 (uncurry mk_csum) (map (mk_card_of o HOLogic.mk_UNIV) killedAs)) bnf_bd;
   315 
   316     fun map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   317     fun map_comp_tac {context, ...} =
   318       unfold_thms_tac context ((map_comp_of_bnf bnf RS sym) :: @{thms o_assoc id_o o_id}) THEN
   319       rtac refl 1;
   320     fun map_cong_tac {context, ...} =
   321       mk_kill_map_cong_tac context n (live - n) (map_cong_of_bnf bnf);
   322     val set_natural_tacs = map (fn thm => fn _ => rtac thm 1) (drop n (set_natural_of_bnf bnf));
   323     fun bd_card_order_tac _ = mk_kill_bd_card_order_tac n (bd_card_order_of_bnf bnf);
   324     fun bd_cinfinite_tac _ = mk_kill_bd_cinfinite_tac (bd_Cinfinite_of_bnf bnf);
   325     val set_bd_tacs =
   326       map (fn thm => fn _ => mk_kill_set_bd_tac (bd_Card_order_of_bnf bnf) thm)
   327         (drop n (set_bd_of_bnf bnf));
   328 
   329     val in_alt_thm =
   330       let
   331         val inx = mk_in Asets sets T;
   332         val in_alt = mk_in (map HOLogic.mk_UNIV killedAs @ Asets) bnf_sets T;
   333         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   334       in
   335         Skip_Proof.prove lthy [] [] goal (K kill_in_alt_tac) |> Thm.close_derivation
   336       end;
   337 
   338     fun in_bd_tac _ =
   339       mk_kill_in_bd_tac n (live > n) in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf)
   340         (bd_Cinfinite_of_bnf bnf) (bd_Cnotzero_of_bnf bnf);
   341     fun map_wpull_tac _ = mk_map_wpull_tac in_alt_thm [] (map_wpull_of_bnf bnf);
   342 
   343     fun srel_O_Gr_tac _ =
   344       let
   345         val srel_Gr = srel_Gr_of_bnf bnf RS sym
   346         val thm =
   347           (trans OF [in_alt_thm RS @{thm O_Gr_cong},
   348             trans OF [@{thm arg_cong2[of _ _ _ _ relcomp]} OF
   349               [trans OF [srel_Gr RS @{thm arg_cong[of _ _ converse]},
   350                 srel_converse_of_bnf bnf RS sym], srel_Gr],
   351               trans OF [srel_O_of_bnf bnf RS sym, srel_cong_of_bnf bnf OF
   352                 (replicate n @{thm trans[OF Gr_UNIV_id[OF refl] Id_alt[symmetric]]} @
   353                  replicate (live - n) @{thm Gr_fst_snd})]]] RS sym)
   354           |> unfold_thms lthy (srel_def_of_bnf bnf :: @{thms Id_def' mem_Collect_eq split_conv});
   355       in
   356         rtac thm 1
   357       end;
   358 
   359     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   360       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   361 
   362     val bnf_wits = mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf;
   363 
   364     val wits = map (fn t => fold absfree (Term.add_frees t []) t)
   365       (map (fn (I, wit) => Term.list_comb (wit, map (nth xs) I)) bnf_wits);
   366 
   367     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   368 
   369     val (bnf', lthy') =
   370       bnf_def Smart_Inline (K Dont_Note) qualify tacs wit_tac (SOME (killedAs @ Ds))
   371         (((((b, mapx), sets), Term.absdummy T bd), wits), SOME rel) lthy;
   372   in
   373     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   374   end;
   375 
   376 (* Adding dummy live variables *)
   377 
   378 fun lift_bnf qualify n bnf (unfold_set, lthy) = if n = 0 then (bnf, (unfold_set, lthy)) else
   379   let
   380     val b = Binding.suffix_name (mk_liftN n) (name_of_bnf bnf);
   381     val live = live_of_bnf bnf;
   382     val dead = dead_of_bnf bnf;
   383     val nwits = nwits_of_bnf bnf;
   384 
   385     (* TODO: check 0 < n *)
   386 
   387     val (Ds, lthy1) = apfst (map TFree)
   388       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   389     val ((newAs, As), lthy2) = apfst (chop n o map TFree)
   390       (Variable.invent_types (replicate (n + live) HOLogic.typeS) lthy1);
   391     val ((newBs, Bs), _(*lthy3*)) = apfst (chop n o map TFree)
   392       (Variable.invent_types (replicate (n + live) HOLogic.typeS) lthy2);
   393 
   394     val (Asets, _(*names_lthy*)) = lthy
   395       |> mk_Frees "A" (map HOLogic.mk_setT (newAs @ As));
   396 
   397     val T = mk_T_of_bnf Ds As bnf;
   398 
   399     (*%f1 ... fn. bnf.map*)
   400     val mapx =
   401       fold_rev Term.absdummy (map2 (curry (op -->)) newAs newBs) (mk_map_of_bnf Ds As Bs bnf);
   402     (*%Q1 ... Qn. bnf.rel*)
   403     val rel = fold_rev Term.absdummy (map2 mk_pred2T newAs newBs) (mk_rel_of_bnf Ds As Bs bnf);
   404 
   405     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   406     val sets = map (fn A => absdummy T (HOLogic.mk_set A [])) newAs @ bnf_sets;
   407 
   408     val bd = mk_bd_of_bnf Ds As bnf;
   409 
   410     fun map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   411     fun map_comp_tac {context, ...} =
   412       unfold_thms_tac context ((map_comp_of_bnf bnf RS sym) :: @{thms o_assoc id_o o_id}) THEN
   413       rtac refl 1;
   414     fun map_cong_tac {context, ...} =
   415       rtac (map_cong_of_bnf bnf) 1 THEN REPEAT_DETERM_N live (Goal.assume_rule_tac context 1);
   416     val set_natural_tacs =
   417       if ! quick_and_dirty then
   418         replicate (n + live) (K all_tac)
   419       else
   420         replicate n (K empty_natural_tac) @
   421         map (fn thm => fn _ => rtac thm 1) (set_natural_of_bnf bnf);
   422     fun bd_card_order_tac _ = rtac (bd_card_order_of_bnf bnf) 1;
   423     fun bd_cinfinite_tac _ = rtac (bd_cinfinite_of_bnf bnf) 1;
   424     val set_bd_tacs =
   425       if ! quick_and_dirty then
   426         replicate (n + live) (K all_tac)
   427       else
   428         replicate n (K (mk_lift_set_bd_tac (bd_Card_order_of_bnf bnf))) @
   429         (map (fn thm => fn _ => rtac thm 1) (set_bd_of_bnf bnf));
   430 
   431     val in_alt_thm =
   432       let
   433         val inx = mk_in Asets sets T;
   434         val in_alt = mk_in (drop n Asets) bnf_sets T;
   435         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   436       in
   437         Skip_Proof.prove lthy [] [] goal (K lift_in_alt_tac) |> Thm.close_derivation
   438       end;
   439 
   440     fun in_bd_tac _ = mk_lift_in_bd_tac n in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf);
   441     fun map_wpull_tac _ = mk_map_wpull_tac in_alt_thm [] (map_wpull_of_bnf bnf);
   442 
   443     fun srel_O_Gr_tac _ =
   444       mk_simple_srel_O_Gr_tac lthy (srel_def_of_bnf bnf) (srel_O_Gr_of_bnf bnf) in_alt_thm;
   445 
   446     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   447       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   448 
   449     val wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   450 
   451     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   452 
   453     val (bnf', lthy') =
   454       bnf_def Smart_Inline (K Dont_Note) qualify tacs wit_tac (SOME Ds)
   455         (((((b, mapx), sets), Term.absdummy T bd), wits), SOME rel) lthy;
   456 
   457   in
   458     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   459   end;
   460 
   461 (* Changing the order of live variables *)
   462 
   463 fun permute_bnf qualify src dest bnf (unfold_set, lthy) =
   464   if src = dest then (bnf, (unfold_set, lthy)) else
   465   let
   466     val b = Binding.suffix_name (mk_permuteN src dest) (name_of_bnf bnf);
   467     val live = live_of_bnf bnf;
   468     val dead = dead_of_bnf bnf;
   469     val nwits = nwits_of_bnf bnf;
   470     fun permute xs = mk_permute src dest xs;
   471     fun permute_rev xs = mk_permute dest src xs;
   472 
   473     val (Ds, lthy1) = apfst (map TFree)
   474       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   475     val (As, lthy2) = apfst (map TFree)
   476       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   477     val (Bs, _(*lthy3*)) = apfst (map TFree)
   478       (Variable.invent_types (replicate live HOLogic.typeS) lthy2);
   479 
   480     val (Asets, _(*names_lthy*)) = lthy
   481       |> mk_Frees "A" (map HOLogic.mk_setT (permute As));
   482 
   483     val T = mk_T_of_bnf Ds As bnf;
   484 
   485     (*%f(1) ... f(n). bnf.map f\<sigma>(1) ... f\<sigma>(n)*)
   486     val mapx = fold_rev Term.absdummy (permute (map2 (curry op -->) As Bs))
   487       (Term.list_comb (mk_map_of_bnf Ds As Bs bnf, permute_rev (map Bound (live - 1 downto 0))));
   488     (*%Q(1) ... Q(n). bnf.rel Q\<sigma>(1) ... Q\<sigma>(n)*)
   489     val rel = fold_rev Term.absdummy (permute (map2 mk_pred2T As Bs))
   490       (Term.list_comb (mk_rel_of_bnf Ds As Bs bnf, permute_rev (map Bound (live - 1 downto 0))));
   491 
   492     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   493     val sets = permute bnf_sets;
   494 
   495     val bd = mk_bd_of_bnf Ds As bnf;
   496 
   497     fun map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   498     fun map_comp_tac _ = rtac (map_comp_of_bnf bnf) 1;
   499     fun map_cong_tac {context, ...} =
   500       rtac (map_cong_of_bnf bnf) 1 THEN REPEAT_DETERM_N live (Goal.assume_rule_tac context 1);
   501     val set_natural_tacs = permute (map (fn thm => fn _ => rtac thm 1) (set_natural_of_bnf bnf));
   502     fun bd_card_order_tac _ = rtac (bd_card_order_of_bnf bnf) 1;
   503     fun bd_cinfinite_tac _ = rtac (bd_cinfinite_of_bnf bnf) 1;
   504     val set_bd_tacs = permute (map (fn thm => fn _ => rtac thm 1) (set_bd_of_bnf bnf));
   505 
   506     val in_alt_thm =
   507       let
   508         val inx = mk_in Asets sets T;
   509         val in_alt = mk_in (permute_rev Asets) bnf_sets T;
   510         val goal = fold_rev Logic.all Asets (mk_Trueprop_eq (inx, in_alt));
   511       in
   512         Skip_Proof.prove lthy [] [] goal (K (mk_permute_in_alt_tac src dest))
   513         |> Thm.close_derivation
   514       end;
   515 
   516     fun in_bd_tac _ =
   517       mk_permute_in_bd_tac src dest in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf);
   518     fun map_wpull_tac _ = mk_map_wpull_tac in_alt_thm [] (map_wpull_of_bnf bnf);
   519 
   520     fun srel_O_Gr_tac _ =
   521       mk_simple_srel_O_Gr_tac lthy (srel_def_of_bnf bnf) (srel_O_Gr_of_bnf bnf) in_alt_thm;
   522 
   523     val tacs = zip_axioms map_id_tac map_comp_tac map_cong_tac set_natural_tacs bd_card_order_tac
   524       bd_cinfinite_tac set_bd_tacs in_bd_tac map_wpull_tac srel_O_Gr_tac;
   525 
   526     val wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   527 
   528     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   529 
   530     val (bnf', lthy') =
   531       bnf_def Smart_Inline (K Dont_Note) qualify tacs wit_tac (SOME Ds)
   532         (((((b, mapx), sets), Term.absdummy T bd), wits), SOME rel) lthy;
   533   in
   534     (bnf', (add_bnf_to_unfolds bnf' unfold_set, lthy'))
   535   end;
   536 
   537 (* Composition pipeline *)
   538 
   539 fun permute_and_kill qualify n src dest bnf =
   540   bnf
   541   |> permute_bnf qualify src dest
   542   #> uncurry (kill_bnf qualify n);
   543 
   544 fun lift_and_permute qualify n src dest bnf =
   545   bnf
   546   |> lift_bnf qualify n
   547   #> uncurry (permute_bnf qualify src dest);
   548 
   549 fun normalize_bnfs qualify Ass Ds sort bnfs unfold_set lthy =
   550   let
   551     val before_kill_src = map (fn As => 0 upto (length As - 1)) Ass;
   552     val kill_poss = map (find_indices Ds) Ass;
   553     val live_poss = map2 (subtract (op =)) kill_poss before_kill_src;
   554     val before_kill_dest = map2 append kill_poss live_poss;
   555     val kill_ns = map length kill_poss;
   556     val (inners', (unfold_set', lthy')) =
   557       fold_map5 (fn i => permute_and_kill (qualify i))
   558         (if length bnfs = 1 then [0] else (1 upto length bnfs))
   559         kill_ns before_kill_src before_kill_dest bnfs (unfold_set, lthy);
   560 
   561     val Ass' = map2 (map o nth) Ass live_poss;
   562     val As = sort Ass';
   563     val after_lift_dest = replicate (length Ass') (0 upto (length As - 1));
   564     val old_poss = map (map (fn x => find_index (fn y => x = y) As)) Ass';
   565     val new_poss = map2 (subtract (op =)) old_poss after_lift_dest;
   566     val after_lift_src = map2 append new_poss old_poss;
   567     val lift_ns = map (fn xs => length As - length xs) Ass';
   568   in
   569     ((kill_poss, As), fold_map5 (fn i => lift_and_permute (qualify i))
   570       (if length bnfs = 1 then [0] else (1 upto length bnfs))
   571       lift_ns after_lift_src after_lift_dest inners' (unfold_set', lthy'))
   572   end;
   573 
   574 fun default_comp_sort Ass =
   575   Library.sort (Term_Ord.typ_ord o pairself TFree) (fold (fold (insert (op =))) Ass []);
   576 
   577 fun compose_bnf const_policy qualify sort outer inners oDs Dss tfreess (unfold_set, lthy) =
   578   let
   579     val b = name_of_bnf outer;
   580 
   581     val Ass = map (map Term.dest_TFree) tfreess;
   582     val Ds = fold (fold Term.add_tfreesT) (oDs :: Dss) [];
   583 
   584     val ((kill_poss, As), (inners', (unfold_set', lthy'))) =
   585       normalize_bnfs qualify Ass Ds sort inners unfold_set lthy;
   586 
   587     val Ds = oDs @ flat (map3 (append oo map o nth) tfreess kill_poss Dss);
   588     val As = map TFree As;
   589   in
   590     apfst (rpair (Ds, As))
   591       (clean_compose_bnf const_policy (qualify 0) b outer inners' (unfold_set', lthy'))
   592   end;
   593 
   594 (* Hide the type of the bound (optimization) and unfold the definitions (nicer to the user) *)
   595 
   596 fun seal_bnf unfold_set b Ds bnf lthy =
   597   let
   598     val live = live_of_bnf bnf;
   599     val nwits = nwits_of_bnf bnf;
   600 
   601     val (As, lthy1) = apfst (map TFree)
   602       (Variable.invent_types (replicate live HOLogic.typeS) (fold Variable.declare_typ Ds lthy));
   603     val (Bs, _) = apfst (map TFree)
   604       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   605 
   606     val map_unfolds = map_unfolds_of unfold_set;
   607     val set_unfoldss = set_unfoldss_of unfold_set;
   608     val rel_unfolds = rel_unfolds_of unfold_set;
   609     val srel_unfolds = srel_unfolds_of unfold_set;
   610 
   611     val expand_maps =
   612       fold expand_term_const (map (single o Logic.dest_equals o Thm.prop_of) map_unfolds);
   613     val expand_sets =
   614       fold expand_term_const (map (map (Logic.dest_equals o Thm.prop_of)) set_unfoldss);
   615     val expand_rels =
   616       fold expand_term_const (map (single o Logic.dest_equals o Thm.prop_of) rel_unfolds);
   617     val unfold_maps = fold (unfold_thms lthy o single) map_unfolds;
   618     val unfold_sets = fold (unfold_thms lthy) set_unfoldss;
   619     val unfold_rels = unfold_thms lthy rel_unfolds;
   620     val unfold_srels = unfold_thms lthy srel_unfolds;
   621     val unfold_all = unfold_sets o unfold_maps o unfold_rels o unfold_srels;
   622     val bnf_map = expand_maps (mk_map_of_bnf Ds As Bs bnf);
   623     val bnf_sets = map (expand_maps o expand_sets)
   624       (mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf);
   625     val bnf_bd = mk_bd_of_bnf Ds As bnf;
   626     val bnf_rel = expand_rels (mk_rel_of_bnf Ds As Bs bnf);
   627     val T = mk_T_of_bnf Ds As bnf;
   628 
   629     (*bd should only depend on dead type variables!*)
   630     val bd_repT = fst (dest_relT (fastype_of bnf_bd));
   631     val bdT_bind = Binding.suffix_name ("_" ^ bdTN) b;
   632     val params = fold Term.add_tfreesT Ds [];
   633     val deads = map TFree params;
   634 
   635     val ((bdT_name, (bdT_glob_info, bdT_loc_info)), lthy) =
   636       typedef false NONE (bdT_bind, params, NoSyn)
   637         (HOLogic.mk_UNIV bd_repT) NONE (EVERY' [rtac exI, rtac UNIV_I] 1) lthy;
   638 
   639     val bnf_bd' = mk_dir_image bnf_bd
   640       (Const (#Abs_name bdT_glob_info, bd_repT --> Type (bdT_name, deads)))
   641 
   642     val Abs_bdT_inj = mk_Abs_inj_thm (#Abs_inject bdT_loc_info);
   643     val Abs_bdT_bij = mk_Abs_bij_thm lthy Abs_bdT_inj (#Abs_cases bdT_loc_info);
   644 
   645     val bd_ordIso = @{thm dir_image} OF [Abs_bdT_inj, bd_Card_order_of_bnf bnf];
   646     val bd_card_order =
   647       @{thm card_order_dir_image} OF [Abs_bdT_bij, bd_card_order_of_bnf bnf];
   648     val bd_cinfinite =
   649       (@{thm Cinfinite_cong} OF [bd_ordIso, bd_Cinfinite_of_bnf bnf]) RS conjunct1;
   650 
   651     val set_bds =
   652       map (fn thm => @{thm ordLeq_ordIso_trans} OF [thm, bd_ordIso]) (set_bd_of_bnf bnf);
   653     val in_bd =
   654       @{thm ordLeq_ordIso_trans} OF [in_bd_of_bnf bnf,
   655         @{thm cexp_cong2_Cnotzero} OF [bd_ordIso, if live = 0 then
   656           @{thm ctwo_Cnotzero} else @{thm ctwo_Cnotzero} RS @{thm csum_Cnotzero2},
   657             bd_Card_order_of_bnf bnf]];
   658 
   659     fun mk_tac thm {context = ctxt, prems = _} =
   660       (rtac (unfold_all thm) THEN'
   661       SOLVE o REPEAT_DETERM o (atac ORELSE' Goal.assume_rule_tac ctxt)) 1;
   662 
   663     val tacs = zip_axioms (mk_tac (map_id_of_bnf bnf)) (mk_tac (map_comp_of_bnf bnf))
   664       (mk_tac (map_cong_of_bnf bnf)) (map mk_tac (set_natural_of_bnf bnf))
   665       (K (rtac bd_card_order 1)) (K (rtac bd_cinfinite 1)) (map mk_tac set_bds) (mk_tac in_bd)
   666       (mk_tac (map_wpull_of_bnf bnf))
   667       (mk_tac (unfold_thms lthy [srel_def_of_bnf bnf] (srel_O_Gr_of_bnf bnf)));
   668 
   669     val bnf_wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   670 
   671     fun wit_tac _ = mk_simple_wit_tac (map unfold_all (wit_thms_of_bnf bnf));
   672 
   673     val (bnf', lthy') = bnf_def Hardly_Inline (user_policy Dont_Note) I tacs wit_tac (SOME deads)
   674       (((((b, bnf_map), bnf_sets), Term.absdummy T bnf_bd'), bnf_wits), SOME bnf_rel) lthy;
   675   in
   676     ((bnf', deads), lthy')
   677   end;
   678 
   679 fun bnf_of_typ _ _ _ (T as TFree _) accum = ((ID_bnf, ([], [T])), accum)
   680   | bnf_of_typ _ _ _ (TVar _) _ = error "Unexpected schematic variable"
   681   | bnf_of_typ const_policy qualify' sort (T as Type (C, Ts)) (unfold_set, lthy) =
   682     let
   683       val tfrees = Term.add_tfreesT T [];
   684       val bnf_opt = if null tfrees then NONE else bnf_of lthy C;
   685     in
   686       (case bnf_opt of
   687         NONE => ((DEADID_bnf, ([T], [])), (unfold_set, lthy))
   688       | SOME bnf =>
   689         if forall (can Term.dest_TFree) Ts andalso length Ts = length tfrees then
   690           let
   691             val T' = T_of_bnf bnf;
   692             val deads = deads_of_bnf bnf;
   693             val lives = lives_of_bnf bnf;
   694             val tvars' = Term.add_tvarsT T' [];
   695             val deads_lives =
   696               pairself (map (Term.typ_subst_TVars (map fst tvars' ~~ map TFree tfrees)))
   697                 (deads, lives);
   698           in ((bnf, deads_lives), (unfold_set, lthy)) end
   699         else
   700           let
   701             val name = Long_Name.base_name C;
   702             fun qualify i =
   703               let val namei = name ^ nonzero_string_of_int i;
   704               in qualify' o Binding.qualify true namei end;
   705             val odead = dead_of_bnf bnf;
   706             val olive = live_of_bnf bnf;
   707             val oDs_pos = find_indices [TFree ("dead", [])] (snd (Term.dest_Type
   708               (mk_T_of_bnf (replicate odead (TFree ("dead", []))) (replicate olive dummyT) bnf)));
   709             val oDs = map (nth Ts) oDs_pos;
   710             val Ts' = map (nth Ts) (subtract (op =) oDs_pos (0 upto length Ts - 1));
   711             val ((inners, (Dss, Ass)), (unfold_set', lthy')) =
   712               apfst (apsnd split_list o split_list)
   713                 (fold_map2 (fn i => bnf_of_typ Smart_Inline (qualify i) sort)
   714                 (if length Ts' = 1 then [0] else (1 upto length Ts')) Ts' (unfold_set, lthy));
   715           in
   716             compose_bnf const_policy qualify sort bnf inners oDs Dss Ass (unfold_set', lthy')
   717           end)
   718     end;
   719 
   720 end;