Nominal/Attic/Parser.thy
changeset 2008 1bddffddc03f
parent 2001 7c8242a02f39
equal deleted inserted replaced
2007:7ee9a2fefc77 2008:1bddffddc03f
       
     1 theory Parser
       
     2 imports "../Nominal-General/Nominal2_Atoms" 
       
     3         "../Nominal-General/Nominal2_Eqvt" 
       
     4         "../Nominal-General/Nominal2_Supp" 
       
     5         "Perm" "Equivp" "Rsp" "Lift"
       
     6 begin
       
     7 
       
     8 section{* Interface for nominal_datatype *}
       
     9 
       
    10 text {*
       
    11 
       
    12 Nominal-Datatype-part:
       
    13 
       
    14 
       
    15 1nd Arg: (string list * binding * mixfix * (binding * typ list * mixfix) list) list
       
    16          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       
    17                type(s) to be defined             constructors list
       
    18                (ty args, name, syn)              (name, typs, syn)
       
    19 
       
    20 Binder-Function-part:
       
    21 
       
    22 2rd Arg: (binding * typ option * mixfix) list 
       
    23          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    
       
    24             binding function(s)           
       
    25               to be defined               
       
    26             (name, type, syn)             
       
    27 
       
    28 3th Arg:  term list 
       
    29           ^^^^^^^^^
       
    30           the equations of the binding functions
       
    31           (Trueprop equations)
       
    32 *}
       
    33 
       
    34 ML {*
       
    35 
       
    36 *}
       
    37 
       
    38 text {*****************************************************}
       
    39 ML {* 
       
    40 (* nominal datatype parser *)
       
    41 local
       
    42   structure P = OuterParse
       
    43 
       
    44   fun tuple ((x, y, z), u) = (x, y, z, u)
       
    45   fun tswap (((x, y), z), u) = (x, y, u, z)
       
    46 in
       
    47 
       
    48 val _ = OuterKeyword.keyword "bind"
       
    49 val anno_typ = Scan.option (P.name --| P.$$$ "::") -- P.typ
       
    50 
       
    51 (* binding specification *)
       
    52 (* maybe use and_list *)
       
    53 val bind_parser = 
       
    54   P.enum "," ((P.$$$ "bind" |-- P.term) -- (P.$$$ "in" |-- P.name) >> swap)
       
    55 
       
    56 val constr_parser =
       
    57   P.binding -- Scan.repeat anno_typ
       
    58 
       
    59 (* datatype parser *)
       
    60 val dt_parser =
       
    61   (P.type_args -- P.binding -- P.opt_mixfix >> P.triple1) -- 
       
    62     (P.$$$ "=" |-- P.enum1 "|" (constr_parser -- bind_parser -- P.opt_mixfix >> tswap)) >> tuple
       
    63 
       
    64 (* function equation parser *)
       
    65 val fun_parser = 
       
    66   Scan.optional (P.$$$ "binder" |-- P.fixes -- SpecParse.where_alt_specs) ([],[])
       
    67 
       
    68 (* main parser *)
       
    69 val main_parser =
       
    70   (P.and_list1 dt_parser) -- fun_parser >> P.triple2
       
    71 
       
    72 end
       
    73 *}
       
    74 
       
    75 (* adds "_raw" to the end of constants and types *)
       
    76 ML {*
       
    77 fun add_raw s = s ^ "_raw"
       
    78 fun add_raws ss = map add_raw ss
       
    79 fun raw_bind bn = Binding.suffix_name "_raw" bn
       
    80 
       
    81 fun replace_str ss s = 
       
    82   case (AList.lookup (op=) ss s) of 
       
    83      SOME s' => s'
       
    84    | NONE => s
       
    85 
       
    86 fun replace_typ ty_ss (Type (a, Ts)) = Type (replace_str ty_ss a, map (replace_typ ty_ss) Ts)
       
    87   | replace_typ ty_ss T = T  
       
    88 
       
    89 fun raw_dts ty_ss dts =
       
    90 let
       
    91 
       
    92   fun raw_dts_aux1 (bind, tys, mx) =
       
    93     (raw_bind bind, map (replace_typ ty_ss) tys, mx)
       
    94 
       
    95   fun raw_dts_aux2 (ty_args, bind, mx, constrs) =
       
    96     (ty_args, raw_bind bind, mx, map raw_dts_aux1 constrs)
       
    97 in
       
    98   map raw_dts_aux2 dts
       
    99 end
       
   100 
       
   101 fun replace_aterm trm_ss (Const (a, T)) = Const (replace_str trm_ss a, T)
       
   102   | replace_aterm trm_ss (Free (a, T)) = Free (replace_str trm_ss a, T)
       
   103   | replace_aterm trm_ss trm = trm
       
   104 
       
   105 fun replace_term trm_ss ty_ss trm =
       
   106   trm |> Term.map_aterms (replace_aterm trm_ss) |> map_types (replace_typ ty_ss) 
       
   107 *}
       
   108 
       
   109 ML {*
       
   110 fun get_cnstrs dts =
       
   111   map (fn (_, _, _, constrs) => constrs) dts
       
   112 
       
   113 fun get_typed_cnstrs dts =
       
   114   flat (map (fn (_, bn, _, constrs) => 
       
   115    (map (fn (bn', _, _) => (Binding.name_of bn, Binding.name_of bn')) constrs)) dts)
       
   116 
       
   117 fun get_cnstr_strs dts =
       
   118   map (fn (bn, _, _) => Binding.name_of bn) (flat (get_cnstrs dts))
       
   119 
       
   120 fun get_bn_fun_strs bn_funs =
       
   121   map (fn (bn_fun, _, _) => Binding.name_of bn_fun) bn_funs
       
   122 *}
       
   123 
       
   124 ML {*
       
   125 fun rawify_dts dt_names dts dts_env =
       
   126 let
       
   127   val raw_dts = raw_dts dts_env dts
       
   128   val raw_dt_names = add_raws dt_names
       
   129 in
       
   130   (raw_dt_names, raw_dts)
       
   131 end 
       
   132 *}
       
   133 
       
   134 ML {*
       
   135 fun rawify_bn_funs dts_env cnstrs_env bn_fun_env bn_funs bn_eqs =
       
   136 let
       
   137   val bn_funs' = map (fn (bn, ty, mx) => 
       
   138     (raw_bind bn, replace_typ dts_env ty, mx)) bn_funs
       
   139   
       
   140   val bn_eqs' = map (fn (attr, trm) => 
       
   141     (attr, replace_term (cnstrs_env @ bn_fun_env) dts_env trm)) bn_eqs
       
   142 in
       
   143   (bn_funs', bn_eqs') 
       
   144 end 
       
   145 *}
       
   146 
       
   147 ML {*
       
   148 fun apfst3 f (a, b, c) = (f a, b, c)
       
   149 *}
       
   150 
       
   151 ML {* 
       
   152 fun rawify_binds dts_env cnstrs_env bn_fun_env binds =
       
   153   map (map (map (map (fn (opt_trm, i, j, aty) => 
       
   154     (Option.map (apfst (replace_term (cnstrs_env @ bn_fun_env) dts_env)) opt_trm, i, j, aty))))) binds
       
   155 *}
       
   156 
       
   157 ML {*
       
   158 fun find [] _ = error ("cannot find element")
       
   159   | find ((x, z)::xs) y = if (Long_Name.base_name x) = y then z else find xs y
       
   160 *}
       
   161 
       
   162 ML {*
       
   163 fun strip_bn_fun t =
       
   164   case t of
       
   165     Const (@{const_name sup}, _) $ l $ r => strip_bn_fun l @ strip_bn_fun r
       
   166   | Const (@{const_name append}, _) $ l $ r => strip_bn_fun l @ strip_bn_fun r
       
   167   | Const (@{const_name insert}, _) $ (Const (@{const_name atom}, _) $ Bound i) $ y =>
       
   168       (i, NONE) :: strip_bn_fun y
       
   169   | Const (@{const_name Cons}, _) $ (Const (@{const_name atom}, _) $ Bound i) $ y =>
       
   170       (i, NONE) :: strip_bn_fun y
       
   171   | Const (@{const_name bot}, _) => []
       
   172   | Const (@{const_name Nil}, _) => []
       
   173   | (f as Free _) $ Bound i => [(i, SOME f)]
       
   174   | _ => error ("Unsupported binding function: " ^ (PolyML.makestring t))
       
   175 *}
       
   176 
       
   177 ML {*
       
   178 fun prep_bn dt_names dts eqs = 
       
   179 let
       
   180   fun aux eq = 
       
   181   let
       
   182     val (lhs, rhs) = eq
       
   183       |> strip_qnt_body "all" 
       
   184       |> HOLogic.dest_Trueprop
       
   185       |> HOLogic.dest_eq
       
   186     val (bn_fun, [cnstr]) = strip_comb lhs
       
   187     val (_, ty) = dest_Free bn_fun
       
   188     val (ty_name, _) = dest_Type (domain_type ty)
       
   189     val dt_index = find_index (fn x => x = ty_name) dt_names
       
   190     val (cnstr_head, cnstr_args) = strip_comb cnstr
       
   191     val rhs_elements = strip_bn_fun rhs
       
   192     val included = map (apfst (fn i => length (cnstr_args) - i - 1)) rhs_elements
       
   193   in
       
   194     (dt_index, (bn_fun, (cnstr_head, included)))
       
   195   end 
       
   196   fun order dts i ts = 
       
   197   let
       
   198     val dt = nth dts i
       
   199     val cts = map (fn (x, _, _) => Binding.name_of x) ((fn (_, _, _, x) => x) dt)
       
   200     val ts' = map (fn (x, y) => (fst (dest_Const x), y)) ts
       
   201   in
       
   202     map (find ts') cts
       
   203   end
       
   204 
       
   205   val unordered = AList.group (op=) (map aux eqs)
       
   206   val unordered' = map (fn (x, y) =>  (x, AList.group (op=) y)) unordered
       
   207   val ordered = map (fn (x, y) => (x, map (fn (v, z) => (v, order dts x z)) y)) unordered' 
       
   208 in
       
   209   ordered
       
   210 end
       
   211 *}
       
   212 
       
   213 ML {* 
       
   214 fun add_primrec_wrapper funs eqs lthy = 
       
   215   if null funs then (([], []), lthy)
       
   216   else 
       
   217    let 
       
   218      val eqs' = map (fn (_, eq) => (Attrib.empty_binding, eq)) eqs
       
   219      val funs' = map (fn (bn, ty, mx) => (bn, SOME ty, mx)) funs
       
   220    in 
       
   221      Primrec.add_primrec funs' eqs' lthy
       
   222    end
       
   223 *}
       
   224 
       
   225 ML {*
       
   226 fun add_datatype_wrapper dt_names dts =
       
   227 let
       
   228   val conf = Datatype.default_config
       
   229 in
       
   230   Local_Theory.theory_result (Datatype.add_datatype conf dt_names dts)
       
   231 end
       
   232 *}
       
   233 
       
   234 ML {* 
       
   235 fun raw_nominal_decls dts bn_funs bn_eqs binds lthy =
       
   236 let
       
   237   val thy = ProofContext.theory_of lthy
       
   238   val thy_name = Context.theory_name thy
       
   239 
       
   240   val dt_names = map (fn (_, s, _, _) => Binding.name_of s) dts
       
   241   val dt_full_names = map (Long_Name.qualify thy_name) dt_names 
       
   242   val dt_full_names' = add_raws dt_full_names
       
   243   val dts_env = dt_full_names ~~ dt_full_names'
       
   244 
       
   245   val cnstrs = get_cnstr_strs dts
       
   246   val cnstrs_ty = get_typed_cnstrs dts
       
   247   val cnstrs_full_names = map (Long_Name.qualify thy_name) cnstrs
       
   248   val cnstrs_full_names' = map (fn (x, y) => Long_Name.qualify thy_name 
       
   249     (Long_Name.qualify (add_raw x) (add_raw y))) cnstrs_ty
       
   250   val cnstrs_env = cnstrs_full_names ~~ cnstrs_full_names'
       
   251 
       
   252   val bn_fun_strs = get_bn_fun_strs bn_funs
       
   253   val bn_fun_strs' = add_raws bn_fun_strs
       
   254   val bn_fun_env = bn_fun_strs ~~ bn_fun_strs'
       
   255   val bn_fun_full_env = map (pairself (Long_Name.qualify thy_name)) 
       
   256     (bn_fun_strs ~~ bn_fun_strs')
       
   257   
       
   258   val (raw_dt_names, raw_dts) = rawify_dts dt_names dts dts_env
       
   259 
       
   260   val (raw_bn_funs, raw_bn_eqs) = rawify_bn_funs dts_env cnstrs_env bn_fun_env bn_funs bn_eqs 
       
   261   
       
   262   val raw_binds = rawify_binds dts_env cnstrs_env bn_fun_full_env binds 
       
   263 
       
   264   val raw_bns = prep_bn dt_full_names' raw_dts (map snd raw_bn_eqs)
       
   265 
       
   266 (*val _ = tracing (cat_lines (map PolyML.makestring raw_bns))*)
       
   267 in
       
   268   lthy 
       
   269   |> add_datatype_wrapper raw_dt_names raw_dts 
       
   270   ||>> add_primrec_wrapper raw_bn_funs raw_bn_eqs
       
   271   ||>> pair raw_binds
       
   272   ||>> pair raw_bns
       
   273 end
       
   274 *}
       
   275 
       
   276 lemma equivp_hack: "equivp x"
       
   277 sorry
       
   278 ML {*
       
   279 fun equivp_hack ctxt rel =
       
   280 let
       
   281   val thy = ProofContext.theory_of ctxt
       
   282   val ty = domain_type (fastype_of rel)
       
   283   val cty = ctyp_of thy ty
       
   284   val ct = cterm_of thy rel
       
   285 in
       
   286   Drule.instantiate' [SOME cty] [SOME ct] @{thm equivp_hack}
       
   287 end
       
   288 *}
       
   289 
       
   290 ML {* val cheat_alpha_eqvt = Unsynchronized.ref false *}
       
   291 ML {* val cheat_equivp = Unsynchronized.ref false *}
       
   292 ML {* val cheat_fv_rsp = Unsynchronized.ref false *}
       
   293 ML {* val cheat_const_rsp = Unsynchronized.ref false *}
       
   294 
       
   295 (* nominal_datatype2 does the following things in order:
       
   296 
       
   297 Parser.thy/raw_nominal_decls
       
   298   1) define the raw datatype
       
   299   2) define the raw binding functions 
       
   300 
       
   301 Perm.thy/define_raw_perms
       
   302   3) define permutations of the raw datatype and show that the raw type is 
       
   303      in the pt typeclass
       
   304       
       
   305 Lift.thy/define_fv_alpha_export, Fv.thy/define_fv & define_alpha
       
   306   4) define fv and fv_bn
       
   307   5) define alpha and alpha_bn
       
   308 
       
   309 Perm.thy/distinct_rel
       
   310   6) prove alpha_distincts (C1 x \<notsimeq> C2 y ...)             (Proof by cases; simp)
       
   311 
       
   312 Tacs.thy/build_rel_inj
       
   313   6) prove alpha_eq_iff    (C1 x = C2 y \<leftrightarrow> P x y ...)
       
   314      (left-to-right by intro rule, right-to-left by cases; simp)
       
   315 Equivp.thy/prove_eqvt
       
   316   7) prove bn_eqvt (common induction on the raw datatype)
       
   317   8) prove fv_eqvt (common induction on the raw datatype with help of above)
       
   318 Rsp.thy/build_alpha_eqvts
       
   319   9) prove alpha_eqvt and alpha_bn_eqvt
       
   320      (common alpha-induction, unfolding alpha_gen, permute of #* and =)
       
   321 Equivp.thy/build_alpha_refl & Equivp.thy/build_equivps
       
   322  10) prove that alpha and alpha_bn are equivalence relations
       
   323      (common induction and application of 'compose' lemmas)
       
   324 Lift.thy/define_quotient_types
       
   325  11) define quotient types
       
   326 Rsp.thy/build_fvbv_rsps
       
   327  12) prove bn respects     (common induction and simp with alpha_gen)
       
   328 Rsp.thy/prove_const_rsp
       
   329  13) prove fv respects     (common induction and simp with alpha_gen)
       
   330  14) prove permute respects    (unfolds to alpha_eqvt)
       
   331 Rsp.thy/prove_alpha_bn_rsp
       
   332  15) prove alpha_bn respects
       
   333      (alpha_induct then cases then sym and trans of the relations)
       
   334 Rsp.thy/prove_alpha_alphabn
       
   335  16) show that alpha implies alpha_bn (by unduction, needed in following step)
       
   336 Rsp.thy/prove_const_rsp
       
   337  17) prove respects for all datatype constructors
       
   338      (unfold eq_iff and alpha_gen; introduce zero permutations; simp)
       
   339 Perm.thy/quotient_lift_consts_export
       
   340  18) define lifted constructors, fv, bn, alpha_bn, permutations
       
   341 Perm.thy/define_lifted_perms
       
   342  19) lift permutation zero and add properties to show that quotient type is in the pt typeclass
       
   343 Lift.thy/lift_thm
       
   344  20) lift permutation simplifications
       
   345  21) lift induction
       
   346  22) lift fv
       
   347  23) lift bn
       
   348  24) lift eq_iff
       
   349  25) lift alpha_distincts
       
   350  26) lift fv and bn eqvts
       
   351 Equivp.thy/prove_supports
       
   352  27) prove that union of arguments supports constructors
       
   353 Equivp.thy/prove_fs
       
   354  28) show that the lifted type is in fs typeclass     (* by q_induct, supports *)
       
   355 Equivp.thy/supp_eq
       
   356  29) prove supp = fv
       
   357 *)
       
   358 ML {*
       
   359 fun nominal_datatype2 dts bn_funs bn_eqs binds lthy =
       
   360 let
       
   361   val _ = tracing "Raw declarations";
       
   362   val thy = ProofContext.theory_of lthy
       
   363   val thy_name = Context.theory_name thy
       
   364   val ((((raw_dt_names, (raw_bn_funs_loc, raw_bn_eqs_loc)), raw_binds), raw_bns), lthy2) =
       
   365     raw_nominal_decls dts bn_funs bn_eqs binds lthy
       
   366   val morphism_2_1 = ProofContext.export_morphism lthy2 lthy
       
   367   fun export_fun f (t, l) = (f t, map (map (apsnd (Option.map f))) l);
       
   368   val raw_bns_exp = map (apsnd (map (export_fun (Morphism.term morphism_2_1)))) raw_bns;
       
   369   val bn_funs_decls = flat (map (fn (ith, l) => map (fn (bn, data) => (bn, ith, data)) l) raw_bns_exp);
       
   370   val raw_bn_funs = map (Morphism.term morphism_2_1) raw_bn_funs_loc
       
   371   val raw_bn_eqs = ProofContext.export lthy2 lthy raw_bn_eqs_loc
       
   372 
       
   373   val dtinfo = Datatype.the_info (ProofContext.theory_of lthy2) (hd raw_dt_names);
       
   374   val {descr, sorts, ...} = dtinfo;
       
   375   fun nth_dtyp i = typ_of_dtyp descr sorts (DtRec i);
       
   376   val raw_tys = map (fn (i, _) => nth_dtyp i) descr;
       
   377   val all_typs = map (fn i => typ_of_dtyp descr sorts (DtRec i)) (map fst descr)
       
   378   val all_full_tnames = map (fn (_, (n, _, _)) => n) descr;
       
   379   val dtinfos = map (Datatype.the_info (ProofContext.theory_of lthy2)) all_full_tnames;
       
   380   val rel_dtinfos = List.take (dtinfos, (length dts));
       
   381   val inject = flat (map #inject dtinfos);
       
   382   val distincts = flat (map #distinct dtinfos);
       
   383   val rel_distinct = map #distinct rel_dtinfos;
       
   384   val induct = #induct dtinfo;
       
   385   val exhausts = map #exhaust dtinfos;
       
   386   val _ = tracing "Defining permutations, fv and alpha";
       
   387   val ((raw_perm_def, raw_perm_simps, perms), lthy3) =
       
   388     Local_Theory.theory_result (define_raw_perms dtinfo (length dts)) lthy2;
       
   389   val raw_binds_flat = map (map flat) raw_binds;
       
   390   val ((((_, fv_ts), fv_def), ((alpha_ts, alpha_intros), (alpha_cases, alpha_induct))), lthy4) =
       
   391     define_fv_alpha_export dtinfo raw_binds_flat bn_funs_decls lthy3;
       
   392   val (fv, fvbn) = chop (length perms) fv_ts;
       
   393 
       
   394   val (alpha_ts_nobn, alpha_ts_bn) = chop (length fv) alpha_ts
       
   395   val dts_names = map (fn (i, (s, _, _)) => (s, i)) (#descr dtinfo);
       
   396   val bn_tys = map (domain_type o fastype_of) raw_bn_funs;
       
   397   val bn_nos = map (dtyp_no_of_typ dts_names) bn_tys;
       
   398   val bns = raw_bn_funs ~~ bn_nos;
       
   399   val rel_dists = flat (map (distinct_rel lthy4 alpha_cases)
       
   400     (rel_distinct ~~ alpha_ts_nobn));
       
   401   val rel_dists_bn = flat (map (distinct_rel lthy4 alpha_cases)
       
   402     ((map (fn i => nth rel_distinct i) bn_nos) ~~ alpha_ts_bn))
       
   403   val alpha_eq_iff = build_rel_inj alpha_intros (inject @ distincts) alpha_cases lthy4
       
   404   val _ = tracing "Proving equivariance";
       
   405   val (bv_eqvt, lthy5) = prove_eqvt raw_tys induct (raw_bn_eqs @ raw_perm_def) (map fst bns) lthy4
       
   406   val (fv_eqvt, lthy6) = prove_eqvt raw_tys induct (fv_def @ raw_perm_def) (fv @ fvbn) lthy5
       
   407   fun alpha_eqvt_tac' _ =
       
   408     if !cheat_alpha_eqvt then Skip_Proof.cheat_tac thy
       
   409     else alpha_eqvt_tac alpha_induct (raw_perm_def @ alpha_eq_iff) lthy6 1
       
   410   val alpha_eqvt = build_alpha_eqvts alpha_ts alpha_eqvt_tac' lthy6;
       
   411   val _ = tracing "Proving equivalence";
       
   412   val fv_alpha_all = combine_fv_alpha_bns (fv, fvbn) (alpha_ts_nobn, alpha_ts_bn) bn_nos;
       
   413   val reflps = build_alpha_refl fv_alpha_all alpha_ts induct alpha_eq_iff lthy6;
       
   414   val alpha_equivp =
       
   415     if !cheat_equivp then map (equivp_hack lthy6) alpha_ts_nobn
       
   416     else build_equivps alpha_ts reflps alpha_induct
       
   417       inject alpha_eq_iff distincts alpha_cases alpha_eqvt lthy6;
       
   418   val qty_binds = map (fn (_, b, _, _) => b) dts;
       
   419   val qty_names = map Name.of_binding qty_binds;
       
   420   val qty_full_names = map (Long_Name.qualify thy_name) qty_names
       
   421   val (qtys, lthy7) = define_quotient_types qty_binds all_typs alpha_ts_nobn alpha_equivp lthy6;
       
   422   val const_names = map Name.of_binding (flat (map (fn (_, _, _, t) => map (fn (b, _, _) => b) t) dts));
       
   423   val raw_consts =
       
   424     flat (map (fn (i, (_, _, l)) =>
       
   425       map (fn (cname, dts) =>
       
   426         Const (cname, map (typ_of_dtyp descr sorts) dts --->
       
   427           typ_of_dtyp descr sorts (DtRec i))) l) descr);
       
   428   val (consts, const_defs, lthy8) = quotient_lift_consts_export qtys (const_names ~~ raw_consts) lthy7;
       
   429   val _ = tracing "Proving respects";
       
   430   val bns_rsp_pre' = build_fvbv_rsps alpha_ts alpha_induct raw_bn_eqs (map fst bns) lthy8;
       
   431   val (bns_rsp_pre, lthy9) = fold_map (
       
   432     fn (bn_t, _) => prove_const_rsp qtys Binding.empty [bn_t] (fn _ =>
       
   433        resolve_tac bns_rsp_pre' 1)) bns lthy8;
       
   434   val bns_rsp = flat (map snd bns_rsp_pre);
       
   435   fun fv_rsp_tac _ = if !cheat_fv_rsp then Skip_Proof.cheat_tac thy
       
   436     else fvbv_rsp_tac alpha_induct fv_def lthy8 1;
       
   437   val fv_rsps = prove_fv_rsp fv_alpha_all alpha_ts fv_rsp_tac lthy9;
       
   438   val (fv_rsp_pre, lthy10) = fold_map
       
   439     (fn fv => fn ctxt => prove_const_rsp qtys Binding.empty [fv]
       
   440     (fn _ => asm_simp_tac (HOL_ss addsimps fv_rsps) 1) ctxt) (fv @ fvbn) lthy9;
       
   441   val fv_rsp = flat (map snd fv_rsp_pre);
       
   442   val (perms_rsp, lthy11) = prove_const_rsp qtys Binding.empty perms
       
   443     (fn _ => asm_simp_tac (HOL_ss addsimps alpha_eqvt) 1) lthy10;
       
   444   val alpha_bn_rsp_pre = prove_alpha_bn_rsp alpha_ts alpha_induct (alpha_eq_iff @ rel_dists @ rel_dists_bn) alpha_equivp exhausts alpha_ts_bn lthy11;
       
   445   val (alpha_bn_rsps, lthy11a) = fold_map (fn cnst => prove_const_rsp qtys Binding.empty [cnst]
       
   446         (fn _ => asm_simp_tac (HOL_ss addsimps alpha_bn_rsp_pre) 1)) alpha_ts_bn lthy11
       
   447 (*  val _ = map tracing (map PolyML.makestring alpha_bn_rsps);*)
       
   448   fun const_rsp_tac _ =
       
   449     if !cheat_const_rsp then Skip_Proof.cheat_tac thy
       
   450     else let val alpha_alphabn = prove_alpha_alphabn alpha_ts alpha_induct alpha_eq_iff alpha_ts_bn lthy11a
       
   451       in constr_rsp_tac alpha_eq_iff (fv_rsp @ bns_rsp @ reflps @ alpha_alphabn) 1 end
       
   452   val (const_rsps, lthy12) = fold_map (fn cnst => prove_const_rsp qtys Binding.empty [cnst]
       
   453     const_rsp_tac) raw_consts lthy11a
       
   454   val qfv_names = map (unsuffix "_raw" o Long_Name.base_name o fst o dest_Const) (fv @ fvbn)
       
   455   val (qfv_ts, qfv_defs, lthy12a) = quotient_lift_consts_export qtys (qfv_names ~~ (fv @ fvbn)) lthy12;
       
   456   val (qfv_ts_nobn, qfv_ts_bn) = chop (length perms) qfv_ts;
       
   457   val qbn_names = map (fn (b, _ , _) => Name.of_binding b) bn_funs
       
   458   val (qbn_ts, qbn_defs, lthy12b) = quotient_lift_consts_export qtys (qbn_names ~~ raw_bn_funs) lthy12a;
       
   459   val qalpha_bn_names = map (unsuffix "_raw" o Long_Name.base_name o fst o dest_Const) alpha_ts_bn
       
   460   val (qalpha_ts_bn, qalphabn_defs, lthy12c) = quotient_lift_consts_export qtys (qalpha_bn_names ~~ alpha_ts_bn) lthy12b;
       
   461   val _ = tracing "Lifting permutations";
       
   462   val thy = Local_Theory.exit_global lthy12c;
       
   463   val perm_names = map (fn x => "permute_" ^ x) qty_names
       
   464   val thy' = define_lifted_perms qtys qty_full_names (perm_names ~~ perms) raw_perm_simps thy;
       
   465   val lthy13 = Theory_Target.init NONE thy';
       
   466   val q_name = space_implode "_" qty_names;
       
   467   fun suffix_bind s = Binding.qualify true q_name (Binding.name s);
       
   468   val _ = tracing "Lifting induction";
       
   469   val constr_names = map (Long_Name.base_name o fst o dest_Const) consts;
       
   470   val q_induct = Rule_Cases.name constr_names (lift_thm qtys lthy13 induct);
       
   471   fun note_suffix s th ctxt =
       
   472     snd (Local_Theory.note ((suffix_bind s, []), th) ctxt);
       
   473   fun note_simp_suffix s th ctxt =
       
   474     snd (Local_Theory.note ((suffix_bind s, [Attrib.internal (K Simplifier.simp_add)]), th) ctxt);
       
   475   val (_, lthy14) = Local_Theory.note ((suffix_bind "induct",
       
   476     [Attrib.internal (K (Rule_Cases.case_names constr_names))]), [Rule_Cases.name constr_names q_induct]) lthy13;
       
   477   val q_inducts = Project_Rule.projects lthy13 (1 upto (length fv)) q_induct
       
   478   val (_, lthy14a) = Local_Theory.note ((suffix_bind "inducts", []), q_inducts) lthy14;
       
   479   val q_perm = map (lift_thm qtys lthy14) raw_perm_def;
       
   480   val lthy15 = note_simp_suffix "perm" q_perm lthy14a;
       
   481   val q_fv = map (lift_thm qtys lthy15) fv_def;
       
   482   val lthy16 = note_simp_suffix "fv" q_fv lthy15;
       
   483   val q_bn = map (lift_thm qtys lthy16) raw_bn_eqs;
       
   484   val lthy17 = note_simp_suffix "bn" q_bn lthy16;
       
   485   val _ = tracing "Lifting eq-iff";
       
   486   val _ = map tracing (map PolyML.makestring alpha_eq_iff);
       
   487   val eq_iff_unfolded0 = map (Local_Defs.unfold lthy17 @{thms alphas3}) alpha_eq_iff
       
   488   val eq_iff_unfolded1 = map (Local_Defs.unfold lthy17 @{thms alphas2}) eq_iff_unfolded0
       
   489   val eq_iff_unfolded2 = map (Local_Defs.unfold lthy17 @{thms alphas} ) eq_iff_unfolded1
       
   490   val q_eq_iff_pre0 = map (lift_thm qtys lthy17) eq_iff_unfolded2;
       
   491   val q_eq_iff_pre1 = map (Local_Defs.fold lthy17 @{thms alphas3}) q_eq_iff_pre0
       
   492   val q_eq_iff_pre2 = map (Local_Defs.fold lthy17 @{thms alphas2}) q_eq_iff_pre1
       
   493   val q_eq_iff = map (Local_Defs.fold lthy17 @{thms alphas}) q_eq_iff_pre2
       
   494   val (_, lthy18) = Local_Theory.note ((suffix_bind "eq_iff", []), q_eq_iff) lthy17;
       
   495   val q_dis = map (lift_thm qtys lthy18) rel_dists;
       
   496   val lthy19 = note_simp_suffix "distinct" q_dis lthy18;
       
   497   val q_eqvt = map (lift_thm qtys lthy19) (bv_eqvt @ fv_eqvt);
       
   498   val (_, lthy20) = Local_Theory.note ((Binding.empty,
       
   499     [Attrib.internal (fn _ => Nominal_ThmDecls.eqvt_add)]), q_eqvt) lthy19;
       
   500   val _ = tracing "Finite Support";
       
   501   val supports = map (prove_supports lthy20 q_perm) consts;
       
   502   val fin_supp = HOLogic.conj_elims (prove_fs lthy20 q_induct supports qtys);
       
   503   val thy3 = Local_Theory.exit_global lthy20;
       
   504   val lthy21 = Theory_Target.instantiation (qty_full_names, [], @{sort fs}) thy3;
       
   505   fun tac _ = Class.intro_classes_tac [] THEN (ALLGOALS (resolve_tac fin_supp))
       
   506   val lthy22 = Class.prove_instantiation_instance tac lthy21
       
   507   val fv_alpha_all = combine_fv_alpha_bns (qfv_ts_nobn, qfv_ts_bn) (alpha_ts_nobn, qalpha_ts_bn) bn_nos;
       
   508   val (names, supp_eq_t) = supp_eq fv_alpha_all;
       
   509   val q_supp = HOLogic.conj_elims (Goal.prove lthy22 names [] supp_eq_t (fn _ => supp_eq_tac q_induct q_fv q_perm q_eq_iff lthy22 1)) handle _ => [];
       
   510   val lthy23 = note_suffix "supp" q_supp lthy22;
       
   511 in
       
   512   ((raw_dt_names, raw_bn_funs, raw_bn_eqs, raw_binds), lthy23)
       
   513 end
       
   514 *}
       
   515 
       
   516 
       
   517 ML {* 
       
   518 (* parsing the datatypes and declaring *)
       
   519 (* constructors in the local theory    *)
       
   520 fun prepare_dts dt_strs lthy = 
       
   521 let
       
   522   val thy = ProofContext.theory_of lthy
       
   523   
       
   524   fun mk_type full_tname tvrs =
       
   525     Type (full_tname, map (fn a => TVar ((a, 0), [])) tvrs)
       
   526 
       
   527   fun prep_cnstr lthy full_tname tvs (cname, anno_tys, mx, _) =
       
   528   let
       
   529     val tys = map (Syntax.read_typ lthy o snd) anno_tys
       
   530     val ty = mk_type full_tname tvs
       
   531   in
       
   532     ((cname, tys ---> ty, mx), (cname, tys, mx))
       
   533   end
       
   534   
       
   535   fun prep_dt lthy (tvs, tname, mx, cnstrs) = 
       
   536   let
       
   537     val full_tname = Sign.full_name thy tname
       
   538     val (cnstrs', cnstrs'') = 
       
   539       split_list (map (prep_cnstr lthy full_tname tvs) cnstrs)
       
   540   in
       
   541     (cnstrs', (tvs, tname, mx, cnstrs''))
       
   542   end 
       
   543 
       
   544   val (cnstrs, dts) = 
       
   545     split_list (map (prep_dt lthy) dt_strs)
       
   546 in
       
   547   lthy
       
   548   |> Local_Theory.theory (Sign.add_consts_i (flat cnstrs))
       
   549   |> pair dts
       
   550 end
       
   551 *}
       
   552 
       
   553 ML {*
       
   554 (* parsing the binding function specification and *)
       
   555 (* declaring the functions in the local theory    *)
       
   556 fun prepare_bn_funs bn_fun_strs bn_eq_strs lthy =
       
   557 let
       
   558   val ((bn_funs, bn_eqs), _) = 
       
   559     Specification.read_spec bn_fun_strs bn_eq_strs lthy
       
   560 
       
   561   fun prep_bn_fun ((bn, T), mx) = (bn, T, mx) 
       
   562   val bn_funs' = map prep_bn_fun bn_funs
       
   563 in
       
   564   lthy
       
   565   |> Local_Theory.theory (Sign.add_consts_i bn_funs')
       
   566   |> pair (bn_funs', bn_eqs) 
       
   567 end 
       
   568 *}
       
   569 
       
   570 ML {*
       
   571 fun find_all eq xs (k',i) = 
       
   572   maps (fn (k, (v1, v2)) => if eq (k, k') then [(v1, v2, i)] else []) xs
       
   573 *}
       
   574 
       
   575 ML {*
       
   576 (* associates every SOME with the index in the list; drops NONEs *)
       
   577 fun mk_env xs =
       
   578   let
       
   579     fun mapp (_: int) [] = []
       
   580       | mapp i (a :: xs) = 
       
   581          case a of
       
   582            NONE => mapp (i + 1) xs
       
   583          | SOME x => (x, i) :: mapp (i + 1) xs
       
   584   in mapp 0 xs end
       
   585 *}
       
   586 
       
   587 ML {*
       
   588 fun env_lookup xs x =
       
   589   case AList.lookup (op =) xs x of
       
   590     SOME x => x
       
   591   | NONE => error ("cannot find " ^ x ^ " in the binding specification.");
       
   592 *}
       
   593 
       
   594 ML {*
       
   595 val recursive = Unsynchronized.ref false
       
   596 val alpha_type = Unsynchronized.ref AlphaGen
       
   597 *}
       
   598 
       
   599 ML {*
       
   600 fun prepare_binds dt_strs lthy = 
       
   601 let
       
   602   fun extract_annos_binds dt_strs =
       
   603     map (map (fn (_, antys, _, bns) => (map fst antys, bns))) dt_strs
       
   604 
       
   605   fun prep_bn env bn_str =
       
   606     case (Syntax.read_term lthy bn_str) of
       
   607        Free (x, _) => (NONE, env_lookup env x)
       
   608      | Const (a, T) $ Free (x, _) => (SOME (Const (a, T), !recursive), env_lookup env x)
       
   609      | _ => error (bn_str ^ " not allowed as binding specification.");  
       
   610  
       
   611   fun prep_typ env (i, opt_name) = 
       
   612     case opt_name of
       
   613       NONE => []
       
   614     | SOME x => find_all (op=) env (x,i);
       
   615         
       
   616   (* annos - list of annotation for each type (either NONE or SOME fo a type *)
       
   617   
       
   618   fun prep_binds (annos, bind_strs) = 
       
   619   let
       
   620     val env = mk_env annos (* for every label the index *)
       
   621     val binds = map (fn (x, y) => (x, prep_bn env y)) bind_strs  
       
   622   in
       
   623     map_index (prep_typ binds) annos
       
   624   end
       
   625 
       
   626   val result = map (map (map (map (fn (a, b, c) => 
       
   627     (a, b, c, if !alpha_type=AlphaLst andalso a = NONE then AlphaGen else !alpha_type)))))
       
   628       (map (map prep_binds) (extract_annos_binds (get_cnstrs dt_strs)))
       
   629  
       
   630   val _ = warning (@{make_string} result)
       
   631 
       
   632 in
       
   633   result
       
   634 end
       
   635 *}
       
   636 
       
   637 ML {*
       
   638 fun nominal_datatype2_cmd (dt_strs, bn_fun_strs, bn_eq_strs) lthy =
       
   639 let
       
   640   fun prep_typ (tvs, tname, mx, _) = (tname, length tvs, mx)
       
   641 
       
   642   val lthy0 = 
       
   643     Local_Theory.theory (Sign.add_types (map prep_typ dt_strs)) lthy
       
   644   val (dts, lthy1) = 
       
   645     prepare_dts dt_strs lthy0
       
   646   val ((bn_funs, bn_eqs), lthy2) = 
       
   647     prepare_bn_funs bn_fun_strs bn_eq_strs lthy1
       
   648   val binds = prepare_binds dt_strs lthy2
       
   649 in
       
   650   nominal_datatype2 dts bn_funs bn_eqs binds lthy |> snd
       
   651 end
       
   652 *}
       
   653 
       
   654 
       
   655 (* Command Keyword *)
       
   656 
       
   657 ML {*
       
   658 let
       
   659    val kind = OuterKeyword.thy_decl
       
   660 in
       
   661    OuterSyntax.local_theory "nominal_datatype" "test" kind 
       
   662      (main_parser >> nominal_datatype2_cmd)
       
   663 end
       
   664 *}
       
   665 
       
   666 
       
   667 end
       
   668 
       
   669 
       
   670