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