src/HOL/Nominal/nominal_package.ML
author wenzelm
Fri Mar 28 19:43:54 2008 +0100 (2008-03-28)
changeset 26462 dac4e2bce00d
parent 26359 6d437bde2f1d
child 26475 3cc1e48d0ce1
permissions -rw-r--r--
avoid rebinding of existing facts;
     1 (*  Title:      HOL/Nominal/nominal_package.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer and Christian Urban, TU Muenchen
     4 
     5 Nominal datatype package for Isabelle/HOL.
     6 *)
     7 
     8 signature NOMINAL_PACKAGE =
     9 sig
    10   val add_nominal_datatype : bool -> string list -> (string list * bstring * mixfix *
    11     (bstring * string list * mixfix) list) list -> theory -> theory
    12   type descr
    13   type nominal_datatype_info
    14   val get_nominal_datatypes : theory -> nominal_datatype_info Symtab.table
    15   val get_nominal_datatype : theory -> string -> nominal_datatype_info option
    16   val mk_perm: typ list -> term -> term -> term
    17   val perm_of_pair: term * term -> term
    18   val mk_not_sym: thm list -> thm list
    19   val perm_simproc: simproc
    20   val fresh_const: typ -> typ -> term
    21 end
    22 
    23 structure NominalPackage : NOMINAL_PACKAGE =
    24 struct
    25 
    26 val finite_emptyI = thm "finite.emptyI";
    27 val finite_Diff = thm "finite_Diff";
    28 val finite_Un = thm "finite_Un";
    29 val Un_iff = thm "Un_iff";
    30 val In0_eq = thm "In0_eq";
    31 val In1_eq = thm "In1_eq";
    32 val In0_not_In1 = thm "In0_not_In1";
    33 val In1_not_In0 = thm "In1_not_In0";
    34 val Un_assoc = thm "Un_assoc";
    35 val Collect_disj_eq = thm "Collect_disj_eq";
    36 val empty_def = thm "empty_def";
    37 val empty_iff = thm "empty_iff";
    38 
    39 open DatatypeAux;
    40 open NominalAtoms;
    41 
    42 (** FIXME: DatatypePackage should export this function **)
    43 
    44 local
    45 
    46 fun dt_recs (DtTFree _) = []
    47   | dt_recs (DtType (_, dts)) = List.concat (map dt_recs dts)
    48   | dt_recs (DtRec i) = [i];
    49 
    50 fun dt_cases (descr: descr) (_, args, constrs) =
    51   let
    52     fun the_bname i = Sign.base_name (#1 (valOf (AList.lookup (op =) descr i)));
    53     val bnames = map the_bname (distinct op = (List.concat (map dt_recs args)));
    54   in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
    55 
    56 
    57 fun induct_cases descr =
    58   DatatypeProp.indexify_names (List.concat (map (dt_cases descr) (map #2 descr)));
    59 
    60 fun exhaust_cases descr i = dt_cases descr (valOf (AList.lookup (op =) descr i));
    61 
    62 in
    63 
    64 fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
    65 
    66 fun mk_case_names_exhausts descr new =
    67   map (RuleCases.case_names o exhaust_cases descr o #1)
    68     (List.filter (fn ((_, (name, _, _))) => name mem_string new) descr);
    69 
    70 end;
    71 
    72 (* theory data *)
    73 
    74 type descr = (int * (string * dtyp list * (string * (dtyp list * dtyp) list) list)) list;
    75 
    76 type nominal_datatype_info =
    77   {index : int,
    78    descr : descr,
    79    sorts : (string * sort) list,
    80    rec_names : string list,
    81    rec_rewrites : thm list,
    82    induction : thm,
    83    distinct : thm list,
    84    inject : thm list};
    85 
    86 structure NominalDatatypesData = TheoryDataFun
    87 (
    88   type T = nominal_datatype_info Symtab.table;
    89   val empty = Symtab.empty;
    90   val copy = I;
    91   val extend = I;
    92   fun merge _ tabs : T = Symtab.merge (K true) tabs;
    93 );
    94 
    95 val get_nominal_datatypes = NominalDatatypesData.get;
    96 val put_nominal_datatypes = NominalDatatypesData.put;
    97 val map_nominal_datatypes = NominalDatatypesData.map;
    98 val get_nominal_datatype = Symtab.lookup o get_nominal_datatypes;
    99 
   100 
   101 (**** make datatype info ****)
   102 
   103 fun make_dt_info descr sorts induct reccomb_names rec_thms
   104     (((i, (_, (tname, _, _))), distinct), inject) =
   105   (tname,
   106    {index = i,
   107     descr = descr,
   108     sorts = sorts,
   109     rec_names = reccomb_names,
   110     rec_rewrites = rec_thms,
   111     induction = induct,
   112     distinct = distinct,
   113     inject = inject});
   114 
   115 (*******************************)
   116 
   117 val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
   118 
   119 fun read_typ sign ((Ts, sorts), str) =
   120   let
   121     val T = Type.no_tvars (Sign.read_def_typ (sign, (AList.lookup op =)
   122       (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
   123   in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
   124 
   125 (** simplification procedure for sorting permutations **)
   126 
   127 val dj_cp = thm "dj_cp";
   128 
   129 fun dest_permT (Type ("fun", [Type ("List.list", [Type ("*", [T, _])]),
   130       Type ("fun", [_, U])])) = (T, U);
   131 
   132 fun permTs_of (Const ("Nominal.perm", T) $ t $ u) = fst (dest_permT T) :: permTs_of u
   133   | permTs_of _ = [];
   134 
   135 fun perm_simproc' thy ss (Const ("Nominal.perm", T) $ t $ (u as Const ("Nominal.perm", U) $ r $ s)) =
   136       let
   137         val (aT as Type (a, []), S) = dest_permT T;
   138         val (bT as Type (b, []), _) = dest_permT U
   139       in if aT mem permTs_of u andalso aT <> bT then
   140           let
   141             val a' = Sign.base_name a;
   142             val b' = Sign.base_name b;
   143             val cp = PureThy.get_thm thy ("cp_" ^ a' ^ "_" ^ b' ^ "_inst");
   144             val dj = PureThy.get_thm thy ("dj_" ^ b' ^ "_" ^ a');
   145             val dj_cp' = [cp, dj] MRS dj_cp;
   146             val cert = SOME o cterm_of thy
   147           in
   148             SOME (mk_meta_eq (Drule.instantiate' [SOME (ctyp_of thy S)]
   149               [cert t, cert r, cert s] dj_cp'))
   150           end
   151         else NONE
   152       end
   153   | perm_simproc' thy ss _ = NONE;
   154 
   155 val perm_simproc =
   156   Simplifier.simproc (the_context ()) "perm_simp" ["pi1 \<bullet> (pi2 \<bullet> x)"] perm_simproc';
   157 
   158 val allE_Nil = read_instantiate_sg (the_context()) [("x", "[]")] allE;
   159 
   160 val meta_spec = thm "meta_spec";
   161 
   162 fun projections rule =
   163   ProjectRule.projections (ProofContext.init (Thm.theory_of_thm rule)) rule
   164   |> map (standard #> RuleCases.save rule);
   165 
   166 val supp_prod = thm "supp_prod";
   167 val fresh_prod = thm "fresh_prod";
   168 val supports_fresh = thm "supports_fresh";
   169 val supports_def = thm "Nominal.supports_def";
   170 val fresh_def = thm "fresh_def";
   171 val supp_def = thm "supp_def";
   172 val rev_simps = thms "rev.simps";
   173 val app_simps = thms "append.simps";
   174 val at_fin_set_supp = thm "at_fin_set_supp";
   175 val at_fin_set_fresh = thm "at_fin_set_fresh";
   176 val abs_fun_eq1 = thm "abs_fun_eq1";
   177 
   178 val collect_simp = rewrite_rule [mk_meta_eq mem_Collect_eq];
   179 
   180 fun mk_perm Ts t u =
   181   let
   182     val T = fastype_of1 (Ts, t);
   183     val U = fastype_of1 (Ts, u)
   184   in Const ("Nominal.perm", T --> U --> U) $ t $ u end;
   185 
   186 fun perm_of_pair (x, y) =
   187   let
   188     val T = fastype_of x;
   189     val pT = mk_permT T
   190   in Const ("List.list.Cons", HOLogic.mk_prodT (T, T) --> pT --> pT) $
   191     HOLogic.mk_prod (x, y) $ Const ("List.list.Nil", pT)
   192   end;
   193 
   194 fun mk_not_sym ths = maps (fn th => case prop_of th of
   195     _ $ (Const ("Not", _) $ (Const ("op =", _) $ _ $ _)) => [th, th RS not_sym]
   196   | _ => [th]) ths;
   197 
   198 fun fresh_const T U = Const ("Nominal.fresh", T --> U --> HOLogic.boolT);
   199 
   200 fun gen_add_nominal_datatype prep_typ err flat_names new_type_names dts thy =
   201   let
   202     (* this theory is used just for parsing *)
   203 
   204     val tmp_thy = thy |>
   205       Theory.copy |>
   206       Sign.add_types (map (fn (tvs, tname, mx, _) =>
   207         (tname, length tvs, mx)) dts);
   208 
   209     val atoms = atoms_of thy;
   210     val classes = map (NameSpace.map_base (fn s => "pt_" ^ s)) atoms;
   211     val cp_classes = List.concat (map (fn atom1 => map (fn atom2 =>
   212       Sign.intern_class thy ("cp_" ^ Sign.base_name atom1 ^ "_" ^
   213         Sign.base_name atom2)) atoms) atoms);
   214     fun augment_sort S = S union classes;
   215     val augment_sort_typ = map_type_tfree (fn (s, S) => TFree (s, augment_sort S));
   216 
   217     fun prep_constr ((constrs, sorts), (cname, cargs, mx)) =
   218       let val (cargs', sorts') = Library.foldl (prep_typ tmp_thy) (([], sorts), cargs)
   219       in (constrs @ [(cname, cargs', mx)], sorts') end
   220 
   221     fun prep_dt_spec ((dts, sorts), (tvs, tname, mx, constrs)) =
   222       let val (constrs', sorts') = Library.foldl prep_constr (([], sorts), constrs)
   223       in (dts @ [(tvs, tname, mx, constrs')], sorts') end
   224 
   225     val (dts', sorts) = Library.foldl prep_dt_spec (([], []), dts);
   226     val sorts' = map (apsnd augment_sort) sorts;
   227     val tyvars = map #1 dts';
   228 
   229     val types_syntax = map (fn (tvs, tname, mx, constrs) => (tname, mx)) dts';
   230     val constr_syntax = map (fn (tvs, tname, mx, constrs) =>
   231       map (fn (cname, cargs, mx) => (cname, mx)) constrs) dts';
   232 
   233     val ps = map (fn (_, n, _, _) =>
   234       (Sign.full_name tmp_thy n, Sign.full_name tmp_thy (n ^ "_Rep"))) dts;
   235     val rps = map Library.swap ps;
   236 
   237     fun replace_types (Type ("Nominal.ABS", [T, U])) =
   238           Type ("fun", [T, Type ("Nominal.noption", [replace_types U])])
   239       | replace_types (Type (s, Ts)) =
   240           Type (getOpt (AList.lookup op = ps s, s), map replace_types Ts)
   241       | replace_types T = T;
   242 
   243     val dts'' = map (fn (tvs, tname, mx, constrs) => (tvs, tname ^ "_Rep", NoSyn,
   244       map (fn (cname, cargs, mx) => (cname ^ "_Rep",
   245         map (augment_sort_typ o replace_types) cargs, NoSyn)) constrs)) dts';
   246 
   247     val new_type_names' = map (fn n => n ^ "_Rep") new_type_names;
   248     val full_new_type_names' = map (Sign.full_name thy) new_type_names';
   249 
   250     val ({induction, ...},thy1) =
   251       DatatypePackage.add_datatype_i err flat_names new_type_names' dts'' thy;
   252 
   253     val SOME {descr, ...} = Symtab.lookup
   254       (DatatypePackage.get_datatypes thy1) (hd full_new_type_names');
   255     fun nth_dtyp i = typ_of_dtyp descr sorts' (DtRec i);
   256 
   257     (**** define permutation functions ****)
   258 
   259     val permT = mk_permT (TFree ("'x", HOLogic.typeS));
   260     val pi = Free ("pi", permT);
   261     val perm_types = map (fn (i, _) =>
   262       let val T = nth_dtyp i
   263       in permT --> T --> T end) descr;
   264     val perm_names = replicate (length new_type_names) "Nominal.perm" @
   265       DatatypeProp.indexify_names (map (fn i => Sign.full_name thy1
   266         ("perm_" ^ name_of_typ (nth_dtyp i)))
   267           (length new_type_names upto length descr - 1));
   268     val perm_names_types = perm_names ~~ perm_types;
   269 
   270     val perm_eqs = List.concat (map (fn (i, (_, _, constrs)) =>
   271       let val T = nth_dtyp i
   272       in map (fn (cname, dts) =>
   273         let
   274           val Ts = map (typ_of_dtyp descr sorts') dts;
   275           val names = DatatypeProp.make_tnames Ts;
   276           val args = map Free (names ~~ Ts);
   277           val c = Const (cname, Ts ---> T);
   278           fun perm_arg (dt, x) =
   279             let val T = type_of x
   280             in if is_rec_type dt then
   281                 let val (Us, _) = strip_type T
   282                 in list_abs (map (pair "x") Us,
   283                   Const (List.nth (perm_names_types, body_index dt)) $ pi $
   284                     list_comb (x, map (fn (i, U) =>
   285                       Const ("Nominal.perm", permT --> U --> U) $
   286                         (Const ("List.rev", permT --> permT) $ pi) $
   287                         Bound i) ((length Us - 1 downto 0) ~~ Us)))
   288                 end
   289               else Const ("Nominal.perm", permT --> T --> T) $ pi $ x
   290             end;
   291         in
   292           (("", HOLogic.mk_Trueprop (HOLogic.mk_eq
   293             (Const (List.nth (perm_names_types, i)) $
   294                Free ("pi", mk_permT (TFree ("'x", HOLogic.typeS))) $
   295                list_comb (c, args),
   296              list_comb (c, map perm_arg (dts ~~ args))))), [])
   297         end) constrs
   298       end) descr);
   299 
   300     val (perm_simps, thy2) = thy1 |>
   301       Sign.add_consts_i (map (fn (s, T) => (Sign.base_name s, T, NoSyn))
   302         (List.drop (perm_names_types, length new_type_names))) |>
   303       OldPrimrecPackage.add_primrec_unchecked_i "" perm_eqs;
   304 
   305     (**** prove that permutation functions introduced by unfolding are ****)
   306     (**** equivalent to already existing permutation functions         ****)
   307 
   308     val _ = warning ("length descr: " ^ string_of_int (length descr));
   309     val _ = warning ("length new_type_names: " ^ string_of_int (length new_type_names));
   310 
   311     val perm_indnames = DatatypeProp.make_tnames (map body_type perm_types);
   312     val perm_fun_def = PureThy.get_thm thy2 "perm_fun_def";
   313 
   314     val unfolded_perm_eq_thms =
   315       if length descr = length new_type_names then []
   316       else map standard (List.drop (split_conj_thm
   317         (Goal.prove_global thy2 [] []
   318           (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   319             (map (fn (c as (s, T), x) =>
   320                let val [T1, T2] = binder_types T
   321                in HOLogic.mk_eq (Const c $ pi $ Free (x, T2),
   322                  Const ("Nominal.perm", T) $ pi $ Free (x, T2))
   323                end)
   324              (perm_names_types ~~ perm_indnames))))
   325           (fn _ => EVERY [indtac induction perm_indnames 1,
   326             ALLGOALS (asm_full_simp_tac
   327               (simpset_of thy2 addsimps [perm_fun_def]))])),
   328         length new_type_names));
   329 
   330     (**** prove [] \<bullet> t = t ****)
   331 
   332     val _ = warning "perm_empty_thms";
   333 
   334     val perm_empty_thms = List.concat (map (fn a =>
   335       let val permT = mk_permT (Type (a, []))
   336       in map standard (List.take (split_conj_thm
   337         (Goal.prove_global thy2 [] []
   338           (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   339             (map (fn ((s, T), x) => HOLogic.mk_eq
   340                 (Const (s, permT --> T --> T) $
   341                    Const ("List.list.Nil", permT) $ Free (x, T),
   342                  Free (x, T)))
   343              (perm_names ~~
   344               map body_type perm_types ~~ perm_indnames))))
   345           (fn _ => EVERY [indtac induction perm_indnames 1,
   346             ALLGOALS (asm_full_simp_tac (simpset_of thy2))])),
   347         length new_type_names))
   348       end)
   349       atoms);
   350 
   351     (**** prove (pi1 @ pi2) \<bullet> t = pi1 \<bullet> (pi2 \<bullet> t) ****)
   352 
   353     val _ = warning "perm_append_thms";
   354 
   355     (*FIXME: these should be looked up statically*)
   356     val at_pt_inst = PureThy.get_thm thy2 "at_pt_inst";
   357     val pt2 = PureThy.get_thm thy2 "pt2";
   358 
   359     val perm_append_thms = List.concat (map (fn a =>
   360       let
   361         val permT = mk_permT (Type (a, []));
   362         val pi1 = Free ("pi1", permT);
   363         val pi2 = Free ("pi2", permT);
   364         val pt_inst = PureThy.get_thm thy2 ("pt_" ^ Sign.base_name a ^ "_inst");
   365         val pt2' = pt_inst RS pt2;
   366         val pt2_ax = PureThy.get_thm thy2 (NameSpace.map_base (fn s => "pt_" ^ s ^ "2") a);
   367       in List.take (map standard (split_conj_thm
   368         (Goal.prove_global thy2 [] []
   369              (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   370                 (map (fn ((s, T), x) =>
   371                     let val perm = Const (s, permT --> T --> T)
   372                     in HOLogic.mk_eq
   373                       (perm $ (Const ("List.append", permT --> permT --> permT) $
   374                          pi1 $ pi2) $ Free (x, T),
   375                        perm $ pi1 $ (perm $ pi2 $ Free (x, T)))
   376                     end)
   377                   (perm_names ~~
   378                    map body_type perm_types ~~ perm_indnames))))
   379            (fn _ => EVERY [indtac induction perm_indnames 1,
   380               ALLGOALS (asm_full_simp_tac (simpset_of thy2 addsimps [pt2', pt2_ax]))]))),
   381          length new_type_names)
   382       end) atoms);
   383 
   384     (**** prove pi1 ~ pi2 ==> pi1 \<bullet> t = pi2 \<bullet> t ****)
   385 
   386     val _ = warning "perm_eq_thms";
   387 
   388     val pt3 = PureThy.get_thm thy2 "pt3";
   389     val pt3_rev = PureThy.get_thm thy2 "pt3_rev";
   390 
   391     val perm_eq_thms = List.concat (map (fn a =>
   392       let
   393         val permT = mk_permT (Type (a, []));
   394         val pi1 = Free ("pi1", permT);
   395         val pi2 = Free ("pi2", permT);
   396         (*FIXME: not robust - better access these theorems using NominalData?*)
   397         val at_inst = PureThy.get_thm thy2 ("at_" ^ Sign.base_name a ^ "_inst");
   398         val pt_inst = PureThy.get_thm thy2 ("pt_" ^ Sign.base_name a ^ "_inst");
   399         val pt3' = pt_inst RS pt3;
   400         val pt3_rev' = at_inst RS (pt_inst RS pt3_rev);
   401         val pt3_ax = PureThy.get_thm thy2 (NameSpace.map_base (fn s => "pt_" ^ s ^ "3") a);
   402       in List.take (map standard (split_conj_thm
   403         (Goal.prove_global thy2 [] [] (Logic.mk_implies
   404              (HOLogic.mk_Trueprop (Const ("Nominal.prm_eq",
   405                 permT --> permT --> HOLogic.boolT) $ pi1 $ pi2),
   406               HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   407                 (map (fn ((s, T), x) =>
   408                     let val perm = Const (s, permT --> T --> T)
   409                     in HOLogic.mk_eq
   410                       (perm $ pi1 $ Free (x, T),
   411                        perm $ pi2 $ Free (x, T))
   412                     end)
   413                   (perm_names ~~
   414                    map body_type perm_types ~~ perm_indnames)))))
   415            (fn _ => EVERY [indtac induction perm_indnames 1,
   416               ALLGOALS (asm_full_simp_tac (simpset_of thy2 addsimps [pt3', pt3_rev', pt3_ax]))]))),
   417          length new_type_names)
   418       end) atoms);
   419 
   420     (**** prove pi1 \<bullet> (pi2 \<bullet> t) = (pi1 \<bullet> pi2) \<bullet> (pi1 \<bullet> t) ****)
   421 
   422     val cp1 = PureThy.get_thm thy2 "cp1";
   423     val dj_cp = PureThy.get_thm thy2 "dj_cp";
   424     val pt_perm_compose = PureThy.get_thm thy2 "pt_perm_compose";
   425     val pt_perm_compose_rev = PureThy.get_thm thy2 "pt_perm_compose_rev";
   426     val dj_perm_perm_forget = PureThy.get_thm thy2 "dj_perm_perm_forget";
   427 
   428     fun composition_instance name1 name2 thy =
   429       let
   430         val name1' = Sign.base_name name1;
   431         val name2' = Sign.base_name name2;
   432         val cp_class = Sign.intern_class thy ("cp_" ^ name1' ^ "_" ^ name2');
   433         val permT1 = mk_permT (Type (name1, []));
   434         val permT2 = mk_permT (Type (name2, []));
   435         val augment = map_type_tfree
   436           (fn (x, S) => TFree (x, cp_class :: S));
   437         val Ts = map (augment o body_type) perm_types;
   438         val cp_inst = PureThy.get_thm thy ("cp_" ^ name1' ^ "_" ^ name2' ^ "_inst");
   439         val simps = simpset_of thy addsimps (perm_fun_def ::
   440           (if name1 <> name2 then
   441              let val dj = PureThy.get_thm thy ("dj_" ^ name2' ^ "_" ^ name1')
   442              in [dj RS (cp_inst RS dj_cp), dj RS dj_perm_perm_forget] end
   443            else
   444              let
   445                val at_inst = PureThy.get_thm thy ("at_" ^ name1' ^ "_inst");
   446                val pt_inst = PureThy.get_thm thy ("pt_" ^ name1' ^ "_inst");
   447              in
   448                [cp_inst RS cp1 RS sym,
   449                 at_inst RS (pt_inst RS pt_perm_compose) RS sym,
   450                 at_inst RS (pt_inst RS pt_perm_compose_rev) RS sym]
   451             end))
   452         val thms = split_conj_thm (Goal.prove_global thy [] []
   453             (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   454               (map (fn ((s, T), x) =>
   455                   let
   456                     val pi1 = Free ("pi1", permT1);
   457                     val pi2 = Free ("pi2", permT2);
   458                     val perm1 = Const (s, permT1 --> T --> T);
   459                     val perm2 = Const (s, permT2 --> T --> T);
   460                     val perm3 = Const ("Nominal.perm", permT1 --> permT2 --> permT2)
   461                   in HOLogic.mk_eq
   462                     (perm1 $ pi1 $ (perm2 $ pi2 $ Free (x, T)),
   463                      perm2 $ (perm3 $ pi1 $ pi2) $ (perm1 $ pi1 $ Free (x, T)))
   464                   end)
   465                 (perm_names ~~ Ts ~~ perm_indnames))))
   466           (fn _ => EVERY [indtac induction perm_indnames 1,
   467              ALLGOALS (asm_full_simp_tac simps)]))
   468       in
   469         foldl (fn ((s, tvs), thy) => AxClass.prove_arity
   470             (s, replicate (length tvs) (cp_class :: classes), [cp_class])
   471             (Class.intro_classes_tac [] THEN ALLGOALS (resolve_tac thms)) thy)
   472           thy (full_new_type_names' ~~ tyvars)
   473       end;
   474 
   475     val (perm_thmss,thy3) = thy2 |>
   476       fold (fn name1 => fold (composition_instance name1) atoms) atoms |>
   477       curry (Library.foldr (fn ((i, (tyname, args, _)), thy) =>
   478         AxClass.prove_arity (tyname, replicate (length args) classes, classes)
   479         (Class.intro_classes_tac [] THEN REPEAT (EVERY
   480            [resolve_tac perm_empty_thms 1,
   481             resolve_tac perm_append_thms 1,
   482             resolve_tac perm_eq_thms 1, assume_tac 1])) thy))
   483         (List.take (descr, length new_type_names)) |>
   484       PureThy.add_thmss
   485         [((space_implode "_" new_type_names ^ "_unfolded_perm_eq",
   486           unfolded_perm_eq_thms), [Simplifier.simp_add]),
   487          ((space_implode "_" new_type_names ^ "_perm_empty",
   488           perm_empty_thms), [Simplifier.simp_add]),
   489          ((space_implode "_" new_type_names ^ "_perm_append",
   490           perm_append_thms), [Simplifier.simp_add]),
   491          ((space_implode "_" new_type_names ^ "_perm_eq",
   492           perm_eq_thms), [Simplifier.simp_add])];
   493 
   494     (**** Define representing sets ****)
   495 
   496     val _ = warning "representing sets";
   497 
   498     val rep_set_names = DatatypeProp.indexify_names
   499       (map (fn (i, _) => name_of_typ (nth_dtyp i) ^ "_set") descr);
   500     val big_rep_name =
   501       space_implode "_" (DatatypeProp.indexify_names (List.mapPartial
   502         (fn (i, ("Nominal.noption", _, _)) => NONE
   503           | (i, _) => SOME (name_of_typ (nth_dtyp i))) descr)) ^ "_set";
   504     val _ = warning ("big_rep_name: " ^ big_rep_name);
   505 
   506     fun strip_option (dtf as DtType ("fun", [dt, DtRec i])) =
   507           (case AList.lookup op = descr i of
   508              SOME ("Nominal.noption", _, [(_, [dt']), _]) =>
   509                apfst (cons dt) (strip_option dt')
   510            | _ => ([], dtf))
   511       | strip_option (DtType ("fun", [dt, DtType ("Nominal.noption", [dt'])])) =
   512           apfst (cons dt) (strip_option dt')
   513       | strip_option dt = ([], dt);
   514 
   515     val dt_atomTs = distinct op = (map (typ_of_dtyp descr sorts')
   516       (List.concat (map (fn (_, (_, _, cs)) => List.concat
   517         (map (List.concat o map (fst o strip_option) o snd) cs)) descr)));
   518 
   519     fun make_intr s T (cname, cargs) =
   520       let
   521         fun mk_prem (dt, (j, j', prems, ts)) =
   522           let
   523             val (dts, dt') = strip_option dt;
   524             val (dts', dt'') = strip_dtyp dt';
   525             val Ts = map (typ_of_dtyp descr sorts') dts;
   526             val Us = map (typ_of_dtyp descr sorts') dts';
   527             val T = typ_of_dtyp descr sorts' dt'';
   528             val free = mk_Free "x" (Us ---> T) j;
   529             val free' = app_bnds free (length Us);
   530             fun mk_abs_fun (T, (i, t)) =
   531               let val U = fastype_of t
   532               in (i + 1, Const ("Nominal.abs_fun", [T, U, T] --->
   533                 Type ("Nominal.noption", [U])) $ mk_Free "y" T i $ t)
   534               end
   535           in (j + 1, j' + length Ts,
   536             case dt'' of
   537                 DtRec k => list_all (map (pair "x") Us,
   538                   HOLogic.mk_Trueprop (Free (List.nth (rep_set_names, k),
   539                     T --> HOLogic.boolT) $ free')) :: prems
   540               | _ => prems,
   541             snd (foldr mk_abs_fun (j', free) Ts) :: ts)
   542           end;
   543 
   544         val (_, _, prems, ts) = foldr mk_prem (1, 1, [], []) cargs;
   545         val concl = HOLogic.mk_Trueprop (Free (s, T --> HOLogic.boolT) $
   546           list_comb (Const (cname, map fastype_of ts ---> T), ts))
   547       in Logic.list_implies (prems, concl)
   548       end;
   549 
   550     val (intr_ts, (rep_set_names', recTs')) =
   551       apfst List.concat (apsnd ListPair.unzip (ListPair.unzip (List.mapPartial
   552         (fn ((_, ("Nominal.noption", _, _)), _) => NONE
   553           | ((i, (_, _, constrs)), rep_set_name) =>
   554               let val T = nth_dtyp i
   555               in SOME (map (make_intr rep_set_name T) constrs,
   556                 (rep_set_name, T))
   557               end)
   558                 (descr ~~ rep_set_names))));
   559     val rep_set_names'' = map (Sign.full_name thy3) rep_set_names';
   560 
   561     val ({raw_induct = rep_induct, intrs = rep_intrs, ...}, thy4) =
   562       setmp InductivePackage.quiet_mode false
   563         (InductivePackage.add_inductive_global (serial_string ())
   564           {verbose = false, kind = Thm.internalK,
   565             alt_name = big_rep_name, coind = false, no_elim = true, no_ind = false}
   566           (map (fn (s, T) => ((s, T --> HOLogic.boolT), NoSyn))
   567              (rep_set_names' ~~ recTs'))
   568           [] (map (fn x => (("", []), x)) intr_ts) []) thy3;
   569 
   570     (**** Prove that representing set is closed under permutation ****)
   571 
   572     val _ = warning "proving closure under permutation...";
   573 
   574     val abs_perm = PureThy.get_thms thy4 "abs_perm";
   575 
   576     val perm_indnames' = List.mapPartial
   577       (fn (x, (_, ("Nominal.noption", _, _))) => NONE | (x, _) => SOME x)
   578       (perm_indnames ~~ descr);
   579 
   580     fun mk_perm_closed name = map (fn th => standard (th RS mp))
   581       (List.take (split_conj_thm (Goal.prove_global thy4 [] []
   582         (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj (map
   583            (fn ((s, T), x) =>
   584               let
   585                 val T = map_type_tfree
   586                   (fn (s, cs) => TFree (s, cs union cp_classes)) T;
   587                 val S = Const (s, T --> HOLogic.boolT);
   588                 val permT = mk_permT (Type (name, []))
   589               in HOLogic.mk_imp (S $ Free (x, T),
   590                 S $ (Const ("Nominal.perm", permT --> T --> T) $
   591                   Free ("pi", permT) $ Free (x, T)))
   592               end) (rep_set_names'' ~~ recTs' ~~ perm_indnames'))))
   593         (fn _ => EVERY (* CU: added perm_fun_def in the final tactic in order to deal with funs *)
   594            [indtac rep_induct [] 1,
   595             ALLGOALS (simp_tac (simpset_of thy4 addsimps
   596               (symmetric perm_fun_def :: abs_perm))),
   597             ALLGOALS (resolve_tac rep_intrs
   598                THEN_ALL_NEW (asm_full_simp_tac (simpset_of thy4 addsimps [perm_fun_def])))])),
   599         length new_type_names));
   600 
   601     (* FIXME: theorems are stored in database for testing only *)
   602     val perm_closed_thmss = map mk_perm_closed atoms;
   603     val (_, thy5) = PureThy.add_thmss [(("perm_closed", List.concat perm_closed_thmss), [])] thy4;
   604 
   605     (**** typedef ****)
   606 
   607     val _ = warning "defining type...";
   608 
   609     val (typedefs, thy6) =
   610       thy5
   611       |> fold_map (fn ((((name, mx), tvs), (cname, U)), name') => fn thy =>
   612         setmp TypedefPackage.quiet_mode true
   613           (TypedefPackage.add_typedef_i false (SOME name') (name, tvs, mx)
   614             (Const ("Collect", (U --> HOLogic.boolT) --> HOLogic.mk_setT U) $
   615                Const (cname, U --> HOLogic.boolT)) NONE
   616             (rtac exI 1 THEN rtac CollectI 1 THEN
   617               QUIET_BREADTH_FIRST (has_fewer_prems 1)
   618               (resolve_tac rep_intrs 1))) thy |> (fn ((_, r), thy) =>
   619         let
   620           val permT = mk_permT (TFree (Name.variant tvs "'a", HOLogic.typeS));
   621           val pi = Free ("pi", permT);
   622           val tvs' = map (fn s => TFree (s, the (AList.lookup op = sorts' s))) tvs;
   623           val T = Type (Sign.intern_type thy name, tvs');
   624         in apfst (pair r o hd)
   625           (PureThy.add_defs_unchecked_i true [(("prm_" ^ name ^ "_def", Logic.mk_equals
   626             (Const ("Nominal.perm", permT --> T --> T) $ pi $ Free ("x", T),
   627              Const (Sign.intern_const thy ("Abs_" ^ name), U --> T) $
   628                (Const ("Nominal.perm", permT --> U --> U) $ pi $
   629                  (Const (Sign.intern_const thy ("Rep_" ^ name), T --> U) $
   630                    Free ("x", T))))), [])] thy)
   631         end))
   632           (types_syntax ~~ tyvars ~~
   633             List.take (rep_set_names'' ~~ recTs', length new_type_names) ~~
   634             new_type_names);
   635 
   636     val perm_defs = map snd typedefs;
   637     val Abs_inverse_thms = map (collect_simp o #Abs_inverse o fst) typedefs;
   638     val Rep_inverse_thms = map (#Rep_inverse o fst) typedefs;
   639     val Rep_thms = map (collect_simp o #Rep o fst) typedefs;
   640 
   641     val big_name = space_implode "_" new_type_names;
   642 
   643 
   644     (** prove that new types are in class pt_<name> **)
   645 
   646     val _ = warning "prove that new types are in class pt_<name> ...";
   647 
   648     fun pt_instance ((class, atom), perm_closed_thms) =
   649       fold (fn ((((((Abs_inverse, Rep_inverse), Rep),
   650         perm_def), name), tvs), perm_closed) => fn thy =>
   651           AxClass.prove_arity
   652             (Sign.intern_type thy name,
   653               replicate (length tvs) (classes @ cp_classes), [class])
   654             (EVERY [Class.intro_classes_tac [],
   655               rewrite_goals_tac [perm_def],
   656               asm_full_simp_tac (simpset_of thy addsimps [Rep_inverse]) 1,
   657               asm_full_simp_tac (simpset_of thy addsimps
   658                 [Rep RS perm_closed RS Abs_inverse]) 1,
   659               asm_full_simp_tac (HOL_basic_ss addsimps [PureThy.get_thm thy
   660                 ("pt_" ^ Sign.base_name atom ^ "3")]) 1]) thy)
   661         (Abs_inverse_thms ~~ Rep_inverse_thms ~~ Rep_thms ~~ perm_defs ~~
   662            new_type_names ~~ tyvars ~~ perm_closed_thms);
   663 
   664 
   665     (** prove that new types are in class cp_<name1>_<name2> **)
   666 
   667     val _ = warning "prove that new types are in class cp_<name1>_<name2> ...";
   668 
   669     fun cp_instance (atom1, perm_closed_thms1) (atom2, perm_closed_thms2) thy =
   670       let
   671         val name = "cp_" ^ Sign.base_name atom1 ^ "_" ^ Sign.base_name atom2;
   672         val class = Sign.intern_class thy name;
   673         val cp1' = PureThy.get_thm thy (name ^ "_inst") RS cp1
   674       in fold (fn ((((((Abs_inverse, Rep),
   675         perm_def), name), tvs), perm_closed1), perm_closed2) => fn thy =>
   676           AxClass.prove_arity
   677             (Sign.intern_type thy name,
   678               replicate (length tvs) (classes @ cp_classes), [class])
   679             (EVERY [Class.intro_classes_tac [],
   680               rewrite_goals_tac [perm_def],
   681               asm_full_simp_tac (simpset_of thy addsimps
   682                 ((Rep RS perm_closed1 RS Abs_inverse) ::
   683                  (if atom1 = atom2 then []
   684                   else [Rep RS perm_closed2 RS Abs_inverse]))) 1,
   685               cong_tac 1,
   686               rtac refl 1,
   687               rtac cp1' 1]) thy)
   688         (Abs_inverse_thms ~~ Rep_thms ~~ perm_defs ~~ new_type_names ~~
   689            tyvars ~~ perm_closed_thms1 ~~ perm_closed_thms2) thy
   690       end;
   691 
   692     val thy7 = fold (fn x => fn thy => thy |>
   693       pt_instance x |>
   694       fold (cp_instance (apfst snd x)) (atoms ~~ perm_closed_thmss))
   695         (classes ~~ atoms ~~ perm_closed_thmss) thy6;
   696 
   697     (**** constructors ****)
   698 
   699     fun mk_abs_fun (x, t) =
   700       let
   701         val T = fastype_of x;
   702         val U = fastype_of t
   703       in
   704         Const ("Nominal.abs_fun", T --> U --> T -->
   705           Type ("Nominal.noption", [U])) $ x $ t
   706       end;
   707 
   708     val (ty_idxs, _) = foldl
   709       (fn ((i, ("Nominal.noption", _, _)), p) => p
   710         | ((i, _), (ty_idxs, j)) => (ty_idxs @ [(i, j)], j + 1)) ([], 0) descr;
   711 
   712     fun reindex (DtType (s, dts)) = DtType (s, map reindex dts)
   713       | reindex (DtRec i) = DtRec (the (AList.lookup op = ty_idxs i))
   714       | reindex dt = dt;
   715 
   716     fun strip_suffix i s = implode (List.take (explode s, size s - i));
   717 
   718     (** strips the "_Rep" in type names *)
   719     fun strip_nth_name i s =
   720       let val xs = NameSpace.explode s;
   721       in NameSpace.implode (Library.nth_map (length xs - i) (strip_suffix 4) xs) end;
   722 
   723     val (descr'', ndescr) = ListPair.unzip (List.mapPartial
   724       (fn (i, ("Nominal.noption", _, _)) => NONE
   725         | (i, (s, dts, constrs)) =>
   726              let
   727                val SOME index = AList.lookup op = ty_idxs i;
   728                val (constrs1, constrs2) = ListPair.unzip
   729                  (map (fn (cname, cargs) => apfst (pair (strip_nth_name 2 (strip_nth_name 1 cname)))
   730                    (foldl_map (fn (dts, dt) =>
   731                      let val (dts', dt') = strip_option dt
   732                      in (dts @ dts' @ [reindex dt'], (length dts, length dts')) end)
   733                        ([], cargs))) constrs)
   734              in SOME ((index, (strip_nth_name 1 s,  map reindex dts, constrs1)),
   735                (index, constrs2))
   736              end) descr);
   737 
   738     val (descr1, descr2) = chop (length new_type_names) descr'';
   739     val descr' = [descr1, descr2];
   740 
   741     fun partition_cargs idxs xs = map (fn (i, j) =>
   742       (List.take (List.drop (xs, i), j), List.nth (xs, i + j))) idxs;
   743 
   744     val pdescr = map (fn ((i, (s, dts, constrs)), (_, idxss)) => (i, (s, dts,
   745       map (fn ((cname, cargs), idxs) => (cname, partition_cargs idxs cargs))
   746         (constrs ~~ idxss)))) (descr'' ~~ ndescr);
   747 
   748     fun nth_dtyp' i = typ_of_dtyp descr'' sorts' (DtRec i);
   749 
   750     val rep_names = map (fn s =>
   751       Sign.intern_const thy7 ("Rep_" ^ s)) new_type_names;
   752     val abs_names = map (fn s =>
   753       Sign.intern_const thy7 ("Abs_" ^ s)) new_type_names;
   754 
   755     val recTs = get_rec_types descr'' sorts';
   756     val newTs' = Library.take (length new_type_names, recTs');
   757     val newTs = Library.take (length new_type_names, recTs);
   758 
   759     val full_new_type_names = map (Sign.full_name thy) new_type_names;
   760 
   761     fun make_constr_def tname T T' ((thy, defs, eqns),
   762         (((cname_rep, _), (cname, cargs)), (cname', mx))) =
   763       let
   764         fun constr_arg ((dts, dt), (j, l_args, r_args)) =
   765           let
   766             val xs = map (fn (dt, i) => mk_Free "x" (typ_of_dtyp descr'' sorts' dt) i)
   767               (dts ~~ (j upto j + length dts - 1))
   768             val x = mk_Free "x" (typ_of_dtyp descr'' sorts' dt) (j + length dts)
   769           in
   770             (j + length dts + 1,
   771              xs @ x :: l_args,
   772              foldr mk_abs_fun
   773                (case dt of
   774                   DtRec k => if k < length new_type_names then
   775                       Const (List.nth (rep_names, k), typ_of_dtyp descr'' sorts' dt -->
   776                         typ_of_dtyp descr sorts' dt) $ x
   777                     else error "nested recursion not (yet) supported"
   778                 | _ => x) xs :: r_args)
   779           end
   780 
   781         val (_, l_args, r_args) = foldr constr_arg (1, [], []) cargs;
   782         val abs_name = Sign.intern_const thy ("Abs_" ^ tname);
   783         val rep_name = Sign.intern_const thy ("Rep_" ^ tname);
   784         val constrT = map fastype_of l_args ---> T;
   785         val lhs = list_comb (Const (cname, constrT), l_args);
   786         val rhs = list_comb (Const (cname_rep, map fastype_of r_args ---> T'), r_args);
   787         val def = Logic.mk_equals (lhs, Const (abs_name, T' --> T) $ rhs);
   788         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   789           (Const (rep_name, T --> T') $ lhs, rhs));
   790         val def_name = (Sign.base_name cname) ^ "_def";
   791         val ([def_thm], thy') = thy |>
   792           Sign.add_consts_i [(cname', constrT, mx)] |>
   793           (PureThy.add_defs_i false o map Thm.no_attributes) [(def_name, def)]
   794       in (thy', defs @ [def_thm], eqns @ [eqn]) end;
   795 
   796     fun dt_constr_defs ((thy, defs, eqns, dist_lemmas), ((((((_, (_, _, constrs)),
   797         (_, (_, _, constrs'))), tname), T), T'), constr_syntax)) =
   798       let
   799         val rep_const = cterm_of thy
   800           (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> T'));
   801         val dist = standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
   802         val (thy', defs', eqns') = Library.foldl (make_constr_def tname T T')
   803           ((Sign.add_path tname thy, defs, []), constrs ~~ constrs' ~~ constr_syntax)
   804       in
   805         (parent_path flat_names thy', defs', eqns @ [eqns'], dist_lemmas @ [dist])
   806       end;
   807 
   808     val (thy8, constr_defs, constr_rep_eqns, dist_lemmas) = Library.foldl dt_constr_defs
   809       ((thy7, [], [], []), List.take (descr, length new_type_names) ~~
   810         List.take (pdescr, length new_type_names) ~~
   811         new_type_names ~~ newTs ~~ newTs' ~~ constr_syntax);
   812 
   813     val abs_inject_thms = map (collect_simp o #Abs_inject o fst) typedefs
   814     val rep_inject_thms = map (#Rep_inject o fst) typedefs
   815 
   816     (* prove theorem  Rep_i (Constr_j ...) = Constr'_j ...  *)
   817 
   818     fun prove_constr_rep_thm eqn =
   819       let
   820         val inj_thms = map (fn r => r RS iffD1) abs_inject_thms;
   821         val rewrites = constr_defs @ map mk_meta_eq Rep_inverse_thms
   822       in Goal.prove_global thy8 [] [] eqn (fn _ => EVERY
   823         [resolve_tac inj_thms 1,
   824          rewrite_goals_tac rewrites,
   825          rtac refl 3,
   826          resolve_tac rep_intrs 2,
   827          REPEAT (resolve_tac Rep_thms 1)])
   828       end;
   829 
   830     val constr_rep_thmss = map (map prove_constr_rep_thm) constr_rep_eqns;
   831 
   832     (* prove theorem  pi \<bullet> Rep_i x = Rep_i (pi \<bullet> x) *)
   833 
   834     fun prove_perm_rep_perm (atom, perm_closed_thms) = map (fn th =>
   835       let
   836         val _ $ (_ $ (Rep $ x)) = Logic.unvarify (prop_of th);
   837         val Type ("fun", [T, U]) = fastype_of Rep;
   838         val permT = mk_permT (Type (atom, []));
   839         val pi = Free ("pi", permT);
   840       in
   841         Goal.prove_global thy8 [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq
   842             (Const ("Nominal.perm", permT --> U --> U) $ pi $ (Rep $ x),
   843              Rep $ (Const ("Nominal.perm", permT --> T --> T) $ pi $ x))))
   844           (fn _ => simp_tac (HOL_basic_ss addsimps (perm_defs @ Abs_inverse_thms @
   845             perm_closed_thms @ Rep_thms)) 1)
   846       end) Rep_thms;
   847 
   848     val perm_rep_perm_thms = List.concat (map prove_perm_rep_perm
   849       (atoms ~~ perm_closed_thmss));
   850 
   851     (* prove distinctness theorems *)
   852 
   853     val distinctness_limit = Config.get_thy thy8 DatatypeProp.distinctness_limit;
   854     val thy8' = Config.put_thy DatatypeProp.distinctness_limit 1000 thy8;
   855     val distinct_props = DatatypeProp.make_distincts new_type_names descr' sorts' thy8';
   856     val thy8 = Config.put_thy DatatypeProp.distinctness_limit distinctness_limit thy8';
   857 
   858     val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
   859       dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   860         (constr_rep_thmss ~~ dist_lemmas);
   861 
   862     fun prove_distinct_thms (_, []) = []
   863       | prove_distinct_thms (p as (rep_thms, dist_lemma), t::ts) =
   864           let
   865             val dist_thm = Goal.prove_global thy8 [] [] t (fn _ =>
   866               simp_tac (simpset_of thy8 addsimps (dist_lemma :: rep_thms)) 1)
   867           in dist_thm::(standard (dist_thm RS not_sym))::
   868             (prove_distinct_thms (p, ts))
   869           end;
   870 
   871     val distinct_thms = map prove_distinct_thms
   872       (constr_rep_thmss ~~ dist_lemmas ~~ distinct_props);
   873 
   874     (** prove equations for permutation functions **)
   875 
   876     val perm_simps' = map (fn (((i, (_, _, constrs)), tname), constr_rep_thms) =>
   877       let val T = nth_dtyp' i
   878       in List.concat (map (fn (atom, perm_closed_thms) =>
   879           map (fn ((cname, dts), constr_rep_thm) =>
   880         let
   881           val cname = Sign.intern_const thy8
   882             (NameSpace.append tname (Sign.base_name cname));
   883           val permT = mk_permT (Type (atom, []));
   884           val pi = Free ("pi", permT);
   885 
   886           fun perm t =
   887             let val T = fastype_of t
   888             in Const ("Nominal.perm", permT --> T --> T) $ pi $ t end;
   889 
   890           fun constr_arg ((dts, dt), (j, l_args, r_args)) =
   891             let
   892               val Ts = map (typ_of_dtyp descr'' sorts') dts;
   893               val xs = map (fn (T, i) => mk_Free "x" T i)
   894                 (Ts ~~ (j upto j + length dts - 1))
   895               val x = mk_Free "x" (typ_of_dtyp descr'' sorts' dt) (j + length dts)
   896             in
   897               (j + length dts + 1,
   898                xs @ x :: l_args,
   899                map perm (xs @ [x]) @ r_args)
   900             end
   901 
   902           val (_, l_args, r_args) = foldr constr_arg (1, [], []) dts;
   903           val c = Const (cname, map fastype_of l_args ---> T)
   904         in
   905           Goal.prove_global thy8 [] []
   906             (HOLogic.mk_Trueprop (HOLogic.mk_eq
   907               (perm (list_comb (c, l_args)), list_comb (c, r_args))))
   908             (fn _ => EVERY
   909               [simp_tac (simpset_of thy8 addsimps (constr_rep_thm :: perm_defs)) 1,
   910                simp_tac (HOL_basic_ss addsimps (Rep_thms @ Abs_inverse_thms @
   911                  constr_defs @ perm_closed_thms)) 1,
   912                TRY (simp_tac (HOL_basic_ss addsimps
   913                  (symmetric perm_fun_def :: abs_perm)) 1),
   914                TRY (simp_tac (HOL_basic_ss addsimps
   915                  (perm_fun_def :: perm_defs @ Rep_thms @ Abs_inverse_thms @
   916                     perm_closed_thms)) 1)])
   917         end) (constrs ~~ constr_rep_thms)) (atoms ~~ perm_closed_thmss))
   918       end) (List.take (pdescr, length new_type_names) ~~ new_type_names ~~ constr_rep_thmss);
   919 
   920     (** prove injectivity of constructors **)
   921 
   922     val rep_inject_thms' = map (fn th => th RS sym) rep_inject_thms;
   923     val alpha = PureThy.get_thms thy8 "alpha";
   924     val abs_fresh = PureThy.get_thms thy8 "abs_fresh";
   925 
   926     val inject_thms = map (fn (((i, (_, _, constrs)), tname), constr_rep_thms) =>
   927       let val T = nth_dtyp' i
   928       in List.mapPartial (fn ((cname, dts), constr_rep_thm) =>
   929         if null dts then NONE else SOME
   930         let
   931           val cname = Sign.intern_const thy8
   932             (NameSpace.append tname (Sign.base_name cname));
   933 
   934           fun make_inj ((dts, dt), (j, args1, args2, eqs)) =
   935             let
   936               val Ts_idx = map (typ_of_dtyp descr'' sorts') dts ~~ (j upto j + length dts - 1);
   937               val xs = map (fn (T, i) => mk_Free "x" T i) Ts_idx;
   938               val ys = map (fn (T, i) => mk_Free "y" T i) Ts_idx;
   939               val x = mk_Free "x" (typ_of_dtyp descr'' sorts' dt) (j + length dts);
   940               val y = mk_Free "y" (typ_of_dtyp descr'' sorts' dt) (j + length dts)
   941             in
   942               (j + length dts + 1,
   943                xs @ (x :: args1), ys @ (y :: args2),
   944                HOLogic.mk_eq
   945                  (foldr mk_abs_fun x xs, foldr mk_abs_fun y ys) :: eqs)
   946             end;
   947 
   948           val (_, args1, args2, eqs) = foldr make_inj (1, [], [], []) dts;
   949           val Ts = map fastype_of args1;
   950           val c = Const (cname, Ts ---> T)
   951         in
   952           Goal.prove_global thy8 [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq
   953               (HOLogic.mk_eq (list_comb (c, args1), list_comb (c, args2)),
   954                foldr1 HOLogic.mk_conj eqs)))
   955             (fn _ => EVERY
   956                [asm_full_simp_tac (simpset_of thy8 addsimps (constr_rep_thm ::
   957                   rep_inject_thms')) 1,
   958                 TRY (asm_full_simp_tac (HOL_basic_ss addsimps (fresh_def :: supp_def ::
   959                   alpha @ abs_perm @ abs_fresh @ rep_inject_thms @
   960                   perm_rep_perm_thms)) 1),
   961                 TRY (asm_full_simp_tac (HOL_basic_ss addsimps (perm_fun_def ::
   962                   @{thm expand_fun_eq} :: rep_inject_thms @ perm_rep_perm_thms)) 1)])
   963         end) (constrs ~~ constr_rep_thms)
   964       end) (List.take (pdescr, length new_type_names) ~~ new_type_names ~~ constr_rep_thmss);
   965 
   966     (** equations for support and freshness **)
   967 
   968     val (supp_thms, fresh_thms) = ListPair.unzip (map ListPair.unzip
   969       (map (fn ((((i, (_, _, constrs)), tname), inject_thms'), perm_thms') =>
   970       let val T = nth_dtyp' i
   971       in List.concat (map (fn (cname, dts) => map (fn atom =>
   972         let
   973           val cname = Sign.intern_const thy8
   974             (NameSpace.append tname (Sign.base_name cname));
   975           val atomT = Type (atom, []);
   976 
   977           fun process_constr ((dts, dt), (j, args1, args2)) =
   978             let
   979               val Ts_idx = map (typ_of_dtyp descr'' sorts') dts ~~ (j upto j + length dts - 1);
   980               val xs = map (fn (T, i) => mk_Free "x" T i) Ts_idx;
   981               val x = mk_Free "x" (typ_of_dtyp descr'' sorts' dt) (j + length dts)
   982             in
   983               (j + length dts + 1,
   984                xs @ (x :: args1), foldr mk_abs_fun x xs :: args2)
   985             end;
   986 
   987           val (_, args1, args2) = foldr process_constr (1, [], []) dts;
   988           val Ts = map fastype_of args1;
   989           val c = list_comb (Const (cname, Ts ---> T), args1);
   990           fun supp t =
   991             Const ("Nominal.supp", fastype_of t --> HOLogic.mk_setT atomT) $ t;
   992           fun fresh t = fresh_const atomT (fastype_of t) $ Free ("a", atomT) $ t;
   993           val supp_thm = Goal.prove_global thy8 [] []
   994               (HOLogic.mk_Trueprop (HOLogic.mk_eq
   995                 (supp c,
   996                  if null dts then Const ("{}", HOLogic.mk_setT atomT)
   997                  else foldr1 (HOLogic.mk_binop "op Un") (map supp args2))))
   998             (fn _ =>
   999               simp_tac (HOL_basic_ss addsimps (supp_def ::
  1000                  Un_assoc :: de_Morgan_conj :: Collect_disj_eq :: finite_Un ::
  1001                  symmetric empty_def :: finite_emptyI :: simp_thms @
  1002                  abs_perm @ abs_fresh @ inject_thms' @ perm_thms')) 1)
  1003         in
  1004           (supp_thm,
  1005            Goal.prove_global thy8 [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1006               (fresh c,
  1007                if null dts then HOLogic.true_const
  1008                else foldr1 HOLogic.mk_conj (map fresh args2))))
  1009              (fn _ =>
  1010                simp_tac (HOL_ss addsimps [Un_iff, empty_iff, fresh_def, supp_thm]) 1))
  1011         end) atoms) constrs)
  1012       end) (List.take (pdescr, length new_type_names) ~~ new_type_names ~~ inject_thms ~~ perm_simps')));
  1013 
  1014     (**** weak induction theorem ****)
  1015 
  1016     fun mk_indrule_lemma ((prems, concls), (((i, _), T), U)) =
  1017       let
  1018         val Rep_t = Const (List.nth (rep_names, i), T --> U) $
  1019           mk_Free "x" T i;
  1020 
  1021         val Abs_t =  Const (List.nth (abs_names, i), U --> T)
  1022 
  1023       in (prems @ [HOLogic.imp $
  1024             (Const (List.nth (rep_set_names'', i), U --> HOLogic.boolT) $ Rep_t) $
  1025               (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
  1026           concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
  1027       end;
  1028 
  1029     val (indrule_lemma_prems, indrule_lemma_concls) =
  1030       Library.foldl mk_indrule_lemma (([], []), (descr'' ~~ recTs ~~ recTs'));
  1031 
  1032     val indrule_lemma = Goal.prove_global thy8 [] []
  1033       (Logic.mk_implies
  1034         (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
  1035          HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
  1036            [REPEAT (etac conjE 1),
  1037             REPEAT (EVERY
  1038               [TRY (rtac conjI 1), full_simp_tac (HOL_basic_ss addsimps Rep_inverse_thms) 1,
  1039                etac mp 1, resolve_tac Rep_thms 1])]);
  1040 
  1041     val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
  1042     val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
  1043       map (Free o apfst fst o dest_Var) Ps;
  1044     val indrule_lemma' = cterm_instantiate
  1045       (map (cterm_of thy8) Ps ~~ map (cterm_of thy8) frees) indrule_lemma;
  1046 
  1047     val Abs_inverse_thms' = map (fn r => r RS subst) Abs_inverse_thms;
  1048 
  1049     val dt_induct_prop = DatatypeProp.make_ind descr' sorts';
  1050     val dt_induct = Goal.prove_global thy8 []
  1051       (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
  1052       (fn prems => EVERY
  1053         [rtac indrule_lemma' 1,
  1054          (indtac rep_induct [] THEN_ALL_NEW ObjectLogic.atomize_prems_tac) 1,
  1055          EVERY (map (fn (prem, r) => (EVERY
  1056            [REPEAT (eresolve_tac Abs_inverse_thms' 1),
  1057             simp_tac (HOL_basic_ss addsimps [symmetric r]) 1,
  1058             DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
  1059                 (prems ~~ constr_defs))]);
  1060 
  1061     val case_names_induct = mk_case_names_induct descr'';
  1062 
  1063     (**** prove that new datatypes have finite support ****)
  1064 
  1065     val _ = warning "proving finite support for the new datatype";
  1066 
  1067     val indnames = DatatypeProp.make_tnames recTs;
  1068 
  1069     val abs_supp = PureThy.get_thms thy8 "abs_supp";
  1070     val supp_atm = PureThy.get_thms thy8 "supp_atm";
  1071 
  1072     val finite_supp_thms = map (fn atom =>
  1073       let val atomT = Type (atom, [])
  1074       in map standard (List.take
  1075         (split_conj_thm (Goal.prove_global thy8 [] [] (HOLogic.mk_Trueprop
  1076            (foldr1 HOLogic.mk_conj (map (fn (s, T) =>
  1077              Const ("Finite_Set.finite", HOLogic.mk_setT atomT --> HOLogic.boolT) $
  1078                (Const ("Nominal.supp", T --> HOLogic.mk_setT atomT) $ Free (s, T)))
  1079                (indnames ~~ recTs))))
  1080            (fn _ => indtac dt_induct indnames 1 THEN
  1081             ALLGOALS (asm_full_simp_tac (simpset_of thy8 addsimps
  1082               (abs_supp @ supp_atm @
  1083                PureThy.get_thms thy8 ("fs_" ^ Sign.base_name atom ^ "1") @
  1084                List.concat supp_thms))))),
  1085          length new_type_names))
  1086       end) atoms;
  1087 
  1088     val simp_atts = replicate (length new_type_names) [Simplifier.simp_add];
  1089 
  1090 	(* Function to add both the simp and eqvt attributes *)
  1091         (* These two attributes are duplicated on all the types in the mutual nominal datatypes *)
  1092 
  1093     val simp_eqvt_atts = replicate (length new_type_names) [Simplifier.simp_add, NominalThmDecls.eqvt_add];
  1094  
  1095     val (_, thy9) = thy8 |>
  1096       Sign.add_path big_name |>
  1097       PureThy.add_thms [(("weak_induct", dt_induct), [case_names_induct])] ||>>
  1098       PureThy.add_thmss [(("weak_inducts", projections dt_induct), [case_names_induct])] ||>
  1099       Sign.parent_path ||>>
  1100       DatatypeAux.store_thmss_atts "distinct" new_type_names simp_atts distinct_thms ||>>
  1101       DatatypeAux.store_thmss "constr_rep" new_type_names constr_rep_thmss ||>>
  1102       DatatypeAux.store_thmss_atts "perm" new_type_names simp_eqvt_atts perm_simps' ||>>
  1103       DatatypeAux.store_thmss "inject" new_type_names inject_thms ||>>
  1104       DatatypeAux.store_thmss "supp" new_type_names supp_thms ||>>
  1105       DatatypeAux.store_thmss_atts "fresh" new_type_names simp_atts fresh_thms ||>
  1106       fold (fn (atom, ths) => fn thy =>
  1107         let val class = Sign.intern_class thy ("fs_" ^ Sign.base_name atom)
  1108         in fold (fn T => AxClass.prove_arity
  1109             (fst (dest_Type T),
  1110               replicate (length sorts) [class], [class])
  1111             (Class.intro_classes_tac [] THEN resolve_tac ths 1)) newTs thy
  1112         end) (atoms ~~ finite_supp_thms);
  1113 
  1114     (**** strong induction theorem ****)
  1115 
  1116     val pnames = if length descr'' = 1 then ["P"]
  1117       else map (fn i => "P" ^ string_of_int i) (1 upto length descr'');
  1118     val ind_sort = if null dt_atomTs then HOLogic.typeS
  1119       else Sign.certify_sort thy9 (map (fn T => Sign.intern_class thy9 ("fs_" ^
  1120         Sign.base_name (fst (dest_Type T)))) dt_atomTs);
  1121     val fsT = TFree ("'n", ind_sort);
  1122     val fsT' = TFree ("'n", HOLogic.typeS);
  1123 
  1124     val fresh_fs = map (fn (s, T) => (T, Free (s, fsT' --> HOLogic.mk_setT T)))
  1125       (DatatypeProp.indexify_names (replicate (length dt_atomTs) "f") ~~ dt_atomTs);
  1126 
  1127     fun make_pred fsT i T =
  1128       Free (List.nth (pnames, i), fsT --> T --> HOLogic.boolT);
  1129 
  1130     fun mk_fresh1 xs [] = []
  1131       | mk_fresh1 xs ((y as (_, T)) :: ys) = map (fn x => HOLogic.mk_Trueprop
  1132             (HOLogic.mk_not (HOLogic.mk_eq (Free y, Free x))))
  1133               (filter (fn (_, U) => T = U) (rev xs)) @
  1134           mk_fresh1 (y :: xs) ys;
  1135 
  1136     fun mk_fresh2 xss [] = []
  1137       | mk_fresh2 xss ((p as (ys, _)) :: yss) = List.concat (map (fn y as (_, T) =>
  1138             map (fn (_, x as (_, U)) => HOLogic.mk_Trueprop
  1139               (fresh_const T U $ Free y $ Free x)) (rev xss @ yss)) ys) @
  1140           mk_fresh2 (p :: xss) yss;
  1141 
  1142     fun make_ind_prem fsT f k T ((cname, cargs), idxs) =
  1143       let
  1144         val recs = List.filter is_rec_type cargs;
  1145         val Ts = map (typ_of_dtyp descr'' sorts') cargs;
  1146         val recTs' = map (typ_of_dtyp descr'' sorts') recs;
  1147         val tnames = Name.variant_list pnames (DatatypeProp.make_tnames Ts);
  1148         val rec_tnames = map fst (List.filter (is_rec_type o snd) (tnames ~~ cargs));
  1149         val frees = tnames ~~ Ts;
  1150         val frees' = partition_cargs idxs frees;
  1151         val z = (Name.variant tnames "z", fsT);
  1152 
  1153         fun mk_prem ((dt, s), T) =
  1154           let
  1155             val (Us, U) = strip_type T;
  1156             val l = length Us
  1157           in list_all (z :: map (pair "x") Us, HOLogic.mk_Trueprop
  1158             (make_pred fsT (body_index dt) U $ Bound l $ app_bnds (Free (s, T)) l))
  1159           end;
  1160 
  1161         val prems = map mk_prem (recs ~~ rec_tnames ~~ recTs');
  1162         val prems' = map (fn p as (_, T) => HOLogic.mk_Trueprop
  1163             (f T (Free p) (Free z))) (List.concat (map fst frees')) @
  1164           mk_fresh1 [] (List.concat (map fst frees')) @
  1165           mk_fresh2 [] frees'
  1166 
  1167       in list_all_free (frees @ [z], Logic.list_implies (prems' @ prems,
  1168         HOLogic.mk_Trueprop (make_pred fsT k T $ Free z $
  1169           list_comb (Const (cname, Ts ---> T), map Free frees))))
  1170       end;
  1171 
  1172     val ind_prems = List.concat (map (fn (((i, (_, _, constrs)), (_, idxss)), T) =>
  1173       map (make_ind_prem fsT (fn T => fn t => fn u =>
  1174         fresh_const T fsT $ t $ u) i T)
  1175           (constrs ~~ idxss)) (descr'' ~~ ndescr ~~ recTs));
  1176     val tnames = DatatypeProp.make_tnames recTs;
  1177     val zs = Name.variant_list tnames (replicate (length descr'') "z");
  1178     val ind_concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
  1179       (map (fn ((((i, _), T), tname), z) =>
  1180         make_pred fsT i T $ Free (z, fsT) $ Free (tname, T))
  1181         (descr'' ~~ recTs ~~ tnames ~~ zs)));
  1182     val induct = Logic.list_implies (ind_prems, ind_concl);
  1183 
  1184     val ind_prems' =
  1185       map (fn (_, f as Free (_, T)) => list_all_free ([("x", fsT')],
  1186         HOLogic.mk_Trueprop (Const ("Finite_Set.finite", body_type T -->
  1187           HOLogic.boolT) $ (f $ Free ("x", fsT'))))) fresh_fs @
  1188       List.concat (map (fn (((i, (_, _, constrs)), (_, idxss)), T) =>
  1189         map (make_ind_prem fsT' (fn T => fn t => fn u => HOLogic.Not $
  1190           HOLogic.mk_mem (t, the (AList.lookup op = fresh_fs T) $ u)) i T)
  1191             (constrs ~~ idxss)) (descr'' ~~ ndescr ~~ recTs));
  1192     val ind_concl' = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
  1193       (map (fn ((((i, _), T), tname), z) =>
  1194         make_pred fsT' i T $ Free (z, fsT') $ Free (tname, T))
  1195         (descr'' ~~ recTs ~~ tnames ~~ zs)));
  1196     val induct' = Logic.list_implies (ind_prems', ind_concl');
  1197 
  1198     val aux_ind_vars =
  1199       (DatatypeProp.indexify_names (replicate (length dt_atomTs) "pi") ~~
  1200        map mk_permT dt_atomTs) @ [("z", fsT')];
  1201     val aux_ind_Ts = rev (map snd aux_ind_vars);
  1202     val aux_ind_concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
  1203       (map (fn (((i, _), T), tname) =>
  1204         HOLogic.list_all (aux_ind_vars, make_pred fsT' i T $ Bound 0 $
  1205           fold_rev (mk_perm aux_ind_Ts) (map Bound (length dt_atomTs downto 1))
  1206             (Free (tname, T))))
  1207         (descr'' ~~ recTs ~~ tnames)));
  1208 
  1209     val fin_set_supp = map (fn Type (s, _) =>
  1210       PureThy.get_thm thy9 ("at_" ^ Sign.base_name s ^ "_inst") RS
  1211         at_fin_set_supp) dt_atomTs;
  1212     val fin_set_fresh = map (fn Type (s, _) =>
  1213       PureThy.get_thm thy9 ("at_" ^ Sign.base_name s ^ "_inst") RS
  1214         at_fin_set_fresh) dt_atomTs;
  1215     val pt1_atoms = map (fn Type (s, _) =>
  1216       PureThy.get_thm thy9 ("pt_" ^ Sign.base_name s ^ "1")) dt_atomTs;
  1217     val pt2_atoms = map (fn Type (s, _) =>
  1218       PureThy.get_thm thy9 ("pt_" ^ Sign.base_name s ^ "2") RS sym) dt_atomTs;
  1219     val exists_fresh' = PureThy.get_thms thy9 "exists_fresh'";
  1220     val fs_atoms = PureThy.get_thms thy9 "fin_supp";
  1221     val abs_supp = PureThy.get_thms thy9 "abs_supp";
  1222     val perm_fresh_fresh = PureThy.get_thms thy9 "perm_fresh_fresh";
  1223     val calc_atm = PureThy.get_thms thy9 "calc_atm";
  1224     val fresh_atm = PureThy.get_thms thy9 "fresh_atm";
  1225     val fresh_left = PureThy.get_thms thy9 "fresh_left";
  1226     val perm_swap = PureThy.get_thms thy9 "perm_swap";
  1227 
  1228     fun obtain_fresh_name' ths ts T (freshs1, freshs2, ctxt) =
  1229       let
  1230         val p = foldr1 HOLogic.mk_prod (ts @ freshs1);
  1231         val ex = Goal.prove ctxt [] [] (HOLogic.mk_Trueprop
  1232             (HOLogic.exists_const T $ Abs ("x", T,
  1233               fresh_const T (fastype_of p) $
  1234                 Bound 0 $ p)))
  1235           (fn _ => EVERY
  1236             [resolve_tac exists_fresh' 1,
  1237              simp_tac (HOL_ss addsimps (supp_prod :: finite_Un :: fs_atoms @
  1238                fin_set_supp @ ths)) 1]);
  1239         val (([cx], ths), ctxt') = Obtain.result
  1240           (fn _ => EVERY
  1241             [etac exE 1,
  1242              full_simp_tac (HOL_ss addsimps (fresh_prod :: fresh_atm)) 1,
  1243              REPEAT (etac conjE 1)])
  1244           [ex] ctxt
  1245       in (freshs1 @ [term_of cx], freshs2 @ ths, ctxt') end;
  1246 
  1247     fun fresh_fresh_inst thy a b =
  1248       let
  1249         val T = fastype_of a;
  1250         val SOME th = find_first (fn th => case prop_of th of
  1251             _ $ (_ $ (Const (_, Type (_, [U, _])) $ _ $ _)) $ _ => U = T
  1252           | _ => false) perm_fresh_fresh
  1253       in
  1254         Drule.instantiate' []
  1255           [SOME (cterm_of thy a), NONE, SOME (cterm_of thy b)] th
  1256       end;
  1257 
  1258     (**********************************************************************
  1259       The subgoals occurring in the proof of induct_aux have the
  1260       following parameters:
  1261 
  1262         x_1 ... x_k p_1 ... p_m z
  1263 
  1264       where
  1265 
  1266         x_i : constructor arguments (introduced by weak induction rule)
  1267         p_i : permutations (one for each atom type in the data type)
  1268         z   : freshness context
  1269     ***********************************************************************)
  1270 
  1271     val _ = warning "proving strong induction theorem ...";
  1272 
  1273     val induct_aux = Goal.prove_global thy9 [] ind_prems' ind_concl' (fn prems =>
  1274       let
  1275         val (prems1, prems2) = chop (length dt_atomTs) prems;
  1276         val ind_ss2 = HOL_ss addsimps
  1277           finite_Diff :: abs_fresh @ abs_supp @ fs_atoms;
  1278         val ind_ss1 = ind_ss2 addsimps fresh_left @ calc_atm @
  1279           fresh_atm @ rev_simps @ app_simps;
  1280         val ind_ss3 = HOL_ss addsimps abs_fun_eq1 ::
  1281           abs_perm @ calc_atm @ perm_swap;
  1282         val ind_ss4 = HOL_basic_ss addsimps fresh_left @ prems1 @
  1283           fin_set_fresh @ calc_atm;
  1284         val ind_ss5 = HOL_basic_ss addsimps pt1_atoms;
  1285         val ind_ss6 = HOL_basic_ss addsimps flat perm_simps';
  1286         val th = Goal.prove (ProofContext.init thy9) [] [] aux_ind_concl
  1287           (fn {context = context1, ...} =>
  1288              EVERY (indtac dt_induct tnames 1 ::
  1289                maps (fn ((_, (_, _, constrs)), (_, constrs')) =>
  1290                  map (fn ((cname, cargs), is) =>
  1291                    REPEAT (rtac allI 1) THEN
  1292                    SUBPROOF (fn {prems = iprems, params, concl,
  1293                        context = context2, ...} =>
  1294                      let
  1295                        val concl' = term_of concl;
  1296                        val _ $ (_ $ _ $ u) = concl';
  1297                        val U = fastype_of u;
  1298                        val (xs, params') =
  1299                          chop (length cargs) (map term_of params);
  1300                        val Ts = map fastype_of xs;
  1301                        val cnstr = Const (cname, Ts ---> U);
  1302                        val (pis, z) = split_last params';
  1303                        val mk_pi = fold_rev (mk_perm []) pis;
  1304                        val xs' = partition_cargs is xs;
  1305                        val xs'' = map (fn (ts, u) => (map mk_pi ts, mk_pi u)) xs';
  1306                        val ts = maps (fn (ts, u) => ts @ [u]) xs'';
  1307                        val (freshs1, freshs2, context3) = fold (fn t =>
  1308                          let val T = fastype_of t
  1309                          in obtain_fresh_name' prems1
  1310                            (the (AList.lookup op = fresh_fs T) $ z :: ts) T
  1311                          end) (maps fst xs') ([], [], context2);
  1312                        val freshs1' = unflat (map fst xs') freshs1;
  1313                        val freshs2' = map (Simplifier.simplify ind_ss4)
  1314                          (mk_not_sym freshs2);
  1315                        val ind_ss1' = ind_ss1 addsimps freshs2';
  1316                        val ind_ss3' = ind_ss3 addsimps freshs2';
  1317                        val rename_eq =
  1318                          if forall (null o fst) xs' then []
  1319                          else [Goal.prove context3 [] []
  1320                            (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1321                              (list_comb (cnstr, ts),
  1322                               list_comb (cnstr, maps (fn ((bs, t), cs) =>
  1323                                 cs @ [fold_rev (mk_perm []) (map perm_of_pair
  1324                                   (bs ~~ cs)) t]) (xs'' ~~ freshs1')))))
  1325                            (fn _ => EVERY
  1326                               (simp_tac (HOL_ss addsimps flat inject_thms) 1 ::
  1327                                REPEAT (FIRSTGOAL (rtac conjI)) ::
  1328                                maps (fn ((bs, t), cs) =>
  1329                                  if null bs then []
  1330                                  else rtac sym 1 :: maps (fn (b, c) =>
  1331                                    [rtac trans 1, rtac sym 1,
  1332                                     rtac (fresh_fresh_inst thy9 b c) 1,
  1333                                     simp_tac ind_ss1' 1,
  1334                                     simp_tac ind_ss2 1,
  1335                                     simp_tac ind_ss3' 1]) (bs ~~ cs))
  1336                                  (xs'' ~~ freshs1')))];
  1337                        val th = Goal.prove context3 [] [] concl' (fn _ => EVERY
  1338                          [simp_tac (ind_ss6 addsimps rename_eq) 1,
  1339                           cut_facts_tac iprems 1,
  1340                           (resolve_tac prems THEN_ALL_NEW
  1341                             SUBGOAL (fn (t, i) => case Logic.strip_assums_concl t of
  1342                                 _ $ (Const ("Nominal.fresh", _) $ _ $ _) =>
  1343                                   simp_tac ind_ss1' i
  1344                               | _ $ (Const ("Not", _) $ _) =>
  1345                                   resolve_tac freshs2' i
  1346                               | _ => asm_simp_tac (HOL_basic_ss addsimps
  1347                                   pt2_atoms addsimprocs [perm_simproc]) i)) 1])
  1348                        val final = ProofContext.export context3 context2 [th]
  1349                      in
  1350                        resolve_tac final 1
  1351                      end) context1 1) (constrs ~~ constrs')) (descr'' ~~ ndescr)))
  1352       in
  1353         EVERY
  1354           [cut_facts_tac [th] 1,
  1355            REPEAT (eresolve_tac [conjE, allE_Nil] 1),
  1356            REPEAT (etac allE 1),
  1357            REPEAT (TRY (rtac conjI 1) THEN asm_full_simp_tac ind_ss5 1)]
  1358       end);
  1359 
  1360     val induct_aux' = Thm.instantiate ([],
  1361       map (fn (s, T) =>
  1362         let val pT = TVar (("'n", 0), HOLogic.typeS) --> T --> HOLogic.boolT
  1363         in (cterm_of thy9 (Var ((s, 0), pT)), cterm_of thy9 (Free (s, pT))) end)
  1364           (pnames ~~ recTs) @
  1365       map (fn (_, f) =>
  1366         let val f' = Logic.varify f
  1367         in (cterm_of thy9 f',
  1368           cterm_of thy9 (Const ("Nominal.supp", fastype_of f')))
  1369         end) fresh_fs) induct_aux;
  1370 
  1371     val induct = Goal.prove_global thy9 [] ind_prems ind_concl
  1372       (fn prems => EVERY
  1373          [rtac induct_aux' 1,
  1374           REPEAT (resolve_tac fs_atoms 1),
  1375           REPEAT ((resolve_tac prems THEN_ALL_NEW
  1376             (etac meta_spec ORELSE' full_simp_tac (HOL_basic_ss addsimps [fresh_def]))) 1)])
  1377 
  1378     val (_, thy10) = thy9 |>
  1379       Sign.add_path big_name |>
  1380       PureThy.add_thms [(("induct'", induct_aux), [])] ||>>
  1381       PureThy.add_thms [(("induct", induct), [case_names_induct])] ||>>
  1382       PureThy.add_thmss [(("inducts", projections induct), [case_names_induct])];
  1383 
  1384     (**** recursion combinator ****)
  1385 
  1386     val _ = warning "defining recursion combinator ...";
  1387 
  1388     val used = foldr add_typ_tfree_names [] recTs;
  1389 
  1390     val (rec_result_Ts', rec_fn_Ts') = DatatypeProp.make_primrec_Ts descr' sorts' used;
  1391 
  1392     val rec_sort = if null dt_atomTs then HOLogic.typeS else
  1393       let val names = map (Sign.base_name o fst o dest_Type) dt_atomTs
  1394       in Sign.certify_sort thy10 (map (Sign.intern_class thy10)
  1395         (map (fn s => "pt_" ^ s) names @
  1396          List.concat (map (fn s => List.mapPartial (fn s' =>
  1397            if s = s' then NONE
  1398            else SOME ("cp_" ^ s ^ "_" ^ s')) names) names)))
  1399       end;
  1400 
  1401     val rec_result_Ts = map (fn TFree (s, _) => TFree (s, rec_sort)) rec_result_Ts';
  1402     val rec_fn_Ts = map (typ_subst_atomic (rec_result_Ts' ~~ rec_result_Ts)) rec_fn_Ts';
  1403 
  1404     val rec_set_Ts = map (fn (T1, T2) =>
  1405       rec_fn_Ts @ [T1, T2] ---> HOLogic.boolT) (recTs ~~ rec_result_Ts);
  1406 
  1407     val big_rec_name = big_name ^ "_rec_set";
  1408     val rec_set_names' =
  1409       if length descr'' = 1 then [big_rec_name] else
  1410         map ((curry (op ^) (big_rec_name ^ "_")) o string_of_int)
  1411           (1 upto (length descr''));
  1412     val rec_set_names =  map (Sign.full_name thy10) rec_set_names';
  1413 
  1414     val rec_fns = map (uncurry (mk_Free "f"))
  1415       (rec_fn_Ts ~~ (1 upto (length rec_fn_Ts)));
  1416     val rec_sets' = map (fn c => list_comb (Free c, rec_fns))
  1417       (rec_set_names' ~~ rec_set_Ts);
  1418     val rec_sets = map (fn c => list_comb (Const c, rec_fns))
  1419       (rec_set_names ~~ rec_set_Ts);
  1420 
  1421     (* introduction rules for graph of recursion function *)
  1422 
  1423     val rec_preds = map (fn (a, T) =>
  1424       Free (a, T --> HOLogic.boolT)) (pnames ~~ rec_result_Ts);
  1425 
  1426     fun mk_fresh3 rs [] = []
  1427       | mk_fresh3 rs ((p as (ys, z)) :: yss) = List.concat (map (fn y as (_, T) =>
  1428             List.mapPartial (fn ((_, (_, x)), r as (_, U)) => if z = x then NONE
  1429               else SOME (HOLogic.mk_Trueprop
  1430                 (fresh_const T U $ Free y $ Free r))) rs) ys) @
  1431           mk_fresh3 rs yss;
  1432 
  1433     (* FIXME: avoid collisions with other variable names? *)
  1434     val rec_ctxt = Free ("z", fsT');
  1435 
  1436     fun make_rec_intr T p rec_set ((rec_intr_ts, rec_prems, rec_prems',
  1437           rec_eq_prems, l), ((cname, cargs), idxs)) =
  1438       let
  1439         val Ts = map (typ_of_dtyp descr'' sorts') cargs;
  1440         val frees = map (fn i => "x" ^ string_of_int i) (1 upto length Ts) ~~ Ts;
  1441         val frees' = partition_cargs idxs frees;
  1442         val binders = List.concat (map fst frees');
  1443         val atomTs = distinct op = (maps (map snd o fst) frees');
  1444         val recs = List.mapPartial
  1445           (fn ((_, DtRec i), p) => SOME (i, p) | _ => NONE)
  1446           (partition_cargs idxs cargs ~~ frees');
  1447         val frees'' = map (fn i => "y" ^ string_of_int i) (1 upto length recs) ~~
  1448           map (fn (i, _) => List.nth (rec_result_Ts, i)) recs;
  1449         val prems1 = map (fn ((i, (_, x)), y) => HOLogic.mk_Trueprop
  1450           (List.nth (rec_sets', i) $ Free x $ Free y)) (recs ~~ frees'');
  1451         val prems2 =
  1452           map (fn f => map (fn p as (_, T) => HOLogic.mk_Trueprop
  1453             (fresh_const T (fastype_of f) $ Free p $ f)) binders) rec_fns;
  1454         val prems3 = mk_fresh1 [] binders @ mk_fresh2 [] frees';
  1455         val prems4 = map (fn ((i, _), y) =>
  1456           HOLogic.mk_Trueprop (List.nth (rec_preds, i) $ Free y)) (recs ~~ frees'');
  1457         val prems5 = mk_fresh3 (recs ~~ frees'') frees';
  1458         val prems6 = maps (fn aT => map (fn y as (_, T) => HOLogic.mk_Trueprop
  1459           (Const ("Finite_Set.finite", HOLogic.mk_setT aT --> HOLogic.boolT) $
  1460              (Const ("Nominal.supp", T --> HOLogic.mk_setT aT) $ Free y)))
  1461                frees'') atomTs;
  1462         val prems7 = map (fn x as (_, T) => HOLogic.mk_Trueprop
  1463           (fresh_const T fsT' $ Free x $ rec_ctxt)) binders;
  1464         val result = list_comb (List.nth (rec_fns, l), map Free (frees @ frees''));
  1465         val result_freshs = map (fn p as (_, T) =>
  1466           fresh_const T (fastype_of result) $ Free p $ result) binders;
  1467         val P = HOLogic.mk_Trueprop (p $ result)
  1468       in
  1469         (rec_intr_ts @ [Logic.list_implies (List.concat prems2 @ prems3 @ prems1,
  1470            HOLogic.mk_Trueprop (rec_set $
  1471              list_comb (Const (cname, Ts ---> T), map Free frees) $ result))],
  1472          rec_prems @ [list_all_free (frees @ frees'', Logic.list_implies (prems4, P))],
  1473          rec_prems' @ map (fn fr => list_all_free (frees @ frees'',
  1474            Logic.list_implies (List.nth (prems2, l) @ prems3 @ prems5 @ prems7 @ prems6 @ [P],
  1475              HOLogic.mk_Trueprop fr))) result_freshs,
  1476          rec_eq_prems @ [List.concat prems2 @ prems3],
  1477          l + 1)
  1478       end;
  1479 
  1480     val (rec_intr_ts, rec_prems, rec_prems', rec_eq_prems, _) =
  1481       Library.foldl (fn (x, ((((d, d'), T), p), rec_set)) =>
  1482         Library.foldl (make_rec_intr T p rec_set) (x, #3 (snd d) ~~ snd d'))
  1483           (([], [], [], [], 0), descr'' ~~ ndescr ~~ recTs ~~ rec_preds ~~ rec_sets');
  1484 
  1485     val ({intrs = rec_intrs, elims = rec_elims, raw_induct = rec_induct, ...}, thy11) =
  1486       thy10 |>
  1487       setmp InductivePackage.quiet_mode (!quiet_mode)
  1488         (InductivePackage.add_inductive_global (serial_string ())
  1489           {verbose = false, kind = Thm.internalK,
  1490             alt_name = big_rec_name, coind = false, no_elim = false, no_ind = false}
  1491           (map (fn (s, T) => ((s, T), NoSyn)) (rec_set_names' ~~ rec_set_Ts))
  1492           (map dest_Free rec_fns)
  1493           (map (fn x => (("", []), x)) rec_intr_ts) []) ||>
  1494       PureThy.hide_thms true [NameSpace.append
  1495         (Sign.full_name thy10 big_rec_name) "induct"];
  1496 
  1497     (** equivariance **)
  1498 
  1499     val fresh_bij = PureThy.get_thms thy11 "fresh_bij";
  1500     val perm_bij = PureThy.get_thms thy11 "perm_bij";
  1501 
  1502     val (rec_equiv_thms, rec_equiv_thms') = ListPair.unzip (map (fn aT =>
  1503       let
  1504         val permT = mk_permT aT;
  1505         val pi = Free ("pi", permT);
  1506         val rec_fns_pi = map (mk_perm [] pi o uncurry (mk_Free "f"))
  1507           (rec_fn_Ts ~~ (1 upto (length rec_fn_Ts)));
  1508         val rec_sets_pi = map (fn c => list_comb (Const c, rec_fns_pi))
  1509           (rec_set_names ~~ rec_set_Ts);
  1510         val ps = map (fn ((((T, U), R), R'), i) =>
  1511           let
  1512             val x = Free ("x" ^ string_of_int i, T);
  1513             val y = Free ("y" ^ string_of_int i, U)
  1514           in
  1515             (R $ x $ y, R' $ mk_perm [] pi x $ mk_perm [] pi y)
  1516           end) (recTs ~~ rec_result_Ts ~~ rec_sets ~~ rec_sets_pi ~~ (1 upto length recTs));
  1517         val ths = map (fn th => standard (th RS mp)) (split_conj_thm
  1518           (Goal.prove_global thy11 [] []
  1519             (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj (map HOLogic.mk_imp ps)))
  1520             (fn _ => rtac rec_induct 1 THEN REPEAT
  1521                (NominalPermeq.perm_simp_tac (HOL_basic_ss addsimps flat perm_simps') 1 THEN
  1522                 (resolve_tac rec_intrs THEN_ALL_NEW
  1523                  asm_simp_tac (HOL_ss addsimps (fresh_bij @ perm_bij))) 1))))
  1524         val ths' = map (fn ((P, Q), th) =>
  1525           Goal.prove_global thy11 [] []
  1526             (Logic.mk_implies (HOLogic.mk_Trueprop Q, HOLogic.mk_Trueprop P))
  1527             (fn _ => dtac (Thm.instantiate ([],
  1528                  [(cterm_of thy11 (Var (("pi", 0), permT)),
  1529                    cterm_of thy11 (Const ("List.rev", permT --> permT) $ pi))]) th) 1 THEN
  1530                NominalPermeq.perm_simp_tac HOL_ss 1)) (ps ~~ ths)
  1531       in (ths, ths') end) dt_atomTs);
  1532 
  1533     (** finite support **)
  1534 
  1535     val rec_fin_supp_thms = map (fn aT =>
  1536       let
  1537         val name = Sign.base_name (fst (dest_Type aT));
  1538         val fs_name = PureThy.get_thm thy11 ("fs_" ^ name ^ "1");
  1539         val aset = HOLogic.mk_setT aT;
  1540         val finite = Const ("Finite_Set.finite", aset --> HOLogic.boolT);
  1541         val fins = map (fn (f, T) => HOLogic.mk_Trueprop
  1542           (finite $ (Const ("Nominal.supp", T --> aset) $ f)))
  1543             (rec_fns ~~ rec_fn_Ts)
  1544       in
  1545         map (fn th => standard (th RS mp)) (split_conj_thm
  1546           (Goal.prove_global thy11 [] fins
  1547             (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
  1548               (map (fn (((T, U), R), i) =>
  1549                  let
  1550                    val x = Free ("x" ^ string_of_int i, T);
  1551                    val y = Free ("y" ^ string_of_int i, U)
  1552                  in
  1553                    HOLogic.mk_imp (R $ x $ y,
  1554                      finite $ (Const ("Nominal.supp", U --> aset) $ y))
  1555                  end) (recTs ~~ rec_result_Ts ~~ rec_sets ~~ (1 upto length recTs)))))
  1556             (fn fins => (rtac rec_induct THEN_ALL_NEW cut_facts_tac fins) 1 THEN REPEAT
  1557                (NominalPermeq.finite_guess_tac (HOL_ss addsimps [fs_name]) 1))))
  1558       end) dt_atomTs;
  1559 
  1560     (** freshness **)
  1561 
  1562     val finite_premss = map (fn aT =>
  1563       map (fn (f, T) => HOLogic.mk_Trueprop
  1564         (Const ("Finite_Set.finite", HOLogic.mk_setT aT --> HOLogic.boolT) $
  1565            (Const ("Nominal.supp", T --> HOLogic.mk_setT aT) $ f)))
  1566            (rec_fns ~~ rec_fn_Ts)) dt_atomTs;
  1567 
  1568     val rec_fresh_thms = map (fn ((aT, eqvt_ths), finite_prems) =>
  1569       let
  1570         val name = Sign.base_name (fst (dest_Type aT));
  1571         val fs_name = PureThy.get_thm thy11 ("fs_" ^ name ^ "1");
  1572         val a = Free ("a", aT);
  1573         val freshs = map (fn (f, fT) => HOLogic.mk_Trueprop
  1574           (fresh_const aT fT $ a $ f)) (rec_fns ~~ rec_fn_Ts)
  1575       in
  1576         map (fn (((T, U), R), eqvt_th) =>
  1577           let
  1578             val x = Free ("x", T);
  1579             val y = Free ("y", U);
  1580             val y' = Free ("y'", U)
  1581           in
  1582             standard (Goal.prove (ProofContext.init thy11) [] (finite_prems @
  1583                 [HOLogic.mk_Trueprop (R $ x $ y),
  1584                  HOLogic.mk_Trueprop (HOLogic.mk_all ("y'", U,
  1585                    HOLogic.mk_imp (R $ x $ y', HOLogic.mk_eq (y', y)))),
  1586                  HOLogic.mk_Trueprop (fresh_const aT T $ a $ x)] @
  1587               freshs)
  1588               (HOLogic.mk_Trueprop (fresh_const aT U $ a $ y))
  1589               (fn {prems, context} =>
  1590                  let
  1591                    val (finite_prems, rec_prem :: unique_prem ::
  1592                      fresh_prems) = chop (length finite_prems) prems;
  1593                    val unique_prem' = unique_prem RS spec RS mp;
  1594                    val unique = [unique_prem', unique_prem' RS sym] MRS trans;
  1595                    val _ $ (_ $ (_ $ S $ _)) $ _ = prop_of supports_fresh;
  1596                    val tuple = foldr1 HOLogic.mk_prod (x :: rec_fns)
  1597                  in EVERY
  1598                    [rtac (Drule.cterm_instantiate
  1599                       [(cterm_of thy11 S,
  1600                         cterm_of thy11 (Const ("Nominal.supp",
  1601                           fastype_of tuple --> HOLogic.mk_setT aT) $ tuple))]
  1602                       supports_fresh) 1,
  1603                     simp_tac (HOL_basic_ss addsimps
  1604                       [supports_def, symmetric fresh_def, fresh_prod]) 1,
  1605                     REPEAT_DETERM (resolve_tac [allI, impI] 1),
  1606                     REPEAT_DETERM (etac conjE 1),
  1607                     rtac unique 1,
  1608                     SUBPROOF (fn {prems = prems', params = [a, b], ...} => EVERY
  1609                       [cut_facts_tac [rec_prem] 1,
  1610                        rtac (Thm.instantiate ([],
  1611                          [(cterm_of thy11 (Var (("pi", 0), mk_permT aT)),
  1612                            cterm_of thy11 (perm_of_pair (term_of a, term_of b)))]) eqvt_th) 1,
  1613                        asm_simp_tac (HOL_ss addsimps
  1614                          (prems' @ perm_swap @ perm_fresh_fresh)) 1]) context 1,
  1615                     rtac rec_prem 1,
  1616                     simp_tac (HOL_ss addsimps (fs_name ::
  1617                       supp_prod :: finite_Un :: finite_prems)) 1,
  1618                     simp_tac (HOL_ss addsimps (symmetric fresh_def ::
  1619                       fresh_prod :: fresh_prems)) 1]
  1620                  end))
  1621           end) (recTs ~~ rec_result_Ts ~~ rec_sets ~~ eqvt_ths)
  1622       end) (dt_atomTs ~~ rec_equiv_thms' ~~ finite_premss);
  1623 
  1624     (** uniqueness **)
  1625 
  1626     val fun_tuple = foldr1 HOLogic.mk_prod (rec_ctxt :: rec_fns);
  1627     val fun_tupleT = fastype_of fun_tuple;
  1628     val rec_unique_frees =
  1629       DatatypeProp.indexify_names (replicate (length recTs) "x") ~~ recTs;
  1630     val rec_unique_frees'' = map (fn (s, T) => (s ^ "'", T)) rec_unique_frees;
  1631     val rec_unique_frees' =
  1632       DatatypeProp.indexify_names (replicate (length recTs) "y") ~~ rec_result_Ts;
  1633     val rec_unique_concls = map (fn ((x, U), R) =>
  1634         Const ("Ex1", (U --> HOLogic.boolT) --> HOLogic.boolT) $
  1635           Abs ("y", U, R $ Free x $ Bound 0))
  1636       (rec_unique_frees ~~ rec_result_Ts ~~ rec_sets);
  1637 
  1638     val induct_aux_rec = Drule.cterm_instantiate
  1639       (map (pairself (cterm_of thy11))
  1640          (map (fn (aT, f) => (Logic.varify f, Abs ("z", HOLogic.unitT,
  1641             Const ("Nominal.supp", fun_tupleT --> HOLogic.mk_setT aT) $ fun_tuple)))
  1642               fresh_fs @
  1643           map (fn (((P, T), (x, U)), Q) =>
  1644            (Var ((P, 0), Logic.varifyT (fsT' --> T --> HOLogic.boolT)),
  1645             Abs ("z", HOLogic.unitT, absfree (x, U, Q))))
  1646               (pnames ~~ recTs ~~ rec_unique_frees ~~ rec_unique_concls) @
  1647           map (fn (s, T) => (Var ((s, 0), Logic.varifyT T), Free (s, T)))
  1648             rec_unique_frees)) induct_aux;
  1649 
  1650     fun obtain_fresh_name vs ths rec_fin_supp T (freshs1, freshs2, ctxt) =
  1651       let
  1652         val p = foldr1 HOLogic.mk_prod (vs @ freshs1);
  1653         val ex = Goal.prove ctxt [] [] (HOLogic.mk_Trueprop
  1654             (HOLogic.exists_const T $ Abs ("x", T,
  1655               fresh_const T (fastype_of p) $ Bound 0 $ p)))
  1656           (fn _ => EVERY
  1657             [cut_facts_tac ths 1,
  1658              REPEAT_DETERM (dresolve_tac (the (AList.lookup op = rec_fin_supp T)) 1),
  1659              resolve_tac exists_fresh' 1,
  1660              asm_simp_tac (HOL_ss addsimps (supp_prod :: finite_Un :: fs_atoms)) 1]);
  1661         val (([cx], ths), ctxt') = Obtain.result
  1662           (fn _ => EVERY
  1663             [etac exE 1,
  1664              full_simp_tac (HOL_ss addsimps (fresh_prod :: fresh_atm)) 1,
  1665              REPEAT (etac conjE 1)])
  1666           [ex] ctxt
  1667       in (freshs1 @ [term_of cx], freshs2 @ ths, ctxt') end;
  1668 
  1669     val finite_ctxt_prems = map (fn aT =>
  1670       HOLogic.mk_Trueprop
  1671         (Const ("Finite_Set.finite", HOLogic.mk_setT aT --> HOLogic.boolT) $
  1672            (Const ("Nominal.supp", fsT' --> HOLogic.mk_setT aT) $ rec_ctxt))) dt_atomTs;
  1673 
  1674     val rec_unique_thms = split_conj_thm (Goal.prove
  1675       (ProofContext.init thy11) (map fst rec_unique_frees)
  1676       (List.concat finite_premss @ finite_ctxt_prems @ rec_prems @ rec_prems')
  1677       (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj rec_unique_concls))
  1678       (fn {prems, context} =>
  1679          let
  1680            val k = length rec_fns;
  1681            val (finite_thss, ths1) = fold_map (fn T => fn xs =>
  1682              apfst (pair T) (chop k xs)) dt_atomTs prems;
  1683            val (finite_ctxt_ths, ths2) = chop (length dt_atomTs) ths1;
  1684            val (P_ind_ths, fcbs) = chop k ths2;
  1685            val P_ths = map (fn th => th RS mp) (split_conj_thm
  1686              (Goal.prove context
  1687                (map fst (rec_unique_frees'' @ rec_unique_frees')) []
  1688                (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
  1689                   (map (fn (((x, y), S), P) => HOLogic.mk_imp
  1690                     (S $ Free x $ Free y, P $ (Free y)))
  1691                       (rec_unique_frees'' ~~ rec_unique_frees' ~~ rec_sets ~~ rec_preds))))
  1692                (fn _ =>
  1693                   rtac rec_induct 1 THEN
  1694                   REPEAT ((resolve_tac P_ind_ths THEN_ALL_NEW assume_tac) 1))));
  1695            val rec_fin_supp_thms' = map
  1696              (fn (ths, (T, fin_ths)) => (T, map (curry op MRS fin_ths) ths))
  1697              (rec_fin_supp_thms ~~ finite_thss);
  1698          in EVERY
  1699            ([rtac induct_aux_rec 1] @
  1700             maps (fn ((_, finite_ths), finite_th) =>
  1701               [cut_facts_tac (finite_th :: finite_ths) 1,
  1702                asm_simp_tac (HOL_ss addsimps [supp_prod, finite_Un]) 1])
  1703                 (finite_thss ~~ finite_ctxt_ths) @
  1704             maps (fn ((_, idxss), elim) => maps (fn idxs =>
  1705               [full_simp_tac (HOL_ss addsimps [symmetric fresh_def, supp_prod, Un_iff]) 1,
  1706                REPEAT_DETERM (eresolve_tac [conjE, ex1E] 1),
  1707                rtac ex1I 1,
  1708                (resolve_tac rec_intrs THEN_ALL_NEW atac) 1,
  1709                rotate_tac ~1 1,
  1710                ((DETERM o etac elim) THEN_ALL_NEW full_simp_tac
  1711                   (HOL_ss addsimps List.concat distinct_thms)) 1] @
  1712                (if null idxs then [] else [hyp_subst_tac 1,
  1713                 SUBPROOF (fn {asms, concl, prems = prems', params, context = context', ...} =>
  1714                   let
  1715                     val SOME prem = find_first (can (HOLogic.dest_eq o
  1716                       HOLogic.dest_Trueprop o prop_of)) prems';
  1717                     val _ $ (_ $ lhs $ rhs) = prop_of prem;
  1718                     val _ $ (_ $ lhs' $ rhs') = term_of concl;
  1719                     val rT = fastype_of lhs';
  1720                     val (c, cargsl) = strip_comb lhs;
  1721                     val cargsl' = partition_cargs idxs cargsl;
  1722                     val boundsl = List.concat (map fst cargsl');
  1723                     val (_, cargsr) = strip_comb rhs;
  1724                     val cargsr' = partition_cargs idxs cargsr;
  1725                     val boundsr = List.concat (map fst cargsr');
  1726                     val (params1, _ :: params2) =
  1727                       chop (length params div 2) (map term_of params);
  1728                     val params' = params1 @ params2;
  1729                     val rec_prems = filter (fn th => case prop_of th of
  1730                       _ $ (S $ _ $ _) => S mem rec_sets | _ => false) prems';
  1731                     val fresh_prems = filter (fn th => case prop_of th of
  1732                         _ $ (Const ("Nominal.fresh", _) $ _ $ _) => true
  1733                       | _ $ (Const ("Not", _) $ _) => true
  1734                       | _ => false) prems';
  1735                     val Ts = map fastype_of boundsl;
  1736 
  1737                     val _ = warning "step 1: obtaining fresh names";
  1738                     val (freshs1, freshs2, context'') = fold
  1739                       (obtain_fresh_name (rec_ctxt :: rec_fns @ params')
  1740                          (List.concat (map snd finite_thss) @
  1741                             finite_ctxt_ths @ rec_prems)
  1742                          rec_fin_supp_thms')
  1743                       Ts ([], [], context');
  1744                     val pi1 = map perm_of_pair (boundsl ~~ freshs1);
  1745                     val rpi1 = rev pi1;
  1746                     val pi2 = map perm_of_pair (boundsr ~~ freshs1);
  1747                     val rpi2 = rev pi2;
  1748 
  1749                     val fresh_prems' = mk_not_sym fresh_prems;
  1750                     val freshs2' = mk_not_sym freshs2;
  1751 
  1752                     (** as, bs, cs # K as ts, K bs us **)
  1753                     val _ = warning "step 2: as, bs, cs # K as ts, K bs us";
  1754                     val prove_fresh_ss = HOL_ss addsimps
  1755                       (finite_Diff :: List.concat fresh_thms @
  1756                        fs_atoms @ abs_fresh @ abs_supp @ fresh_atm);
  1757                     (* FIXME: avoid asm_full_simp_tac ? *)
  1758                     fun prove_fresh ths y x = Goal.prove context'' [] []
  1759                       (HOLogic.mk_Trueprop (fresh_const
  1760                          (fastype_of x) (fastype_of y) $ x $ y))
  1761                       (fn _ => cut_facts_tac ths 1 THEN asm_full_simp_tac prove_fresh_ss 1);
  1762                     val constr_fresh_thms =
  1763                       map (prove_fresh fresh_prems lhs) boundsl @
  1764                       map (prove_fresh fresh_prems rhs) boundsr @
  1765                       map (prove_fresh freshs2 lhs) freshs1 @
  1766                       map (prove_fresh freshs2 rhs) freshs1;
  1767 
  1768                     (** pi1 o (K as ts) = pi2 o (K bs us) **)
  1769                     val _ = warning "step 3: pi1 o (K as ts) = pi2 o (K bs us)";
  1770                     val pi1_pi2_eq = Goal.prove context'' [] []
  1771                       (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1772                         (fold_rev (mk_perm []) pi1 lhs, fold_rev (mk_perm []) pi2 rhs)))
  1773                       (fn _ => EVERY
  1774                          [cut_facts_tac constr_fresh_thms 1,
  1775                           asm_simp_tac (HOL_basic_ss addsimps perm_fresh_fresh) 1,
  1776                           rtac prem 1]);
  1777 
  1778                     (** pi1 o ts = pi2 o us **)
  1779                     val _ = warning "step 4: pi1 o ts = pi2 o us";
  1780                     val pi1_pi2_eqs = map (fn (t, u) =>
  1781                       Goal.prove context'' [] []
  1782                         (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1783                           (fold_rev (mk_perm []) pi1 t, fold_rev (mk_perm []) pi2 u)))
  1784                         (fn _ => EVERY
  1785                            [cut_facts_tac [pi1_pi2_eq] 1,
  1786                             asm_full_simp_tac (HOL_ss addsimps
  1787                               (calc_atm @ List.concat perm_simps' @
  1788                                fresh_prems' @ freshs2' @ abs_perm @
  1789                                alpha @ List.concat inject_thms)) 1]))
  1790                         (map snd cargsl' ~~ map snd cargsr');
  1791 
  1792                     (** pi1^-1 o pi2 o us = ts **)
  1793                     val _ = warning "step 5: pi1^-1 o pi2 o us = ts";
  1794                     val rpi1_pi2_eqs = map (fn ((t, u), eq) =>
  1795                       Goal.prove context'' [] []
  1796                         (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1797                           (fold_rev (mk_perm []) (rpi1 @ pi2) u, t)))
  1798                         (fn _ => simp_tac (HOL_ss addsimps
  1799                            ((eq RS sym) :: perm_swap)) 1))
  1800                         (map snd cargsl' ~~ map snd cargsr' ~~ pi1_pi2_eqs);
  1801 
  1802                     val (rec_prems1, rec_prems2) =
  1803                       chop (length rec_prems div 2) rec_prems;
  1804 
  1805                     (** (ts, pi1^-1 o pi2 o vs) in rec_set **)
  1806                     val _ = warning "step 6: (ts, pi1^-1 o pi2 o vs) in rec_set";
  1807                     val rec_prems' = map (fn th =>
  1808                       let
  1809                         val _ $ (S $ x $ y) = prop_of th;
  1810                         val k = find_index (equal S) rec_sets;
  1811                         val pi = rpi1 @ pi2;
  1812                         fun mk_pi z = fold_rev (mk_perm []) pi z;
  1813                         fun eqvt_tac p =
  1814                           let
  1815                             val U as Type (_, [Type (_, [T, _])]) = fastype_of p;
  1816                             val l = find_index (equal T) dt_atomTs;
  1817                             val th = List.nth (List.nth (rec_equiv_thms', l), k);
  1818                             val th' = Thm.instantiate ([],
  1819                               [(cterm_of thy11 (Var (("pi", 0), U)),
  1820                                 cterm_of thy11 p)]) th;
  1821                           in rtac th' 1 end;
  1822                         val th' = Goal.prove context'' [] []
  1823                           (HOLogic.mk_Trueprop (S $ mk_pi x $ mk_pi y))
  1824                           (fn _ => EVERY
  1825                              (map eqvt_tac pi @
  1826                               [simp_tac (HOL_ss addsimps (fresh_prems' @ freshs2' @
  1827                                  perm_swap @ perm_fresh_fresh)) 1,
  1828                                rtac th 1]))
  1829                       in
  1830                         Simplifier.simplify
  1831                           (HOL_basic_ss addsimps rpi1_pi2_eqs) th'
  1832                       end) rec_prems2;
  1833 
  1834                     val ihs = filter (fn th => case prop_of th of
  1835                       _ $ (Const ("All", _) $ _) => true | _ => false) prems';
  1836 
  1837                     (** pi1 o rs = pi2 o vs , rs = pi1^-1 o pi2 o vs **)
  1838                     val _ = warning "step 7: pi1 o rs = pi2 o vs , rs = pi1^-1 o pi2 o vs";
  1839                     val rec_eqns = map (fn (th, ih) =>
  1840                       let
  1841                         val th' = th RS (ih RS spec RS mp) RS sym;
  1842                         val _ $ (_ $ lhs $ rhs) = prop_of th';
  1843                         fun strip_perm (_ $ _ $ t) = strip_perm t
  1844                           | strip_perm t = t;
  1845                       in
  1846                         Goal.prove context'' [] []
  1847                            (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1848                               (fold_rev (mk_perm []) pi1 lhs,
  1849                                fold_rev (mk_perm []) pi2 (strip_perm rhs))))
  1850                            (fn _ => simp_tac (HOL_basic_ss addsimps
  1851                               (th' :: perm_swap)) 1)
  1852                       end) (rec_prems' ~~ ihs);
  1853 
  1854                     (** as # rs **)
  1855                     val _ = warning "step 8: as # rs";
  1856                     val rec_freshs = List.concat
  1857                       (map (fn (rec_prem, ih) =>
  1858                         let
  1859                           val _ $ (S $ x $ (y as Free (_, T))) =
  1860                             prop_of rec_prem;
  1861                           val k = find_index (equal S) rec_sets;
  1862                           val atoms = List.concat (List.mapPartial (fn (bs, z) =>
  1863                             if z = x then NONE else SOME bs) cargsl')
  1864                         in
  1865                           map (fn a as Free (_, aT) =>
  1866                             let val l = find_index (equal aT) dt_atomTs;
  1867                             in
  1868                               Goal.prove context'' [] []
  1869                                 (HOLogic.mk_Trueprop (fresh_const aT T $ a $ y))
  1870                                 (fn _ => EVERY
  1871                                    (rtac (List.nth (List.nth (rec_fresh_thms, l), k)) 1 ::
  1872                                     map (fn th => rtac th 1)
  1873                                       (snd (List.nth (finite_thss, l))) @
  1874                                     [rtac rec_prem 1, rtac ih 1,
  1875                                      REPEAT_DETERM (resolve_tac fresh_prems 1)]))
  1876                             end) atoms
  1877                         end) (rec_prems1 ~~ ihs));
  1878 
  1879                     (** as # fK as ts rs , bs # fK bs us vs **)
  1880                     val _ = warning "step 9: as # fK as ts rs , bs # fK bs us vs";
  1881                     fun prove_fresh_result (a as Free (_, aT)) =
  1882                       Goal.prove context'' [] []
  1883                         (HOLogic.mk_Trueprop (fresh_const aT rT $ a $ rhs'))
  1884                         (fn _ => EVERY
  1885                            [resolve_tac fcbs 1,
  1886                             REPEAT_DETERM (resolve_tac
  1887                               (fresh_prems @ rec_freshs) 1),
  1888                             REPEAT_DETERM (resolve_tac (maps snd rec_fin_supp_thms') 1
  1889                               THEN resolve_tac rec_prems 1),
  1890                             resolve_tac P_ind_ths 1,
  1891                             REPEAT_DETERM (resolve_tac (P_ths @ rec_prems) 1)]);
  1892 
  1893                     val fresh_results'' = map prove_fresh_result boundsl;
  1894 
  1895                     fun prove_fresh_result'' ((a as Free (_, aT), b), th) =
  1896                       let val th' = Goal.prove context'' [] []
  1897                         (HOLogic.mk_Trueprop (fresh_const aT rT $
  1898                             fold_rev (mk_perm []) (rpi2 @ pi1) a $
  1899                             fold_rev (mk_perm []) (rpi2 @ pi1) rhs'))
  1900                         (fn _ => simp_tac (HOL_ss addsimps fresh_bij) 1 THEN
  1901                            rtac th 1)
  1902                       in
  1903                         Goal.prove context'' [] []
  1904                           (HOLogic.mk_Trueprop (fresh_const aT rT $ b $ lhs'))
  1905                           (fn _ => EVERY
  1906                              [cut_facts_tac [th'] 1,
  1907                               full_simp_tac (Simplifier.theory_context thy11 HOL_ss
  1908                                 addsimps rec_eqns @ pi1_pi2_eqs @ perm_swap
  1909                                 addsimprocs [NominalPermeq.perm_simproc_app]) 1,
  1910                               full_simp_tac (HOL_ss addsimps (calc_atm @
  1911                                 fresh_prems' @ freshs2' @ perm_fresh_fresh)) 1])
  1912                       end;
  1913 
  1914                     val fresh_results = fresh_results'' @ map prove_fresh_result''
  1915                       (boundsl ~~ boundsr ~~ fresh_results'');
  1916 
  1917                     (** cs # fK as ts rs , cs # fK bs us vs **)
  1918                     val _ = warning "step 10: cs # fK as ts rs , cs # fK bs us vs";
  1919                     fun prove_fresh_result' recs t (a as Free (_, aT)) =
  1920                       Goal.prove context'' [] []
  1921                         (HOLogic.mk_Trueprop (fresh_const aT rT $ a $ t))
  1922                         (fn _ => EVERY
  1923                           [cut_facts_tac recs 1,
  1924                            REPEAT_DETERM (dresolve_tac
  1925                              (the (AList.lookup op = rec_fin_supp_thms' aT)) 1),
  1926                            NominalPermeq.fresh_guess_tac
  1927                              (HOL_ss addsimps (freshs2 @
  1928                                 fs_atoms @ fresh_atm @
  1929                                 List.concat (map snd finite_thss))) 1]);
  1930 
  1931                     val fresh_results' =
  1932                       map (prove_fresh_result' rec_prems1 rhs') freshs1 @
  1933                       map (prove_fresh_result' rec_prems2 lhs') freshs1;
  1934 
  1935                     (** pi1 o (fK as ts rs) = pi2 o (fK bs us vs) **)
  1936                     val _ = warning "step 11: pi1 o (fK as ts rs) = pi2 o (fK bs us vs)";
  1937                     val pi1_pi2_result = Goal.prove context'' [] []
  1938                       (HOLogic.mk_Trueprop (HOLogic.mk_eq
  1939                         (fold_rev (mk_perm []) pi1 rhs', fold_rev (mk_perm []) pi2 lhs')))
  1940                       (fn _ => NominalPermeq.perm_simp_tac (HOL_ss addsimps
  1941                            pi1_pi2_eqs @ rec_eqns) 1 THEN
  1942                          TRY (simp_tac (HOL_ss addsimps
  1943                            (fresh_prems' @ freshs2' @ calc_atm @ perm_fresh_fresh)) 1));
  1944 
  1945                     val _ = warning "final result";
  1946                     val final = Goal.prove context'' [] [] (term_of concl)
  1947                       (fn _ => cut_facts_tac [pi1_pi2_result RS sym] 1 THEN
  1948                         full_simp_tac (HOL_basic_ss addsimps perm_fresh_fresh @
  1949                           fresh_results @ fresh_results') 1);
  1950                     val final' = ProofContext.export context'' context' [final];
  1951                     val _ = warning "finished!"
  1952                   in
  1953                     resolve_tac final' 1
  1954                   end) context 1])) idxss) (ndescr ~~ rec_elims))
  1955          end));
  1956 
  1957     val rec_total_thms = map (fn r => r RS theI') rec_unique_thms;
  1958 
  1959     (* define primrec combinators *)
  1960 
  1961     val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
  1962     val reccomb_names = map (Sign.full_name thy11)
  1963       (if length descr'' = 1 then [big_reccomb_name] else
  1964         (map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
  1965           (1 upto (length descr''))));
  1966     val reccombs = map (fn ((name, T), T') => list_comb
  1967       (Const (name, rec_fn_Ts @ [T] ---> T'), rec_fns))
  1968         (reccomb_names ~~ recTs ~~ rec_result_Ts);
  1969 
  1970     val (reccomb_defs, thy12) =
  1971       thy11
  1972       |> Sign.add_consts_i (map (fn ((name, T), T') =>
  1973           (Sign.base_name name, rec_fn_Ts @ [T] ---> T', NoSyn))
  1974           (reccomb_names ~~ recTs ~~ rec_result_Ts))
  1975       |> (PureThy.add_defs_i false o map Thm.no_attributes) (map (fn ((((name, comb), set), T), T') =>
  1976           ((Sign.base_name name) ^ "_def", Logic.mk_equals (comb, absfree ("x", T,
  1977            Const ("The", (T' --> HOLogic.boolT) --> T') $ absfree ("y", T',
  1978              set $ Free ("x", T) $ Free ("y", T'))))))
  1979                (reccomb_names ~~ reccombs ~~ rec_sets ~~ recTs ~~ rec_result_Ts));
  1980 
  1981     (* prove characteristic equations for primrec combinators *)
  1982 
  1983     val rec_thms = map (fn (prems, concl) =>
  1984       let
  1985         val _ $ (_ $ (_ $ x) $ _) = concl;
  1986         val (_, cargs) = strip_comb x;
  1987         val ps = map (fn (x as Free (_, T), i) =>
  1988           (Free ("x" ^ string_of_int i, T), x)) (cargs ~~ (1 upto length cargs));
  1989         val concl' = subst_atomic_types (rec_result_Ts' ~~ rec_result_Ts) concl;
  1990         val prems' = List.concat finite_premss @ finite_ctxt_prems @
  1991           rec_prems @ rec_prems' @ map (subst_atomic ps) prems;
  1992         fun solve rules prems = resolve_tac rules THEN_ALL_NEW
  1993           (resolve_tac prems THEN_ALL_NEW atac)
  1994       in
  1995         Goal.prove_global thy12 [] prems' concl'
  1996           (fn prems => EVERY
  1997             [rewrite_goals_tac reccomb_defs,
  1998              rtac the1_equality 1,
  1999              solve rec_unique_thms prems 1,
  2000              resolve_tac rec_intrs 1,
  2001              REPEAT (solve (prems @ rec_total_thms) prems 1)])
  2002       end) (rec_eq_prems ~~
  2003         DatatypeProp.make_primrecs new_type_names descr' sorts' thy12);
  2004 
  2005     val dt_infos = map (make_dt_info pdescr sorts induct reccomb_names rec_thms)
  2006       ((0 upto length descr1 - 1) ~~ descr1 ~~ distinct_thms ~~ inject_thms);
  2007 
  2008     (* FIXME: theorems are stored in database for testing only *)
  2009     val (_, thy13) = thy12 |>
  2010       PureThy.add_thmss
  2011         [(("rec_equiv", List.concat rec_equiv_thms), []),
  2012          (("rec_equiv'", List.concat rec_equiv_thms'), []),
  2013          (("rec_fin_supp", List.concat rec_fin_supp_thms), []),
  2014          (("rec_fresh", List.concat rec_fresh_thms), []),
  2015          (("rec_unique", map standard rec_unique_thms), []),
  2016          (("recs", rec_thms), [])] ||>
  2017       Sign.parent_path ||>
  2018       map_nominal_datatypes (fold Symtab.update dt_infos);
  2019 
  2020   in
  2021     thy13
  2022   end;
  2023 
  2024 val add_nominal_datatype = gen_add_nominal_datatype read_typ true;
  2025 
  2026 
  2027 (* FIXME: The following stuff should be exported by DatatypePackage *)
  2028 
  2029 local structure P = OuterParse and K = OuterKeyword in
  2030 
  2031 val datatype_decl =
  2032   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
  2033     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
  2034 
  2035 fun mk_datatype args =
  2036   let
  2037     val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
  2038     val specs = map (fn ((((_, vs), t), mx), cons) =>
  2039       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
  2040   in add_nominal_datatype false names specs end;
  2041 
  2042 val _ =
  2043   OuterSyntax.command "nominal_datatype" "define inductive datatypes" K.thy_decl
  2044     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
  2045 
  2046 end;
  2047 
  2048 end