src/HOL/Nominal/nominal_package.ML
author urbanc
Sat Dec 10 00:11:35 2005 +0100 (2005-12-10)
changeset 18381 246807ef6dfb
parent 18366 78b4f225b640
child 18579 002d371401f5
permissions -rw-r--r--
changed the types in accordance with Florian's changes
     1 (* $Id$ *)
     2 
     3 signature NOMINAL_PACKAGE =
     4 sig
     5   val add_nominal_datatype : bool -> string list -> (string list * bstring * mixfix *
     6     (bstring * string list * mixfix) list) list -> theory -> theory
     7 end
     8 
     9 structure NominalPackage : NOMINAL_PACKAGE =
    10 struct
    11 
    12 open DatatypeAux;
    13 open NominalAtoms;
    14 
    15 (** FIXME: DatatypePackage should export this function **)
    16 
    17 local
    18 
    19 fun dt_recs (DtTFree _) = []
    20   | dt_recs (DtType (_, dts)) = List.concat (map dt_recs dts)
    21   | dt_recs (DtRec i) = [i];
    22 
    23 fun dt_cases (descr: descr) (_, args, constrs) =
    24   let
    25     fun the_bname i = Sign.base_name (#1 (valOf (AList.lookup (op =) descr i)));
    26     val bnames = map the_bname (distinct (List.concat (map dt_recs args)));
    27   in map (fn (c, _) => space_implode "_" (Sign.base_name c :: bnames)) constrs end;
    28 
    29 
    30 fun induct_cases descr =
    31   DatatypeProp.indexify_names (List.concat (map (dt_cases descr) (map #2 descr)));
    32 
    33 fun exhaust_cases descr i = dt_cases descr (valOf (AList.lookup (op =) descr i));
    34 
    35 in
    36 
    37 fun mk_case_names_induct descr = RuleCases.case_names (induct_cases descr);
    38 
    39 fun mk_case_names_exhausts descr new =
    40   map (RuleCases.case_names o exhaust_cases descr o #1)
    41     (List.filter (fn ((_, (name, _, _))) => name mem_string new) descr);
    42 
    43 end;
    44 
    45 (*******************************)
    46 
    47 val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
    48 
    49 fun read_typ sign ((Ts, sorts), str) =
    50   let
    51     val T = Type.no_tvars (Sign.read_typ (sign, (AList.lookup op =)
    52       (map (apfst (rpair ~1)) sorts)) str) handle TYPE (msg, _, _) => error msg
    53   in (Ts @ [T], add_typ_tfrees (T, sorts)) end;
    54 
    55 (** taken from HOL/Tools/datatype_aux.ML **)
    56 
    57 fun indtac indrule indnames i st =
    58   let
    59     val ts = HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule));
    60     val ts' = HOLogic.dest_conj (HOLogic.dest_Trueprop
    61       (Logic.strip_imp_concl (List.nth (prems_of st, i - 1))));
    62     val getP = if can HOLogic.dest_imp (hd ts) then
    63       (apfst SOME) o HOLogic.dest_imp else pair NONE;
    64     fun abstr (t1, t2) = (case t1 of
    65         NONE => (case filter (fn Free (s, _) => s mem indnames | _ => false)
    66               (term_frees t2) of
    67             [Free (s, T)] => absfree (s, T, t2)
    68           | _ => sys_error "indtac")
    69       | SOME (_ $ t' $ _) => Abs ("x", fastype_of t', abstract_over (t', t2)))
    70     val cert = cterm_of (Thm.sign_of_thm st);
    71     val Ps = map (cert o head_of o snd o getP) ts;
    72     val indrule' = cterm_instantiate (Ps ~~
    73       (map (cert o abstr o getP) ts')) indrule
    74   in
    75     rtac indrule' i st
    76   end;
    77 
    78 fun gen_add_nominal_datatype prep_typ err flat_names new_type_names dts thy =
    79   let
    80     (* this theory is used just for parsing *)
    81   
    82     val tmp_thy = thy |>
    83       Theory.copy |>
    84       Theory.add_types (map (fn (tvs, tname, mx, _) =>
    85         (tname, length tvs, mx)) dts);
    86 
    87     val sign = Theory.sign_of tmp_thy;
    88 
    89     val atoms = atoms_of thy;
    90     val classes = map (NameSpace.map_base (fn s => "pt_" ^ s)) atoms;
    91     val cp_classes = List.concat (map (fn atom1 => map (fn atom2 =>
    92       Sign.intern_class thy ("cp_" ^ Sign.base_name atom1 ^ "_" ^
    93         Sign.base_name atom2)) atoms) atoms);
    94     fun augment_sort S = S union classes;
    95     val augment_sort_typ = map_type_tfree (fn (s, S) => TFree (s, augment_sort S));
    96 
    97     fun prep_constr ((constrs, sorts), (cname, cargs, mx)) =
    98       let val (cargs', sorts') = Library.foldl (prep_typ sign) (([], sorts), cargs)
    99       in (constrs @ [(cname, cargs', mx)], sorts') end
   100 
   101     fun prep_dt_spec ((dts, sorts), (tvs, tname, mx, constrs)) =
   102       let val (constrs', sorts') = Library.foldl prep_constr (([], sorts), constrs)
   103       in (dts @ [(tvs, tname, mx, constrs')], sorts') end
   104 
   105     val (dts', sorts) = Library.foldl prep_dt_spec (([], []), dts);
   106     val sorts' = map (apsnd augment_sort) sorts;
   107     val tyvars = map #1 dts';
   108 
   109     val types_syntax = map (fn (tvs, tname, mx, constrs) => (tname, mx)) dts';
   110     val constr_syntax = map (fn (tvs, tname, mx, constrs) =>
   111       map (fn (cname, cargs, mx) => (cname, mx)) constrs) dts';
   112 
   113     val ps = map (fn (_, n, _, _) =>
   114       (Sign.full_name sign n, Sign.full_name sign (n ^ "_Rep"))) dts;
   115     val rps = map Library.swap ps;
   116 
   117     fun replace_types (Type ("nominal.ABS", [T, U])) = 
   118           Type ("fun", [T, Type ("nominal.nOption", [replace_types U])])
   119       | replace_types (Type (s, Ts)) =
   120           Type (getOpt (AList.lookup op = ps s, s), map replace_types Ts)
   121       | replace_types T = T;
   122 
   123     fun replace_types' (Type (s, Ts)) =
   124           Type (getOpt (AList.lookup op = rps s, s), map replace_types' Ts)
   125       | replace_types' T = T;
   126 
   127     val dts'' = map (fn (tvs, tname, mx, constrs) => (tvs, tname ^ "_Rep", NoSyn,
   128       map (fn (cname, cargs, mx) => (cname,
   129         map (augment_sort_typ o replace_types) cargs, NoSyn)) constrs)) dts';
   130 
   131     val new_type_names' = map (fn n => n ^ "_Rep") new_type_names;
   132     val full_new_type_names' = map (Sign.full_name (sign_of thy)) new_type_names';
   133 
   134     val ({induction, ...},thy1) =
   135       DatatypePackage.add_datatype_i err flat_names new_type_names' dts'' thy;
   136 
   137     val SOME {descr, ...} = Symtab.lookup
   138       (DatatypePackage.get_datatypes thy1) (hd full_new_type_names');
   139     fun nth_dtyp i = typ_of_dtyp descr sorts' (DtRec i);
   140 
   141     (**** define permutation functions ****)
   142 
   143     val permT = mk_permT (TFree ("'x", HOLogic.typeS));
   144     val pi = Free ("pi", permT);
   145     val perm_types = map (fn (i, _) =>
   146       let val T = nth_dtyp i
   147       in permT --> T --> T end) descr;
   148     val perm_names = replicate (length new_type_names) "nominal.perm" @
   149       DatatypeProp.indexify_names (map (fn i => Sign.full_name (sign_of thy1)
   150         ("perm_" ^ name_of_typ (nth_dtyp i)))
   151           (length new_type_names upto length descr - 1));
   152     val perm_names_types = perm_names ~~ perm_types;
   153 
   154     val perm_eqs = List.concat (map (fn (i, (_, _, constrs)) =>
   155       let val T = nth_dtyp i
   156       in map (fn (cname, dts) => 
   157         let
   158           val Ts = map (typ_of_dtyp descr sorts') dts;
   159           val names = DatatypeProp.make_tnames Ts;
   160           val args = map Free (names ~~ Ts);
   161           val c = Const (cname, Ts ---> T);
   162           fun perm_arg (dt, x) =
   163             let val T = type_of x
   164             in if is_rec_type dt then
   165                 let val (Us, _) = strip_type T
   166                 in list_abs (map (pair "x") Us,
   167                   Const (List.nth (perm_names_types, body_index dt)) $ pi $
   168                     list_comb (x, map (fn (i, U) =>
   169                       Const ("nominal.perm", permT --> U --> U) $
   170                         (Const ("List.rev", permT --> permT) $ pi) $
   171                         Bound i) ((length Us - 1 downto 0) ~~ Us)))
   172                 end
   173               else Const ("nominal.perm", permT --> T --> T) $ pi $ x
   174             end;  
   175         in
   176           (("", HOLogic.mk_Trueprop (HOLogic.mk_eq
   177             (Const (List.nth (perm_names_types, i)) $
   178                Free ("pi", mk_permT (TFree ("'x", HOLogic.typeS))) $
   179                list_comb (c, args),
   180              list_comb (c, map perm_arg (dts ~~ args))))), [])
   181         end) constrs
   182       end) descr);
   183 
   184     val (thy2, perm_simps) = thy1 |>
   185       Theory.add_consts_i (map (fn (s, T) => (Sign.base_name s, T, NoSyn))
   186         (List.drop (perm_names_types, length new_type_names))) |>
   187       PrimrecPackage.add_primrec_i "" perm_eqs;
   188 
   189     (**** prove that permutation functions introduced by unfolding are ****)
   190     (**** equivalent to already existing permutation functions         ****)
   191 
   192     val _ = warning ("length descr: " ^ string_of_int (length descr));
   193     val _ = warning ("length new_type_names: " ^ string_of_int (length new_type_names));
   194 
   195     val perm_indnames = DatatypeProp.make_tnames (map body_type perm_types);
   196     val perm_fun_def = PureThy.get_thm thy2 (Name "perm_fun_def");
   197 
   198     val unfolded_perm_eq_thms =
   199       if length descr = length new_type_names then []
   200       else map standard (List.drop (split_conj_thm
   201         (Goal.prove thy2 [] []
   202           (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   203             (map (fn (c as (s, T), x) =>
   204                let val [T1, T2] = binder_types T
   205                in HOLogic.mk_eq (Const c $ pi $ Free (x, T2),
   206                  Const ("nominal.perm", T) $ pi $ Free (x, T2))
   207                end)
   208              (perm_names_types ~~ perm_indnames))))
   209           (fn _ => EVERY [indtac induction perm_indnames 1,
   210             ALLGOALS (asm_full_simp_tac
   211               (simpset_of thy2 addsimps [perm_fun_def]))])),
   212         length new_type_names));
   213 
   214     (**** prove [] \<bullet> t = t ****)
   215 
   216     val _ = warning "perm_empty_thms";
   217 
   218     val perm_empty_thms = List.concat (map (fn a =>
   219       let val permT = mk_permT (Type (a, []))
   220       in map standard (List.take (split_conj_thm
   221         (Goal.prove thy2 [] []
   222           (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   223             (map (fn ((s, T), x) => HOLogic.mk_eq
   224                 (Const (s, permT --> T --> T) $
   225                    Const ("List.list.Nil", permT) $ Free (x, T),
   226                  Free (x, T)))
   227              (perm_names ~~
   228               map body_type perm_types ~~ perm_indnames))))
   229           (fn _ => EVERY [indtac induction perm_indnames 1,
   230             ALLGOALS (asm_full_simp_tac (simpset_of thy2))])),
   231         length new_type_names))
   232       end)
   233       atoms);
   234 
   235     (**** prove (pi1 @ pi2) \<bullet> t = pi1 \<bullet> (pi2 \<bullet> t) ****)
   236 
   237     val _ = warning "perm_append_thms";
   238 
   239     (*FIXME: these should be looked up statically*)
   240     val at_pt_inst = PureThy.get_thm thy2 (Name "at_pt_inst");
   241     val pt2 = PureThy.get_thm thy2 (Name "pt2");
   242 
   243     val perm_append_thms = List.concat (map (fn a =>
   244       let
   245         val permT = mk_permT (Type (a, []));
   246         val pi1 = Free ("pi1", permT);
   247         val pi2 = Free ("pi2", permT);
   248         val pt_inst = PureThy.get_thm thy2 (Name ("pt_" ^ Sign.base_name a ^ "_inst"));
   249         val pt2' = pt_inst RS pt2;
   250         val pt2_ax = PureThy.get_thm thy2
   251           (Name (NameSpace.map_base (fn s => "pt_" ^ s ^ "2") a));
   252       in List.take (map standard (split_conj_thm
   253         (Goal.prove thy2 [] []
   254              (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   255                 (map (fn ((s, T), x) =>
   256                     let val perm = Const (s, permT --> T --> T)
   257                     in HOLogic.mk_eq
   258                       (perm $ (Const ("List.op @", permT --> permT --> permT) $
   259                          pi1 $ pi2) $ Free (x, T),
   260                        perm $ pi1 $ (perm $ pi2 $ Free (x, T)))
   261                     end)
   262                   (perm_names ~~
   263                    map body_type perm_types ~~ perm_indnames))))
   264            (fn _ => EVERY [indtac induction perm_indnames 1,
   265               ALLGOALS (asm_full_simp_tac (simpset_of thy2 addsimps [pt2', pt2_ax]))]))),
   266          length new_type_names)
   267       end) atoms);
   268 
   269     (**** prove pi1 ~ pi2 ==> pi1 \<bullet> t = pi2 \<bullet> t ****)
   270 
   271     val _ = warning "perm_eq_thms";
   272 
   273     val pt3 = PureThy.get_thm thy2 (Name "pt3");
   274     val pt3_rev = PureThy.get_thm thy2 (Name "pt3_rev");
   275 
   276     val perm_eq_thms = List.concat (map (fn a =>
   277       let
   278         val permT = mk_permT (Type (a, []));
   279         val pi1 = Free ("pi1", permT);
   280         val pi2 = Free ("pi2", permT);
   281         (*FIXME: not robust - better access these theorems using NominalData?*)
   282         val at_inst = PureThy.get_thm thy2 (Name ("at_" ^ Sign.base_name a ^ "_inst"));
   283         val pt_inst = PureThy.get_thm thy2 (Name ("pt_" ^ Sign.base_name a ^ "_inst"));
   284         val pt3' = pt_inst RS pt3;
   285         val pt3_rev' = at_inst RS (pt_inst RS pt3_rev);
   286         val pt3_ax = PureThy.get_thm thy2
   287           (Name (NameSpace.map_base (fn s => "pt_" ^ s ^ "3") a));
   288       in List.take (map standard (split_conj_thm
   289         (Goal.prove thy2 [] [] (Logic.mk_implies
   290              (HOLogic.mk_Trueprop (Const ("nominal.prm_eq",
   291                 permT --> permT --> HOLogic.boolT) $ pi1 $ pi2),
   292               HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   293                 (map (fn ((s, T), x) =>
   294                     let val perm = Const (s, permT --> T --> T)
   295                     in HOLogic.mk_eq
   296                       (perm $ pi1 $ Free (x, T),
   297                        perm $ pi2 $ Free (x, T))
   298                     end)
   299                   (perm_names ~~
   300                    map body_type perm_types ~~ perm_indnames)))))
   301            (fn _ => EVERY [indtac induction perm_indnames 1,
   302               ALLGOALS (asm_full_simp_tac (simpset_of thy2 addsimps [pt3', pt3_rev', pt3_ax]))]))),
   303          length new_type_names)
   304       end) atoms);
   305 
   306     (**** prove pi1 \<bullet> (pi2 \<bullet> t) = (pi1 \<bullet> pi2) \<bullet> (pi1 \<bullet> t) ****)
   307 
   308     val cp1 = PureThy.get_thm thy2 (Name "cp1");
   309     val dj_cp = PureThy.get_thm thy2 (Name "dj_cp");
   310     val pt_perm_compose = PureThy.get_thm thy2 (Name "pt_perm_compose");
   311     val pt_perm_compose_rev = PureThy.get_thm thy2 (Name "pt_perm_compose_rev");
   312     val dj_perm_perm_forget = PureThy.get_thm thy2 (Name "dj_perm_perm_forget");
   313 
   314     fun composition_instance name1 name2 thy =
   315       let
   316         val name1' = Sign.base_name name1;
   317         val name2' = Sign.base_name name2;
   318         val cp_class = Sign.intern_class thy ("cp_" ^ name1' ^ "_" ^ name2');
   319         val permT1 = mk_permT (Type (name1, []));
   320         val permT2 = mk_permT (Type (name2, []));
   321         val augment = map_type_tfree
   322           (fn (x, S) => TFree (x, cp_class :: S));
   323         val Ts = map (augment o body_type) perm_types;
   324         val cp_inst = PureThy.get_thm thy
   325           (Name ("cp_" ^ name1' ^ "_" ^ name2' ^ "_inst"));
   326         val simps = simpset_of thy addsimps (perm_fun_def ::
   327           (if name1 <> name2 then
   328              let val dj = PureThy.get_thm thy (Name ("dj_" ^ name2' ^ "_" ^ name1'))
   329              in [dj RS (cp_inst RS dj_cp), dj RS dj_perm_perm_forget] end
   330            else
   331              let
   332                val at_inst = PureThy.get_thm thy (Name ("at_" ^ name1' ^ "_inst"));
   333                val pt_inst = PureThy.get_thm thy (Name ("pt_" ^ name1' ^ "_inst"))
   334              in
   335                [cp_inst RS cp1 RS sym,
   336                 at_inst RS (pt_inst RS pt_perm_compose) RS sym,
   337                 at_inst RS (pt_inst RS pt_perm_compose_rev) RS sym]
   338             end))
   339         val thms = split_conj_thm (standard (Goal.prove thy [] []
   340             (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj
   341               (map (fn ((s, T), x) =>
   342                   let
   343                     val pi1 = Free ("pi1", permT1);
   344                     val pi2 = Free ("pi2", permT2);
   345                     val perm1 = Const (s, permT1 --> T --> T);
   346                     val perm2 = Const (s, permT2 --> T --> T);
   347                     val perm3 = Const ("nominal.perm", permT1 --> permT2 --> permT2)
   348                   in HOLogic.mk_eq
   349                     (perm1 $ pi1 $ (perm2 $ pi2 $ Free (x, T)),
   350                      perm2 $ (perm3 $ pi1 $ pi2) $ (perm1 $ pi1 $ Free (x, T)))
   351                   end)
   352                 (perm_names ~~ Ts ~~ perm_indnames))))
   353           (fn _ => EVERY [indtac induction perm_indnames 1,
   354              ALLGOALS (asm_full_simp_tac simps)])))
   355       in
   356         foldl (fn ((s, tvs), thy) => AxClass.add_inst_arity_i
   357             (s, replicate (length tvs) (cp_class :: classes), [cp_class])
   358             (AxClass.intro_classes_tac [] THEN ALLGOALS (resolve_tac thms)) thy)
   359           thy (full_new_type_names' ~~ tyvars)
   360       end;
   361 
   362     val (perm_thmss,thy3) = thy2 |>
   363       fold (fn name1 => fold (composition_instance name1) atoms) atoms |>
   364       curry (Library.foldr (fn ((i, (tyname, args, _)), thy) =>
   365         AxClass.add_inst_arity_i (tyname, replicate (length args) classes, classes)
   366         (AxClass.intro_classes_tac [] THEN REPEAT (EVERY
   367            [resolve_tac perm_empty_thms 1,
   368             resolve_tac perm_append_thms 1,
   369             resolve_tac perm_eq_thms 1, assume_tac 1])) thy))
   370         (List.take (descr, length new_type_names)) |>
   371       PureThy.add_thmss
   372         [((space_implode "_" new_type_names ^ "_unfolded_perm_eq",
   373           unfolded_perm_eq_thms), [Simplifier.simp_add_global]),
   374          ((space_implode "_" new_type_names ^ "_perm_empty",
   375           perm_empty_thms), [Simplifier.simp_add_global]),
   376          ((space_implode "_" new_type_names ^ "_perm_append",
   377           perm_append_thms), [Simplifier.simp_add_global]),
   378          ((space_implode "_" new_type_names ^ "_perm_eq",
   379           perm_eq_thms), [Simplifier.simp_add_global])];
   380   
   381     (**** Define representing sets ****)
   382 
   383     val _ = warning "representing sets";
   384 
   385     val rep_set_names = map (Sign.full_name thy3) (DatatypeProp.indexify_names
   386       (map (fn (i, _) => name_of_typ (nth_dtyp i) ^ "_set") descr));
   387     val big_rep_name =
   388       space_implode "_" (DatatypeProp.indexify_names (List.mapPartial
   389         (fn (i, ("nominal.nOption", _, _)) => NONE
   390           | (i, _) => SOME (name_of_typ (nth_dtyp i))) descr)) ^ "_set";
   391     val _ = warning ("big_rep_name: " ^ big_rep_name);
   392 
   393     fun strip_option (dtf as DtType ("fun", [dt, DtRec i])) =
   394           (case AList.lookup op = descr i of
   395              SOME ("nominal.nOption", _, [(_, [dt']), _]) =>
   396                apfst (cons dt) (strip_option dt')
   397            | _ => ([], dtf))
   398       | strip_option (DtType ("fun", [dt, DtType ("nominal.nOption", [dt'])])) =
   399           apfst (cons dt) (strip_option dt')
   400       | strip_option dt = ([], dt);
   401 
   402     val dt_atomTs = distinct (map (typ_of_dtyp descr sorts')
   403       (List.concat (map (fn (_, (_, _, cs)) => List.concat
   404         (map (List.concat o map (fst o strip_option) o snd) cs)) descr)));
   405 
   406     fun make_intr s T (cname, cargs) =
   407       let
   408         fun mk_prem (dt, (j, j', prems, ts)) = 
   409           let
   410             val (dts, dt') = strip_option dt;
   411             val (dts', dt'') = strip_dtyp dt';
   412             val Ts = map (typ_of_dtyp descr sorts') dts;
   413             val Us = map (typ_of_dtyp descr sorts') dts';
   414             val T = typ_of_dtyp descr sorts' dt'';
   415             val free = mk_Free "x" (Us ---> T) j;
   416             val free' = app_bnds free (length Us);
   417             fun mk_abs_fun (T, (i, t)) =
   418               let val U = fastype_of t
   419               in (i + 1, Const ("nominal.abs_fun", [T, U, T] --->
   420                 Type ("nominal.nOption", [U])) $ mk_Free "y" T i $ t)
   421               end
   422           in (j + 1, j' + length Ts,
   423             case dt'' of
   424                 DtRec k => list_all (map (pair "x") Us,
   425                   HOLogic.mk_Trueprop (HOLogic.mk_mem (free',
   426                     Const (List.nth (rep_set_names, k),
   427                       HOLogic.mk_setT T)))) :: prems
   428               | _ => prems,
   429             snd (foldr mk_abs_fun (j', free) Ts) :: ts)
   430           end;
   431 
   432         val (_, _, prems, ts) = foldr mk_prem (1, 1, [], []) cargs;
   433         val concl = HOLogic.mk_Trueprop (HOLogic.mk_mem
   434           (list_comb (Const (cname, map fastype_of ts ---> T), ts),
   435            Const (s, HOLogic.mk_setT T)))
   436       in Logic.list_implies (prems, concl)
   437       end;
   438 
   439     val (intr_ts, ind_consts) =
   440       apfst List.concat (ListPair.unzip (List.mapPartial
   441         (fn ((_, ("nominal.nOption", _, _)), _) => NONE
   442           | ((i, (_, _, constrs)), rep_set_name) =>
   443               let val T = nth_dtyp i
   444               in SOME (map (make_intr rep_set_name T) constrs,
   445                 Const (rep_set_name, HOLogic.mk_setT T))
   446               end)
   447                 (descr ~~ rep_set_names)));
   448 
   449     val (thy4, {raw_induct = rep_induct, intrs = rep_intrs, ...}) =
   450       setmp InductivePackage.quiet_mode false
   451         (InductivePackage.add_inductive_i false true big_rep_name false true false
   452            ind_consts (map (fn x => (("", x), [])) intr_ts) []) thy3;
   453 
   454     (**** Prove that representing set is closed under permutation ****)
   455 
   456     val _ = warning "proving closure under permutation...";
   457 
   458     val perm_indnames' = List.mapPartial
   459       (fn (x, (_, ("nominal.nOption", _, _))) => NONE | (x, _) => SOME x)
   460       (perm_indnames ~~ descr);
   461 
   462     fun mk_perm_closed name = map (fn th => standard (th RS mp))
   463       (List.take (split_conj_thm (Goal.prove thy4 [] []
   464         (HOLogic.mk_Trueprop (foldr1 HOLogic.mk_conj (map
   465            (fn (S, x) =>
   466               let
   467                 val S = map_term_types (map_type_tfree
   468                   (fn (s, cs) => TFree (s, cs union cp_classes))) S;
   469                 val T = HOLogic.dest_setT (fastype_of S);
   470                 val permT = mk_permT (Type (name, []))
   471               in HOLogic.mk_imp (HOLogic.mk_mem (Free (x, T), S),
   472                 HOLogic.mk_mem (Const ("nominal.perm", permT --> T --> T) $
   473                   Free ("pi", permT) $ Free (x, T), S))
   474               end) (ind_consts ~~ perm_indnames'))))
   475         (fn _ => EVERY (* CU: added perm_fun_def in the final tactic in order to deal with funs *)
   476            [indtac rep_induct [] 1,
   477             ALLGOALS (simp_tac (simpset_of thy4 addsimps
   478               (symmetric perm_fun_def :: PureThy.get_thms thy4 (Name ("abs_perm"))))),
   479             ALLGOALS (resolve_tac rep_intrs 
   480                THEN_ALL_NEW (asm_full_simp_tac (simpset_of thy4 addsimps [perm_fun_def])))])),
   481         length new_type_names));
   482 
   483     (* FIXME: theorems are stored in database for testing only *)
   484     val perm_closed_thmss = map mk_perm_closed atoms;
   485     val (_,thy5) = PureThy.add_thmss [(("perm_closed", List.concat perm_closed_thmss), [])] thy4;
   486 
   487     (**** typedef ****)
   488 
   489     val _ = warning "defining type...";
   490 
   491     val (typedefs, thy6) =
   492       fold_map (fn ((((name, mx), tvs), c), name') => fn thy =>
   493         setmp TypedefPackage.quiet_mode true
   494           (TypedefPackage.add_typedef_i false (SOME name') (name, tvs, mx) c NONE
   495             (rtac exI 1 THEN
   496               QUIET_BREADTH_FIRST (has_fewer_prems 1)
   497               (resolve_tac rep_intrs 1))) thy |> (fn (thy, r) =>
   498         let
   499           val permT = mk_permT (TFree (variant tvs "'a", HOLogic.typeS));
   500           val pi = Free ("pi", permT);
   501           val tvs' = map (fn s => TFree (s, the (AList.lookup op = sorts' s))) tvs;
   502           val T = Type (Sign.intern_type thy name, tvs');
   503           val Const (_, Type (_, [U])) = c
   504         in apfst (pair r o hd)
   505           (PureThy.add_defs_i true [(("prm_" ^ name ^ "_def", Logic.mk_equals
   506             (Const ("nominal.perm", permT --> T --> T) $ pi $ Free ("x", T),
   507              Const (Sign.intern_const thy ("Abs_" ^ name), U --> T) $
   508                (Const ("nominal.perm", permT --> U --> U) $ pi $
   509                  (Const (Sign.intern_const thy ("Rep_" ^ name), T --> U) $
   510                    Free ("x", T))))), [])] thy)
   511         end))
   512           (types_syntax ~~ tyvars ~~
   513             (List.take (ind_consts, length new_type_names)) ~~ new_type_names) thy5;
   514 
   515     val perm_defs = map snd typedefs;
   516     val Abs_inverse_thms = map (#Abs_inverse o fst) typedefs;
   517     val Rep_inverse_thms = map (#Rep_inverse o fst) typedefs;
   518     val Rep_thms = map (#Rep o fst) typedefs;
   519 
   520     val big_name = space_implode "_" new_type_names;
   521 
   522 
   523     (** prove that new types are in class pt_<name> **)
   524 
   525     val _ = warning "prove that new types are in class pt_<name> ...";
   526 
   527     fun pt_instance ((class, atom), perm_closed_thms) =
   528       fold (fn (((({Abs_inverse, Rep_inverse, Rep, ...},
   529         perm_def), name), tvs), perm_closed) => fn thy =>
   530           AxClass.add_inst_arity_i
   531             (Sign.intern_type thy name,
   532               replicate (length tvs) (classes @ cp_classes), [class])
   533             (EVERY [AxClass.intro_classes_tac [],
   534               rewrite_goals_tac [perm_def],
   535               asm_full_simp_tac (simpset_of thy addsimps [Rep_inverse]) 1,
   536               asm_full_simp_tac (simpset_of thy addsimps
   537                 [Rep RS perm_closed RS Abs_inverse]) 1,
   538               asm_full_simp_tac (HOL_basic_ss addsimps [PureThy.get_thm thy
   539                 (Name ("pt_" ^ Sign.base_name atom ^ "3"))]) 1]) thy)
   540         (typedefs ~~ new_type_names ~~ tyvars ~~ perm_closed_thms);
   541 
   542 
   543     (** prove that new types are in class cp_<name1>_<name2> **)
   544 
   545     val _ = warning "prove that new types are in class cp_<name1>_<name2> ...";
   546 
   547     fun cp_instance (atom1, perm_closed_thms1) (atom2, perm_closed_thms2) thy =
   548       let
   549         val name = "cp_" ^ Sign.base_name atom1 ^ "_" ^ Sign.base_name atom2;
   550         val class = Sign.intern_class thy name;
   551         val cp1' = PureThy.get_thm thy (Name (name ^ "_inst")) RS cp1
   552       in fold (fn ((((({Abs_inverse, Rep_inverse, Rep, ...},
   553         perm_def), name), tvs), perm_closed1), perm_closed2) => fn thy =>
   554           AxClass.add_inst_arity_i
   555             (Sign.intern_type thy name,
   556               replicate (length tvs) (classes @ cp_classes), [class])
   557             (EVERY [AxClass.intro_classes_tac [],
   558               rewrite_goals_tac [perm_def],
   559               asm_full_simp_tac (simpset_of thy addsimps
   560                 ((Rep RS perm_closed1 RS Abs_inverse) ::
   561                  (if atom1 = atom2 then []
   562                   else [Rep RS perm_closed2 RS Abs_inverse]))) 1,
   563               cong_tac 1,
   564               rtac refl 1,
   565               rtac cp1' 1]) thy)
   566         (typedefs ~~ new_type_names ~~ tyvars ~~ perm_closed_thms1 ~~
   567           perm_closed_thms2) thy
   568       end;
   569 
   570     val thy7 = fold (fn x => fn thy => thy |>
   571       pt_instance x |>
   572       fold (cp_instance (apfst snd x)) (atoms ~~ perm_closed_thmss))
   573         (classes ~~ atoms ~~ perm_closed_thmss) thy6;
   574 
   575     (**** constructors ****)
   576 
   577     fun mk_abs_fun (x, t) =
   578       let
   579         val T = fastype_of x;
   580         val U = fastype_of t
   581       in
   582         Const ("nominal.abs_fun", T --> U --> T -->
   583           Type ("nominal.nOption", [U])) $ x $ t
   584       end;
   585 
   586     val (ty_idxs, _) = foldl
   587       (fn ((i, ("nominal.nOption", _, _)), p) => p
   588         | ((i, _), (ty_idxs, j)) => (ty_idxs @ [(i, j)], j + 1)) ([], 0) descr;
   589 
   590     fun reindex (DtType (s, dts)) = DtType (s, map reindex dts)
   591       | reindex (DtRec i) = DtRec (the (AList.lookup op = ty_idxs i))
   592       | reindex dt = dt;
   593 
   594     fun strip_suffix i s = implode (List.take (explode s, size s - i));
   595 
   596     (** strips the "_Rep" in type names *)
   597     fun strip_nth_name i s = 
   598       let val xs = NameSpace.unpack s; 
   599       in NameSpace.pack (Library.nth_map (length xs - i) (strip_suffix 4) xs) end;
   600 
   601     val (descr'', ndescr) = ListPair.unzip (List.mapPartial
   602       (fn (i, ("nominal.nOption", _, _)) => NONE
   603         | (i, (s, dts, constrs)) =>
   604              let
   605                val SOME index = AList.lookup op = ty_idxs i;
   606                val (constrs1, constrs2) = ListPair.unzip
   607                  (map (fn (cname, cargs) => apfst (pair (strip_nth_name 2 cname))
   608                    (foldl_map (fn (dts, dt) =>
   609                      let val (dts', dt') = strip_option dt
   610                      in (dts @ dts' @ [reindex dt'], (length dts, length dts')) end)
   611                        ([], cargs))) constrs)
   612              in SOME ((index, (strip_nth_name 1 s,  map reindex dts, constrs1)),
   613                (index, constrs2))
   614              end) descr);
   615 
   616     val (descr1, descr2) = splitAt (length new_type_names, descr'');
   617     val descr' = [descr1, descr2];
   618 
   619     val typ_of_dtyp' = replace_types' o typ_of_dtyp descr sorts';
   620 
   621     val rep_names = map (fn s =>
   622       Sign.intern_const thy7 ("Rep_" ^ s)) new_type_names;
   623     val abs_names = map (fn s =>
   624       Sign.intern_const thy7 ("Abs_" ^ s)) new_type_names;
   625 
   626     val recTs' = List.mapPartial
   627       (fn ((_, ("nominal.nOption", _, _)), T) => NONE
   628         | (_, T) => SOME T) (descr ~~ get_rec_types descr sorts');
   629     val recTs = get_rec_types descr'' sorts';
   630     val newTs' = Library.take (length new_type_names, recTs');
   631     val newTs = Library.take (length new_type_names, recTs);
   632 
   633     val full_new_type_names = map (Sign.full_name (sign_of thy)) new_type_names;
   634 
   635     fun make_constr_def tname T T' ((thy, defs, eqns), ((cname, cargs), (cname', mx))) =
   636       let
   637         fun constr_arg (dt, (j, l_args, r_args)) =
   638           let
   639             val x' = mk_Free "x" (typ_of_dtyp' dt) j;
   640             val (dts, dt') = strip_option dt;
   641             val xs = map (fn (dt, i) => mk_Free "x" (typ_of_dtyp' dt) i)
   642               (dts ~~ (j upto j + length dts - 1))
   643             val x = mk_Free "x" (typ_of_dtyp' dt') (j + length dts)
   644             val (dts', dt'') = strip_dtyp dt'
   645           in
   646             (j + length dts + 1,
   647              xs @ x :: l_args,
   648              foldr mk_abs_fun
   649                (case dt'' of
   650                   DtRec k => if k < length new_type_names then
   651                       list_abs (map (pair "z" o typ_of_dtyp') dts',
   652                         Const (List.nth (rep_names, k), typ_of_dtyp' dt'' -->
   653                           typ_of_dtyp descr sorts' dt'') $ app_bnds x (length dts'))
   654                     else error "nested recursion not (yet) supported"
   655                 | _ => x) xs :: r_args)
   656           end
   657 
   658         val (_, l_args, r_args) = foldr constr_arg (1, [], []) cargs;
   659         val abs_name = Sign.intern_const (Theory.sign_of thy) ("Abs_" ^ tname);
   660         val rep_name = Sign.intern_const (Theory.sign_of thy) ("Rep_" ^ tname);
   661         val constrT = map fastype_of l_args ---> T;
   662         val lhs = list_comb (Const (Sign.full_name thy (Sign.base_name cname),
   663           constrT), l_args);
   664         val rhs = list_comb (Const (cname, map fastype_of r_args ---> T'), r_args);
   665         val def = Logic.mk_equals (lhs, Const (abs_name, T' --> T) $ rhs);
   666         val eqn = HOLogic.mk_Trueprop (HOLogic.mk_eq
   667           (Const (rep_name, T --> T') $ lhs, rhs));
   668         val def_name = (Sign.base_name cname) ^ "_def";
   669         val ([def_thm], thy') = thy |>
   670           Theory.add_consts_i [(cname', constrT, mx)] |>
   671           (PureThy.add_defs_i false o map Thm.no_attributes) [(def_name, def)]
   672       in (thy', defs @ [def_thm], eqns @ [eqn]) end;
   673 
   674     fun dt_constr_defs ((thy, defs, eqns, dist_lemmas),
   675         (((((_, (_, _, constrs)), tname), T), T'), constr_syntax)) =
   676       let
   677         val rep_const = cterm_of thy
   678           (Const (Sign.intern_const thy ("Rep_" ^ tname), T --> T'));
   679         val dist = standard (cterm_instantiate [(cterm_of thy distinct_f, rep_const)] distinct_lemma);
   680         val (thy', defs', eqns') = Library.foldl (make_constr_def tname T T')
   681           ((Theory.add_path tname thy, defs, []), constrs ~~ constr_syntax)
   682       in
   683         (parent_path flat_names thy', defs', eqns @ [eqns'], dist_lemmas @ [dist])
   684       end;
   685 
   686     val (thy8, constr_defs, constr_rep_eqns, dist_lemmas) = Library.foldl dt_constr_defs
   687       ((thy7, [], [], []), List.take (descr, length new_type_names) ~~
   688         new_type_names ~~ newTs ~~ newTs' ~~ constr_syntax);
   689 
   690     val abs_inject_thms = map (fn tname =>
   691       PureThy.get_thm thy8 (Name ("Abs_" ^ tname ^ "_inject"))) new_type_names;
   692 
   693     val rep_inject_thms = map (fn tname =>
   694       PureThy.get_thm thy8 (Name ("Rep_" ^ tname ^ "_inject"))) new_type_names;
   695 
   696     val rep_thms = map (fn tname =>
   697       PureThy.get_thm thy8 (Name ("Rep_" ^ tname))) new_type_names;
   698 
   699     val rep_inverse_thms = map (fn tname =>
   700       PureThy.get_thm thy8 (Name ("Rep_" ^ tname ^ "_inverse"))) new_type_names;
   701 
   702     (* prove theorem  Rep_i (Constr_j ...) = Constr'_j ...  *)
   703     
   704     fun prove_constr_rep_thm eqn =
   705       let
   706         val inj_thms = map (fn r => r RS iffD1) abs_inject_thms;
   707         val rewrites = constr_defs @ map mk_meta_eq rep_inverse_thms
   708       in standard (Goal.prove thy8 [] [] eqn (fn _ => EVERY
   709         [resolve_tac inj_thms 1,
   710          rewrite_goals_tac rewrites,
   711          rtac refl 3,
   712          resolve_tac rep_intrs 2,
   713          REPEAT (resolve_tac rep_thms 1)]))
   714       end;
   715 
   716     val constr_rep_thmss = map (map prove_constr_rep_thm) constr_rep_eqns;
   717 
   718     (* prove theorem  pi \<bullet> Rep_i x = Rep_i (pi \<bullet> x) *)
   719 
   720     fun prove_perm_rep_perm (atom, perm_closed_thms) = map (fn th =>
   721       let
   722         val _ $ (_ $ (Rep $ x) $ _) = Logic.unvarify (prop_of th);
   723         val Type ("fun", [T, U]) = fastype_of Rep;
   724         val permT = mk_permT (Type (atom, []));
   725         val pi = Free ("pi", permT);
   726       in
   727         standard (Goal.prove thy8 [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq
   728             (Const ("nominal.perm", permT --> U --> U) $ pi $ (Rep $ x),
   729              Rep $ (Const ("nominal.perm", permT --> T --> T) $ pi $ x))))
   730           (fn _ => simp_tac (HOL_basic_ss addsimps (perm_defs @ Abs_inverse_thms @
   731             perm_closed_thms @ Rep_thms)) 1))
   732       end) Rep_thms;
   733 
   734     val perm_rep_perm_thms = List.concat (map prove_perm_rep_perm
   735       (atoms ~~ perm_closed_thmss));
   736 
   737     (* prove distinctness theorems *)
   738 
   739     val distinct_props = setmp DatatypeProp.dtK 1000
   740       (DatatypeProp.make_distincts new_type_names descr' sorts') thy8;
   741 
   742     val dist_rewrites = map (fn (rep_thms, dist_lemma) =>
   743       dist_lemma::(rep_thms @ [In0_eq, In1_eq, In0_not_In1, In1_not_In0]))
   744         (constr_rep_thmss ~~ dist_lemmas);
   745 
   746     fun prove_distinct_thms (_, []) = []
   747       | prove_distinct_thms (p as (rep_thms, dist_lemma), t::ts) =
   748           let
   749             val dist_thm = standard (Goal.prove thy8 [] [] t (fn _ =>
   750               simp_tac (simpset_of thy8 addsimps (dist_lemma :: rep_thms)) 1))
   751           in dist_thm::(standard (dist_thm RS not_sym))::
   752             (prove_distinct_thms (p, ts))
   753           end;
   754 
   755     val distinct_thms = map prove_distinct_thms
   756       (constr_rep_thmss ~~ dist_lemmas ~~ distinct_props);
   757 
   758     (** prove equations for permutation functions **)
   759 
   760     val abs_perm = PureThy.get_thms thy8 (Name "abs_perm"); (* FIXME *)
   761 
   762     val perm_simps' = map (fn (((i, (_, _, constrs)), tname), constr_rep_thms) =>
   763       let val T = replace_types' (nth_dtyp i)
   764       in List.concat (map (fn (atom, perm_closed_thms) =>
   765           map (fn ((cname, dts), constr_rep_thm) => 
   766         let
   767           val cname = Sign.intern_const thy8
   768             (NameSpace.append tname (Sign.base_name cname));
   769           val permT = mk_permT (Type (atom, []));
   770           val pi = Free ("pi", permT);
   771 
   772           fun perm t =
   773             let val T = fastype_of t
   774             in Const ("nominal.perm", permT --> T --> T) $ pi $ t end;
   775 
   776           fun constr_arg (dt, (j, l_args, r_args)) =
   777             let
   778               val x' = mk_Free "x" (typ_of_dtyp' dt) j;
   779               val (dts, dt') = strip_option dt;
   780               val Ts = map typ_of_dtyp' dts;
   781               val xs = map (fn (T, i) => mk_Free "x" T i)
   782                 (Ts ~~ (j upto j + length dts - 1))
   783               val x = mk_Free "x" (typ_of_dtyp' dt') (j + length dts);
   784               val (dts', dt'') = strip_dtyp dt';
   785             in
   786               (j + length dts + 1,
   787                xs @ x :: l_args,
   788                map perm (xs @ [x]) @ r_args)
   789             end
   790 
   791           val (_, l_args, r_args) = foldr constr_arg (1, [], []) dts;
   792           val c = Const (cname, map fastype_of l_args ---> T)
   793         in
   794           standard (Goal.prove thy8 [] []
   795             (HOLogic.mk_Trueprop (HOLogic.mk_eq
   796               (perm (list_comb (c, l_args)), list_comb (c, r_args))))
   797             (fn _ => EVERY
   798               [simp_tac (simpset_of thy8 addsimps (constr_rep_thm :: perm_defs)) 1,
   799                simp_tac (HOL_basic_ss addsimps (Rep_thms @ Abs_inverse_thms @
   800                  constr_defs @ perm_closed_thms)) 1,
   801                TRY (simp_tac (HOL_basic_ss addsimps
   802                  (symmetric perm_fun_def :: abs_perm)) 1),
   803                TRY (simp_tac (HOL_basic_ss addsimps
   804                  (perm_fun_def :: perm_defs @ Rep_thms @ Abs_inverse_thms @
   805                     perm_closed_thms)) 1)]))
   806         end) (constrs ~~ constr_rep_thms)) (atoms ~~ perm_closed_thmss))
   807       end) (List.take (descr, length new_type_names) ~~ new_type_names ~~ constr_rep_thmss);
   808 
   809     (** prove injectivity of constructors **)
   810 
   811     val rep_inject_thms' = map (fn th => th RS sym) rep_inject_thms;
   812     val alpha = PureThy.get_thms thy8 (Name "alpha");
   813     val abs_fresh = PureThy.get_thms thy8 (Name "abs_fresh");
   814     val fresh_def = PureThy.get_thm thy8 (Name "fresh_def");
   815     val supp_def = PureThy.get_thm thy8 (Name "supp_def");
   816 
   817     val inject_thms = map (fn (((i, (_, _, constrs)), tname), constr_rep_thms) =>
   818       let val T = replace_types' (nth_dtyp i)
   819       in List.mapPartial (fn ((cname, dts), constr_rep_thm) =>
   820         if null dts then NONE else SOME
   821         let
   822           val cname = Sign.intern_const thy8
   823             (NameSpace.append tname (Sign.base_name cname));
   824 
   825           fun make_inj (dt, (j, args1, args2, eqs)) =
   826             let
   827               val x' = mk_Free "x" (typ_of_dtyp' dt) j;
   828               val y' = mk_Free "y" (typ_of_dtyp' dt) j;
   829               val (dts, dt') = strip_option dt;
   830               val Ts_idx = map typ_of_dtyp' dts ~~ (j upto j + length dts - 1);
   831               val xs = map (fn (T, i) => mk_Free "x" T i) Ts_idx;
   832               val ys = map (fn (T, i) => mk_Free "y" T i) Ts_idx;
   833               val x = mk_Free "x" (typ_of_dtyp' dt') (j + length dts);
   834               val y = mk_Free "y" (typ_of_dtyp' dt') (j + length dts);
   835               val (dts', dt'') = strip_dtyp dt';
   836             in
   837               (j + length dts + 1,
   838                xs @ (x :: args1), ys @ (y :: args2),
   839                HOLogic.mk_eq
   840                  (foldr mk_abs_fun x xs, foldr mk_abs_fun y ys) :: eqs)
   841             end;
   842 
   843           val (_, args1, args2, eqs) = foldr make_inj (1, [], [], []) dts;
   844           val Ts = map fastype_of args1;
   845           val c = Const (cname, Ts ---> T)
   846         in
   847           standard (Goal.prove thy8 [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq
   848               (HOLogic.mk_eq (list_comb (c, args1), list_comb (c, args2)),
   849                foldr1 HOLogic.mk_conj eqs)))
   850             (fn _ => EVERY
   851                [asm_full_simp_tac (simpset_of thy8 addsimps (constr_rep_thm ::
   852                   rep_inject_thms')) 1,
   853                 TRY (asm_full_simp_tac (HOL_basic_ss addsimps (fresh_def :: supp_def ::
   854                   alpha @ abs_perm @ abs_fresh @ rep_inject_thms @
   855                   perm_rep_perm_thms)) 1),
   856                 TRY (asm_full_simp_tac (HOL_basic_ss addsimps (perm_fun_def ::
   857                   expand_fun_eq :: rep_inject_thms @ perm_rep_perm_thms)) 1)]))
   858         end) (constrs ~~ constr_rep_thms)
   859       end) (List.take (descr, length new_type_names) ~~ new_type_names ~~ constr_rep_thmss);
   860 
   861     (** equations for support and freshness **)
   862 
   863     val Un_assoc = PureThy.get_thm thy8 (Name "Un_assoc");
   864     val de_Morgan_conj = PureThy.get_thm thy8 (Name "de_Morgan_conj");
   865     val Collect_disj_eq = PureThy.get_thm thy8 (Name "Collect_disj_eq");
   866     val finite_Un = PureThy.get_thm thy8 (Name "finite_Un");
   867 
   868     val (supp_thms, fresh_thms) = ListPair.unzip (map ListPair.unzip
   869       (map (fn ((((i, (_, _, constrs)), tname), inject_thms'), perm_thms') =>
   870       let val T = replace_types' (nth_dtyp i)
   871       in List.concat (map (fn (cname, dts) => map (fn atom =>
   872         let
   873           val cname = Sign.intern_const thy8
   874             (NameSpace.append tname (Sign.base_name cname));
   875           val atomT = Type (atom, []);
   876 
   877           fun process_constr (dt, (j, args1, args2)) =
   878             let
   879               val x' = mk_Free "x" (typ_of_dtyp' dt) j;
   880               val (dts, dt') = strip_option dt;
   881               val Ts_idx = map typ_of_dtyp' dts ~~ (j upto j + length dts - 1);
   882               val xs = map (fn (T, i) => mk_Free "x" T i) Ts_idx;
   883               val x = mk_Free "x" (typ_of_dtyp' dt') (j + length dts);
   884               val (dts', dt'') = strip_dtyp dt';
   885             in
   886               (j + length dts + 1,
   887                xs @ (x :: args1), foldr mk_abs_fun x xs :: args2)
   888             end;
   889 
   890           val (_, args1, args2) = foldr process_constr (1, [], []) dts;
   891           val Ts = map fastype_of args1;
   892           val c = list_comb (Const (cname, Ts ---> T), args1);
   893           fun supp t =
   894             Const ("nominal.supp", fastype_of t --> HOLogic.mk_setT atomT) $ t;
   895           fun fresh t =
   896             Const ("nominal.fresh", atomT --> fastype_of t --> HOLogic.boolT) $
   897               Free ("a", atomT) $ t;
   898           val supp_thm = standard (Goal.prove thy8 [] []
   899               (HOLogic.mk_Trueprop (HOLogic.mk_eq
   900                 (supp c,
   901                  if null dts then Const ("{}", HOLogic.mk_setT atomT)
   902                  else foldr1 (HOLogic.mk_binop "op Un") (map supp args2))))
   903             (fn _ =>
   904               simp_tac (HOL_basic_ss addsimps (supp_def ::
   905                  Un_assoc :: de_Morgan_conj :: Collect_disj_eq :: finite_Un ::
   906                  symmetric empty_def :: Finites.emptyI :: simp_thms @
   907                  abs_perm @ abs_fresh @ inject_thms' @ perm_thms')) 1))
   908         in
   909           (supp_thm,
   910            standard (Goal.prove thy8 [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq
   911               (fresh c,
   912                if null dts then HOLogic.true_const
   913                else foldr1 HOLogic.mk_conj (map fresh args2))))
   914              (fn _ =>
   915                simp_tac (simpset_of thy8 addsimps [fresh_def, supp_thm]) 1)))
   916         end) atoms) constrs)
   917       end) (List.take (descr, length new_type_names) ~~ new_type_names ~~ inject_thms ~~ perm_simps')));
   918 
   919     (**** weak induction theorem ****)
   920 
   921     val arities = get_arities descr'';
   922 
   923     fun mk_funs_inv thm =
   924       let
   925         val {sign, prop, ...} = rep_thm thm;
   926         val _ $ (_ $ (Const (_, Type (_, [U, _])) $ _ $ S)) $
   927           (_ $ (_ $ (r $ (a $ _)) $ _)) = Type.freeze prop;
   928         val used = add_term_tfree_names (a, []);
   929 
   930         fun mk_thm i =
   931           let
   932             val Ts = map (TFree o rpair HOLogic.typeS)
   933               (variantlist (replicate i "'t", used));
   934             val f = Free ("f", Ts ---> U)
   935           in standard (Goal.prove sign [] [] (Logic.mk_implies
   936             (HOLogic.mk_Trueprop (HOLogic.list_all
   937                (map (pair "x") Ts, HOLogic.mk_mem (app_bnds f i, S))),
   938              HOLogic.mk_Trueprop (HOLogic.mk_eq (list_abs (map (pair "x") Ts,
   939                r $ (a $ app_bnds f i)), f))))
   940             (fn _ => EVERY [REPEAT (rtac ext 1), REPEAT (etac allE 1), rtac thm 1, atac 1]))
   941           end
   942       in map (fn r => r RS subst) (thm :: map mk_thm arities) end;
   943 
   944     fun mk_indrule_lemma ((prems, concls), (((i, _), T), U)) =
   945       let
   946         val Rep_t = Const (List.nth (rep_names, i), T --> U) $
   947           mk_Free "x" T i;
   948 
   949         val Abs_t =  Const (List.nth (abs_names, i), U --> T)
   950 
   951       in (prems @ [HOLogic.imp $ HOLogic.mk_mem (Rep_t,
   952             Const (List.nth (rep_set_names, i), HOLogic.mk_setT U)) $
   953               (mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ (Abs_t $ Rep_t))],
   954           concls @ [mk_Free "P" (T --> HOLogic.boolT) (i + 1) $ mk_Free "x" T i])
   955       end;
   956 
   957     val (indrule_lemma_prems, indrule_lemma_concls) =
   958       Library.foldl mk_indrule_lemma (([], []), (descr'' ~~ recTs ~~ recTs'));
   959 
   960     val indrule_lemma = standard (Goal.prove thy8 [] []
   961       (Logic.mk_implies
   962         (HOLogic.mk_Trueprop (mk_conj indrule_lemma_prems),
   963          HOLogic.mk_Trueprop (mk_conj indrule_lemma_concls))) (fn _ => EVERY
   964            [REPEAT (etac conjE 1),
   965             REPEAT (EVERY
   966               [TRY (rtac conjI 1), full_simp_tac (HOL_basic_ss addsimps Rep_inverse_thms) 1,
   967                etac mp 1, resolve_tac Rep_thms 1])]));
   968 
   969     val Ps = map head_of (HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of indrule_lemma)));
   970     val frees = if length Ps = 1 then [Free ("P", snd (dest_Var (hd Ps)))] else
   971       map (Free o apfst fst o dest_Var) Ps;
   972     val indrule_lemma' = cterm_instantiate
   973       (map (cterm_of thy8) Ps ~~ map (cterm_of thy8) frees) indrule_lemma;
   974 
   975     val Abs_inverse_thms' = List.concat (map mk_funs_inv Abs_inverse_thms);
   976 
   977     val dt_induct_prop = DatatypeProp.make_ind descr' sorts';
   978     val dt_induct = standard (Goal.prove thy8 []
   979       (Logic.strip_imp_prems dt_induct_prop) (Logic.strip_imp_concl dt_induct_prop)
   980       (fn prems => EVERY
   981         [rtac indrule_lemma' 1,
   982          (DatatypeAux.indtac rep_induct THEN_ALL_NEW ObjectLogic.atomize_tac) 1,
   983          EVERY (map (fn (prem, r) => (EVERY
   984            [REPEAT (eresolve_tac Abs_inverse_thms' 1),
   985             simp_tac (HOL_basic_ss addsimps [symmetric r]) 1,
   986             DEPTH_SOLVE_1 (ares_tac [prem] 1 ORELSE etac allE 1)]))
   987                 (prems ~~ constr_defs))]));
   988 
   989     val case_names_induct = mk_case_names_induct descr'';
   990 
   991     (**** prove that new datatypes have finite support ****)
   992 
   993     val _ = warning "proving finite support for the new datatype";
   994 
   995     val indnames = DatatypeProp.make_tnames recTs;
   996 
   997     val abs_supp = PureThy.get_thms thy8 (Name "abs_supp");
   998     val supp_atm = PureThy.get_thms thy8 (Name "supp_atm");
   999 
  1000     val finite_supp_thms = map (fn atom =>
  1001       let val atomT = Type (atom, [])
  1002       in map standard (List.take
  1003         (split_conj_thm (Goal.prove thy8 [] [] (HOLogic.mk_Trueprop
  1004            (foldr1 HOLogic.mk_conj (map (fn (s, T) => HOLogic.mk_mem
  1005              (Const ("nominal.supp", T --> HOLogic.mk_setT atomT) $ Free (s, T),
  1006               Const ("Finite_Set.Finites", HOLogic.mk_setT (HOLogic.mk_setT atomT))))
  1007                (indnames ~~ recTs))))
  1008            (fn _ => indtac dt_induct indnames 1 THEN
  1009             ALLGOALS (asm_full_simp_tac (simpset_of thy8 addsimps
  1010               (abs_supp @ supp_atm @
  1011                PureThy.get_thms thy8 (Name ("fs_" ^ Sign.base_name atom ^ "1")) @
  1012                List.concat supp_thms))))),
  1013          length new_type_names))
  1014       end) atoms;
  1015 
  1016     (**** strong induction theorem ****)
  1017 
  1018     val pnames = if length descr'' = 1 then ["P"]
  1019       else map (fn i => "P" ^ string_of_int i) (1 upto length descr'');
  1020     val ind_sort = if null dt_atomTs then HOLogic.typeS
  1021       else map (fn T => Sign.intern_class thy8 ("fs_" ^
  1022         Sign.base_name (fst (dest_Type T)))) dt_atomTs;
  1023     val fsT = TFree ("'n", ind_sort);
  1024 
  1025     fun make_pred i T =
  1026       Free (List.nth (pnames, i), fsT --> T --> HOLogic.boolT);
  1027 
  1028     fun make_ind_prem k T ((cname, cargs), idxs) =
  1029       let
  1030         val recs = List.filter is_rec_type cargs;
  1031         val Ts = map (typ_of_dtyp descr'' sorts') cargs;
  1032         val recTs' = map (typ_of_dtyp descr'' sorts') recs;
  1033         val tnames = variantlist (DatatypeProp.make_tnames Ts, pnames);
  1034         val rec_tnames = map fst (List.filter (is_rec_type o snd) (tnames ~~ cargs));
  1035         val frees = tnames ~~ Ts;
  1036         val z = (variant tnames "z", fsT);
  1037 
  1038         fun mk_prem ((dt, s), T) =
  1039           let
  1040             val (Us, U) = strip_type T;
  1041             val l = length Us
  1042           in list_all (z :: map (pair "x") Us, HOLogic.mk_Trueprop
  1043             (make_pred (body_index dt) U $ Bound l $ app_bnds (Free (s, T)) l))
  1044           end;
  1045 
  1046         val prems = map mk_prem (recs ~~ rec_tnames ~~ recTs');
  1047         val prems' = map (fn p as (_, T) => HOLogic.mk_Trueprop
  1048             (Const ("nominal.fresh", T --> fsT --> HOLogic.boolT) $
  1049               Free p $ Free z))
  1050           (map (curry List.nth frees) (List.concat (map (fn (m, n) =>
  1051              m upto m + n - 1) idxs)))
  1052 
  1053       in list_all_free (frees @ [z], Logic.list_implies (prems' @ prems,
  1054         HOLogic.mk_Trueprop (make_pred k T $ Free z $
  1055           list_comb (Const (cname, Ts ---> T), map Free frees))))
  1056       end;
  1057 
  1058     val ind_prems = List.concat (map (fn (((i, (_, _, constrs)), (_, idxss)), T) =>
  1059       map (make_ind_prem i T) (constrs ~~ idxss)) (descr'' ~~ ndescr ~~ recTs));
  1060     val tnames = DatatypeProp.make_tnames recTs;
  1061     val z = (variant tnames "z", fsT);
  1062     val ind_concl = HOLogic.mk_Trueprop (foldr1 (HOLogic.mk_binop "op &")
  1063       (map (fn (((i, _), T), tname) => make_pred i T $ Free z $ Free (tname, T))
  1064         (descr'' ~~ recTs ~~ tnames)));
  1065     val induct = Logic.list_implies (ind_prems, ind_concl);
  1066 
  1067     val simp_atts = replicate (length new_type_names) [Simplifier.simp_add_global];
  1068 
  1069     val (_, thy9) = (thy8:Context.theory) |>
  1070       Theory.add_path big_name |>
  1071       PureThy.add_thms [(("induct_weak", dt_induct), [case_names_induct])] ||>
  1072       Theory.parent_path ||>>
  1073       DatatypeAux.store_thmss_atts "distinct" new_type_names simp_atts distinct_thms ||>>
  1074       DatatypeAux.store_thmss "constr_rep" new_type_names constr_rep_thmss ||>>
  1075       DatatypeAux.store_thmss_atts "perm" new_type_names simp_atts perm_simps' ||>>
  1076       DatatypeAux.store_thmss "inject" new_type_names inject_thms ||>>
  1077       DatatypeAux.store_thmss "supp" new_type_names supp_thms ||>>
  1078       DatatypeAux.store_thmss_atts "fresh" new_type_names simp_atts fresh_thms ||>
  1079       fold (fn (atom, ths) => fn thy =>
  1080         let val class = Sign.intern_class thy ("fs_" ^ Sign.base_name atom)
  1081         in fold (fn T => AxClass.add_inst_arity_i
  1082             (fst (dest_Type T),
  1083               replicate (length sorts) [class], [class])
  1084             (AxClass.intro_classes_tac [] THEN resolve_tac ths 1)) newTs thy
  1085         end) (atoms ~~ finite_supp_thms) ||>
  1086       Theory.add_path big_name ||>>
  1087       PureThy.add_axioms_i [(("induct_unsafe", induct), [case_names_induct])] ||>
  1088       Theory.parent_path;
  1089 
  1090   in
  1091     thy9
  1092   end;
  1093 
  1094 val add_nominal_datatype = gen_add_nominal_datatype read_typ true;
  1095 
  1096 
  1097 (* FIXME: The following stuff should be exported by DatatypePackage *)
  1098 
  1099 local structure P = OuterParse and K = OuterKeyword in
  1100 
  1101 val datatype_decl =
  1102   Scan.option (P.$$$ "(" |-- P.name --| P.$$$ ")") -- P.type_args -- P.name -- P.opt_infix --
  1103     (P.$$$ "=" |-- P.enum1 "|" (P.name -- Scan.repeat P.typ -- P.opt_mixfix));
  1104 
  1105 fun mk_datatype args =
  1106   let
  1107     val names = map (fn ((((NONE, _), t), _), _) => t | ((((SOME t, _), _), _), _) => t) args;
  1108     val specs = map (fn ((((_, vs), t), mx), cons) =>
  1109       (vs, t, mx, map (fn ((x, y), z) => (x, y, z)) cons)) args;
  1110   in add_nominal_datatype false names specs end;
  1111 
  1112 val nominal_datatypeP =
  1113   OuterSyntax.command "nominal_datatype" "define inductive datatypes" K.thy_decl
  1114     (P.and_list1 datatype_decl >> (Toplevel.theory o mk_datatype));
  1115 
  1116 val _ = OuterSyntax.add_parsers [nominal_datatypeP];
  1117 
  1118 end;
  1119 
  1120 end
  1121