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