src/Pure/Isar/code.ML
author wenzelm
Sun Mar 01 23:36:12 2009 +0100 (2009-03-01)
changeset 30190 479806475f3c
parent 30076 f3043dafef5f
child 30242 aea5d7fa7ef5
permissions -rw-r--r--
use long names for old-style fold combinators;
     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 * (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     (SOME o 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 = Symtab.lookup ((fst o the_cases o the_exec) thy);
   578 
   579 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
   580 
   581 structure TypeInterpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
   582 
   583 fun add_datatype raw_cs thy =
   584   let
   585     val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
   586     val (tyco, vs_cos) = Code_Unit.constrset_of_consts thy cs;
   587     val old_cs = (map fst o snd o get_datatype thy) tyco;
   588     fun drop_outdated_cases cases = fold Symtab.delete_safe
   589       (Symtab.fold (fn (c, (_, (_, cos))) =>
   590         if exists (member (op =) old_cs) cos
   591           then insert (op =) c else I) cases []) cases;
   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         #> (map_cases o apfst) drop_outdated_cases)
   598     |> TypeInterpretation.data (tyco, serial ())
   599   end;
   600 
   601 fun type_interpretation f =  TypeInterpretation.interpretation
   602   (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
   603 
   604 fun add_datatype_cmd raw_cs thy =
   605   let
   606     val cs = map (Code_Unit.read_bare_const thy) raw_cs;
   607   in add_datatype cs thy end;
   608 
   609 fun add_case thm thy =
   610   let
   611     val (c, (k, case_pats)) = Code_Unit.case_cert thm;
   612     val _ = case filter (is_none o get_datatype_of_constr thy) case_pats
   613      of [] => ()
   614       | cs => error ("Non-constructor(s) in case certificate: " ^ commas (map quote cs));
   615     val entry = (1 + Int.max (1, length case_pats), (k, case_pats))
   616   in (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update (c, entry)) thy end;
   617 
   618 fun add_undefined c thy =
   619   (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
   620 
   621 val map_pre = map_exec_purge NONE o map_thmproc o apfst o apfst;
   622 val map_post = map_exec_purge NONE o map_thmproc o apfst o apsnd;
   623 
   624 val add_inline = map_pre o MetaSimplifier.add_simp;
   625 val del_inline = map_pre o MetaSimplifier.del_simp;
   626 val add_post = map_post o MetaSimplifier.add_simp;
   627 val del_post = map_post o MetaSimplifier.del_simp;
   628   
   629 fun add_functrans (name, f) =
   630   (map_exec_purge NONE o map_thmproc o apsnd)
   631     (AList.update (op =) (name, (serial (), f)));
   632 
   633 fun del_functrans name =
   634   (map_exec_purge NONE o map_thmproc o apsnd)
   635     (delete_force "function transformer" name);
   636 
   637 val _ = Context.>> (Context.map_theory
   638   (let
   639     fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
   640     fun add_simple_attribute (name, f) =
   641       add_attribute (name, Scan.succeed (mk_attribute f));
   642     fun add_del_attribute (name, (add, del)) =
   643       add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
   644         || Scan.succeed (mk_attribute add))
   645   in
   646     TypeInterpretation.init
   647     #> add_del_attribute ("", (add_eqn, del_eqn))
   648     #> add_simple_attribute ("nbe", add_nonlinear_eqn)
   649     #> add_del_attribute ("inline", (add_inline, del_inline))
   650     #> add_del_attribute ("post", (add_post, del_post))
   651   end));
   652 
   653 
   654 (** post- and preprocessing **)
   655 
   656 local
   657 
   658 fun apply_functrans thy c _ [] = []
   659   | apply_functrans thy c [] eqns = eqns
   660   | apply_functrans thy c functrans eqns = eqns
   661       |> perhaps (perhaps_loop (perhaps_apply functrans))
   662       |> (map o apfst) (AxClass.unoverload thy)
   663       |> recheck_eqns_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 (recheck_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   |> (map o apfst) (Thm.transfer thy)
   715   |> burrow_fst (common_typ_eqns thy);
   716 
   717 fun these_eqns thy c =
   718   let
   719     val functrans = (map (fn (_, (_, f)) => f thy) o #functrans
   720       o the_thmproc o the_exec) thy;
   721   in
   722     get_eqns thy c
   723     |> (map o apfst) (Thm.transfer thy)
   724     |> preprocess thy functrans c
   725   end;
   726 
   727 fun default_typscheme thy c =
   728   let
   729     fun the_const_typscheme c = (curry (Code_Unit.typscheme thy) c o snd o dest_Const
   730       o TermSubst.zero_var_indexes o curry Const "" o Sign.the_const_type thy) c;
   731     fun strip_sorts (vs, ty) = (map (fn (v, _) => (v, [])) vs, ty);
   732   in case AxClass.class_of_param thy c
   733    of SOME class => ([(Name.aT, [class])], snd (the_const_typscheme c))
   734     | NONE => if is_some (get_datatype_of_constr thy c)
   735         then strip_sorts (the_const_typscheme c)
   736         else case get_eqns thy c
   737          of (thm, _) :: _ => snd (Code_Unit.head_eqn thy (Drule.zero_var_indexes thm))
   738           | [] => strip_sorts (the_const_typscheme 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;