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 single 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 del_funcs: string -> theory -> theory
17 val add_funcl: string * thm list Susp.T -> theory -> theory
18 val add_inline: thm -> theory -> theory
19 val del_inline: thm -> theory -> theory
20 val add_inline_proc: string * (theory -> cterm list -> thm list) -> theory -> theory
21 val del_inline_proc: string -> theory -> theory
22 val add_preproc: string * (theory -> thm list -> thm list) -> theory -> theory
23 val del_preproc: string -> theory -> theory
24 val add_post: thm -> theory -> theory
25 val del_post: thm -> theory -> theory
26 val add_datatype: (string * typ) list -> theory -> theory
27 val add_datatype_cmd: string list -> theory -> theory
28 val type_interpretation:
29 (string * ((string * sort) list * (string * typ list) list)
30 -> theory -> theory) -> theory -> theory
31 val add_case: thm -> theory -> theory
32 val add_undefined: string -> theory -> theory
34 val coregular_algebra: theory -> Sorts.algebra
35 val operational_algebra: theory -> (sort -> sort) * Sorts.algebra
36 val these_funcs: theory -> string -> thm 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_typ: theory -> string -> typ
43 val preprocess_conv: cterm -> thm
44 val preprocess_term: theory -> term -> term
45 val postprocess_conv: cterm -> thm
46 val postprocess_term: theory -> term -> term
48 val add_attribute: string * (Args.T list -> attribute * Args.T list) -> theory -> theory
50 val print_codesetup: theory -> unit
53 signature CODE_DATA_ARGS =
57 val merge: Pretty.pp -> T * T -> T
58 val purge: theory option -> string list option -> T -> T
65 val change: theory -> (T -> T) -> T
66 val change_yield: theory -> (T -> 'a * T) -> 'a * T
69 signature PRIVATE_CODE =
72 val declare_data: Object.T -> (Pretty.pp -> Object.T * Object.T -> Object.T)
73 -> (theory option -> string list option -> Object.T -> Object.T) -> serial
74 val get_data: serial * ('a -> Object.T) * (Object.T -> 'a)
76 val change_data: serial * ('a -> Object.T) * (Object.T -> 'a)
77 -> theory -> ('a -> 'a) -> 'a
78 val change_yield_data: serial * ('a -> Object.T) * (Object.T -> 'a)
79 -> theory -> ('a -> 'b * 'a) -> 'b * 'a
82 structure Code : PRIVATE_CODE =
85 (** code attributes **)
87 structure CodeAttr = TheoryDataFun (
88 type T = (string * (Args.T list -> attribute * Args.T list)) list;
92 fun merge _ = AList.merge (op =) (K true);
95 fun add_attribute (attr as (name, _)) =
97 fun add_parser ("", parser) attrs = attrs @ [("", parser)]
98 | add_parser (name, parser) attrs = (name, Args.$$$ name |-- parser) :: attrs;
99 fun error "" = error ("Code attribute already declared")
100 | error name = error ("Code attribute " ^ name ^ " already declared")
101 in CodeAttr.map (fn attrs => if AList.defined (op =) attrs name
102 then error name else add_parser attr attrs)
107 val code_attr = Attrib.syntax (Scan.peek (fn context =>
108 List.foldr op || Scan.fail (map snd (CodeAttr.get (Context.theory_of context)))));
110 Context.add_setup (Attrib.add_attributes
111 [("code", code_attr, "declare theorems for code generation")])
115 (** certificate theorems **)
117 fun string_of_lthms r = case Susp.peek r
118 of SOME thms => (map string_of_thm o rev) thms
121 fun pretty_lthms ctxt r = case Susp.peek r
122 of SOME thms => map (ProofContext.pretty_thm ctxt) thms
123 | NONE => [Pretty.str "[...]"];
125 fun certificate thy f r =
127 of SOME thms => (Susp.value o f thy) thms
129 val thy_ref = Theory.check_thy thy;
130 in Susp.delay (fn () => (f (Theory.deref thy_ref) o Susp.force) r) end;
133 (** logical and syntactical specification of executable code **)
135 (* pairs of (selected, deleted) defining equations *)
137 type sdthms = thm list Susp.T * thm list;
139 fun add_drop_redundant thm (sels, dels) =
141 val thy = Thm.theory_of_thm thm;
142 val args_of = snd o strip_comb o fst o Logic.dest_equals o Thm.plain_prop_of;
143 val args = args_of thm;
144 fun matches [] _ = true
145 | matches (Var _ :: xs) [] = matches xs []
146 | matches (_ :: _) [] = false
147 | matches (x :: xs) (y :: ys) = Pattern.matches thy (x, y) andalso matches xs ys;
148 fun drop thm' = not (matches args (args_of thm'))
149 orelse (warning ("code generator: dropping redundant defining equation\n" ^ string_of_thm thm'); false);
150 val (keeps, drops) = List.partition drop sels;
151 in (thm :: keeps, dels |> remove Thm.eq_thm_prop thm |> fold (insert Thm.eq_thm_prop) drops) end;
153 fun add_thm thm (sels, dels) =
154 apfst Susp.value (add_drop_redundant thm (Susp.force sels, dels));
156 fun add_lthms lthms (sels, []) =
157 (Susp.delay (fn () => fold add_drop_redundant
158 (Susp.force lthms) (Susp.force sels, []) |> fst), [])
160 | add_lthms lthms (sels, dels) =
161 fold add_thm (Susp.force lthms) (sels, dels);
163 fun del_thm thm (sels, dels) =
164 (Susp.value (remove Thm.eq_thm_prop thm (Susp.force sels)), thm :: dels);
166 fun del_thms (sels, dels) =
168 val all_sels = Susp.force sels;
169 in (Susp.value [], rev all_sels @ dels) end;
171 fun pretty_sdthms ctxt (sels, _) = pretty_lthms ctxt sels;
174 (* fundamental melting operations *)
176 fun melt _ ([], []) = (false, [])
177 | melt _ ([], ys) = (true, ys)
178 | melt eq (xs, ys) = fold_rev
179 (fn y => fn (t, xs) => (t orelse not (member eq xs y), insert eq y xs)) ys (false, xs);
181 fun melt_alist eq_key eq (xys as (xs, ys)) =
182 if eq_list (eq_pair eq_key eq) (xs, ys)
184 else (true, AList.merge eq_key eq xys);
186 val melt_thms = melt Thm.eq_thm_prop;
188 fun melt_lthms (r1, r2) =
189 if Susp.same (r1, r2)
191 else case Susp.peek r1
192 of SOME [] => (true, r2)
193 | _ => case Susp.peek r2
194 of SOME [] => (true, r1)
195 | _ => (apsnd (Susp.delay o K)) (melt_thms (Susp.force r1, Susp.force r2));
197 fun melt_sdthms ((sels1, dels1), (sels2, dels2)) =
199 val (dels_t, dels) = melt_thms (dels1, dels2);
202 val (_, sels) = melt_thms
203 (subtract Thm.eq_thm_prop dels2 (Susp.force sels1), Susp.force sels2);
204 val (_, dels) = melt_thms
205 (subtract Thm.eq_thm_prop (Susp.force sels2) dels1, dels2);
206 in (true, ((Susp.delay o K) sels, dels)) end
208 val (sels_t, sels) = melt_lthms (sels1, sels2);
209 in (sels_t, (sels, dels)) end
213 (* specification data *)
215 fun melt_funcs tabs =
217 val tab' = Symtab.join (fn _ => fn ((_, a), (_, b)) => melt_sdthms (a, b)) tabs;
218 val touched = Symtab.fold (fn (c, (true, _)) => insert (op =) c | _ => I) tab' [];
219 in (touched, tab') end;
221 val eq_string = op = : string * string -> bool;
222 fun eq_dtyp ((vs1, cs1), (vs2, cs2)) =
223 gen_eq_set (eq_pair eq_string (gen_eq_set eq_string)) (vs1, vs2)
224 andalso gen_eq_set (eq_fst eq_string) (cs1, cs2);
225 fun melt_dtyps (tabs as (tab1, tab2)) =
227 val tycos1 = Symtab.keys tab1;
228 val tycos2 = Symtab.keys tab2;
229 val tycos' = filter (member eq_string tycos2) tycos1;
230 val touched = not (gen_eq_set (op =) (tycos1, tycos2)
231 andalso gen_eq_set (eq_pair (op =) eq_dtyp)
232 (AList.make (the o Symtab.lookup tab1) tycos',
233 AList.make (the o Symtab.lookup tab2) tycos'));
234 fun join _ (cos as (_, cos2)) = if eq_dtyp cos
235 then raise Symtab.SAME else cos2;
236 in (touched, Symtab.join join tabs) end;
238 fun melt_cases ((cases1, undefs1), (cases2, undefs2)) =
240 val touched1 = subtract (op =) (Symtab.keys cases1) (Symtab.keys cases2)
241 @ subtract (op =) (Symtab.keys cases2) (Symtab.keys cases1);
242 val touched2 = subtract (op =) (Symtab.keys undefs1) (Symtab.keys undefs2)
243 @ subtract (op =) (Symtab.keys undefs2) (Symtab.keys undefs1);
244 val touched = fold (insert (op =)) touched1 touched2;
246 (touched, (Symtab.merge (K true) (cases1, cases2),
247 Symtab.merge (K true) (undefs1, undefs2)))
250 datatype spec = Spec of {
251 funcs: (bool * sdthms) Symtab.table,
252 dtyps: ((string * sort) list * (string * typ list) list) Symtab.table,
253 cases: (int * string list) Symtab.table * unit Symtab.table
256 fun mk_spec (funcs, (dtyps, cases)) =
257 Spec { funcs = funcs, dtyps = dtyps, cases = cases };
258 fun map_spec f (Spec { funcs = funcs, dtyps = dtyps, cases = cases }) =
259 mk_spec (f (funcs, (dtyps, cases)));
260 fun melt_spec (Spec { funcs = funcs1, dtyps = dtyps1, cases = cases1 },
261 Spec { funcs = funcs2, dtyps = dtyps2, cases = cases2 }) =
263 val (touched_funcs, funcs) = melt_funcs (funcs1, funcs2);
264 val (touched_dtyps, dtyps) = melt_dtyps (dtyps1, dtyps2);
265 val (touched_cases, cases) = melt_cases (cases1, cases2);
266 val touched = if touched_dtyps then NONE else
267 SOME (fold (insert (op =)) touched_cases touched_funcs);
268 in (touched, mk_spec (funcs, (dtyps, cases))) end;
271 (* pre- and postprocessor *)
273 datatype thmproc = Thmproc of {
275 inline_procs: (string * (serial * (theory -> cterm list -> thm list))) list,
276 preprocs: (string * (serial * (theory -> thm list -> thm list))) list,
280 fun mk_thmproc (((inlines, inline_procs), preprocs), posts) =
281 Thmproc { inlines = inlines, inline_procs = inline_procs, preprocs = preprocs,
283 fun map_thmproc f (Thmproc { inlines, inline_procs, preprocs, posts }) =
284 mk_thmproc (f (((inlines, inline_procs), preprocs), posts));
285 fun melt_thmproc (Thmproc { inlines = inlines1, inline_procs = inline_procs1,
286 preprocs = preprocs1, posts = posts1 },
287 Thmproc { inlines = inlines2, inline_procs = inline_procs2,
288 preprocs = preprocs2, posts= posts2 }) =
290 val (touched1, inlines) = melt_thms (inlines1, inlines2);
291 val (touched2, inline_procs) = melt_alist (op =) (eq_fst (op =)) (inline_procs1, inline_procs2);
292 val (touched3, preprocs) = melt_alist (op =) (eq_fst (op =)) (preprocs1, preprocs2);
293 val (_, posts) = melt_thms (posts1, posts2);
294 in (touched1 orelse touched2 orelse touched3,
295 mk_thmproc (((inlines, inline_procs), preprocs), posts)) end;
297 datatype exec = Exec of {
302 fun mk_exec (thmproc, spec) =
303 Exec { thmproc = thmproc, spec = spec };
304 fun map_exec f (Exec { thmproc = thmproc, spec = spec }) =
305 mk_exec (f (thmproc, spec));
306 fun melt_exec (Exec { thmproc = thmproc1, spec = spec1 },
307 Exec { thmproc = thmproc2, spec = spec2 }) =
309 val (touched', thmproc) = melt_thmproc (thmproc1, thmproc2);
310 val (touched_cs, spec) = melt_spec (spec1, spec2);
311 val touched = if touched' then NONE else touched_cs;
312 in (touched, mk_exec (thmproc, spec)) end;
313 val empty_exec = mk_exec (mk_thmproc ((([], []), []), []),
314 mk_spec (Symtab.empty, (Symtab.empty, (Symtab.empty, Symtab.empty))));
316 fun the_thmproc (Exec { thmproc = Thmproc x, ...}) = x;
317 fun the_spec (Exec { spec = Spec x, ...}) = x;
318 val the_funcs = #funcs o the_spec;
319 val the_dtyps = #dtyps o the_spec;
320 val the_cases = #cases o the_spec;
321 val map_thmproc = map_exec o apfst o map_thmproc;
322 val map_funcs = map_exec o apsnd o map_spec o apfst;
323 val map_dtyps = map_exec o apsnd o map_spec o apsnd o apfst;
324 val map_cases = map_exec o apsnd o map_spec o apsnd o apsnd;
327 (* data slots dependent on executable content *)
329 (*private copy avoids potential conflict of table exceptions*)
330 structure Datatab = TableFun(type key = int val ord = int_ord);
336 merge: Pretty.pp -> Object.T * Object.T -> Object.T,
337 purge: theory option -> string list option -> Object.T -> Object.T
340 val kinds = ref (Datatab.empty: kind Datatab.table);
341 val kind_keys = ref ([]: serial list);
343 fun invoke f k = case Datatab.lookup (! kinds) k
344 of SOME kind => f kind
345 | NONE => sys_error "Invalid code data identifier";
349 fun declare_data empty merge purge =
352 val kind = {empty = empty, merge = merge, purge = purge};
353 val _ = change kinds (Datatab.update (k, kind));
354 val _ = change kind_keys (cons k);
357 fun invoke_empty k = invoke (fn kind => #empty kind) k;
359 fun invoke_merge_all pp = Datatab.join
360 (invoke (fn kind => #merge kind pp));
362 fun invoke_purge_all thy_opt cs =
363 fold (fn k => Datatab.map_entry k
364 (invoke (fn kind => #purge kind thy_opt cs) k)) (! kind_keys);
373 type data = Object.T Datatab.table;
375 structure CodeData = TheoryDataFun
377 type T = exec * data ref;
378 val empty = (empty_exec, ref Datatab.empty : data ref);
379 fun copy (exec, data) = (exec, ref (! data));
381 fun merge pp ((exec1, data1), (exec2, data2)) =
383 val (touched, exec) = melt_exec (exec1, exec2);
384 val data1' = invoke_purge_all NONE touched (! data1);
385 val data2' = invoke_purge_all NONE touched (! data2);
386 val data = invoke_merge_all pp (data1', data2');
387 in (exec, ref data) end;
390 val _ = Context.add_setup CodeData.init;
392 fun thy_data f thy = f ((snd o CodeData.get) thy);
394 fun get_ensure_init kind data_ref =
395 case Datatab.lookup (! data_ref) kind
397 | NONE => let val y = invoke_empty kind
398 in (change data_ref (Datatab.update (kind, y)); y) end;
402 (* access to executable content *)
404 val the_exec = fst o CodeData.get;
406 fun map_exec_purge touched f thy =
407 CodeData.map (fn (exec, data) =>
408 (f exec, ref (invoke_purge_all (SOME thy) touched (! data)))) thy;
411 (* access to data dependent on abstract executable content *)
413 fun get_data (kind, _, dest) = thy_data (get_ensure_init kind #> dest);
415 fun change_data (kind, mk, dest) =
417 fun chnge data_ref f =
419 val data = get_ensure_init kind data_ref;
420 val data' = f (dest data);
421 in (change data_ref (Datatab.update (kind, mk data')); data') end;
422 in thy_data chnge end;
424 fun change_yield_data (kind, mk, dest) =
426 fun chnge data_ref f =
428 val data = get_ensure_init kind data_ref;
429 val (x, data') = f (dest data);
430 in (x, (change data_ref (Datatab.update (kind, mk data')); data')) end;
431 in thy_data chnge end;
436 (* print executable content *)
438 fun print_codesetup thy =
440 val ctxt = ProofContext.init thy;
441 val exec = the_exec thy;
442 fun pretty_func (s, lthms) =
443 (Pretty.block o Pretty.fbreaks) (
444 Pretty.str s :: pretty_sdthms ctxt lthms
446 fun pretty_dtyp (s, []) =
448 | pretty_dtyp (s, cos) =
449 (Pretty.block o Pretty.breaks) (
452 :: separate (Pretty.str "|") (map (fn (c, []) => Pretty.str c
454 (Pretty.block o Pretty.breaks)
455 (Pretty.str (CodeUnit.string_of_const thy c)
456 :: Pretty.str "of" :: map (Pretty.quote o Sign.pretty_typ thy) tys)) cos)
458 val inlines = (#inlines o the_thmproc) exec;
459 val posts = (#posts o the_thmproc) exec;
460 val inline_procs = (map fst o #inline_procs o the_thmproc) exec;
461 val preprocs = (map fst o #preprocs o the_thmproc) exec;
462 val funs = the_funcs exec
465 |> (map o apfst) (CodeUnit.string_of_const thy)
466 |> sort (string_ord o pairself fst);
467 val dtyps = the_dtyps exec
469 |> map (fn (dtco, (vs, cos)) => (Sign.string_of_typ thy (Type (dtco, map TFree vs)), cos))
470 |> sort (string_ord o pairself fst)
472 (Pretty.writeln o Pretty.chunks) [
474 Pretty.str "defining equations:"
476 :: (Pretty.fbreaks o map pretty_func) funs
479 Pretty.str "inlining theorems:"
481 :: (Pretty.fbreaks o map (ProofContext.pretty_thm ctxt)) inlines
484 Pretty.str "inlining procedures:"
486 :: (Pretty.fbreaks o map Pretty.str) inline_procs
489 Pretty.str "preprocessors:"
491 :: (Pretty.fbreaks o map Pretty.str) preprocs
494 Pretty.str "postprocessor theorems:"
496 :: (Pretty.fbreaks o map (ProofContext.pretty_thm ctxt)) posts
499 Pretty.str "datatypes:"
501 :: (Pretty.fbreaks o map pretty_dtyp) dtyps
508 (** theorem transformation and certification **)
510 fun common_typ_funcs [] = []
511 | common_typ_funcs [thm] = [thm]
512 | common_typ_funcs (thms as thm :: _) =
514 val thy = Thm.theory_of_thm thm;
515 fun incr_thm thm max =
517 val thm' = incr_indexes max thm;
518 val max' = Thm.maxidx_of thm' + 1;
520 val (thms', maxidx) = fold_map incr_thm thms 0;
521 val ty1 :: tys = map (snd o CodeUnit.head_func) thms';
522 fun unify ty env = Sign.typ_unify thy (ty1, ty) env
523 handle Type.TUNIFY =>
524 error ("Type unificaton failed, while unifying defining equations\n"
525 ^ (cat_lines o map Display.string_of_thm) thms
527 ^ (cat_lines o map (CodeUnit.string_of_typ thy)) (ty1 :: tys));
528 val (env, _) = fold unify tys (Vartab.empty, maxidx)
529 val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
530 cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
531 in map (Thm.instantiate (instT, [])) thms' end;
533 fun const_of_func thy = AxClass.unoverload_const thy o CodeUnit.head_func;
535 fun certify_const thy const thms =
537 fun cert thm = if const = const_of_func thy thm
538 then thm else error ("Wrong head of defining equation,\nexpected constant "
539 ^ CodeUnit.string_of_const thy const ^ "\n" ^ string_of_thm thm)
540 in map cert thms end;
544 (** operational sort algebra and class discipline **)
548 fun aggr_neutr f y [] = y
549 | aggr_neutr f y (x::xs) = aggr_neutr f (f y x) xs;
551 fun aggregate f [] = NONE
552 | aggregate f (x::xs) = SOME (aggr_neutr f x xs);
554 fun inter_sorts algebra =
555 aggregate (map2 (curry (Sorts.inter_sort algebra)));
557 fun specific_constraints thy (class, tyco) =
559 val vs = Name.invents Name.context "" (Sign.arity_number thy tyco);
560 val classparams = (map fst o these o try (#params o AxClass.get_info thy)) class;
561 val funcs = classparams
562 |> map_filter (fn c => try (AxClass.param_of_inst thy) (c, tyco))
563 |> map (Symtab.lookup ((the_funcs o the_exec) thy))
564 |> (map o Option.map) (Susp.force o fst o snd)
566 |> map (Thm.transfer thy)
567 fun sorts_of [Type (_, tys)] = map (snd o dest_TVar) tys
568 | sorts_of tys = map (snd o dest_TVar) tys;
569 val sorts = map (sorts_of o Sign.const_typargs thy o CodeUnit.head_func) funcs;
572 fun weakest_constraints thy algebra (class, tyco) =
574 val all_superclasses = Sorts.complete_sort algebra [class];
575 in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) all_superclasses)
576 of SOME sorts => sorts
577 | NONE => Sorts.mg_domain algebra tyco [class]
580 fun strongest_constraints thy algebra (class, tyco) =
582 val all_subclasses = class :: Graph.all_preds ((#classes o Sorts.rep_algebra) algebra) [class];
583 val inst_subclasses = filter (can (Sorts.mg_domain algebra tyco) o single) all_subclasses;
584 in case inter_sorts algebra (maps (fn class => specific_constraints thy (class, tyco)) inst_subclasses)
585 of SOME sorts => sorts
587 (Sign.arity_number thy tyco) (Sorts.minimize_sort algebra (Sorts.all_classes algebra))
590 fun get_algebra thy (class, tyco) =
592 val base_algebra = Sign.classes_of thy;
593 in if can (Sorts.mg_domain base_algebra tyco) [class]
596 val superclasses = Sorts.super_classes base_algebra class;
597 val sorts = inter_sorts base_algebra
598 (map_filter (fn class => try (Sorts.mg_domain base_algebra tyco) [class]) superclasses)
599 |> the_default (replicate (Sign.arity_number thy tyco) [])
602 |> Sorts.add_arities (Sign.pp thy) (tyco, [(class, sorts)])
606 fun gen_classparam_typ constr thy class (c, tyco) =
608 val algebra = get_algebra thy (class, tyco);
609 val cs = these (try (#params o AxClass.get_info thy) class);
610 val SOME ty = AList.lookup (op =) cs c;
611 val sort_args = Name.names (Name.declare Name.aT Name.context) Name.aT
612 (constr thy algebra (class, tyco));
613 val ty_inst = Type (tyco, map TFree sort_args);
614 in Logic.varifyT (map_type_tfree (K ty_inst) ty) end;
616 fun retrieve_algebra thy operational =
617 Sorts.subalgebra (Sign.pp thy) operational
618 (weakest_constraints thy (Sign.classes_of thy))
619 (Sign.classes_of thy);
623 fun coregular_algebra thy = retrieve_algebra thy (K true) |> snd;
624 fun operational_algebra thy =
626 fun add_iff_operational class =
627 can (AxClass.get_info thy) class ? cons class;
628 val operational_classes = fold add_iff_operational (Sign.all_classes thy) []
629 in retrieve_algebra thy (member (op =) operational_classes) end;
631 val classparam_weakest_typ = gen_classparam_typ weakest_constraints;
632 val classparam_strongest_typ = gen_classparam_typ strongest_constraints;
634 fun assert_func_typ thm =
636 val thy = Thm.theory_of_thm thm;
637 fun check_typ_classparam tyco (c, thm) =
639 val SOME class = AxClass.class_of_param thy c;
640 val (_, ty) = CodeUnit.head_func thm;
641 val ty_decl = classparam_weakest_typ thy class (c, tyco);
642 val ty_strongest = classparam_strongest_typ thy class (c, tyco);
645 val max = Thm.maxidx_of thm + 1;
646 val ty_decl' = Logic.incr_tvar max ty_decl;
647 val (_, ty') = CodeUnit.head_func thm;
648 val (env, _) = Sign.typ_unify thy (ty_decl', ty') (Vartab.empty, max);
649 val instT = Vartab.fold (fn (x_i, (sort, ty)) =>
650 cons (Thm.ctyp_of thy (TVar (x_i, sort)), Thm.ctyp_of thy ty)) env [];
651 in Thm.instantiate (instT, []) thm end;
652 in if Sign.typ_instance thy (ty_strongest, ty)
653 then if Sign.typ_instance thy (ty, ty_decl)
655 else (warning ("Constraining type\n" ^ CodeUnit.string_of_typ thy ty
656 ^ "\nof defining equation\n"
658 ^ "\nto permitted most general type\n"
659 ^ CodeUnit.string_of_typ thy ty_decl);
661 else CodeUnit.bad_thm ("Type\n" ^ CodeUnit.string_of_typ thy ty
662 ^ "\nof defining equation\n"
664 ^ "\nis incompatible with permitted least general type\n"
665 ^ CodeUnit.string_of_typ thy ty_strongest)
667 fun check_typ_fun (c, thm) =
669 val (_, ty) = CodeUnit.head_func thm;
670 val ty_decl = Sign.the_const_type thy c;
671 in if Sign.typ_equiv thy (Type.strip_sorts ty_decl, Type.strip_sorts ty)
673 else CodeUnit.bad_thm ("Type\n" ^ CodeUnit.string_of_typ thy ty
674 ^ "\nof defining equation\n"
676 ^ "\nis incompatible with declared function type\n"
677 ^ CodeUnit.string_of_typ thy ty_decl)
679 fun check_typ (c, thm) =
680 case AxClass.inst_of_param thy c
681 of SOME (c, tyco) => check_typ_classparam tyco (c, thm)
682 | NONE => check_typ_fun (c, thm);
683 in check_typ (const_of_func thy thm, thm) end;
685 val mk_func = CodeUnit.error_thm (assert_func_typ o CodeUnit.mk_func);
686 val mk_liberal_func = CodeUnit.warning_thm (assert_func_typ o CodeUnit.mk_func);
687 val mk_default_func = CodeUnit.try_thm (assert_func_typ o CodeUnit.mk_func);
693 (** interfaces and attributes **)
695 fun delete_force msg key xs =
696 if AList.defined (op =) xs key then AList.delete (op =) key xs
697 else error ("No such " ^ msg ^ ": " ^ quote key);
699 fun get_datatype thy tyco =
700 case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
702 | NONE => Sign.arity_number thy tyco
703 |> Name.invents Name.context Name.aT
707 fun get_datatype_of_constr thy c =
708 case (snd o strip_type o Sign.the_const_type thy) c
709 of Type (tyco, _) => if member (op =)
710 ((the_default [] o Option.map (map fst o snd) o Symtab.lookup ((the_dtyps o the_exec) thy)) tyco) c
711 then SOME tyco else NONE
714 fun get_constr_typ thy c =
715 case get_datatype_of_constr thy c
717 val (vs, cos) = get_datatype thy tyco;
718 val SOME tys = AList.lookup (op =) cos c;
719 val ty = tys ---> Type (tyco, map TFree vs);
720 in SOME (Logic.varifyT ty) end
723 val get_case_data = Symtab.lookup o fst o the_cases o the_exec;
725 val is_undefined = Symtab.defined o snd o the_cases o the_exec;
727 fun add_func thm thy =
729 val func = mk_func thm;
730 val c = const_of_func thy func;
731 val _ = if (is_some o AxClass.class_of_param thy) c
732 then error ("Rejected polymorphic equation for overloaded constant:\n"
735 val _ = if (is_some o get_datatype_of_constr thy) c
736 then error ("Rejected equation for datatype constructor:\n"
737 ^ string_of_thm func)
740 (map_exec_purge (SOME [c]) o map_funcs) (Symtab.map_default
741 (c, (false, (Susp.value [], []))) (apsnd (add_thm func))) thy
744 fun add_liberal_func thm thy =
745 case mk_liberal_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 add_default_func thm thy =
758 case mk_default_func thm
760 val c = const_of_func thy func
761 in if (is_some o AxClass.class_of_param thy) c
762 orelse (is_some o get_datatype_of_constr thy) c
764 else map_exec_purge (SOME [c]) (map_funcs
766 (c, (false, (Susp.value [], []))) (apsnd (add_thm func)))) thy
770 fun del_func thm thy =
771 case mk_liberal_func thm
773 val c = const_of_func thy func;
774 in map_exec_purge (SOME [c]) (map_funcs
775 (Symtab.map_entry c (apsnd (del_thm func)))) thy
779 fun del_funcs const = map_exec_purge (SOME [const])
780 (map_funcs (Symtab.map_entry const (apsnd del_thms)));
782 fun add_funcl (const, lthms) thy =
784 val lthms' = certificate thy (fn thy => certify_const thy const) lthms;
785 (*FIXME must check compatibility with sort algebra;
786 alas, naive checking results in non-termination!*)
788 map_exec_purge (SOME [const])
789 (map_funcs (Symtab.map_default (const, (false, (Susp.value [], [])))
790 (apsnd (add_lthms lthms')))) thy
793 val add_default_func_attr = Attrib.internal (fn _ => Thm.declaration_attribute
794 (fn thm => Context.mapping (add_default_func thm) I));
796 structure TypeInterpretation = InterpretationFun(type T = string * serial val eq = eq_snd (op =) : T * T -> bool);
798 fun add_datatype raw_cs thy =
800 val cs = map (fn c_ty as (_, ty) => (AxClass.unoverload_const thy c_ty, ty)) raw_cs;
801 val (tyco, vs_cos) = CodeUnit.constrset_of_consts thy cs;
802 val cs' = map fst (snd vs_cos);
803 val purge_cs = case Symtab.lookup ((the_dtyps o the_exec) thy) tyco
804 of SOME (vs, cos) => if null cos then NONE else SOME (cs' @ map fst cos)
808 |> map_exec_purge purge_cs (map_dtyps (Symtab.update (tyco, vs_cos))
809 #> map_funcs (fold (Symtab.delete_safe o fst) cs))
810 |> TypeInterpretation.data (tyco, serial ())
813 fun type_interpretation f = TypeInterpretation.interpretation
814 (fn (tyco, _) => fn thy => f (tyco, get_datatype thy tyco) thy);
816 fun add_datatype_cmd raw_cs thy =
818 val cs = map (CodeUnit.read_bare_const thy) raw_cs;
819 in add_datatype cs thy end;
821 fun add_case thm thy =
823 val entry as (c, _) = CodeUnit.case_cert thm;
825 (map_exec_purge (SOME [c]) o map_cases o apfst) (Symtab.update entry) thy
828 fun add_undefined c thy =
829 (map_exec_purge (SOME [c]) o map_cases o apsnd) (Symtab.update (c, ())) thy;
831 fun add_inline thm thy =
832 (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
833 (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
834 (*fully applied in order to get right context for mk_rew!*)
836 fun del_inline thm thy =
837 (map_exec_purge NONE o map_thmproc o apfst o apfst o apfst)
838 (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
839 (*fully applied in order to get right context for mk_rew!*)
841 fun add_inline_proc (name, f) =
842 (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
843 (AList.update (op =) (name, (serial (), f)));
845 fun del_inline_proc name =
846 (map_exec_purge NONE o map_thmproc o apfst o apfst o apsnd)
847 (delete_force "inline procedure" name);
849 fun add_preproc (name, f) =
850 (map_exec_purge NONE o map_thmproc o apfst o apsnd)
851 (AList.update (op =) (name, (serial (), f)));
853 fun del_preproc name =
854 (map_exec_purge NONE o map_thmproc o apfst o apsnd)
855 (delete_force "preprocessor" name);
857 fun add_post thm thy =
858 (map_exec_purge NONE o map_thmproc o apsnd)
859 (insert Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
860 (*fully applied in order to get right context for mk_rew!*)
862 fun del_post thm thy =
863 (map_exec_purge NONE o map_thmproc o apsnd)
864 (remove Thm.eq_thm_prop (CodeUnit.error_thm CodeUnit.mk_rew thm)) thy;
865 (*fully applied in order to get right context for mk_rew!*)
867 val _ = Context.add_setup
869 fun mk_attribute f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
870 fun add_simple_attribute (name, f) =
871 add_attribute (name, Scan.succeed (mk_attribute f));
872 fun add_del_attribute (name, (add, del)) =
873 add_attribute (name, Args.del |-- Scan.succeed (mk_attribute del)
874 || Scan.succeed (mk_attribute add))
876 TypeInterpretation.init
877 #> add_del_attribute ("func", (add_func, del_func))
878 #> add_del_attribute ("inline", (add_inline, del_inline))
879 #> add_del_attribute ("post", (add_post, del_post))
883 (** post- and preprocessing **)
887 fun gen_apply_inline_proc prep post thy f x =
890 val rews = map CodeUnit.assert_rew (f thy cts);
893 val apply_inline_proc = gen_apply_inline_proc (maps
894 ((fn [args, rhs] => rhs :: (snd o Drule.strip_comb) args) o snd o Drule.strip_comb o Thm.cprop_of))
895 (fn rews => map (CodeUnit.rewrite_func rews));
896 val apply_inline_proc_cterm = gen_apply_inline_proc single
897 (MetaSimplifier.rewrite false);
899 fun apply_preproc thy f [] = []
900 | apply_preproc thy f (thms as (thm :: _)) =
902 val const = const_of_func thy thm;
903 val thms' = f thy thms;
904 in certify_const thy const thms' end;
906 fun rhs_conv conv thm =
908 val thm' = (conv o Thm.rhs_of) thm;
909 in Thm.transitive thm thm' end
911 fun term_of_conv thy f =
920 fun preprocess thy thms =
922 |> fold (fn (_, (_, f)) => apply_preproc thy f) ((#preprocs o the_thmproc o the_exec) thy)
923 |> map (CodeUnit.rewrite_func ((#inlines o the_thmproc o the_exec) thy))
924 |> fold (fn (_, (_, f)) => apply_inline_proc thy f) ((#inline_procs o the_thmproc o the_exec) thy)
925 (*FIXME - must check: rewrite rule, defining equation, proper constant |> map (snd o check_func false thy) *)
927 |> map (AxClass.unoverload thy);
929 fun preprocess_conv ct =
931 val thy = Thm.theory_of_cterm ct;
934 |> MetaSimplifier.rewrite false ((#inlines o the_thmproc o the_exec) thy)
935 |> fold (fn (_, (_, f)) => rhs_conv (apply_inline_proc_cterm thy f))
936 ((#inline_procs o the_thmproc o the_exec) thy)
937 |> rhs_conv (AxClass.unoverload_conv thy)
940 fun preprocess_term thy = term_of_conv thy preprocess_conv;
942 fun postprocess_conv ct =
944 val thy = Thm.theory_of_cterm ct;
947 |> AxClass.overload_conv thy
948 |> rhs_conv (MetaSimplifier.rewrite false ((#posts o the_thmproc o the_exec) thy))
951 fun postprocess_term thy = term_of_conv thy postprocess_conv;
955 fun default_typ_proto thy c = case AxClass.inst_of_param thy c
956 of SOME (c, tyco) => classparam_weakest_typ thy ((the o AxClass.class_of_param thy) c)
958 | NONE => (case AxClass.class_of_param thy c
959 of SOME class => SOME (Term.map_type_tvar
960 (K (TVar ((Name.aT, 0), [class]))) (Sign.the_const_type thy c))
961 | NONE => get_constr_typ thy c);
965 fun get_funcs thy const =
966 Symtab.lookup ((the_funcs o the_exec) thy) const
967 |> Option.map (Susp.force o fst o snd)
969 |> map (Thm.transfer thy);
973 fun these_funcs thy const =
975 fun drop_refl thy = filter_out (is_equal o Term.fast_term_ord o Logic.dest_equals
976 o ObjectLogic.drop_judgment thy o Thm.plain_prop_of);
983 fun default_typ thy c = case default_typ_proto thy c
985 | NONE => (case get_funcs thy c
986 of thm :: _ => snd (CodeUnit.head_func (AxClass.unoverload thy thm))
987 | [] => Sign.the_const_type thy c);
994 (** type-safe interfaces for data depedent on executable content **)
996 functor CodeDataFun(Data: CODE_DATA_ARGS): CODE_DATA =
1000 exception Data of T;
1001 fun dest (Data x) = x
1003 val kind = Code.declare_data (Data Data.empty)
1004 (fn pp => fn (Data x1, Data x2) => Data (Data.merge pp (x1, x2)))
1005 (fn thy_opt => fn cs => fn Data x => Data (Data.purge thy_opt cs x));
1007 val data_op = (kind, Data, dest);
1009 val get = Code.get_data data_op;
1010 val change = Code.change_data data_op;
1011 fun change_yield thy = Code.change_yield_data data_op thy;
1015 structure Code : CODE =