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