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