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