src/HOL/Codatatype/Tools/bnf_comp.ML
author blanchet
Thu Aug 30 09:47:46 2012 +0200 (2012-08-30)
changeset 49018 b2884253b421
parent 49016 640ce226a973
child 49019 fc4decdba5ce
permissions -rw-r--r--
renamed ML function for consistency
     1 (*  Title:      HOL/Codatatype/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   type unfold_thms
    12   val empty_unfold: unfold_thms
    13   val map_unfolds_of: unfold_thms -> thm list
    14   val set_unfoldss_of: unfold_thms -> thm list list
    15   val rel_unfolds_of: unfold_thms -> thm list
    16   val pred_unfolds_of: unfold_thms -> thm list
    17 
    18   val bnf_of_typ: BNF_Def.const_policy -> binding -> (binding -> binding) ->
    19     ((string * sort) list list -> (string * sort) list) -> typ -> unfold_thms * Proof.context ->
    20     (BNF_Def.BNF * (typ list * typ list)) * (unfold_thms * Proof.context)
    21   val default_comp_sort: (string * sort) list list -> (string * sort) list
    22   val normalize_bnfs: (int -> binding -> binding) -> ''a list list -> ''a list ->
    23     (''a list list -> ''a list) -> BNF_Def.BNF list -> unfold_thms -> Proof.context ->
    24     (int list list * ''a list) * (BNF_Def.BNF list * (unfold_thms * Proof.context))
    25   val seal_bnf: unfold_thms -> binding -> typ list -> BNF_Def.BNF -> Proof.context ->
    26     BNF_Def.BNF * local_theory
    27 end;
    28 
    29 structure BNF_Comp : BNF_COMP =
    30 struct
    31 
    32 open BNF_Def
    33 open BNF_Util
    34 open BNF_Tactics
    35 open BNF_Comp_Tactics
    36 
    37 type unfold_thms = {
    38   map_unfolds: thm list,
    39   set_unfoldss: thm list list,
    40   rel_unfolds: thm list,
    41   pred_unfolds: thm list
    42 };
    43 
    44 fun add_to_thms thms NONE = thms
    45   | add_to_thms thms (SOME new) = if Thm.is_reflexive new then thms else insert Thm.eq_thm new thms;
    46 fun adds_to_thms thms NONE = thms
    47   | adds_to_thms thms (SOME news) = insert (eq_set Thm.eq_thm) (filter_refl news) thms;
    48 
    49 fun mk_unfold_thms maps setss rels preds =
    50   {map_unfolds = maps, set_unfoldss = setss, rel_unfolds = rels, pred_unfolds = preds};
    51 
    52 val empty_unfold = mk_unfold_thms [] [] [] [];
    53 
    54 fun add_to_unfold_opt map_opt sets_opt rel_opt pred_opt
    55   {map_unfolds = maps, set_unfoldss = setss, rel_unfolds = rels, pred_unfolds = preds} = {
    56     map_unfolds = add_to_thms maps map_opt,
    57     set_unfoldss = adds_to_thms setss sets_opt,
    58     rel_unfolds = add_to_thms rels rel_opt,
    59     pred_unfolds = add_to_thms preds pred_opt};
    60 
    61 fun add_to_unfold map sets rel pred =
    62   add_to_unfold_opt (SOME map) (SOME sets) (SOME rel) (SOME pred);
    63 
    64 val map_unfolds_of = #map_unfolds;
    65 val set_unfoldss_of = #set_unfoldss;
    66 val rel_unfolds_of = #rel_unfolds;
    67 val pred_unfolds_of = #pred_unfolds;
    68 
    69 val bdTN = "bdT";
    70 
    71 val compN = "comp_"
    72 fun mk_killN n = "kill" ^ string_of_int n ^ "_";
    73 fun mk_liftN n = "lift" ^ string_of_int n ^ "_";
    74 fun mk_permuteN src dest =
    75   "permute_" ^ implode (map string_of_int src) ^ "_" ^ implode (map string_of_int dest) ^ "_";
    76 
    77 val no_thm = refl;
    78 val Collect_split_box_equals = box_equals RS @{thm Collect_split_cong};
    79 val abs_pred_sym = sym RS @{thm abs_pred_def};
    80 val abs_pred_sym_pred_abs = abs_pred_sym RS @{thm pred_def_abs};
    81 
    82 (*copied from Envir.expand_term_free*)
    83 fun expand_term_const defs =
    84   let
    85     val eqs = map ((fn ((x, U), u) => (x, (U, u))) o apfst dest_Const) defs;
    86     val get = fn Const (x, _) => AList.lookup (op =) eqs x | _ => NONE;
    87   in Envir.expand_term get end;
    88 
    89 fun clean_compose_bnf const_policy qualify b outer inners (unfold, lthy) =
    90   let
    91     val olive = live_of_bnf outer;
    92     val onwits = nwits_of_bnf outer;
    93     val odead = dead_of_bnf outer;
    94     val inner = hd inners;
    95     val ilive = live_of_bnf inner;
    96     val ideads = map dead_of_bnf inners;
    97     val inwitss = map nwits_of_bnf inners;
    98 
    99     (* TODO: check olive = length inners > 0,
   100                    forall inner from inners. ilive = live,
   101                    forall inner from inners. idead = dead  *)
   102 
   103     val (oDs, lthy1) = apfst (map TFree)
   104       (Variable.invent_types (replicate odead HOLogic.typeS) lthy);
   105     val (Dss, lthy2) = apfst (map (map TFree))
   106         (fold_map Variable.invent_types (map (fn n => replicate n HOLogic.typeS) ideads) lthy1);
   107     val (Ass, lthy3) = apfst (replicate ilive o map TFree)
   108       (Variable.invent_types (replicate ilive HOLogic.typeS) lthy2);
   109     val As = if ilive > 0 then hd Ass else [];
   110     val Ass_repl = replicate olive As;
   111     val (Bs, _(*lthy4*)) = apfst (map TFree)
   112       (Variable.invent_types (replicate ilive HOLogic.typeS) lthy3);
   113     val Bss_repl = replicate olive Bs;
   114 
   115     val (((fs', Asets), xs), _(*names_lthy*)) = lthy
   116       |> apfst snd o mk_Frees' "f" (map2 (curry (op -->)) As Bs)
   117       ||>> mk_Frees "A" (map (HOLogic.mk_setT) As)
   118       ||>> mk_Frees "x" As;
   119 
   120     val CAs = map3 mk_T_of_bnf Dss Ass_repl inners;
   121     val CCA = mk_T_of_bnf oDs CAs outer;
   122     val CBs = map3 mk_T_of_bnf Dss Bss_repl inners;
   123     val outer_sets = mk_sets_of_bnf (replicate olive oDs) (replicate olive CAs) outer;
   124     val inner_setss = map3 mk_sets_of_bnf (map (replicate ilive) Dss) (replicate olive Ass) inners;
   125     val inner_bds = map3 mk_bd_of_bnf Dss Ass_repl inners;
   126     val outer_bd = mk_bd_of_bnf oDs CAs outer;
   127 
   128     (*%f1 ... fn. outer.map (inner_1.map f1 ... fn) ... (inner_m.map f1 ... fn)*)
   129     val comp_map = fold_rev Term.abs fs'
   130       (Term.list_comb (mk_map_of_bnf oDs CAs CBs outer,
   131         map2 (fn Ds => (fn f => Term.list_comb (f, map Bound ((ilive - 1) downto 0))) o
   132           mk_map_of_bnf Ds As Bs) Dss inners));
   133 
   134     (*Union o collect {outer.set_1 ... outer.set_m} o outer.map inner_1.set_i ... inner_m.set_i*)
   135     (*Union o collect {image inner_1.set_i o outer.set_1 ... image inner_m.set_i o outer.set_m}*)
   136     fun mk_comp_set i =
   137       let
   138         val (setTs, T) = `(replicate olive o HOLogic.mk_setT) (nth As i);
   139         val outer_set = mk_collect
   140           (mk_sets_of_bnf (replicate olive oDs) (replicate olive setTs) outer)
   141           (mk_T_of_bnf oDs setTs outer --> HOLogic.mk_setT T);
   142         val inner_sets = map (fn sets => nth sets i) inner_setss;
   143         val outer_map = mk_map_of_bnf oDs CAs setTs outer;
   144         val map_inner_sets = Term.list_comb (outer_map, inner_sets);
   145         val collect_image = mk_collect
   146           (map2 (fn f => fn set => HOLogic.mk_comp (mk_image f, set)) inner_sets outer_sets)
   147           (CCA --> HOLogic.mk_setT T);
   148       in
   149         (Library.foldl1 HOLogic.mk_comp [mk_Union T, outer_set, map_inner_sets],
   150         HOLogic.mk_comp (mk_Union T, collect_image))
   151       end;
   152 
   153     val (comp_sets, comp_sets_alt) = map_split mk_comp_set (0 upto ilive - 1);
   154 
   155     (*(inner_1.bd +c ... +c inner_m.bd) *c outer.bd*)
   156     val comp_bd = Term.absdummy CCA (mk_cprod
   157       (Library.foldr1 (uncurry mk_csum) inner_bds) outer_bd);
   158 
   159     fun comp_map_id_tac {context = ctxt, ...} =
   160       let
   161         (*order the theorems by reverse size to prevent bad interaction with nonconfluent rewrite
   162           rules*)
   163         val thms = (map map_id_of_bnf inners
   164           |> map (`(Term.size_of_term o Thm.prop_of))
   165           |> sort (rev_order o int_ord o pairself fst)
   166           |> map snd) @ [map_id_of_bnf outer];
   167       in
   168         (EVERY' (map (fn thm => subst_tac ctxt [thm]) thms) THEN' rtac refl) 1
   169       end;
   170 
   171     fun comp_map_comp_tac _ =
   172       mk_comp_map_comp_tac (map_comp_of_bnf outer) (map_cong_of_bnf outer)
   173         (map map_comp_of_bnf inners);
   174 
   175     fun mk_single_comp_set_natural_tac i _ =
   176       mk_comp_set_natural_tac (map_comp_of_bnf outer) (map_cong_of_bnf outer)
   177         (collect_set_natural_of_bnf outer)
   178         (map ((fn thms => nth thms i) o set_natural_of_bnf) inners);
   179 
   180     val comp_set_natural_tacs = map mk_single_comp_set_natural_tac (0 upto ilive - 1);
   181 
   182     fun comp_bd_card_order_tac _ =
   183       mk_comp_bd_card_order_tac (map bd_card_order_of_bnf inners) (bd_card_order_of_bnf outer);
   184 
   185     fun comp_bd_cinfinite_tac _ =
   186       mk_comp_bd_cinfinite_tac (bd_cinfinite_of_bnf inner) (bd_cinfinite_of_bnf outer);
   187 
   188     val comp_set_alt_thms =
   189       if ! quick_and_dirty then
   190         replicate ilive no_thm
   191       else
   192         map (fn goal => Skip_Proof.prove lthy [] [] goal
   193         (fn {context, ...} => (mk_comp_set_alt_tac context (collect_set_natural_of_bnf outer))))
   194         (map2 (curry (HOLogic.mk_Trueprop o HOLogic.mk_eq)) comp_sets comp_sets_alt);
   195 
   196     fun comp_map_cong_tac _ =
   197       mk_comp_map_cong_tac comp_set_alt_thms (map_cong_of_bnf outer) (map map_cong_of_bnf inners);
   198 
   199     val comp_set_bd_tacs =
   200       if ! quick_and_dirty then
   201         replicate (length comp_set_alt_thms) (K all_tac)
   202       else
   203         let
   204           val outer_set_bds = set_bd_of_bnf outer;
   205           val inner_set_bdss = map set_bd_of_bnf inners;
   206           val inner_bd_Card_orders = map bd_Card_order_of_bnf inners;
   207           fun comp_single_set_bd_thm i j =
   208             @{thm comp_single_set_bd} OF [nth inner_bd_Card_orders j, nth (nth inner_set_bdss j) i,
   209               nth outer_set_bds j]
   210           val single_set_bd_thmss =
   211             map ((fn f => map f (0 upto olive - 1)) o comp_single_set_bd_thm) (0 upto ilive - 1);
   212         in
   213           map2 (fn comp_set_alt => fn single_set_bds => fn {context, ...} =>
   214             mk_comp_set_bd_tac context comp_set_alt single_set_bds)
   215           comp_set_alt_thms single_set_bd_thmss
   216         end;
   217 
   218     val comp_in_alt_thm =
   219       if ! quick_and_dirty then
   220         no_thm
   221       else
   222         let
   223           val comp_in = mk_in Asets comp_sets CCA;
   224           val comp_in_alt = mk_in (map2 (mk_in Asets) inner_setss CAs) outer_sets CCA;
   225           val goal =
   226             fold_rev Logic.all Asets
   227               (HOLogic.mk_Trueprop (HOLogic.mk_eq (comp_in, comp_in_alt)));
   228         in
   229           Skip_Proof.prove lthy [] [] goal
   230             (fn {context, ...} => mk_comp_in_alt_tac context comp_set_alt_thms)
   231         end;
   232 
   233     fun comp_in_bd_tac _ =
   234       mk_comp_in_bd_tac comp_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 comp_map_wpull_tac _ =
   238       mk_map_wpull_tac comp_in_alt_thm (map map_wpull_of_bnf inners) (map_wpull_of_bnf outer);
   239 
   240     val tacs = [comp_map_id_tac, comp_map_comp_tac, comp_map_cong_tac] @ comp_set_natural_tacs @
   241       [comp_bd_card_order_tac, comp_bd_cinfinite_tac] @ comp_set_bd_tacs @
   242       [comp_in_bd_tac, comp_map_wpull_tac];
   243 
   244     val outer_wits = mk_wits_of_bnf (replicate onwits oDs) (replicate onwits CAs) outer;
   245 
   246     val inner_witss = map (map (fn (I, wit) => Term.list_comb (wit, map (nth xs) I)))
   247       (map3 (fn Ds => fn n => mk_wits_of_bnf (replicate n Ds) (replicate n As))
   248         Dss inwitss inners);
   249 
   250     val inner_witsss = map (map (nth inner_witss) o fst) outer_wits;
   251 
   252     val comp_wits = (inner_witsss, (map (single o snd) outer_wits))
   253       |-> map2 (fold (map_product (fn iwit => fn owit => owit $ iwit)))
   254       |> flat
   255       |> map (`(fn t => Term.add_frees t []))
   256       |> minimize_wits
   257       |> map (fn (frees, t) => fold absfree frees t);
   258 
   259     fun wit_tac {context = ctxt, ...} =
   260       mk_comp_wit_tac ctxt (wit_thms_of_bnf outer) (collect_set_natural_of_bnf outer)
   261         (maps wit_thms_of_bnf inners);
   262 
   263     val (bnf', lthy') =
   264       bnf_def const_policy (K Derive_Some_Facts) qualify tacs wit_tac (SOME (oDs @ flat Dss))
   265         ((((b, comp_map), comp_sets), comp_bd), comp_wits) lthy;
   266 
   267     val outer_rel_Gr = rel_Gr_of_bnf outer RS sym;
   268     val outer_rel_cong = rel_cong_of_bnf outer;
   269 
   270     val comp_rel_unfold_thm =
   271       trans OF [rel_def_of_bnf bnf',
   272         trans OF [comp_in_alt_thm RS @{thm subst_rel_def},
   273           trans OF [@{thm arg_cong2[of _ _ _ _ relcomp]} OF
   274             [trans OF [outer_rel_Gr RS @{thm arg_cong[of _ _ converse]},
   275               rel_converse_of_bnf outer RS sym], outer_rel_Gr],
   276             trans OF [rel_O_of_bnf outer RS sym, outer_rel_cong OF
   277               (map (fn bnf => rel_def_of_bnf bnf RS sym) inners)]]]];
   278 
   279     val comp_pred_unfold_thm = Collect_split_box_equals OF [comp_rel_unfold_thm,
   280       pred_def_of_bnf bnf' RS abs_pred_sym,
   281         trans OF [outer_rel_cong OF (map (fn bnf => pred_def_of_bnf bnf RS abs_pred_sym) inners),
   282           pred_def_of_bnf outer RS abs_pred_sym]];
   283 
   284     val unfold' = add_to_unfold (map_def_of_bnf bnf') (set_defs_of_bnf bnf')
   285       comp_rel_unfold_thm comp_pred_unfold_thm unfold;
   286   in
   287     (bnf', (unfold', lthy'))
   288   end;
   289 
   290 (* Killing live variables *)
   291 
   292 fun killN_bnf qualify n bnf (unfold, lthy) = if n = 0 then (bnf, (unfold, lthy)) else
   293   let
   294     val b = Binding.prefix_name (mk_killN n) (name_of_bnf bnf);
   295     val live = live_of_bnf bnf;
   296     val dead = dead_of_bnf bnf;
   297     val nwits = nwits_of_bnf bnf;
   298 
   299     (* TODO: check 0 < n <= live *)
   300 
   301     val (Ds, lthy1) = apfst (map TFree)
   302       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   303     val ((killedAs, As), lthy2) = apfst (`(take n) o map TFree)
   304       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   305     val (Bs, _(*lthy3*)) = apfst (append killedAs o map TFree)
   306       (Variable.invent_types (replicate (live - n) HOLogic.typeS) lthy2);
   307 
   308     val ((Asets, lives), _(*names_lthy*)) = lthy
   309       |> mk_Frees "A" (map (HOLogic.mk_setT) (drop n As))
   310       ||>> mk_Frees "x" (drop n As);
   311     val xs = map (fn T => HOLogic.choice_const T $ absdummy T @{term True}) killedAs @ lives;
   312 
   313     val T = mk_T_of_bnf Ds As bnf;
   314 
   315     (*bnf.map id ... id*)
   316     val killN_map = Term.list_comb (mk_map_of_bnf Ds As Bs bnf, map HOLogic.id_const killedAs);
   317 
   318     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   319     val killN_sets = drop n bnf_sets;
   320 
   321     (*(|UNIV :: A1 set| +c ... +c |UNIV :: An set|) *c bnf.bd*)
   322     val bnf_bd = mk_bd_of_bnf Ds As bnf;
   323     val killN_bd = mk_cprod
   324       (Library.foldr1 (uncurry mk_csum) (map (mk_card_of o HOLogic.mk_UNIV) killedAs)) bnf_bd;
   325 
   326     fun killN_map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   327     fun killN_map_comp_tac {context, ...} =
   328       Local_Defs.unfold_tac context ((map_comp_of_bnf bnf RS sym) :: @{thms o_assoc id_o o_id}) THEN
   329       rtac refl 1;
   330     fun killN_map_cong_tac {context, ...} =
   331       mk_killN_map_cong_tac context n (live - n) (map_cong_of_bnf bnf);
   332     val killN_set_natural_tacs =
   333       map (fn thm => fn _ => rtac thm 1) (drop n (set_natural_of_bnf bnf));
   334     fun killN_bd_card_order_tac _ = mk_killN_bd_card_order_tac n (bd_card_order_of_bnf bnf);
   335     fun killN_bd_cinfinite_tac _ = mk_killN_bd_cinfinite_tac (bd_Cinfinite_of_bnf bnf);
   336     val killN_set_bd_tacs =
   337       map (fn thm => fn _ => mk_killN_set_bd_tac (bd_Card_order_of_bnf bnf) thm)
   338         (drop n (set_bd_of_bnf bnf));
   339 
   340     val killN_in_alt_thm =
   341       if ! quick_and_dirty then
   342         no_thm
   343       else
   344         let
   345           val killN_in = mk_in Asets killN_sets T;
   346           val killN_in_alt = mk_in (map HOLogic.mk_UNIV killedAs @ Asets) bnf_sets T;
   347           val goal =
   348             fold_rev Logic.all Asets (HOLogic.mk_Trueprop (HOLogic.mk_eq (killN_in, killN_in_alt)));
   349         in
   350           Skip_Proof.prove lthy [] [] goal (K killN_in_alt_tac)
   351         end;
   352 
   353     fun killN_in_bd_tac _ =
   354       mk_killN_in_bd_tac n (live > n) killN_in_alt_thm (in_bd_of_bnf bnf)
   355          (bd_Card_order_of_bnf bnf) (bd_Cinfinite_of_bnf bnf) (bd_Cnotzero_of_bnf bnf);
   356     fun killN_map_wpull_tac _ =
   357       mk_map_wpull_tac killN_in_alt_thm [] (map_wpull_of_bnf bnf);
   358 
   359     val tacs = [killN_map_id_tac, killN_map_comp_tac, killN_map_cong_tac] @ killN_set_natural_tacs @
   360       [killN_bd_card_order_tac, killN_bd_cinfinite_tac] @ killN_set_bd_tacs @
   361       [killN_in_bd_tac, killN_map_wpull_tac];
   362 
   363     val wits = mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf;
   364 
   365     val killN_wits = map (fn t => fold absfree (Term.add_frees t []) t)
   366       (map (fn (I, wit) => Term.list_comb (wit, map (nth xs) I)) wits);
   367 
   368     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   369 
   370     val (bnf', lthy') =
   371       bnf_def Smart_Inline (K Derive_Some_Facts) qualify tacs wit_tac (SOME (killedAs @ Ds))
   372         ((((b, killN_map), killN_sets), Term.absdummy T killN_bd), killN_wits) lthy;
   373 
   374     val rel_Gr = rel_Gr_of_bnf bnf RS sym;
   375 
   376     val killN_rel_unfold_thm =
   377       trans OF [rel_def_of_bnf bnf',
   378         trans OF [killN_in_alt_thm RS @{thm subst_rel_def},
   379           trans OF [@{thm arg_cong2[of _ _ _ _ relcomp]} OF
   380             [trans OF [rel_Gr RS @{thm arg_cong[of _ _ converse]}, rel_converse_of_bnf bnf RS sym],
   381               rel_Gr],
   382             trans OF [rel_O_of_bnf bnf RS sym, rel_cong_of_bnf bnf OF
   383               (replicate n @{thm trans[OF Gr_UNIV_id[OF refl] Id_alt[symmetric]]} @
   384                replicate (live - n) @{thm Gr_fst_snd})]]]];
   385 
   386     val killN_pred_unfold_thm = Collect_split_box_equals OF
   387       [Local_Defs.unfold lthy' @{thms Id_def'} killN_rel_unfold_thm,
   388         pred_def_of_bnf bnf' RS abs_pred_sym, pred_def_of_bnf bnf RS abs_pred_sym];
   389 
   390     val unfold' = add_to_unfold (map_def_of_bnf bnf') (set_defs_of_bnf bnf')
   391       killN_rel_unfold_thm killN_pred_unfold_thm unfold;
   392   in
   393     (bnf', (unfold', lthy'))
   394   end;
   395 
   396 (* Adding dummy live variables *)
   397 
   398 fun liftN_bnf qualify n bnf (unfold, lthy) = if n = 0 then (bnf, (unfold, lthy)) else
   399   let
   400     val b = Binding.prefix_name (mk_liftN n) (name_of_bnf bnf);
   401     val live = live_of_bnf bnf;
   402     val dead = dead_of_bnf bnf;
   403     val nwits = nwits_of_bnf bnf;
   404 
   405     (* TODO: check 0 < n *)
   406 
   407     val (Ds, lthy1) = apfst (map TFree)
   408       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   409     val ((newAs, As), lthy2) = apfst (chop n o map TFree)
   410       (Variable.invent_types (replicate (n + live) HOLogic.typeS) lthy1);
   411     val ((newBs, Bs), _(*lthy3*)) = apfst (chop n o map TFree)
   412       (Variable.invent_types (replicate (n + live) HOLogic.typeS) lthy2);
   413 
   414     val (Asets, _(*names_lthy*)) = lthy
   415       |> mk_Frees "A" (map (HOLogic.mk_setT) (newAs @ As));
   416 
   417     val T = mk_T_of_bnf Ds As bnf;
   418 
   419     (*%f1 ... fn. bnf.map*)
   420     val liftN_map =
   421       fold_rev Term.absdummy (map2 (curry (op -->)) newAs newBs) (mk_map_of_bnf Ds As Bs bnf);
   422 
   423     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   424     val liftN_sets = map (fn A => absdummy T (HOLogic.mk_set A [])) newAs @ bnf_sets;
   425 
   426     val liftN_bd = mk_bd_of_bnf Ds As bnf;
   427 
   428     fun liftN_map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   429     fun liftN_map_comp_tac {context, ...} =
   430       Local_Defs.unfold_tac context ((map_comp_of_bnf bnf RS sym) :: @{thms o_assoc id_o o_id}) THEN
   431       rtac refl 1;
   432     fun liftN_map_cong_tac {context, ...} =
   433       rtac (map_cong_of_bnf bnf) 1 THEN REPEAT_DETERM_N live (Goal.assume_rule_tac context 1);
   434     val liftN_set_natural_tacs =
   435       if ! quick_and_dirty then
   436         replicate (n + live) (K all_tac)
   437       else
   438         replicate n (K empty_natural_tac) @
   439         map (fn thm => fn _ => rtac thm 1) (set_natural_of_bnf bnf);
   440     fun liftN_bd_card_order_tac _ = rtac (bd_card_order_of_bnf bnf) 1;
   441     fun liftN_bd_cinfinite_tac _ = rtac (bd_cinfinite_of_bnf bnf) 1;
   442     val liftN_set_bd_tacs =
   443       if ! quick_and_dirty then
   444         replicate (n + live) (K all_tac)
   445       else
   446         replicate n (K (mk_liftN_set_bd_tac (bd_Card_order_of_bnf bnf))) @
   447         (map (fn thm => fn _ => rtac thm 1) (set_bd_of_bnf bnf));
   448 
   449     val liftN_in_alt_thm =
   450       if ! quick_and_dirty then
   451         no_thm
   452       else
   453         let
   454           val liftN_in = mk_in Asets liftN_sets T;
   455           val liftN_in_alt = mk_in (drop n Asets) bnf_sets T;
   456           val goal =
   457             fold_rev Logic.all Asets (HOLogic.mk_Trueprop (HOLogic.mk_eq (liftN_in, liftN_in_alt)))
   458         in
   459           Skip_Proof.prove lthy [] [] goal (K liftN_in_alt_tac)
   460         end;
   461 
   462     fun liftN_in_bd_tac _ =
   463       mk_liftN_in_bd_tac n liftN_in_alt_thm (in_bd_of_bnf bnf) (bd_Card_order_of_bnf bnf);
   464     fun liftN_map_wpull_tac _ =
   465       mk_map_wpull_tac liftN_in_alt_thm [] (map_wpull_of_bnf bnf);
   466 
   467     val tacs = [liftN_map_id_tac, liftN_map_comp_tac, liftN_map_cong_tac] @ liftN_set_natural_tacs @
   468       [liftN_bd_card_order_tac, liftN_bd_cinfinite_tac] @ liftN_set_bd_tacs @
   469       [liftN_in_bd_tac, liftN_map_wpull_tac];
   470 
   471     val liftN_wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   472 
   473     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   474 
   475     val (bnf', lthy') =
   476       bnf_def Smart_Inline (K Derive_Some_Facts) qualify tacs wit_tac (SOME Ds)
   477         ((((b, liftN_map), liftN_sets), Term.absdummy T liftN_bd), liftN_wits) lthy;
   478 
   479     val liftN_rel_unfold_thm =
   480       trans OF [rel_def_of_bnf bnf',
   481         trans OF [liftN_in_alt_thm RS @{thm subst_rel_def}, rel_def_of_bnf bnf RS sym]];
   482 
   483     val liftN_pred_unfold_thm = Collect_split_box_equals OF [liftN_rel_unfold_thm,
   484       pred_def_of_bnf bnf' RS abs_pred_sym, pred_def_of_bnf bnf RS abs_pred_sym];
   485 
   486     val unfold' = add_to_unfold (map_def_of_bnf bnf') (set_defs_of_bnf bnf')
   487       liftN_rel_unfold_thm liftN_pred_unfold_thm unfold;
   488   in
   489     (bnf', (unfold', lthy'))
   490   end;
   491 
   492 (* Changing the order of live variables *)
   493 
   494 fun permute_bnf qualify src dest bnf (unfold, lthy) = if src = dest then (bnf, (unfold, lthy)) else
   495   let
   496     val b = Binding.prefix_name (mk_permuteN src dest) (name_of_bnf bnf);
   497     val live = live_of_bnf bnf;
   498     val dead = dead_of_bnf bnf;
   499     val nwits = nwits_of_bnf bnf;
   500     fun permute xs = mk_permute src dest xs;
   501     fun permute_rev xs = mk_permute dest src xs;
   502 
   503     val (Ds, lthy1) = apfst (map TFree)
   504       (Variable.invent_types (replicate dead HOLogic.typeS) lthy);
   505     val (As, lthy2) = apfst (map TFree)
   506       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   507     val (Bs, _(*lthy3*)) = apfst (map TFree)
   508       (Variable.invent_types (replicate live HOLogic.typeS) lthy2);
   509 
   510     val (Asets, _(*names_lthy*)) = lthy
   511       |> mk_Frees "A" (map (HOLogic.mk_setT) (permute As));
   512 
   513     val T = mk_T_of_bnf Ds As bnf;
   514 
   515     (*%f(1) ... f(n). bnf.map f\<sigma>(1) ... f\<sigma>(n)*)
   516     val permute_map = fold_rev Term.absdummy (permute (map2 (curry op -->) As Bs))
   517       (Term.list_comb (mk_map_of_bnf Ds As Bs bnf,
   518         permute_rev (map Bound ((live - 1) downto 0))));
   519 
   520     val bnf_sets = mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf;
   521     val permute_sets = permute bnf_sets;
   522 
   523     val permute_bd = mk_bd_of_bnf Ds As bnf;
   524 
   525     fun permute_map_id_tac _ = rtac (map_id_of_bnf bnf) 1;
   526     fun permute_map_comp_tac _ = rtac (map_comp_of_bnf bnf) 1;
   527     fun permute_map_cong_tac {context, ...} =
   528       rtac (map_cong_of_bnf bnf) 1 THEN REPEAT_DETERM_N live (Goal.assume_rule_tac context 1);
   529     val permute_set_natural_tacs =
   530       permute (map (fn thm => fn _ => rtac thm 1) (set_natural_of_bnf bnf));
   531     fun permute_bd_card_order_tac _ = rtac (bd_card_order_of_bnf bnf) 1;
   532     fun permute_bd_cinfinite_tac _ = rtac (bd_cinfinite_of_bnf bnf) 1;
   533     val permute_set_bd_tacs = permute (map (fn thm => fn _ => rtac thm 1) (set_bd_of_bnf bnf));
   534 
   535     val permute_in_alt_thm =
   536       if ! quick_and_dirty then
   537         no_thm
   538       else
   539         let
   540           val permute_in = mk_in Asets permute_sets T;
   541           val permute_in_alt = mk_in (permute_rev Asets) bnf_sets T;
   542           val goal =
   543             fold_rev Logic.all Asets
   544               (HOLogic.mk_Trueprop (HOLogic.mk_eq (permute_in, permute_in_alt)));
   545         in
   546           Skip_Proof.prove lthy [] [] goal (K (mk_permute_in_alt_tac src dest))
   547         end;
   548 
   549     fun permute_in_bd_tac _ =
   550       mk_permute_in_bd_tac src dest permute_in_alt_thm (in_bd_of_bnf bnf)
   551         (bd_Card_order_of_bnf bnf);
   552     fun permute_map_wpull_tac _ =
   553       mk_map_wpull_tac permute_in_alt_thm [] (map_wpull_of_bnf bnf);
   554 
   555     val tacs = [permute_map_id_tac, permute_map_comp_tac, permute_map_cong_tac] @
   556       permute_set_natural_tacs @ [permute_bd_card_order_tac, permute_bd_cinfinite_tac] @
   557       permute_set_bd_tacs @ [permute_in_bd_tac, permute_map_wpull_tac];
   558 
   559     val permute_wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   560 
   561     fun wit_tac _ = mk_simple_wit_tac (wit_thms_of_bnf bnf);
   562 
   563     val (bnf', lthy') =
   564       bnf_def Smart_Inline (K Derive_Some_Facts) qualify tacs wit_tac (SOME Ds)
   565         ((((b, permute_map), permute_sets), Term.absdummy T permute_bd), permute_wits) lthy;
   566 
   567     val permute_rel_unfold_thm =
   568       trans OF [rel_def_of_bnf bnf',
   569         trans OF [permute_in_alt_thm RS @{thm subst_rel_def}, rel_def_of_bnf bnf RS sym]];
   570 
   571     val permute_pred_unfold_thm = Collect_split_box_equals OF [permute_rel_unfold_thm,
   572       pred_def_of_bnf bnf' RS abs_pred_sym, pred_def_of_bnf bnf RS abs_pred_sym];
   573 
   574     val unfold' = add_to_unfold (map_def_of_bnf bnf') (set_defs_of_bnf bnf')
   575       permute_rel_unfold_thm permute_pred_unfold_thm unfold;
   576   in
   577     (bnf', (unfold', lthy'))
   578   end;
   579 
   580 (* Composition pipeline *)
   581 
   582 fun permute_and_kill qualify n src dest bnf =
   583   bnf
   584   |> permute_bnf qualify src dest
   585   #> uncurry (killN_bnf qualify n);
   586 
   587 fun lift_and_permute qualify n src dest bnf =
   588   bnf
   589   |> liftN_bnf qualify n
   590   #> uncurry (permute_bnf qualify src dest);
   591 
   592 fun normalize_bnfs qualify Ass Ds sort bnfs unfold lthy =
   593   let
   594     val before_kill_src = map (fn As => 0 upto (length As - 1)) Ass;
   595     val kill_poss = map (find_indices Ds) Ass;
   596     val live_poss = map2 (subtract (op =)) kill_poss before_kill_src;
   597     val before_kill_dest = map2 append kill_poss live_poss;
   598     val kill_ns = map length kill_poss;
   599     val (inners', (unfold', lthy')) =
   600       fold_map5 (fn i => permute_and_kill (qualify i))
   601         (if length bnfs = 1 then [0] else (1 upto length bnfs))
   602         kill_ns before_kill_src before_kill_dest bnfs (unfold, lthy);
   603 
   604     val Ass' = map2 (map o nth) Ass live_poss;
   605     val As = sort Ass';
   606     val after_lift_dest = replicate (length Ass') (0 upto (length As - 1));
   607     val old_poss = map (map (fn x => find_index (fn y => x = y) As)) Ass';
   608     val new_poss = map2 (subtract (op =)) old_poss after_lift_dest;
   609     val after_lift_src = map2 append new_poss old_poss;
   610     val lift_ns = map (fn xs => length As - length xs) Ass';
   611   in
   612     ((kill_poss, As), fold_map5 (fn i => lift_and_permute (qualify i))
   613       (if length bnfs = 1 then [0] else (1 upto length bnfs))
   614       lift_ns after_lift_src after_lift_dest inners' (unfold', lthy'))
   615   end;
   616 
   617 fun default_comp_sort Ass =
   618   Library.sort (Term_Ord.typ_ord o pairself TFree) (fold (fold (insert (op =))) Ass []);
   619 
   620 fun compose_bnf const_policy qualify' b sort outer inners oDs Dss tfreess (unfold, lthy) =
   621   let
   622     val name = Binding.name_of b;
   623     fun qualify i bind =
   624       let val namei = if i > 0 then name ^ string_of_int i else name;
   625       in
   626         if member (op =) (#2 (Binding.dest bind)) (namei, true) then qualify' bind
   627         else qualify' (Binding.prefix_name namei bind)
   628       end;
   629 
   630     val Ass = map (map dest_TFree) tfreess;
   631     val Ds = fold (fold Term.add_tfreesT) (oDs :: Dss) [];
   632 
   633     val ((kill_poss, As), (inners', (unfold', lthy'))) =
   634       normalize_bnfs qualify Ass Ds sort inners unfold lthy;
   635 
   636     val Ds = oDs @ flat (map3 (append oo map o nth) tfreess kill_poss Dss);
   637     val As = map TFree As;
   638   in
   639     apfst (rpair (Ds, As)) (clean_compose_bnf const_policy I b outer inners' (unfold', lthy'))
   640   end;
   641 
   642 (* Hide the type of the bound (optimization) and unfold the definitions (nicer to the user) *)
   643 
   644 fun seal_bnf unfold b Ds bnf lthy =
   645   let
   646     val live = live_of_bnf bnf;
   647     val nwits = nwits_of_bnf bnf;
   648 
   649     val (As, lthy1) = apfst (map TFree)
   650       (Variable.invent_types (replicate live HOLogic.typeS) (fold Variable.declare_typ Ds lthy));
   651     val (Bs, _) = apfst (map TFree)
   652       (Variable.invent_types (replicate live HOLogic.typeS) lthy1);
   653 
   654     val map_unfolds = filter_refl (map_unfolds_of unfold);
   655     val set_unfoldss = map filter_refl (set_unfoldss_of unfold);
   656 
   657     val expand_maps = fold expand_term_const (map (single o Logic.dest_equals o Thm.prop_of)
   658       map_unfolds);
   659     val expand_sets = fold expand_term_const (map (map (Logic.dest_equals o Thm.prop_of))
   660       set_unfoldss);
   661     val unfold_maps = fold (Local_Defs.unfold lthy o single) map_unfolds;
   662     val unfold_sets = fold (Local_Defs.unfold lthy) set_unfoldss;
   663     val unfold_defs = unfold_sets o unfold_maps;
   664     val bnf_map = expand_maps (mk_map_of_bnf Ds As Bs bnf);
   665     val bnf_sets = map (expand_maps o expand_sets)
   666       (mk_sets_of_bnf (replicate live Ds) (replicate live As) bnf);
   667     val bnf_bd = mk_bd_of_bnf Ds As bnf;
   668     val T = mk_T_of_bnf Ds As bnf;
   669 
   670     (*bd should only depend on dead type variables!*)
   671     val bd_repT = fst (dest_relT (fastype_of bnf_bd));
   672     val bdT_bind = Binding.suffix_name ("_" ^ bdTN) b;
   673     val params = fold Term.add_tfreesT Ds [];
   674 
   675     val ((bdT_name, (bdT_glob_info, bdT_loc_info)), (lthy', lthy)) =
   676       lthy
   677       |> Typedef.add_typedef true NONE (bdT_bind, params, NoSyn)
   678         (HOLogic.mk_UNIV bd_repT) NONE (EVERY' [rtac exI, rtac UNIV_I] 1)
   679       ||> `Local_Theory.restore;
   680 
   681     val phi = Proof_Context.export_morphism lthy lthy';
   682 
   683     val bnf_bd' = mk_dir_image bnf_bd
   684       (Const (#Abs_name bdT_glob_info, bd_repT --> Type (bdT_name, map TFree params)))
   685 
   686     val set_def = Morphism.thm phi (the (#set_def bdT_loc_info));
   687     val Abs_inject = Morphism.thm phi (#Abs_inject bdT_loc_info);
   688     val Abs_cases = Morphism.thm phi (#Abs_cases bdT_loc_info);
   689 
   690     val Abs_bdT_inj = mk_Abs_inj_thm set_def Abs_inject;
   691     val Abs_bdT_bij = mk_Abs_bij_thm lthy' set_def Abs_inject Abs_cases;
   692 
   693     val bd_ordIso = @{thm dir_image} OF [Abs_bdT_inj, bd_Card_order_of_bnf bnf];
   694     val bd_card_order =
   695       @{thm card_order_dir_image} OF [Abs_bdT_bij, bd_card_order_of_bnf bnf];
   696     val bd_cinfinite =
   697       (@{thm Cinfinite_cong} OF [bd_ordIso, bd_Cinfinite_of_bnf bnf]) RS conjunct1;
   698 
   699     val set_bds =
   700       map (fn thm => @{thm ordLeq_ordIso_trans} OF [thm, bd_ordIso]) (set_bd_of_bnf bnf);
   701     val in_bd =
   702       @{thm ordLeq_ordIso_trans} OF [in_bd_of_bnf bnf,
   703         @{thm cexp_cong2_Cnotzero} OF [bd_ordIso, if live = 0 then
   704           @{thm ctwo_Cnotzero} else @{thm ctwo_Cnotzero} RS @{thm csum_Cnotzero2},
   705             bd_Card_order_of_bnf bnf]];
   706 
   707     fun mk_tac thm {context = ctxt, prems = _} = (rtac (unfold_defs thm) THEN'
   708       SOLVE o REPEAT_DETERM o (atac ORELSE' Goal.assume_rule_tac ctxt)) 1;
   709     val tacs =
   710       map mk_tac ([map_id_of_bnf bnf, map_comp_of_bnf bnf, map_cong_of_bnf bnf] @
   711         set_natural_of_bnf bnf) @
   712       map K [rtac bd_card_order 1, rtac bd_cinfinite 1] @
   713       map mk_tac (set_bds @ [in_bd, map_wpull_of_bnf bnf]);
   714 
   715     val bnf_wits = map snd (mk_wits_of_bnf (replicate nwits Ds) (replicate nwits As) bnf);
   716 
   717     fun wit_tac _ = mk_simple_wit_tac (map unfold_defs (wit_thms_of_bnf bnf));
   718 
   719     val (bnf', lthy') = bnf_def Hardly_Inline (K Derive_All_Facts) I tacs wit_tac NONE
   720         ((((b, bnf_map), bnf_sets), Term.absdummy T bnf_bd'), bnf_wits) lthy;
   721 
   722     val defs' = filter_refl (map_def_of_bnf bnf' :: set_defs_of_bnf bnf');
   723     val unfold_defs' = unfold_defs o Local_Defs.unfold lthy' defs';
   724 
   725     val rel_def = unfold_defs' (rel_def_of_bnf bnf');
   726     val rel_unfold = Local_Defs.unfold lthy'
   727       (map unfold_defs (filter_refl (rel_unfolds_of unfold))) rel_def;
   728 
   729     val unfold_defs'' = unfold_defs' o Local_Defs.unfold lthy' (filter_refl [rel_def_of_bnf bnf']);
   730 
   731     val pred_def = unfold_defs'' (pred_def_of_bnf bnf' RS abs_pred_sym_pred_abs);
   732     val pred_unfold = Local_Defs.unfold lthy'
   733       (map unfold_defs (filter_refl (pred_unfolds_of unfold))) pred_def;
   734 
   735     fun note thmN thms =
   736       snd o Local_Theory.note
   737         ((Binding.qualify true (Binding.name_of b) (Binding.name thmN), []), thms);
   738   in
   739     (bnf', lthy'
   740       |> note rel_unfoldN [rel_unfold]
   741       |> note pred_unfoldN [pred_unfold])
   742   end;
   743 
   744 fun bnf_of_typ _ _ _ _ (T as TFree _) (unfold, lthy) =
   745     ((Basic_BNFs.ID_bnf, ([], [T])), (add_to_unfold_opt NONE NONE
   746       (SOME Basic_BNFs.ID_rel_def) (SOME Basic_BNFs.ID_pred_def) unfold, lthy))
   747   | bnf_of_typ _ _ _ _ (TVar _) _ = error "Unexpected schematic variable"
   748   | bnf_of_typ const_policy b qualify' sort (T as Type (C, Ts)) (unfold, lthy) =
   749     let val tfrees = Term.add_tfreesT T [];
   750     in
   751       if null tfrees then
   752         ((Basic_BNFs.DEADID_bnf, ([T], [])), (unfold, lthy))
   753       else if forall (can Term.dest_TFree) Ts andalso length Ts = length tfrees then let
   754         val bnf = the (bnf_of lthy (Long_Name.base_name C));
   755         val T' = T_of_bnf bnf;
   756         val deads = deads_of_bnf bnf;
   757         val lives = lives_of_bnf bnf;
   758         val tvars' = Term.add_tvarsT T' [];
   759         val deads_lives =
   760           pairself (map (Term.typ_subst_TVars (map fst tvars' ~~ map TFree tfrees)))
   761           (deads, lives);
   762       val rel_def = rel_def_of_bnf bnf;
   763       val unfold' = add_to_unfold_opt NONE NONE (SOME (rel_def RS sym))
   764         (SOME (Local_Defs.unfold lthy [rel_def] (pred_def_of_bnf bnf) RS sym)) unfold;
   765       in ((bnf, deads_lives), (unfold', lthy)) end
   766       else
   767         let
   768           (* FIXME: we should allow several BNFs with the same base name *)
   769           val Tname = Long_Name.base_name C;
   770           val name = Binding.name_of b ^ "_" ^ Tname;
   771           fun qualify i bind =
   772             let val namei = if i > 0 then name ^ string_of_int i else name;
   773             in
   774               if member (op =) (#2 (Binding.dest bind)) (namei, true) then qualify' bind
   775               else qualify' (Binding.prefix_name namei bind)
   776             end;
   777           val outer = the (bnf_of lthy Tname);
   778           val odead = dead_of_bnf outer;
   779           val olive = live_of_bnf outer;
   780           val oDs_pos = find_indices [TFree ("dead", [])]
   781             (snd (dest_Type
   782               (mk_T_of_bnf (replicate odead (TFree ("dead", []))) (replicate olive dummyT) outer)));
   783           val oDs = map (nth Ts) oDs_pos;
   784           val Ts' = map (nth Ts) (subtract (op =) oDs_pos (0 upto length Ts - 1));
   785           val ((inners, (Dss, Ass)), (unfold', lthy')) =
   786             apfst (apsnd split_list o split_list)
   787               (fold_map2 (fn i =>
   788                   bnf_of_typ Smart_Inline (Binding.name (name ^ string_of_int i)) (qualify i) sort)
   789                 (if length Ts' = 1 then [0] else (1 upto length Ts'))
   790                 Ts' (unfold, lthy));
   791         in
   792           compose_bnf const_policy (qualify 0) b sort outer inners oDs Dss Ass (unfold', lthy')
   793         end
   794     end;
   795 
   796 end;