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