1 (* Title: Pure/Isar/code.ML
3 Author: Florian Haftmann, TU Muenchen
5 Abstract executable content of theory. Management of data dependent on
6 executable content. Cache assumes non-concurrent processing of a singly theory.
11 val add_func: thm -> theory -> theory
12 val add_liberal_func: thm -> theory -> theory
13 val add_default_func: thm -> theory -> theory
14 val add_default_func_attr: Attrib.src
15 val del_func: thm -> theory -> theory
16 val add_funcl: string * thm list Susp.T -> theory -> theory
17 val add_inline: thm -> theory -> theory
18 val del_inline: thm -> theory -> theory
19 val add_inline_proc: string * (theory -> cterm list -> thm list) -> theory -> theory
20 val del_inline_proc: string -> theory -> theory
21 val add_preproc: string * (theory -> thm list -> thm list) -> theory -> theory
22 val del_preproc: string -> theory -> theory
23 val add_post: thm -> theory -> theory
24 val del_post: thm -> theory -> theory
25 val add_datatype: (string * typ) list -> theory -> theory
26 val add_datatype_cmd: string list -> theory -> theory
27 val type_interpretation: (string * string list -> theory -> theory) -> theory -> theory
28 val add_case: thm -> theory -> theory
29 val add_undefined: string -> theory -> theory
31 val coregular_algebra: theory -> Sorts.algebra
32 val operational_algebra: theory -> (sort -> sort) * Sorts.algebra
33 val these_funcs: theory -> string -> thm list
34 val get_datatype: theory -> string -> ((string * sort) list * (string * typ list) list)
35 val get_datatype_of_constr: theory -> string -> string option
36 val get_case_data: theory -> string -> (int * string list) option
37 val is_undefined: theory -> string -> bool
38 val default_typ: theory -> string -> typ
40 val preprocess_conv: cterm -> thm
41 val preprocess_term: theory -> term -> term
42 val postprocess_conv: cterm -> thm
43 val postprocess_term: theory -> term -> term
45 val add_attribute: string * (Args.T list -> attribute * Args.T list) -> theory -> theory
47 val print_codesetup: theory -> unit
50 signature CODE_DATA_ARGS =
54 val merge: Pretty.pp -> T * T -> T
55 val purge: theory option -> string list option -> T -> T
62 val change: theory -> (T -> T) -> T
63 val change_yield: theory -> (T -> 'a * T) -> 'a * T
66 signature PRIVATE_CODE =
69 val declare_data: Object.T -> (Pretty.pp -> Object.T * Object.T -> Object.T)
70 -> (theory option -> string list option -> Object.T -> Object.T) -> serial
71 val get_data: serial * ('a -> Object.T) * (Object.T -> 'a)
73 val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
74 -> theory -> ('a -> 'a) -> 'a
75 val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
76 -> theory -> ('a -> 'b * 'a) -> 'b * 'a
79 structure Code : PRIVATE_CODE =
82 (** code attributes **)
84 structure CodeAttr = TheoryDataFun (
85 type T = (string * (Args.T list -> attribute * Args.T list)) list;
89 fun merge _ = AList.merge (op =) (K true);
92 fun add_attribute (attr as (name, _)) =
94 fun add_parser ("", parser) attrs = attrs @ [("", parser)]
95 | add_parser (name, parser) attrs = (name, Args.$$$ name |-- parser) :: attrs;
96 fun error "" = error ("Code attribute already declared")
97 | error name = error ("Code attribute " ^ name ^ " already declared")
98 in CodeAttr.map (fn attrs => if AList.defined (op =) attrs name
99 then error name else add_parser attr attrs)
104 val code_attr = Attrib.syntax (Scan.peek (fn context =>
105 List.foldr op || Scan.fail (map snd (CodeAttr.get (Context.theory_of context)))));
107 Context.add_setup (Attrib.add_attributes
108 [("code", code_attr, "declare theorems for code generation")])
112 (** certificate theorems **)
114 fun string_of_lthms r = case Susp.peek r
115 of SOME thms => (map string_of_thm o rev) thms
118 fun pretty_lthms ctxt r = case Susp.peek r
119 of SOME thms => map (ProofContext.pretty_thm ctxt) thms
120 | NONE => [Pretty.str "[...]"];
122 fun certificate thy f r =
124 of SOME thms => (Susp.value o f thy) thms
126 val thy_ref = Theory.check_thy thy;
127 in Susp.delay (fn () => (f (Theory.deref thy_ref) o Susp.force) r) end;
130 (** logical and syntactical specification of executable code **)
132 (* pairs of (selected, deleted) defining equations *)
134 type sdthms = thm list Susp.T * thm list;
136 fun add_drop_redundant thm (sels, dels) =
138 val thy = Thm.theory_of_thm thm;
139 val args_of = snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
140 val args = args_of thm;
141 fun matches [] _ = true
142 | matches (Var _ :: xs) [] = matches xs []
143 | matches (_ :: _) [] = false
144 | matches (x :: xs) (y :: ys) = Pattern.matches thy (x, y) andalso matches xs ys;
145 fun drop thm' = not (matches args (args_of thm'))
146 orelse (warning ("code generator: dropping redundant defining equation\n" ^ string_of_thm thm'); false);
147 val (keeps, drops) = List.partition drop sels;
148 in (thm :: keeps, dels |> remove Thm.eq_thm_prop thm |> fold (insert Thm.eq_thm_prop) drops) end;
150 fun add_thm thm (sels, dels) =
151 apfst Susp.value (add_drop_redundant thm (Susp.force sels, dels));
153 fun add_lthms lthms (sels, []) =
154 (Susp.delay (fn () => fold add_drop_redundant
155 (Susp.force lthms) (Susp.force sels, []) |> fst), [])
157 | add_lthms lthms (sels, dels) =
158 fold add_thm (Susp.force lthms) (sels, dels);
160 fun del_thm thm (sels, dels) =
161 (Susp.value (remove Thm.eq_thm_prop thm (Susp.force sels)), thm :: dels);
163 fun pretty_sdthms ctxt (sels, _) = pretty_lthms ctxt sels;
166 (* fundamental melting operations *)
168 fun melt _ ([], []) = (false, [])
169 | melt _ ([], ys) = (true, ys)
170 | melt eq (xs, ys) = fold_rev
171 (fn y => fn (t, xs) => (t orelse not (member eq xs y), insert eq y xs)) ys (false, xs);
173 fun melt_alist eq_key eq (xys as (xs, ys)) =
174 if eq_list (eq_pair eq_key eq) (xs, ys)
176 else (true, AList.merge eq_key eq xys);
178 val melt_thms = melt Thm.eq_thm_prop;
180 fun melt_lthms (r1, r2) =
181 if Susp.same (r1, r2)
183 else case Susp.peek r1
184 of SOME [] => (true, r2)
185 | _ => case Susp.peek r2
186 of SOME [] => (true, r1)
187 | _ => (apsnd (Susp.delay o K)) (melt_thms (Susp.force r1, Susp.force r2));
189 fun melt_sdthms ((sels1, dels1), (sels2, dels2)) =
191 val (dels_t, dels) = melt_thms (dels1, dels2);
194 val (_, sels) = melt_thms
195 (subtract Thm.eq_thm_prop dels2 (Susp.force sels1), Susp.force sels2);
196 val (_, dels) = melt_thms
197 (subtract Thm.eq_thm_prop (Susp.force sels2) dels1, dels2);
198 in (true, ((Susp.delay o K) sels, dels)) end
200 val (sels_t, sels) = melt_lthms (sels1, sels2);
201 in (sels_t, (sels, dels)) end
205 (* specification data *)
207 fun melt_funcs tabs =
209 val tab' = Symtab.join (fn _ => fn ((_, a), (_, b)) => melt_sdthms (a, b)) tabs;
210 val touched = Symtab.fold (fn (c, (true, _)) => insert (op =) c | _ => I) tab' [];
211 in (touched, tab') end;
213 val eq_string = op = : string * string -> bool;
214 fun eq_dtyp ((vs1, cs1), (vs2, cs2)) =
215 gen_eq_set (eq_pair eq_string (gen_eq_set eq_string)) (vs1, vs2)
216 andalso gen_eq_set (eq_fst eq_string) (cs1, cs2);
217 fun melt_dtyps (tabs as (tab1, tab2)) =
219 val tycos1 = Symtab.keys tab1;
220 val tycos2 = Symtab.keys tab2;
221 val tycos' = filter (member eq_string tycos2) tycos1;
222 val touched = not (gen_eq_set (op =) (tycos1, tycos2)
223 andalso gen_eq_set (eq_pair (op =) eq_dtyp)
224 (AList.make (the o Symtab.lookup tab1) tycos',
225 AList.make (the o Symtab.lookup tab2) tycos'));
226 fun join _ (cos as (_, cos2)) = if eq_dtyp cos
227 then raise Symtab.SAME else cos2;
228 in (touched, Symtab.join join tabs) end;
230 fun melt_cases ((cases1, undefs1), (cases2, undefs2)) =
232 val touched1 = subtract (op =) (Symtab.keys cases1) (Symtab.keys cases2)
233 @ subtract (op =) (Symtab.keys cases2) (Symtab.keys cases1);
234 val touched2 = subtract (op =) (Symtab.keys undefs1) (Symtab.keys undefs2)
235 @ subtract (op =) (Symtab.keys undefs2) (Symtab.keys undefs1);
236 val touched = fold (insert (op =)) touched1 touched2;
238 (touched, (Symtab.merge (K true) (cases1, cases2),
239 Symtab.merge (K true) (undefs1, undefs2)))
242 datatype spec = Spec of {
243 funcs: (bool * sdthms) Symtab.table,
244 dtyps: ((string * sort) list * (string * typ list) list) Symtab.table,
245 cases: (int * string list) Symtab.table * unit Symtab.table
248 fun mk_spec (funcs, (dtyps, cases)) =
249 Spec { funcs = funcs, dtyps = dtyps, cases = cases };
250 fun map_spec f (Spec { funcs = funcs, dtyps = dtyps, cases = cases }) =
251 mk_spec (f (funcs, (dtyps, cases)));
252 fun melt_spec (Spec { funcs = funcs1, dtyps = dtyps1, cases = cases1 },
253 Spec { funcs = funcs2, dtyps = dtyps2, cases = cases2 }) =
255 val (touched_funcs, funcs) = melt_funcs (funcs1, funcs2);
256 val (touched_dtyps, dtyps) = melt_dtyps (dtyps1, dtyps2);
257 val (touched_cases, cases) = melt_cases (cases1, cases2);
258 val touched = if touched_dtyps then NONE else
259 SOME (fold (insert (op =)) touched_cases touched_funcs);
260 in (touched, mk_spec (funcs, (dtyps, cases))) end;
263 (* pre- and postprocessor *)
265 datatype thmproc = Thmproc of {
267 inline_procs: (string * (serial * (theory -> cterm list -> thm list))) list,
268 preprocs: (string * (serial * (theory -> thm list -> thm list))) list,
272 fun mk_thmproc (((inlines, inline_procs), preprocs), posts) =
273 Thmproc { inlines = inlines, inline_procs = inline_procs, preprocs = preprocs,
275 fun map_thmproc f (Thmproc { inlines, inline_procs, preprocs, posts }) =
276 mk_thmproc (f (((inlines, inline_procs), preprocs), posts));
277 fun melt_thmproc (Thmproc { inlines = inlines1, inline_procs = inline_procs1,
278 preprocs = preprocs1, posts = posts1 },
279 Thmproc { inlines = inlines2, inline_procs = inline_procs2,
280 preprocs = preprocs2, posts= posts2 }) =
282 val (touched1, inlines) = melt_thms (inlines1, inlines2);
283 val (touched2, inline_procs) = melt_alist (op =) (eq_fst (op =)) (inline_procs1, inline_procs2);
284 val (touched3, preprocs) = melt_alist (op =) (eq_fst (op =)) (preprocs1, preprocs2);
285 val (_, posts) = melt_thms (posts1, posts2);
286 in (touched1 orelse touched2 orelse touched3,
287 mk_thmproc (((inlines, inline_procs), preprocs), posts)) end;
289 datatype exec = Exec of {
294 fun mk_exec (thmproc, spec) =
295 Exec { thmproc = thmproc, spec = spec };
296 fun map_exec f (Exec { thmproc = thmproc, spec = spec }) =
297 mk_exec (f (thmproc, spec));
298 fun melt_exec (Exec { thmproc = thmproc1, spec = spec1 },
299 Exec { thmproc = thmproc2, spec = spec2 }) =
301 val (touched', thmproc) = melt_thmproc (thmproc1, thmproc2);
302 val (touched_cs, spec) = melt_spec (spec1, spec2);
303 val touched = if touched' then NONE else touched_cs;
304 in (touched, mk_exec (thmproc, spec)) end;
305 val empty_exec = mk_exec (mk_thmproc ((([], []), []), []),
306 mk_spec (Symtab.empty, (Symtab.empty, (Symtab.empty, Symtab.empty))));
308 fun the_thmproc (Exec { thmproc = Thmproc x, ...}) = x;
309 fun the_spec (Exec { spec = Spec x, ...}) = x;
310 val the_funcs = #funcs o the_spec;
311 val the_dtyps = #dtyps o the_spec;
312 val the_cases = #cases o the_spec;
313 val map_thmproc = map_exec o apfst o map_thmproc;
314 val map_funcs = map_exec o apsnd o map_spec o apfst;
315 val map_dtyps = map_exec o apsnd o map_spec o apsnd o apfst;
316 val map_cases = map_exec o apsnd o map_spec o apsnd o apsnd;
319 (* data slots dependent on executable content *)
321 (*private copy avoids potential conflict of table exceptions*)
322 structure Datatab = TableFun(type key = int val ord = int_ord);
328 merge: Pretty.pp -> Object.T * Object.T -> Object.T,
329 purge: theory option -> string list option -> Object.T -> Object.T
332 val kinds = ref (Datatab.empty: kind Datatab.table);
333 val kind_keys = ref ([]: serial list);
335 fun invoke f k = case Datatab.lookup (! kinds) k
336 of SOME kind => f kind
337 | NONE => sys_error "Invalid code data identifier";
341 fun declare_data empty merge purge =
344 val kind = {empty = empty, merge = merge, purge = purge};
345 val _ = change kinds (Datatab.update (k, kind));
346 val _ = change kind_keys (cons k);
349 fun invoke_empty k = invoke (fn kind => #empty kind) k;
351 fun invoke_merge_all pp = Datatab.join
352 (invoke (fn kind => #merge kind pp));
354 fun invoke_purge_all thy_opt cs =
355 fold (fn k => Datatab.map_entry k
356 (invoke (fn kind => #purge kind thy_opt cs) k)) (! kind_keys);
365 type data = Object.T Datatab.table;
367 structure CodeData = TheoryDataFun
369 type T = exec * data ref;
370 val empty = (empty_exec, ref Datatab.empty : data ref);
371 fun copy (exec, data) = (exec, ref (! data));
373 fun merge pp ((exec1, data1), (exec2, data2)) =
375 val (touched, exec) = melt_exec (exec1, exec2);
376 val data1' = invoke_purge_all NONE touched (! data1);
377 val data2' = invoke_purge_all NONE touched (! data2);
378 val data = invoke_merge_all pp (data1', data2');
379 in (exec, ref data) end;
382 val _ = Context.add_setup CodeData.init;
384 fun ch r f = let val x = f (! r) in (r := x; x) end;
385 fun thy_data f thy = f ((snd o CodeData.get) thy);
387 fun get_ensure_init kind data_ref =
388 case Datatab.lookup (! data_ref) kind
390 | NONE => let val y = invoke_empty kind
391 in (change data_ref (Datatab.update (kind, y)); y) end;
395 (* access to executable content *)
397 val the_exec = fst o CodeData.get;
399 fun map_exec_purge touched f thy =
400 CodeData.map (fn (exec, data) =>
401 (f exec, ref (invoke_purge_all (SOME thy) touched (! data)))) thy;
404 (* access to data dependent on abstract executable content *)
406 fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
408 fun change_data (kind, mk, dest) =
410 fun chnge data_ref f =
412 val data = get_ensure_init kind data_ref;
413 val data' = f (dest data);
414 in (change data_ref (Datatab.update (kind, mk data')); data') end;
415 in thy_data chnge end;
417 fun change_yield_data (kind, mk, dest) =
419 fun chnge data_ref f =
421 val data = get_ensure_init kind data_ref;
422 val (x, data') = f (dest data);
423 in (x, (change data_ref (Datatab.update (kind, mk data')); data')) end;
424 in thy_data chnge end;
429 (* print executable content *)
431 fun print_codesetup thy =
433 val ctxt = ProofContext.init thy;
434 val exec = the_exec thy;
435 fun pretty_func (s, lthms) =
436 (Pretty.block o Pretty.fbreaks) (
437 Pretty.str s :: pretty_sdthms ctxt lthms
439 fun pretty_dtyp (s, []) =
441 | pretty_dtyp (s, cos) =
442 (Pretty.block o Pretty.breaks) (
445 :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str c
447 (Pretty.block o Pretty.breaks)
448 (Pretty.str (CodeUnit.string_of_const thy c)
449 :: Pretty.str "of" :: map (Pretty.quote o Sign.pretty_typ thy) tys)) cos)
451 val inlines = (#inlines o the_thmproc) exec;
452 val inline_procs = (map fst o #inline_procs o the_thmproc) exec;
453 val preprocs = (map fst o #preprocs o the_thmproc) exec;
454 val funs = the_funcs exec
457 |> (map o apfst) (CodeUnit.string_of_const thy)
458 |> sort (string_ord o pairself fst);
459 val dtyps = the_dtyps exec
461 |> map (fn (dtco, (vs, cos)) => (Sign.string_of_typ thy (Type (dtco, map TFree vs)), cos))
462 |> sort (string_ord o pairself fst)
464 (Pretty.writeln o Pretty.chunks) [
466 Pretty.str "defining equations:"
468 :: (Pretty.fbreaks o map pretty_func) funs
471 Pretty.str "inlining theorems:"
473 :: (Pretty.fbreaks o map (ProofContext.pretty_thm ctxt)) inlines
476 Pretty.str "inlining procedures:"
478 :: (Pretty.fbreaks o map Pretty.str) inline_procs
481 Pretty.str "preprocessors:"
483 :: (Pretty.fbreaks o map Pretty.str) preprocs
486 Pretty.str "datatypes:"
488 :: (Pretty.fbreaks o map pretty_dtyp) dtyps
495 (** theorem transformation and certification **)
497 fun common_typ_funcs [] = []
498 | common_typ_funcs [thm] = [thm]
499 | common_typ_funcs (thms as thm :: _) =
501 val thy = Thm.theory_of_thm thm;
502 fun incr_thm thm max =
504 val thm' = incr_indexes max thm;
505 val max' = Thm.maxidx_of thm' + 1;
507 val (thms', maxidx) = fold_map incr_thm thms 0;
508 val ty1 :: tys = map (snd o CodeUnit.head_func) thms';
509 fun unify ty env = Sign.typ_unify thy (ty1, ty) env
510 handle Type.TUNIFY =>
511 error ("Type unificaton failed, while unifying defining equations\n"
512 ^ (cat_lines o map Display.string_of_thm) thms
514 ^ (cat_lines o map (CodeUnit.string_of_typ thy)) (ty1 :: tys));
515 val (env, _) = fold unify tys (Vartab.empty, maxidx)
516 val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
517 cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
518 in map (Thm.instantiate (instT, [])) thms' end;
520 fun const_of_func thy = Class.unoverload_const thy o CodeUnit.head_func;
522 fun certify_const thy const thms =
524 fun cert thm = if const = const_of_func thy thm
525 then thm else error ("Wrong head of defining equation,\nexpected constant "
526 ^ CodeUnit.string_of_const thy const ^ "\n" ^ string_of_thm thm)
527 in map cert thms end;
531 (** operational sort algebra and class discipline **)
535 fun aggr_neutr f y [] = y
536 | aggr_neutr f y (x::xs) = aggr_neutr f (f y x) xs;
538 fun aggregate f [] = NONE
539 | aggregate f (x::xs) = SOME (aggr_neutr f x xs);
541 fun inter_sorts algebra =
542 aggregate (map2 (curry (Sorts.inter_sort algebra)));
544 fun specific_constraints thy (class, tyco) =
546 val vs = Name.invents Name.context "" (Sign.arity_number thy tyco);
547 val classparams = (map fst o these o try (#params o AxClass.get_info thy)) class;
548 val funcs = classparams
549 |> map_filter (fn c => try (Class.inst_const thy) (c, tyco))
550 |> map (Symtab.lookup ((the_funcs o the_exec) thy))
551 |> (map o Option.map) (Susp.force o fst o snd)
553 |> map (Thm.transfer thy)
554 fun sorts_of [Type (_, tys)] = map (snd o dest_TVar) tys
555 | sorts_of tys = map (snd o dest_TVar) tys;
556 val sorts = map (sorts_of o Sign.const_typargs thy o CodeUnit.head_func) funcs;
559 fun weakest_constraints thy algebra (class, tyco) =
561 val all_superclasses = Sorts.complete_sort algebra [class];
562 in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) all_superclasses)
563 of SOME sorts => sorts
564 | NONE => Sorts.mg_domain algebra tyco [class]
567 fun strongest_constraints thy algebra (class, tyco) =
569 val all_subclasses = class :: Graph.all_preds ((#classes o Sorts.rep_algebra) algebra) [class];
570 val inst_subclasses = filter (can (Sorts.mg_domain algebra tyco) o single) all_subclasses;
571 in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) inst_subclasses)
572 of SOME sorts => sorts
574 (Sign.arity_number thy tyco) (Sorts.minimize_sort algebra (Sorts.all_classes algebra))
577 fun get_algebra thy (class, tyco) =
579 val base_algebra = Sign.classes_of thy;
580 in if can (Sorts.mg_domain base_algebra tyco) [class]
583 val superclasses = Sorts.super_classes base_algebra class;
584 val sorts = inter_sorts base_algebra
585 (map_filter (fn class => try (Sorts.mg_domain base_algebra tyco) [class]) superclasses)
586 |> the_default (replicate (Sign.arity_number thy tyco) [])
589 |> Sorts.add_arities (Sign.pp thy) (tyco, [(class, sorts)])
593 fun gen_classparam_typ constr thy class (c, tyco) =
595 val algebra = get_algebra thy (class, tyco);
596 val cs = these (try (#params o AxClass.get_info thy) class);
597 val SOME ty = AList.lookup (op =) cs c;
598 val sort_args = Name.names (Name.declare Name.aT Name.context) Name.aT
599 (constr thy algebra (class, tyco));
600 val ty_inst = Type (tyco, map TFree sort_args);
601 in Logic.varifyT (map_type_tfree (K ty_inst) ty) end;
603 fun retrieve_algebra thy operational =
604 Sorts.subalgebra (Sign.pp thy) operational
605 (weakest_constraints thy (Sign.classes_of thy))
606 (Sign.classes_of thy);
610 fun coregular_algebra thy = retrieve_algebra thy (K true) |> snd;
611 fun operational_algebra thy =
613 fun add_iff_operational class =
614 can (AxClass.get_info thy) class ? cons class;
615 val operational_classes = fold add_iff_operational (Sign.all_classes thy) []
616 in retrieve_algebra thy (member (op =) operational_classes) end;
618 val classparam_weakest_typ = gen_classparam_typ weakest_constraints;
619 val classparam_strongest_typ = gen_classparam_typ strongest_constraints;
621 fun assert_func_typ thm =
623 val thy = Thm.theory_of_thm thm;
624 fun check_typ_classparam tyco (c, thm) =
626 val SOME class = AxClass.class_of_param thy c;
627 val (_, ty) = CodeUnit.head_func thm;
628 val ty_decl = classparam_weakest_typ thy class (c, tyco);
629 val ty_strongest = classparam_strongest_typ thy class (c, tyco);
632 val max = Thm.maxidx_of thm + 1;
633 val ty_decl' = Logic.incr_tvar max ty_decl;
634 val (_, ty') = CodeUnit.head_func thm;
635 val (env, _) = Sign.typ_unify thy (ty_decl', ty') (Vartab.empty, max);
636 val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
637 cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
638 in Thm.instantiate (instT, []) thm end;
639 in if Sign.typ_instance thy (ty_strongest, ty)
640 then if Sign.typ_instance thy (ty, ty_decl)
642 else (warning ("Constraining type\n" ^ CodeUnit.string_of_typ thy ty
643 ^ "\nof defining equation\n"
645 ^ "\nto permitted most general type\n"
646 ^ CodeUnit.string_of_typ thy ty_decl);
648 else CodeUnit.bad_thm ("Type\n" ^ CodeUnit.string_of_typ thy ty
649 ^ "\nof defining equation\n"
651 ^ "\nis incompatible with permitted least general type\n"
652 ^ CodeUnit.string_of_typ thy ty_strongest)
654 fun check_typ_fun (c, thm) =
656 val (_, ty) = CodeUnit.head_func thm;
657 val ty_decl = Sign.the_const_type thy c;
658 in if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
660 else CodeUnit.bad_thm ("Type\n" ^ CodeUnit.string_of_typ thy ty
661 ^ "\nof defining equation\n"
663 ^ "\nis incompatible with declared function type\n"
664 ^ CodeUnit.string_of_typ thy ty_decl)
666 fun check_typ (c, thm) =
667 case Class.param_const thy c
668 of SOME (c, tyco) => check_typ_classparam tyco (c, thm)
669 | NONE => check_typ_fun (c, thm);
670 in check_typ (const_of_func thy thm, thm) end;
672 val mk_func = CodeUnit.error_thm (assert_func_typ o CodeUnit.mk_func);
673 val mk_liberal_func = CodeUnit.warning_thm (assert_func_typ o CodeUnit.mk_func);
674 val mk_default_func = CodeUnit.try_thm (assert_func_typ o CodeUnit.mk_func);
680 (** interfaces and attributes **)
682 fun delete_force msg key xs =
683 if AList.defined (op =) xs key then AList.delete (op =) key xs
684 else error ("No such " ^ msg ^ ": " ^ quote key);
686 fun get_datatype thy tyco =
687 case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
689 | NONE => Sign.arity_number thy tyco
690 |> Name.invents Name.context Name.aT
694 fun get_datatype_of_constr thy c =
695 case (snd o strip_type o Sign.the_const_type thy) c
696 of Type (tyco, _) => if member (op =)
697 ((the_default [] o Option.map (map fst o snd) o Symtab.lookup ((the_dtyps o the_exec) thy)) tyco) c
698 then SOME tyco else NONE
701 fun get_constr_typ thy c =
702 case get_datatype_of_constr thy c
704 val (vs, cos) = get_datatype thy tyco;
705 val SOME tys = AList.lookup (op =) cos c;
706 val ty = tys ---> Type (tyco, map TFree vs);
707 in SOME (Logic.varifyT ty) end
710 val get_case_data = Symtab.lookup o fst o the_cases o the_exec;
712 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
714 fun add_func thm thy =
716 val func = mk_func thm;
717 val c = const_of_func thy func;
718 val _ = if (is_some o AxClass.class_of_param thy) c
719 then error ("Rejected polymorphic equation for overloaded constant:\n"
722 val _ = if (is_some o get_datatype_of_constr thy) c
723 then error ("Rejected equation for datatype constructor:\n"
724 ^ string_of_thm func)
727 (map_exec_purge (SOME [c]) o map_funcs) (Symtab.map_default
728 (c, (false, (Susp.value [], []))) (apsnd (add_thm func))) thy
731 fun add_liberal_func thm thy =
732 case mk_liberal_func thm
734 val c = const_of_func thy func
735 in if (is_some o AxClass.class_of_param thy) c
736 orelse (is_some o get_datatype_of_constr thy) c
738 else map_exec_purge (SOME [c]) (map_funcs
740 (c, (false, (Susp.value [], []))) (apsnd (add_thm func)))) thy
744 fun add_default_func thm thy =
745 case mk_default_func thm
747 val c = const_of_func thy func
748 in if (is_some o AxClass.class_of_param thy) c
749 orelse (is_some o get_datatype_of_constr thy) c
751 else map_exec_purge (SOME [c]) (map_funcs
753 (c, (false, (Susp.value [], []))) (apsnd (add_thm func)))) thy
757 fun del_func thm thy =
758 case mk_liberal_func thm
760 val c = const_of_func thy func;
761 in map_exec_purge (SOME [c]) (map_funcs
762 (Symtab.map_entry c (apsnd (del_thm func)))) thy
766 fun add_funcl (const, lthms) thy =
768 val lthms' = certificate thy (fn thy => certify_const thy const) lthms;
769 (*FIXME must check compatibility with sort algebra;
770 alas, naive checking results in non-termination!*)
772 map_exec_purge (SOME [const])
773 (map_funcs (Symtab.map_default (const, (false, (Susp.value [], [])))
774 (apsnd (add_lthms lthms')))) thy
777 val add_default_func_attr = Attrib.internal (fn _ => Thm.declaration_attribute
778 (fn thm => Context.mapping (add_default_func thm) I));
780 structure TypeInterpretation = InterpretationFun(type T = string * string list val eq = op =);
781 val type_interpretation = TypeInterpretation.interpretation;
783 fun add_datatype raw_cs thy =
785 val cs = map (fn c_ty as (_, ty) => (Class.unoverload_const thy c_ty, ty)) raw_cs;
786 val (tyco, vs_cos) = CodeUnit.constrset_of_consts thy cs;
787 val cs' = map fst (snd vs_cos);
788 val purge_cs = case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
789 of SOME (vs, cos) => if null cos then NONE else SOME (cs' @ map fst cos)
793 |> map_exec_purge purge_cs (map_dtyps (Symtab.update (tyco, vs_cos))
794 #> map_funcs (fold (Symtab.delete_safe o fst) cs))
795 |> TypeInterpretation.data (tyco, cs')
798 fun add_datatype_cmd raw_cs thy =
800 val cs = map (CodeUnit.read_bare_const thy) raw_cs;
801 in add_datatype cs thy end;
803 fun add_case thm thy =
805 val entry as (c, _) = CodeUnit.case_cert thm;
807 (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update entry) thy
810 fun add_undefined c thy =
811 (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
813 fun add_inline thm thy =
814 (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
815 (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
816 (*fully applied in order to get right context for mk_rew!*)
818 fun del_inline thm thy =
819 (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
820 (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
821 (*fully applied in order to get right context for mk_rew!*)
823 fun add_inline_proc (name, f) =
824 (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
825 (AList.update (op =) (name, (serial (), f)));
827 fun del_inline_proc name =
828 (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
829 (delete_force "inline procedure" name);
831 fun add_preproc (name, f) =
832 (map_exec_purge NONE o map_thmproc o apfst o apsnd)
833 (AList.update (op =) (name, (serial (), f)));
835 fun del_preproc name =
836 (map_exec_purge NONE o map_thmproc o apfst o apsnd)
837 (delete_force "preprocessor" name);
839 fun add_post thm thy =
840 (map_exec_purge NONE o map_thmproc o apsnd)
841 (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
842 (*fully applied in order to get right context for mk_rew!*)
844 fun del_post thm thy =
845 (map_exec_purge NONE o map_thmproc o apsnd)
846 (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
847 (*fully applied in order to get right context for mk_rew!*)
849 val _ = Context.add_setup
851 fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
852 fun add_simple_attribute (name, f) =
853 add_attribute (name, Scan.succeed (mk_attribute f));
854 fun add_del_attribute (name, (add, del)) =
855 add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
856 || Scan.succeed (mk_attribute add))
858 TypeInterpretation.init
859 #> add_del_attribute ("func", (add_func, del_func))
860 #> add_del_attribute ("inline", (add_inline, del_inline))
861 #> add_del_attribute ("post", (add_post, del_post))
865 (** post- and preprocessing **)
869 fun gen_apply_inline_proc prep post thy f x =
872 val rews = map CodeUnit.assert_rew (f thy cts);
875 val apply_inline_proc = gen_apply_inline_proc (maps
876 ((fn [args, rhs] => rhs :: (snd o Drule.strip_comb) args) o snd o Drule.strip_comb o Thm.cprop_of))
877 (fn rews => map (CodeUnit.rewrite_func rews));
878 val apply_inline_proc_cterm = gen_apply_inline_proc single
879 (MetaSimplifier.rewrite false);
881 fun apply_preproc thy f [] = []
882 | apply_preproc thy f (thms as (thm :: _)) =
884 val const = const_of_func thy thm;
885 val thms' = f thy thms;
886 in certify_const thy const thms' end;
888 fun rhs_conv conv thm =
890 val thm' = (conv o Thm.rhs_of) thm;
891 in Thm.transitive thm thm' end
893 fun term_of_conv thy f =
902 fun preprocess thy thms =
904 |> fold (fn (_, (_, f)) => apply_preproc thy f) ((#preprocs o the_thmproc o the_exec) thy)
905 |> map (CodeUnit.rewrite_func ((#inlines o the_thmproc o the_exec) thy))
906 |> fold (fn (_, (_, f)) => apply_inline_proc thy f) ((#inline_procs o the_thmproc o the_exec) thy)
907 (*FIXME - must check: rewrite rule, defining equation, proper constant |> map (snd o check_func false thy) *)
909 |> map (Conv.fconv_rule (Class.unoverload thy));
911 fun preprocess_conv ct =
913 val thy = Thm.theory_of_cterm ct;
916 |> MetaSimplifier.rewrite false ((#inlines o the_thmproc o the_exec) thy)
917 |> fold (fn (_, (_, f)) => rhs_conv (apply_inline_proc_cterm thy f))
918 ((#inline_procs o the_thmproc o the_exec) thy)
919 |> rhs_conv (Class.unoverload thy)
922 fun preprocess_term thy = term_of_conv thy preprocess_conv;
924 fun postprocess_conv ct =
926 val thy = Thm.theory_of_cterm ct;
929 |> Class.overload thy
930 |> rhs_conv (MetaSimplifier.rewrite false ((#posts o the_thmproc o the_exec) thy))
933 fun postprocess_term thy = term_of_conv thy postprocess_conv;
937 fun default_typ_proto thy c = case Class.param_const thy c
938 of SOME (c, tyco) => classparam_weakest_typ thy ((the o AxClass.class_of_param thy) c)
940 | NONE => (case AxClass.class_of_param thy c
941 of SOME class => SOME (Term.map_type_tvar
942 (K (TVar ((Name.aT, 0), [class]))) (Sign.the_const_type thy c))
943 | NONE => get_constr_typ thy c);
947 fun get_funcs thy const =
948 Symtab.lookup ((the_funcs o the_exec) thy) const
949 |> Option.map (Susp.force o fst o snd)
951 |> map (Thm.transfer thy);
955 fun these_funcs thy const =
957 fun drop_refl thy = filter_out (is_equal o Term.fast_term_ord o Logic.dest_equals
958 o ObjectLogic.drop_judgment thy o Thm.plain_prop_of);
965 fun default_typ thy c = case default_typ_proto thy c
967 | NONE => (case get_funcs thy c
968 of thm :: _ => snd (CodeUnit.head_func (Conv.fconv_rule (Class.unoverload thy) thm))
969 | [] => Sign.the_const_type thy c);
976 (** type-safe interfaces for data depedent on executable content **)
978 functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
983 fun dest (Data x) = x
985 val kind = Code.declare_data (Data Data.empty)
986 (fn pp => fn (Data x1, Data x2) => Data (Data.merge pp (x1, x2)))
987 (fn thy_opt => fn cs => fn Data x => Data (Data.purge thy_opt cs x));
989 val data_op = (kind, Data, dest);
991 val get = Code.get_data data_op;
992 val change = Code.change_data data_op;
993 fun change_yield thy = Code.change_yield_data data_op thy;
997 structure Code : CODE =