src/Pure/Isar/code.ML
author haftmann
Fri Oct 10 06:45:53 2008 +0200 (2008-10-10)
changeset 28562 4e74209f113e
parent 28525 42297ae4df47
child 28672 0baf1d9c6780
permissions -rw-r--r--
`code func` now just `code`
     1 (*  Title:      Pure/Isar/code.ML
     2     ID:         $Id$
     3     Author:     Florian Haftmann, TU Muenchen
     4 
     5 Abstract executable content of theory.  Management of data dependent on
     6 executable content.  Cache assumes non-concurrent processing of a single theory.
     7 *)
     8 
     9 signature CODE =
    10 sig
    11   val add_eqn: thm -> theory -> theory
    12   val add_nonlinear_eqn: thm -> theory -> theory
    13   val add_liberal_eqn: thm -> theory -> theory
    14   val add_default_eqn: thm -> theory -> theory
    15   val add_default_eqn_attr: Attrib.src
    16   val del_eqn: thm -> theory -> theory
    17   val del_eqns: string -> theory -> theory
    18   val add_eqnl: string * (thm * bool) list Susp.T -> theory -> theory
    19   val map_pre: (MetaSimplifier.simpset -> MetaSimplifier.simpset) -> theory -> theory
    20   val map_post: (MetaSimplifier.simpset -> MetaSimplifier.simpset) -> theory -> theory
    21   val add_inline: thm -> theory -> theory
    22   val del_inline: thm -> theory -> theory
    23   val add_post: thm -> theory -> theory
    24   val del_post: thm -> theory -> theory
    25   val add_functrans: string * (theory -> (thm * bool) list -> (thm * bool) list option) -> theory -> theory
    26   val del_functrans: string -> theory -> theory
    27   val add_datatype: (string * typ) list -> theory -> theory
    28   val add_datatype_cmd: string list -> theory -> theory
    29   val type_interpretation:
    30     (string * ((string * sort) list * (string * typ list) list)
    31       -> theory -> theory) -> theory -> theory
    32   val add_case: thm -> theory -> theory
    33   val add_undefined: string -> theory -> theory
    34   val purge_data: theory -> theory
    35 
    36   val coregular_algebra: theory -> Sorts.algebra
    37   val operational_algebra: theory -> (sort -> sort) * Sorts.algebra
    38   val these_eqns: theory -> string -> (thm * bool) list
    39   val these_raw_eqns: theory -> string -> (thm * bool) list
    40   val get_datatype: theory -> string -> ((string * sort) list * (string * typ list) list)
    41   val get_datatype_of_constr: theory -> string -> string option
    42   val get_case_data: theory -> string -> (int * string list) option
    43   val is_undefined: theory -> string -> bool
    44   val default_typscheme: theory -> string -> (string * sort) list * typ
    45 
    46   val preprocess_conv: theory -> cterm -> thm
    47   val preprocess_term: theory -> term -> term
    48   val postprocess_conv: theory -> cterm -> thm
    49   val postprocess_term: theory -> term -> term
    50 
    51   val add_attribute: string * (Args.T list -> attribute * Args.T list) -> theory -> theory
    52 
    53   val print_codesetup: theory -> unit
    54 end;
    55 
    56 signature CODE_DATA_ARGS =
    57 sig
    58   type T
    59   val empty: T
    60   val purge: theory -> string list -> T -> T
    61 end;
    62 
    63 signature CODE_DATA =
    64 sig
    65   type T
    66   val get: theory -> T
    67   val change: theory -> (T -> T) -> T
    68   val change_yield: theory -> (T -> 'a * T) -> 'a * T
    69 end;
    70 
    71 signature PRIVATE_CODE =
    72 sig
    73   include CODE
    74   val declare_data: Object.T -> (theory -> string list -> Object.T -> Object.T)
    75     -> serial
    76   val get_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    77     -> theory -> 'a
    78   val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    79     -> theory -> ('a -> 'a) -> 'a
    80   val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
    81     -> theory -> ('a -> 'b * 'a) -> 'b * 'a
    82 end;
    83 
    84 structure Code : PRIVATE_CODE =
    85 struct
    86 
    87 (** code attributes **)
    88 
    89 structure CodeAttr = TheoryDataFun (
    90   type T = (string * (Args.T list -> attribute * Args.T list)) list;
    91   val empty = [];
    92   val copy = I;
    93   val extend = I;
    94   fun merge _ = AList.merge (op = : string * string -> bool) (K true);
    95 );
    96 
    97 fun add_attribute (attr as (name, _)) =
    98   let
    99     fun add_parser ("", parser) attrs = attrs |> rev |> AList.update (op =) ("", parser) |> rev
   100       | add_parser (name, parser) attrs = (name, Args.$$$ name |-- parser) :: attrs;
   101   in CodeAttr.map (fn attrs => if not (name = "") andalso AList.defined (op =) attrs name
   102     then error ("Code attribute " ^ name ^ " already declared") else add_parser attr attrs)
   103   end;
   104 
   105 val _ =
   106   let
   107     val code_attr = Attrib.syntax (Scan.peek (fn context =>
   108       List.foldr op || Scan.fail (map snd (CodeAttr.get (Context.theory_of context)))));
   109   in
   110     Context.>> (Context.map_theory
   111       (Attrib.add_attributes
   112         [("code", code_attr, "declare theorems for code generation")]))
   113   end;
   114 
   115 
   116 (** logical and syntactical specification of executable code **)
   117 
   118 (* defining equations with linear flag, default flag and lazy theorems *)
   119 
   120 fun pretty_lthms ctxt r = case Susp.peek r
   121  of SOME thms => map (ProofContext.pretty_thm ctxt o fst) thms
   122   | NONE => [Pretty.str "[...]"];
   123 
   124 fun certificate thy f r =
   125   case Susp.peek r
   126    of SOME thms => (Susp.value o f thy) thms
   127     | NONE => let
   128         val thy_ref = Theory.check_thy thy;
   129       in Susp.delay (fn () => (f (Theory.deref thy_ref) o Susp.force) r) end;
   130 
   131 fun add_drop_redundant thy (thm, linear) thms =
   132   let
   133     val args_of = snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
   134     val args = args_of thm;
   135     val incr_idx = Logic.incr_indexes ([], Thm.maxidx_of thm + 1);
   136     fun matches_args args' = length args <= length args' andalso
   137       Pattern.matchess thy (args, (map incr_idx o curry Library.take (length args)) args');
   138     fun drop (thm', linear') = if (linear orelse not linear')
   139       andalso matches_args (args_of thm') then 
   140         (warning ("Code generator: dropping redundant defining equation\n" ^ Display.string_of_thm thm'); true)
   141       else false;
   142   in (thm, linear) :: filter_out drop thms end;
   143 
   144 fun add_thm thy _ thm (false, thms) = (false, Susp.map_force (add_drop_redundant thy thm) thms)
   145   | add_thm thy true thm (true, thms) = (true, Susp.map_force (fn thms => thms @ [thm]) thms)
   146   | add_thm thy false thm (true, thms) = (false, Susp.value [thm]);
   147 
   148 fun add_lthms lthms _ = (false, lthms);
   149 
   150 fun del_thm thm = (apsnd o Susp.map_force) (remove (eq_fst Thm.eq_thm_prop) (thm, true));
   151 
   152 fun merge_defthms ((true, _), defthms2) = defthms2
   153   | merge_defthms (defthms1 as (false, _), (true, _)) = defthms1
   154   | merge_defthms ((false, _), defthms2 as (false, _)) = defthms2;
   155 
   156 
   157 (* syntactic datatypes *)
   158 
   159 val eq_string = op = : string * string -> bool;
   160 
   161 fun eq_dtyp ((vs1, cs1), (vs2, cs2)) = 
   162   gen_eq_set (eq_pair eq_string (gen_eq_set eq_string)) (vs1, vs2)
   163     andalso gen_eq_set (eq_fst eq_string) (cs1, cs2);
   164 
   165 fun merge_dtyps (tabs as (tab1, tab2)) =
   166   let
   167     fun join _ (cos as (_, cos2)) = if eq_dtyp cos then raise Symtab.SAME else cos2;
   168   in Symtab.join join tabs end;
   169 
   170 
   171 (* specification data *)
   172 
   173 datatype spec = Spec of {
   174   eqns: (bool * (thm * bool) list Susp.T) Symtab.table,
   175   dtyps: ((string * sort) list * (string * typ list) list) Symtab.table,
   176   cases: (int * string list) Symtab.table * unit Symtab.table
   177 };
   178 
   179 fun mk_spec (eqns, (dtyps, cases)) =
   180   Spec { eqns = eqns, dtyps = dtyps, cases = cases };
   181 fun map_spec f (Spec { eqns = eqns, dtyps = dtyps, cases = cases }) =
   182   mk_spec (f (eqns, (dtyps, cases)));
   183 fun merge_spec (Spec { eqns = eqns1, dtyps = dtyps1, cases = (cases1, undefs1) },
   184   Spec { eqns = eqns2, dtyps = dtyps2, cases = (cases2, undefs2) }) =
   185   let
   186     val eqns = Symtab.join (K merge_defthms) (eqns1, eqns2);
   187     val dtyps = merge_dtyps (dtyps1, dtyps2);
   188     val cases = (Symtab.merge (K true) (cases1, cases2),
   189       Symtab.merge (K true) (undefs1, undefs2));
   190   in mk_spec (eqns, (dtyps, cases)) end;
   191 
   192 
   193 (* pre- and postprocessor *)
   194 
   195 datatype thmproc = Thmproc of {
   196   pre: MetaSimplifier.simpset,
   197   post: MetaSimplifier.simpset,
   198   functrans: (string * (serial * (theory -> (thm * bool) list -> (thm * bool) list option))) list
   199 };
   200 
   201 fun mk_thmproc ((pre, post), functrans) =
   202   Thmproc { pre = pre, post = post, functrans = functrans };
   203 fun map_thmproc f (Thmproc { pre, post, functrans }) =
   204   mk_thmproc (f ((pre, post), functrans));
   205 fun merge_thmproc (Thmproc { pre = pre1, post = post1, functrans = functrans1 },
   206   Thmproc { pre = pre2, post = post2, functrans = functrans2 }) =
   207     let
   208       val pre = MetaSimplifier.merge_ss (pre1, pre2);
   209       val post = MetaSimplifier.merge_ss (post1, post2);
   210       val functrans = AList.merge (op =) (eq_fst (op =)) (functrans1, functrans2);
   211     in mk_thmproc ((pre, post), functrans) end;
   212 
   213 datatype exec = Exec of {
   214   thmproc: thmproc,
   215   spec: spec
   216 };
   217 
   218 
   219 (* code setup data *)
   220 
   221 fun mk_exec (thmproc, spec) =
   222   Exec { thmproc = thmproc, spec = spec };
   223 fun map_exec f (Exec { thmproc = thmproc, spec = spec }) =
   224   mk_exec (f (thmproc, spec));
   225 fun merge_exec (Exec { thmproc = thmproc1, spec = spec1 },
   226   Exec { thmproc = thmproc2, spec = spec2 }) =
   227   let
   228     val thmproc = merge_thmproc (thmproc1, thmproc2);
   229     val spec = merge_spec (spec1, spec2);
   230   in mk_exec (thmproc, spec) end;
   231 val empty_exec = mk_exec (mk_thmproc ((MetaSimplifier.empty_ss, MetaSimplifier.empty_ss), []),
   232   mk_spec (Symtab.empty, (Symtab.empty, (Symtab.empty, Symtab.empty))));
   233 
   234 fun the_thmproc (Exec { thmproc = Thmproc x, ...}) = x;
   235 fun the_spec (Exec { spec = Spec x, ...}) = x;
   236 val the_eqns = #eqns o the_spec;
   237 val the_dtyps = #dtyps o the_spec;
   238 val the_cases = #cases o the_spec;
   239 val map_thmproc = map_exec o apfst o map_thmproc;
   240 val map_eqns = map_exec o apsnd o map_spec o apfst;
   241 val map_dtyps = map_exec o apsnd o map_spec o apsnd o apfst;
   242 val map_cases = map_exec o apsnd o map_spec o apsnd o apsnd;
   243 
   244 
   245 (* data slots dependent on executable content *)
   246 
   247 (*private copy avoids potential conflict of table exceptions*)
   248 structure Datatab = TableFun(type key = int val ord = int_ord);
   249 
   250 local
   251 
   252 type kind = {
   253   empty: Object.T,
   254   purge: theory -> string list -> Object.T -> Object.T
   255 };
   256 
   257 val kinds = ref (Datatab.empty: kind Datatab.table);
   258 val kind_keys = ref ([]: serial list);
   259 
   260 fun invoke f k = case Datatab.lookup (! kinds) k
   261  of SOME kind => f kind
   262   | NONE => sys_error "Invalid code data identifier";
   263 
   264 in
   265 
   266 fun declare_data empty purge =
   267   let
   268     val k = serial ();
   269     val kind = {empty = empty, purge = purge};
   270     val _ = change kinds (Datatab.update (k, kind));
   271     val _ = change kind_keys (cons k);
   272   in k end;
   273 
   274 fun invoke_init k = invoke (fn kind => #empty kind) k;
   275 
   276 fun invoke_purge_all thy cs =
   277   fold (fn k => Datatab.map_entry k
   278     (invoke (fn kind => #purge kind thy cs) k)) (! kind_keys);
   279 
   280 end; (*local*)
   281 
   282 
   283 (** theory store **)
   284 
   285 local
   286 
   287 type data = Object.T Datatab.table;
   288 val empty_data = Datatab.empty : data;
   289 
   290 structure CodeData = TheoryDataFun
   291 (
   292   type T = exec * data ref;
   293   val empty = (empty_exec, ref empty_data);
   294   fun copy (exec, data) = (exec, ref (! data));
   295   val extend = copy;
   296   fun merge pp ((exec1, data1), (exec2, data2)) =
   297     (merge_exec (exec1, exec2), ref empty_data);
   298 );
   299 
   300 val _ = Context.>> (Context.map_theory CodeData.init);
   301 
   302 fun thy_data f thy = f ((snd o CodeData.get) thy);
   303 
   304 fun get_ensure_init kind data_ref =
   305   case Datatab.lookup (! data_ref) kind
   306    of SOME x => x
   307     | NONE => let val y = invoke_init kind
   308         in (change data_ref (Datatab.update (kind, y)); y) end;
   309 
   310 in
   311 
   312 (* access to executable content *)
   313 
   314 val the_exec = fst o CodeData.get;
   315 
   316 fun complete_class_params thy cs =
   317   fold (fn c => case AxClass.inst_of_param thy c
   318    of NONE => insert (op =) c
   319     | SOME (c', _) => insert (op =) c' #> insert (op =) c) cs [];
   320 
   321 fun map_exec_purge touched f thy =
   322   CodeData.map (fn (exec, data) => (f exec, ref (case touched
   323    of SOME cs => invoke_purge_all thy (complete_class_params thy cs) (! data)
   324     | NONE => empty_data))) thy;
   325 
   326 val purge_data = (CodeData.map o apsnd) (K (ref empty_data));
   327 
   328 
   329 (* access to data dependent on abstract executable content *)
   330 
   331 fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
   332 
   333 fun change_data (kind, mk, dest) =
   334   let
   335     fun chnge data_ref f =
   336       let
   337         val data = get_ensure_init kind data_ref;
   338         val data' = f (dest data);
   339       in (change data_ref (Datatab.update (kind, mk data')); data') end;
   340   in thy_data chnge end;
   341 
   342 fun change_yield_data (kind, mk, dest) =
   343   let
   344     fun chnge data_ref f =
   345       let
   346         val data = get_ensure_init kind data_ref;
   347         val (x, data') = f (dest data);
   348       in (x, (change data_ref (Datatab.update (kind, mk data')); data')) end;
   349   in thy_data chnge end;
   350 
   351 end; (*local*)
   352 
   353 
   354 (* print executable content *)
   355 
   356 fun print_codesetup thy =
   357   let
   358     val ctxt = ProofContext.init thy;
   359     val exec = the_exec thy;
   360     fun pretty_eqn (s, (_, lthms)) =
   361       (Pretty.block o Pretty.fbreaks) (
   362         Pretty.str s :: pretty_lthms ctxt lthms
   363       );
   364     fun pretty_dtyp (s, []) =
   365           Pretty.str s
   366       | pretty_dtyp (s, cos) =
   367           (Pretty.block o Pretty.breaks) (
   368             Pretty.str s
   369             :: Pretty.str "="
   370             :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str (Code_Unit.string_of_const thy c)
   371                  | (c, tys) =>
   372                      (Pretty.block o Pretty.breaks)
   373                         (Pretty.str (Code_Unit.string_of_const thy c)
   374                           :: Pretty.str "of"
   375                           :: map (Pretty.quote o Syntax.pretty_typ_global thy) tys)) cos)
   376           );
   377     val pre = (#pre o the_thmproc) exec;
   378     val post = (#post o the_thmproc) exec;
   379     val functrans = (map fst o #functrans o the_thmproc) exec;
   380     val eqns = the_eqns exec
   381       |> Symtab.dest
   382       |> (map o apfst) (Code_Unit.string_of_const thy)
   383       |> sort (string_ord o pairself fst);
   384     val dtyps = the_dtyps exec
   385       |> Symtab.dest
   386       |> map (fn (dtco, (vs, cos)) =>
   387           (Syntax.string_of_typ_global thy (Type (dtco, map TFree vs)), cos))
   388       |> sort (string_ord o pairself fst)
   389   in
   390     (Pretty.writeln o Pretty.chunks) [
   391       Pretty.block (
   392         Pretty.str "defining equations:"
   393         :: Pretty.fbrk
   394         :: (Pretty.fbreaks o map pretty_eqn) eqns
   395       ),
   396       Pretty.block [
   397         Pretty.str "preprocessing simpset:",
   398         Pretty.fbrk,
   399         MetaSimplifier.pretty_ss pre
   400       ],
   401       Pretty.block [
   402         Pretty.str "postprocessing simpset:",
   403         Pretty.fbrk,
   404         MetaSimplifier.pretty_ss post
   405       ],
   406       Pretty.block (
   407         Pretty.str "function transformers:"
   408         :: Pretty.fbrk
   409         :: (Pretty.fbreaks o map Pretty.str) functrans
   410       ),
   411       Pretty.block (
   412         Pretty.str "datatypes:"
   413         :: Pretty.fbrk
   414         :: (Pretty.fbreaks o map pretty_dtyp) dtyps
   415       )
   416     ]
   417   end;
   418 
   419 
   420 (** theorem transformation and certification **)
   421 
   422 fun common_typ_eqns thy [] = []
   423   | common_typ_eqns thy [thm] = [thm]
   424   | common_typ_eqns thy (thms as thm :: _) = (*FIXME is too general*)
   425       let
   426         fun incr_thm thm max =
   427           let
   428             val thm' = incr_indexes max thm;
   429             val max' = Thm.maxidx_of thm' + 1;
   430           in (thm', max') end;
   431         val (thms', maxidx) = fold_map incr_thm thms 0;
   432         val ty1 :: tys = map (snd o Code_Unit.const_typ_eqn) thms';
   433         fun unify ty env = Sign.typ_unify thy (ty1, ty) env
   434           handle Type.TUNIFY =>
   435             error ("Type unificaton failed, while unifying defining equations\n"
   436             ^ (cat_lines o map Display.string_of_thm) thms
   437             ^ "\nwith types\n"
   438             ^ (cat_lines o map (Code_Unit.string_of_typ thy)) (ty1 :: tys));
   439         val (env, _) = fold unify tys (Vartab.empty, maxidx)
   440         val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
   441           cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
   442       in map (Thm.instantiate (instT, [])) thms' end;
   443 
   444 fun certify_const thy c eqns =
   445   let
   446     fun cert (eqn as (thm, _)) = if c = Code_Unit.const_eqn thm
   447       then eqn else error ("Wrong head of defining equation,\nexpected constant "
   448         ^ Code_Unit.string_of_const thy c ^ "\n" ^ Display.string_of_thm thm)
   449   in map cert eqns end;
   450 
   451 fun check_linear (eqn as (thm, linear)) =
   452   if linear then eqn else Code_Unit.bad_thm
   453     ("Duplicate variables on left hand side of defining equation:\n"
   454       ^ Display.string_of_thm thm);
   455 
   456 fun mk_eqn thy linear =
   457   Code_Unit.error_thm ((if linear then check_linear else I) o Code_Unit.mk_eqn thy);
   458 fun mk_liberal_eqn thy = Code_Unit.warning_thm (check_linear o Code_Unit.mk_eqn thy);
   459 fun mk_syntactic_eqn thy = Code_Unit.warning_thm (Code_Unit.mk_eqn thy);
   460 fun mk_default_eqn thy = Code_Unit.try_thm (check_linear o Code_Unit.mk_eqn thy);
   461 
   462 
   463 (** operational sort algebra and class discipline **)
   464 
   465 local
   466 
   467 fun arity_constraints thy algebra (class, tyco) =
   468   let
   469     val base_constraints = Sorts.mg_domain algebra tyco [class];
   470     val classparam_constraints = Sorts.complete_sort algebra [class]
   471       |> maps (map fst o these o try (#params o AxClass.get_info thy))
   472       |> map_filter (fn c => try (AxClass.param_of_inst thy) (c, tyco))
   473       |> map (Symtab.lookup ((the_eqns o the_exec) thy))
   474       |> (map o Option.map) (map fst o Susp.force o snd)
   475       |> maps these
   476       |> map (map (snd o dest_TVar) o Sign.const_typargs thy o Code_Unit.const_typ_eqn);
   477     val inter_sorts = map2 (curry (Sorts.inter_sort algebra));
   478   in fold inter_sorts classparam_constraints base_constraints end;
   479 
   480 fun retrieve_algebra thy operational =
   481   Sorts.subalgebra (Syntax.pp_global thy) operational
   482     (arity_constraints thy (Sign.classes_of thy))
   483     (Sign.classes_of thy);
   484 
   485 in
   486 
   487 fun coregular_algebra thy = retrieve_algebra thy (K true) |> snd;
   488 fun operational_algebra thy =
   489   let
   490     fun add_iff_operational class =
   491       can (AxClass.get_info thy) class ? cons class;
   492     val operational_classes = fold add_iff_operational (Sign.all_classes thy) []
   493   in retrieve_algebra thy (member (op =) operational_classes) end;
   494 
   495 end; (*local*)
   496 
   497 
   498 (** interfaces and attributes **)
   499 
   500 fun delete_force msg key xs =
   501   if AList.defined (op =) xs key then AList.delete (op =) key xs
   502   else error ("No such " ^ msg ^ ": " ^ quote key);
   503 
   504 fun get_datatype thy tyco =
   505   case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   506    of SOME spec => spec
   507     | NONE => Sign.arity_number thy tyco
   508         |> Name.invents Name.context Name.aT
   509         |> map (rpair [])
   510         |> rpair [];
   511 
   512 fun get_datatype_of_constr thy c =
   513   case (snd o strip_type o Sign.the_const_type thy) c
   514    of Type (tyco, _) => if member (op =)
   515        ((the_default [] o Option.map (map fst o snd) o Symtab.lookup ((the_dtyps o the_exec) thy)) tyco) c
   516        then SOME tyco else NONE
   517     | _ => NONE;
   518 
   519 fun get_constr_typ thy c =
   520   case get_datatype_of_constr thy c
   521    of SOME tyco => let
   522           val (vs, cos) = get_datatype thy tyco;
   523           val SOME tys = AList.lookup (op =) cos c;
   524           val ty = tys ---> Type (tyco, map TFree vs);
   525         in SOME (Logic.varifyT ty) end
   526     | NONE => NONE;
   527 
   528 val get_case_data = Symtab.lookup o fst o the_cases o the_exec;
   529 
   530 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
   531 
   532 fun gen_add_eqn linear strict default thm thy =
   533   case (if strict then SOME o mk_eqn thy linear else mk_liberal_eqn thy) thm
   534    of SOME (thm, _) =>
   535         let
   536           val c = Code_Unit.const_eqn thm;
   537           val _ = if strict andalso (is_some o AxClass.class_of_param thy) c
   538             then error ("Rejected polymorphic equation for overloaded constant:\n"
   539               ^ Display.string_of_thm thm)
   540             else ();
   541           val _ = if strict andalso (is_some o get_datatype_of_constr thy) c
   542             then error ("Rejected equation for datatype constructor:\n"
   543               ^ Display.string_of_thm thm)
   544             else ();
   545         in
   546           (map_exec_purge (SOME [c]) o map_eqns) (Symtab.map_default
   547             (c, (true, Susp.value [])) (add_thm thy default (thm, linear))) thy
   548         end
   549     | NONE => thy;
   550 
   551 val add_eqn = gen_add_eqn true true false;
   552 val add_liberal_eqn = gen_add_eqn true false false;
   553 val add_default_eqn = gen_add_eqn true false true;
   554 val add_nonlinear_eqn = gen_add_eqn false true false;
   555 
   556 fun del_eqn thm thy = case mk_syntactic_eqn thy thm
   557  of SOME (thm, _) => let val c = Code_Unit.const_eqn thm
   558       in map_exec_purge (SOME [c]) (map_eqns (Symtab.map_entry c (del_thm thm))) thy end
   559   | NONE => thy;
   560 
   561 fun del_eqns c = map_exec_purge (SOME [c])
   562   (map_eqns (Symtab.map_entry c (K (false, Susp.value []))));
   563 
   564 fun add_eqnl (c, lthms) thy =
   565   let
   566     val lthms' = certificate thy
   567       (fn thy => map (Code_Unit.assert_linear) o certify_const thy c) lthms;
   568   in
   569     map_exec_purge (SOME [c])
   570       (map_eqns (Symtab.map_default (c, (true, Susp.value []))
   571         (add_lthms lthms'))) thy
   572   end;
   573 
   574 val add_default_eqn_attr = Attrib.internal (fn _ => Thm.declaration_attribute
   575   (fn thm => Context.mapping (add_default_eqn thm) I));
   576 
   577 structure TypeInterpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
   578 
   579 fun add_datatype raw_cs thy =
   580   let
   581     val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
   582     val (tyco, vs_cos) = Code_Unit.constrset_of_consts thy cs;
   583     val cs' = map fst (snd vs_cos);
   584     val purge_cs = case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
   585      of SOME (vs, cos) => if null cos then NONE else SOME (cs' @ map fst cos)
   586       | NONE => NONE;
   587   in
   588     thy
   589     |> map_exec_purge purge_cs (map_dtyps (Symtab.update (tyco, vs_cos))
   590         #> map_eqns (fold (Symtab.delete_safe o fst) cs))
   591     |> TypeInterpretation.data (tyco, serial ())
   592   end;
   593 
   594 fun type_interpretation f =  TypeInterpretation.interpretation
   595   (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
   596 
   597 fun add_datatype_cmd raw_cs thy =
   598   let
   599     val cs = map (Code_Unit.read_bare_const thy) raw_cs;
   600   in add_datatype cs thy end;
   601 
   602 fun add_case thm thy =
   603   let
   604     val entry as (c, _) = Code_Unit.case_cert thm;
   605   in
   606     (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update entry) thy
   607   end;
   608 
   609 fun add_undefined c thy =
   610   (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
   611 
   612 val map_pre = map_exec_purge NONE o map_thmproc o apfst o apfst;
   613 val map_post = map_exec_purge NONE o map_thmproc o apfst o apsnd;
   614 
   615 val add_inline = map_pre o MetaSimplifier.add_simp;
   616 val del_inline = map_pre o MetaSimplifier.del_simp;
   617 val add_post = map_post o MetaSimplifier.add_simp;
   618 val del_post = map_post o MetaSimplifier.del_simp;
   619   
   620 fun add_functrans (name, f) =
   621   (map_exec_purge NONE o map_thmproc o apsnd)
   622     (AList.update (op =) (name, (serial (), f)));
   623 
   624 fun del_functrans name =
   625   (map_exec_purge NONE o map_thmproc o apsnd)
   626     (delete_force "function transformer" name);
   627 
   628 val _ = Context.>> (Context.map_theory
   629   (let
   630     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   631     fun add_simple_attribute (name, f) =
   632       add_attribute (name, Scan.succeed (mk_attribute f));
   633     fun add_del_attribute (name, (add, del)) =
   634       add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
   635         || Scan.succeed (mk_attribute add))
   636   in
   637     TypeInterpretation.init
   638     #> add_del_attribute ("", (add_eqn, del_eqn))
   639     #> add_simple_attribute ("nbe", add_nonlinear_eqn)
   640     #> add_del_attribute ("inline", (add_inline, del_inline))
   641     #> add_del_attribute ("post", (add_post, del_post))
   642   end));
   643 
   644 
   645 (** post- and preprocessing **)
   646 
   647 local
   648 
   649 fun get_eqns thy c =
   650   Symtab.lookup ((the_eqns o the_exec) thy) c
   651   |> Option.map (Susp.force o snd)
   652   |> these
   653   |> (map o apfst) (Thm.transfer thy);
   654 
   655 fun apply_functrans thy c _ [] = []
   656   | apply_functrans thy c [] eqns = eqns
   657   | apply_functrans thy c functrans eqns = eqns
   658       |> perhaps (perhaps_loop (perhaps_apply functrans))
   659       |> (map o apfst) (AxClass.unoverload thy)
   660       |> (map o Code_Unit.error_thm) (Code_Unit.assert_linear o apfst (Code_Unit.assert_eqn thy))
   661       |> certify_const thy c
   662       |> (map o apfst) (AxClass.overload thy);
   663 
   664 fun rhs_conv conv thm = Thm.transitive thm ((conv o Thm.rhs_of) thm);
   665 
   666 fun term_of_conv thy f =
   667   Thm.cterm_of thy
   668   #> f
   669   #> Thm.prop_of
   670   #> Logic.dest_equals
   671   #> snd;
   672 
   673 fun preprocess thy functrans c eqns =
   674   let
   675     val pre = (Simplifier.theory_context thy o #pre o the_thmproc o the_exec) thy;
   676   in
   677     eqns
   678     |> (map o apfst) (AxClass.overload thy)
   679     |> apply_functrans thy c functrans
   680     |> (map o apfst) (Code_Unit.rewrite_eqn pre)
   681     |> (map o apfst) (AxClass.unoverload thy)
   682     |> map (Code_Unit.assert_linear o apfst (Code_Unit.assert_eqn thy))
   683     |> burrow_fst (common_typ_eqns thy)
   684   end;
   685 
   686 in
   687 
   688 fun preprocess_conv thy ct =
   689   let
   690     val pre = (Simplifier.theory_context thy o #pre o the_thmproc o the_exec) thy;
   691   in
   692     ct
   693     |> Simplifier.rewrite pre
   694     |> rhs_conv (AxClass.unoverload_conv thy)
   695   end;
   696 
   697 fun preprocess_term thy = term_of_conv thy (preprocess_conv thy);
   698 
   699 fun postprocess_conv thy ct =
   700   let
   701     val post = (Simplifier.theory_context thy o #post o the_thmproc o the_exec) thy;
   702   in
   703     ct
   704     |> AxClass.overload_conv thy
   705     |> rhs_conv (Simplifier.rewrite post)
   706   end;
   707 
   708 fun postprocess_term thy = term_of_conv thy (postprocess_conv thy);
   709 
   710 fun these_raw_eqns thy c =
   711   get_eqns thy c
   712   |> burrow_fst (common_typ_eqns thy);
   713 
   714 fun these_eqns thy c =
   715   let
   716     val functrans = (map (fn (_, (_, f)) => f thy) o #functrans
   717       o the_thmproc o the_exec) thy;
   718   in
   719     get_eqns thy c
   720     |> preprocess thy functrans c
   721   end;
   722 
   723 fun default_typscheme thy c =
   724   let
   725     val typscheme = curry (Code_Unit.typscheme thy) c
   726     val the_const_type = snd o dest_Const o TermSubst.zero_var_indexes
   727       o curry Const "" o Sign.the_const_type thy;
   728   in case AxClass.class_of_param thy c
   729    of SOME class => the_const_type c
   730         |> Term.map_type_tvar (K (TVar ((Name.aT, 0), [class])))
   731         |> typscheme
   732     | NONE => (case get_constr_typ thy c
   733        of SOME ty => typscheme ty
   734         | NONE => (case get_eqns thy c
   735            of (thm, _) :: _ => snd (Code_Unit.head_eqn thy (Drule.zero_var_indexes thm))
   736             | [] => typscheme (the_const_type c))) end;
   737 
   738 end; (*local*)
   739 
   740 end; (*struct*)
   741 
   742 
   743 (** type-safe interfaces for data depedent on executable content **)
   744 
   745 functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
   746 struct
   747 
   748 type T = Data.T;
   749 exception Data of T;
   750 fun dest (Data x) = x
   751 
   752 val kind = Code.declare_data (Data Data.empty)
   753   (fn thy => fn cs => fn Data x => Data (Data.purge thy cs x));
   754 
   755 val data_op = (kind, Data, dest);
   756 
   757 val get = Code.get_data data_op;
   758 val change = Code.change_data data_op;
   759 fun change_yield thy = Code.change_yield_data data_op thy;
   760 
   761 end;
   762 
   763 structure Code : CODE = struct open Code; end;