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