replaced ML_Lex.read_antiq by more concise ML_Lex.read, which includes full read/report with explicit position information;
ML_Context.eval/expression expect explicit ML_Lex source, which allows surrounding further text without loosing position information;
fall back on ML_Context.eval_text if there is no position or no surrounding text;
proper Args.name_source_position for method "tactic" and "raw_tactic";
tuned;
1 (* Title: Pure/codegen.ML
2 Author: Stefan Berghofer, TU Muenchen
4 Generic code generator.
9 val quiet_mode : bool Unsynchronized.ref
10 val message : string -> unit
11 val mode : string list Unsynchronized.ref
12 val margin : int Unsynchronized.ref
13 val string_of : Pretty.T -> string
14 val str : string -> Pretty.T
28 val add_codegen: string -> term codegen -> theory -> theory
29 val add_tycodegen: string -> typ codegen -> theory -> theory
30 val add_preprocessor: (theory -> thm list -> thm list) -> theory -> theory
31 val preprocess: theory -> thm list -> thm list
32 val preprocess_term: theory -> term -> term
33 val print_codegens: theory -> unit
34 val generate_code: theory -> string list -> string -> (string * string) list ->
35 (string * string) list * codegr
36 val generate_code_i: theory -> string list -> string -> (string * term) list ->
37 (string * string) list * codegr
38 val assoc_const: string * (term mixfix list *
39 (string * string) list) -> theory -> theory
40 val assoc_const_i: (string * typ) * (term mixfix list *
41 (string * string) list) -> theory -> theory
42 val assoc_type: xstring * (typ mixfix list *
43 (string * string) list) -> theory -> theory
44 val get_assoc_code: theory -> string * typ ->
45 (term mixfix list * (string * string) list) option
46 val get_assoc_type: theory -> string ->
47 (typ mixfix list * (string * string) list) option
48 val codegen_error: codegr -> string -> string -> 'a
49 val invoke_codegen: theory -> deftab -> string -> string -> bool ->
50 term -> codegr -> Pretty.T * codegr
51 val invoke_tycodegen: theory -> deftab -> string -> string -> bool ->
52 typ -> codegr -> Pretty.T * codegr
53 val mk_id: string -> string
54 val mk_qual_id: string -> string * string -> string
55 val mk_const_id: string -> string -> codegr -> (string * string) * codegr
56 val get_const_id: codegr -> string -> string * string
57 val mk_type_id: string -> string -> codegr -> (string * string) * codegr
58 val get_type_id: codegr -> string -> string * string
59 val thyname_of_type: theory -> string -> string
60 val thyname_of_const: theory -> string -> string
61 val rename_terms: term list -> term list
62 val rename_term: term -> term
63 val new_names: term -> string list -> string list
64 val new_name: term -> string -> string
65 val if_library: 'a -> 'a -> 'a
66 val get_defn: theory -> deftab -> string -> typ ->
67 ((typ * (string * thm)) * int option) option
68 val is_instance: typ -> typ -> bool
69 val parens: Pretty.T -> Pretty.T
70 val mk_app: bool -> Pretty.T -> Pretty.T list -> Pretty.T
71 val mk_tuple: Pretty.T list -> Pretty.T
72 val mk_let: (Pretty.T * Pretty.T) list -> Pretty.T -> Pretty.T
73 val eta_expand: term -> term list -> int -> term
74 val strip_tname: string -> string
75 val mk_type: bool -> typ -> Pretty.T
76 val mk_term_of: codegr -> string -> bool -> typ -> Pretty.T
77 val mk_gen: codegr -> string -> bool -> string list -> string -> typ -> Pretty.T
78 val test_fn: (int -> term list option) Unsynchronized.ref
79 val test_term: Proof.context -> bool -> term -> int -> term list option * (bool list * bool)
80 val eval_result: (unit -> term) Unsynchronized.ref
81 val eval_term: theory -> term -> term
82 val evaluation_conv: cterm -> thm
83 val parse_mixfix: (string -> 'a) -> string -> 'a mixfix list
84 val quotes_of: 'a mixfix list -> 'a list
85 val num_args_of: 'a mixfix list -> int
86 val replace_quotes: 'b list -> 'a mixfix list -> 'b mixfix list
87 val mk_deftab: theory -> deftab
88 val map_unfold: (simpset -> simpset) -> theory -> theory
89 val add_unfold: thm -> theory -> theory
90 val del_unfold: thm -> theory -> theory
92 val get_node: codegr -> string -> node
93 val add_edge: string * string -> codegr -> codegr
94 val add_edge_acyclic: string * string -> codegr -> codegr
95 val del_nodes: string list -> codegr -> codegr
96 val map_node: string -> (node -> node) -> codegr -> codegr
97 val new_node: string * node -> codegr -> codegr
99 val setup: theory -> theory
102 structure Codegen : CODEGEN =
105 val quiet_mode = Unsynchronized.ref true;
106 fun message s = if !quiet_mode then () else writeln s;
108 val mode = Unsynchronized.ref ([] : string list); (* FIXME proper functional argument *)
110 val margin = Unsynchronized.ref 80;
112 fun string_of p = Print_Mode.setmp [] (Pretty.string_of_margin (!margin)) p;
114 val str = Print_Mode.setmp [] Pretty.str;
116 (**** Mixfix syntax ****)
125 fun is_arg Arg = true
126 | is_arg Ignore = true
129 fun quotes_of [] = []
130 | quotes_of (Quote q :: ms) = q :: quotes_of ms
131 | quotes_of (_ :: ms) = quotes_of ms;
133 fun args_of [] xs = ([], xs)
134 | args_of (Arg :: ms) (x :: xs) = apfst (cons x) (args_of ms xs)
135 | args_of (Ignore :: ms) (_ :: xs) = args_of ms xs
136 | args_of (_ :: ms) xs = args_of ms xs;
138 fun num_args_of x = length (filter is_arg x);
141 (**** theory data ****)
143 (* preprocessed definition table *)
146 (typ * (* type of constant *)
147 (string * (* name of theory containing definition of constant *)
148 thm)) (* definition theorem *)
151 (* code dependency graph *)
153 type nametab = (string * string) Symtab.table * unit Symtab.table;
155 fun merge_nametabs ((tab, used) : nametab, (tab', used')) =
156 (Symtab.merge op = (tab, tab'), Symtab.merge op = (used, used'));
159 (exn option * (* slot for arbitrary data *)
160 string * (* name of structure containing piece of code *)
161 string); (* piece of code *)
165 (nametab * (* table for assigned constant names *)
166 nametab); (* table for assigned type names *)
168 val emptygr : codegr = (Graph.empty,
169 ((Symtab.empty, Symtab.empty), (Symtab.empty, Symtab.empty)));
171 (* type of code generators *)
174 theory -> (* theory in which generate_code was called *)
175 deftab -> (* definition table (for efficiency) *)
176 string -> (* node name of caller (for recording dependencies) *)
177 string -> (* module name of caller (for modular code generation) *)
178 bool -> (* whether to parenthesize generated expression *)
179 'a -> (* item to generate code from *)
180 codegr -> (* code dependency graph *)
181 (Pretty.T * codegr) option;
186 structure CodegenData = Theory_Data
189 {codegens : (string * term codegen) list,
190 tycodegens : (string * typ codegen) list,
191 consts : ((string * typ) * (term mixfix list * (string * string) list)) list,
192 types : (string * (typ mixfix list * (string * string) list)) list,
193 preprocs: (stamp * (theory -> thm list -> thm list)) list,
194 modules: codegr Symtab.table};
197 {codegens = [], tycodegens = [], consts = [], types = [],
198 preprocs = [], modules = Symtab.empty};
202 ({codegens = codegens1, tycodegens = tycodegens1,
203 consts = consts1, types = types1,
204 preprocs = preprocs1, modules = modules1} : T,
205 {codegens = codegens2, tycodegens = tycodegens2,
206 consts = consts2, types = types2,
207 preprocs = preprocs2, modules = modules2}) : T =
208 {codegens = AList.merge (op =) (K true) (codegens1, codegens2),
209 tycodegens = AList.merge (op =) (K true) (tycodegens1, tycodegens2),
210 consts = AList.merge (op =) (K true) (consts1, consts2),
211 types = AList.merge (op =) (K true) (types1, types2),
212 preprocs = AList.merge (op =) (K true) (preprocs1, preprocs2),
213 modules = Symtab.merge (K true) (modules1, modules2)};
216 fun print_codegens thy =
217 let val {codegens, tycodegens, ...} = CodegenData.get thy in
218 Pretty.writeln (Pretty.chunks
219 [Pretty.strs ("term code generators:" :: map fst codegens),
220 Pretty.strs ("type code generators:" :: map fst tycodegens)])
225 (**** access modules ****)
227 fun get_modules thy = #modules (CodegenData.get thy);
229 fun map_modules f thy =
230 let val {codegens, tycodegens, consts, types, preprocs, modules} =
232 in CodegenData.put {codegens = codegens, tycodegens = tycodegens,
233 consts = consts, types = types, preprocs = preprocs,
234 modules = f modules} thy
238 (**** add new code generators to theory ****)
240 fun add_codegen name f thy =
241 let val {codegens, tycodegens, consts, types, preprocs, modules} =
243 in (case AList.lookup (op =) codegens name of
244 NONE => CodegenData.put {codegens = (name, f) :: codegens,
245 tycodegens = tycodegens, consts = consts, types = types,
246 preprocs = preprocs, modules = modules} thy
247 | SOME _ => error ("Code generator " ^ name ^ " already declared"))
250 fun add_tycodegen name f thy =
251 let val {codegens, tycodegens, consts, types, preprocs, modules} =
253 in (case AList.lookup (op =) tycodegens name of
254 NONE => CodegenData.put {tycodegens = (name, f) :: tycodegens,
255 codegens = codegens, consts = consts, types = types,
256 preprocs = preprocs, modules = modules} thy
257 | SOME _ => error ("Code generator " ^ name ^ " already declared"))
261 (**** preprocessors ****)
263 fun add_preprocessor p thy =
264 let val {codegens, tycodegens, consts, types, preprocs, modules} =
266 in CodegenData.put {tycodegens = tycodegens,
267 codegens = codegens, consts = consts, types = types,
268 preprocs = (stamp (), p) :: preprocs,
269 modules = modules} thy
273 let val {preprocs, ...} = CodegenData.get thy
274 in fold (fn (_, f) => f thy) preprocs end;
276 fun preprocess_term thy t =
278 val x = Free (Name.variant (OldTerm.add_term_names (t, [])) "x", fastype_of t);
279 (* fake definition *)
280 val eq = Skip_Proof.make_thm thy (Logic.mk_equals (x, t));
281 fun err () = error "preprocess_term: bad preprocessor"
282 in case map prop_of (preprocess thy [eq]) of
283 [Const ("==", _) $ x' $ t'] => if x = x' then t' else err ()
287 structure UnfoldData = Theory_Data
290 val empty = empty_ss;
292 val merge = merge_ss;
295 val map_unfold = UnfoldData.map;
296 val add_unfold = map_unfold o MetaSimplifier.add_simp;
297 val del_unfold = map_unfold o MetaSimplifier.del_simp;
299 fun unfold_preprocessor thy =
300 let val ss = Simplifier.global_context thy (UnfoldData.get thy)
301 in map (Thm.transfer thy #> Simplifier.full_simplify ss) end;
304 (**** associate constants with target language code ****)
306 fun gen_assoc_const prep_const (raw_const, syn) thy =
308 val {codegens, tycodegens, consts, types, preprocs, modules} =
310 val (cname, T) = prep_const thy raw_const;
312 if num_args_of (fst syn) > length (binder_types T) then
313 error ("More arguments than in corresponding type of " ^ cname)
314 else case AList.lookup (op =) consts (cname, T) of
315 NONE => CodegenData.put {codegens = codegens,
316 tycodegens = tycodegens,
317 consts = ((cname, T), syn) :: consts,
318 types = types, preprocs = preprocs,
319 modules = modules} thy
320 | SOME _ => error ("Constant " ^ cname ^ " already associated with code")
323 val assoc_const_i = gen_assoc_const (K I);
324 val assoc_const = gen_assoc_const Code.read_bare_const;
327 (**** associate types with target language types ****)
329 fun assoc_type (s, syn) thy =
331 val {codegens, tycodegens, consts, types, preprocs, modules} =
333 val tc = Sign.intern_type thy s;
335 case Symtab.lookup (snd (#types (Type.rep_tsig (Sign.tsig_of thy)))) tc of
336 SOME (Type.LogicalType i) =>
337 if num_args_of (fst syn) > i then
338 error ("More arguments than corresponding type constructor " ^ s)
340 (case AList.lookup (op =) types tc of
341 NONE => CodegenData.put {codegens = codegens,
342 tycodegens = tycodegens, consts = consts,
343 types = (tc, syn) :: types,
344 preprocs = preprocs, modules = modules} thy
345 | SOME _ => error ("Type " ^ tc ^ " already associated with code"))
346 | _ => error ("Not a type constructor: " ^ s)
349 fun get_assoc_type thy = AList.lookup (op =) ((#types o CodegenData.get) thy);
352 (**** make valid ML identifiers ****)
354 fun is_ascii_letdig x = Symbol.is_ascii_letter x orelse
355 Symbol.is_ascii_digit x orelse Symbol.is_ascii_quasi x;
357 fun dest_sym s = (case split_last (snd (take_prefix (fn c => c = "\\") (explode s))) of
358 ("<" :: "^" :: xs, ">") => (true, implode xs)
359 | ("<" :: xs, ">") => (false, implode xs)
360 | _ => sys_error "dest_sym");
362 fun mk_id s = if s = "" then "" else
364 fun check_str [] = []
365 | check_str xs = (case take_prefix is_ascii_letdig xs of
366 ([], " " :: zs) => check_str zs
368 if size z = 1 then string_of_int (ord z) :: check_str zs
369 else (case dest_sym z of
370 (true, "isub") => check_str zs
371 | (true, "isup") => "" :: check_str zs
372 | (ctrl, s') => (if ctrl then "ctrl_" ^ s' else s') :: check_str zs)
373 | (ys, zs) => implode ys :: check_str zs);
374 val s' = space_implode "_" (maps (check_str o Symbol.explode) (Long_Name.explode s))
376 if Symbol.is_ascii_letter (hd (explode s')) then s' else "id_" ^ s'
379 fun mk_long_id (p as (tab, used)) module s =
381 fun find_name [] = sys_error "mk_long_id"
382 | find_name (ys :: yss) =
384 val s' = Long_Name.implode ys
385 val s'' = Long_Name.append module s'
386 in case Symtab.lookup used s'' of
387 NONE => ((module, s'),
388 (Symtab.update_new (s, (module, s')) tab,
389 Symtab.update_new (s'', ()) used))
390 | SOME _ => find_name yss
392 in case Symtab.lookup tab s of
393 NONE => find_name (Library.suffixes1 (Long_Name.explode s))
394 | SOME name => (name, p)
397 (* module: module name for caller *)
398 (* module': module name for callee *)
399 (* if caller and callee reside in different modules, use qualified access *)
401 fun mk_qual_id module (module', s) =
402 if module = module' orelse module' = "" then s else module' ^ "." ^ s;
404 fun mk_const_id module cname (gr, (tab1, tab2)) =
406 val ((module, s), tab1') = mk_long_id tab1 module cname
408 val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
409 in (((module, s'')), (gr, (tab1', tab2))) end;
411 fun get_const_id (gr, (tab1, tab2)) cname =
412 case Symtab.lookup (fst tab1) cname of
413 NONE => error ("get_const_id: no such constant: " ^ quote cname)
414 | SOME (module, s) =>
417 val s'' = if ML_Syntax.is_reserved s' then s' ^ "_const" else s'
418 in (module, s'') end;
420 fun mk_type_id module tyname (gr, (tab1, tab2)) =
422 val ((module, s), tab2') = mk_long_id tab2 module tyname
424 val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
425 in ((module, s''), (gr, (tab1, tab2'))) end;
427 fun get_type_id (gr, (tab1, tab2)) tyname =
428 case Symtab.lookup (fst tab2) tyname of
429 NONE => error ("get_type_id: no such type: " ^ quote tyname)
430 | SOME (module, s) =>
433 val s'' = if ML_Syntax.is_reserved s' then s' ^ "_type" else s'
434 in (module, s'') end;
436 fun get_type_id' f tab tyname = apsnd f (get_type_id tab tyname);
438 fun get_node (gr, x) k = Graph.get_node gr k;
439 fun add_edge e (gr, x) = (Graph.add_edge e gr, x);
440 fun add_edge_acyclic e (gr, x) = (Graph.add_edge_acyclic e gr, x);
441 fun del_nodes ks (gr, x) = (Graph.del_nodes ks gr, x);
442 fun map_node k f (gr, x) = (Graph.map_node k f gr, x);
443 fun new_node p (gr, x) = (Graph.new_node p gr, x);
445 fun thyname_of_type thy = #theory_name o Name_Space.the_entry (Sign.type_space thy);
446 fun thyname_of_const thy = #theory_name o Name_Space.the_entry (Sign.const_space thy);
448 fun rename_terms ts =
450 val names = List.foldr OldTerm.add_term_names
451 (map (fst o fst) (rev (fold Term.add_vars ts []))) ts;
452 val reserved = filter ML_Syntax.is_reserved names;
453 val (illegal, alt_names) = split_list (map_filter (fn s =>
454 let val s' = mk_id s in if s = s' then NONE else SOME (s, s') end) names)
455 val ps = (reserved @ illegal) ~~
456 Name.variant_list names (map (suffix "'") reserved @ alt_names);
458 fun rename_id s = AList.lookup (op =) ps s |> the_default s;
460 fun rename (Var ((a, i), T)) = Var ((rename_id a, i), T)
461 | rename (Free (a, T)) = Free (rename_id a, T)
462 | rename (Abs (s, T, t)) = Abs (s, T, rename t)
463 | rename (t $ u) = rename t $ rename u
469 val rename_term = hd o rename_terms o single;
472 (**** retrieve definition of constant ****)
474 fun is_instance T1 T2 =
475 Type.raw_instance (T1, if null (OldTerm.typ_tfrees T2) then T2 else Logic.varifyT_global T2);
477 fun get_assoc_code thy (s, T) = Option.map snd (find_first (fn ((s', T'), _) =>
478 s = s' andalso is_instance T T') (#consts (CodegenData.get thy)));
480 fun get_aux_code xs = map_filter (fn (m, code) =>
481 if m = "" orelse member (op =) (!mode) m then SOME code else NONE) xs;
483 fun dest_prim_def t =
485 val (lhs, rhs) = Logic.dest_equals t;
486 val (c, args) = strip_comb lhs;
487 val (s, T) = dest_Const c
488 in if forall is_Var args then SOME (s, (T, (args, rhs))) else NONE
489 end handle TERM _ => NONE;
493 val axmss = map (fn thy' => (Context.theory_name thy', Theory.axiom_table thy'))
494 (thy :: Theory.ancestors_of thy);
495 fun add_def thyname (name, t) = (case dest_prim_def t of
497 | SOME (s, (T, _)) => Symtab.map_default (s, [])
498 (cons (T, (thyname, Thm.axiom thy name))));
500 fold (fn (thyname, axms) => Symtab.fold (add_def thyname) axms) axmss Symtab.empty
503 fun prep_prim_def thy thm =
505 val prop = case preprocess thy [thm]
506 of [thm'] => Thm.prop_of thm'
507 | _ => error "mk_deftab: bad preprocessor"
508 in ((Option.map o apsnd o apsnd)
509 (fn (args, rhs) => split_last (rename_terms (args @ [rhs]))) o dest_prim_def) prop
512 fun get_defn thy defs s T = (case Symtab.lookup defs s of
515 let val i = find_index (is_instance T o fst) ds
517 SOME (nth ds i, if length ds = 1 then NONE else SOME i)
522 (**** invoke suitable code generator for term / type ****)
524 fun codegen_error (gr, _) dep s =
525 error (s ^ "\nrequired by:\n" ^ commas (Graph.all_succs gr [dep]));
527 fun invoke_codegen thy defs dep module brack t gr = (case get_first
528 (fn (_, f) => f thy defs dep module brack t gr) (#codegens (CodegenData.get thy)) of
529 NONE => codegen_error gr dep ("Unable to generate code for term:\n" ^
530 Syntax.string_of_term_global thy t)
533 fun invoke_tycodegen thy defs dep module brack T gr = (case get_first
534 (fn (_, f) => f thy defs dep module brack T gr ) (#tycodegens (CodegenData.get thy)) of
535 NONE => codegen_error gr dep ("Unable to generate code for type:\n" ^
536 Syntax.string_of_typ_global thy T)
540 (**** code generator for mixfix expressions ****)
542 fun parens p = Pretty.block [str "(", p, str ")"];
544 fun pretty_fn [] p = [p]
545 | pretty_fn (x::xs) p = str ("fn " ^ x ^ " =>") ::
546 Pretty.brk 1 :: pretty_fn xs p;
548 fun pretty_mixfix _ _ [] [] _ = []
549 | pretty_mixfix module module' (Arg :: ms) (p :: ps) qs =
550 p :: pretty_mixfix module module' ms ps qs
551 | pretty_mixfix module module' (Ignore :: ms) ps qs =
552 pretty_mixfix module module' ms ps qs
553 | pretty_mixfix module module' (Module :: ms) ps qs =
554 (if module <> module'
555 then cons (str (module' ^ ".")) else I)
556 (pretty_mixfix module module' ms ps qs)
557 | pretty_mixfix module module' (Pretty p :: ms) ps qs =
558 p :: pretty_mixfix module module' ms ps qs
559 | pretty_mixfix module module' (Quote _ :: ms) ps (q :: qs) =
560 q :: pretty_mixfix module module' ms ps qs;
562 fun replace_quotes [] [] = []
563 | replace_quotes xs (Arg :: ms) =
564 Arg :: replace_quotes xs ms
565 | replace_quotes xs (Ignore :: ms) =
566 Ignore :: replace_quotes xs ms
567 | replace_quotes xs (Module :: ms) =
568 Module :: replace_quotes xs ms
569 | replace_quotes xs (Pretty p :: ms) =
570 Pretty p :: replace_quotes xs ms
571 | replace_quotes (x::xs) (Quote _ :: ms) =
572 Quote x :: replace_quotes xs ms;
575 (**** default code generators ****)
577 fun eta_expand t ts i =
580 val Ts = drop k (binder_types (fastype_of t));
583 List.foldr (fn (T, t) => Abs ("x", T, t))
584 (list_comb (t, ts @ map Bound (j-1 downto 0))) (take j Ts)
587 fun mk_app _ p [] = p
588 | mk_app brack p ps = if brack then
589 Pretty.block (str "(" ::
590 separate (Pretty.brk 1) (p :: ps) @ [str ")"])
591 else Pretty.block (separate (Pretty.brk 1) (p :: ps));
593 fun new_names t xs = Name.variant_list
594 (union (op =) (map (fst o fst o dest_Var) (OldTerm.term_vars t))
595 (OldTerm.add_term_names (t, ML_Syntax.reserved_names))) (map mk_id xs);
597 fun new_name t x = hd (new_names t [x]);
599 fun if_library x y = if member (op =) (!mode) "library" then x else y;
601 fun default_codegen thy defs dep module brack t gr =
603 val (u, ts) = strip_comb t;
604 fun codegens brack = fold_map (invoke_codegen thy defs dep module brack)
608 val (ps, gr') = codegens true ts gr;
609 val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
610 in SOME (mk_app brack (str (s ^
611 (if i=0 then "" else string_of_int i))) ps, gr'')
616 val (ps, gr') = codegens true ts gr;
617 val (_, gr'') = invoke_tycodegen thy defs dep module false T gr'
618 in SOME (mk_app brack (str s) ps, gr'') end
621 (case get_assoc_code thy (s, T) of
623 let val i = num_args_of ms
624 in if length ts < i then
625 default_codegen thy defs dep module brack (eta_expand u ts i) gr
628 val (ts1, ts2) = args_of ms ts;
629 val (ps1, gr1) = codegens false ts1 gr;
630 val (ps2, gr2) = codegens true ts2 gr1;
631 val (ps3, gr3) = codegens false (quotes_of ms) gr2;
632 val (_, gr4) = invoke_tycodegen thy defs dep module false
633 (funpow (length ts) (hd o tl o snd o dest_Type) T) gr3;
634 val (module', suffix) = (case get_defn thy defs s T of
635 NONE => (if_library (thyname_of_const thy s) module, "")
636 | SOME ((U, (module', _)), NONE) =>
637 (if_library module' module, "")
638 | SOME ((U, (module', _)), SOME i) =>
639 (if_library module' module, " def" ^ string_of_int i));
640 val node_id = s ^ suffix;
641 fun p module' = mk_app brack (Pretty.block
642 (pretty_mixfix module module' ms ps1 ps3)) ps2
643 in SOME (case try (get_node gr4) node_id of
644 NONE => (case get_aux_code aux of
645 [] => (p module, gr4)
646 | xs => (p module', add_edge (node_id, dep) (new_node
647 (node_id, (NONE, module', cat_lines xs ^ "\n")) gr4)))
648 | SOME (_, module'', _) =>
649 (p module'', add_edge (node_id, dep) gr4))
652 | NONE => (case get_defn thy defs s T of
654 | SOME ((U, (thyname, thm)), k) => (case prep_prim_def thy thm
655 of SOME (_, (_, (args, rhs))) => let
656 val module' = if_library thyname module;
657 val suffix = (case k of NONE => "" | SOME i => " def" ^ string_of_int i);
658 val node_id = s ^ suffix;
659 val ((ps, def_id), gr') = gr |> codegens true ts
660 ||>> mk_const_id module' (s ^ suffix);
661 val p = mk_app brack (str (mk_qual_id module def_id)) ps
662 in SOME (case try (get_node gr') node_id of
665 val _ = message ("expanding definition of " ^ s);
666 val (Ts, _) = strip_type U;
668 if not (null args) orelse null Ts then (args, rhs) else
669 let val v = Free (new_name rhs "x", hd Ts)
670 in ([v], betapply (rhs, v)) end;
671 val (p', gr1) = invoke_codegen thy defs node_id module' false
672 rhs' (add_edge (node_id, dep)
673 (new_node (node_id, (NONE, "", "")) gr'));
674 val (xs, gr2) = codegens false args' gr1;
675 val (_, gr3) = invoke_tycodegen thy defs dep module false T gr2;
676 val (ty, gr4) = invoke_tycodegen thy defs node_id module' false U gr3;
677 in (p, map_node node_id (K (NONE, module', string_of
678 (Pretty.block (separate (Pretty.brk 1)
680 [str ("val " ^ snd def_id ^ " :"), ty]
681 else str ("fun " ^ snd def_id) :: xs) @
682 [str " =", Pretty.brk 1, p', str ";"])) ^ "\n\n")) gr4)
684 | SOME _ => (p, add_edge (node_id, dep) gr'))
690 val (bs, Ts) = ListPair.unzip (strip_abs_vars u);
691 val t = strip_abs_body u
692 val bs' = new_names t bs;
693 val (ps, gr1) = codegens true ts gr;
694 val (p, gr2) = invoke_codegen thy defs dep module false
695 (subst_bounds (map Free (rev (bs' ~~ Ts)), t)) gr1;
697 SOME (mk_app brack (Pretty.block (str "(" :: pretty_fn bs' p @
704 fun default_tycodegen thy defs dep module brack (TVar ((s, i), _)) gr =
705 SOME (str (s ^ (if i = 0 then "" else string_of_int i)), gr)
706 | default_tycodegen thy defs dep module brack (TFree (s, _)) gr =
708 | default_tycodegen thy defs dep module brack (Type (s, Ts)) gr =
709 (case AList.lookup (op =) ((#types o CodegenData.get) thy) s of
713 val (ps, gr') = fold_map
714 (invoke_tycodegen thy defs dep module false)
715 (fst (args_of ms Ts)) gr;
716 val (qs, gr'') = fold_map
717 (invoke_tycodegen thy defs dep module false)
719 val module' = if_library (thyname_of_type thy s) module;
720 val node_id = s ^ " (type)";
721 fun p module' = Pretty.block (pretty_mixfix module module' ms ps qs)
722 in SOME (case try (get_node gr'') node_id of
723 NONE => (case get_aux_code aux of
724 [] => (p module', gr'')
725 | xs => (p module', snd (mk_type_id module' s
726 (add_edge (node_id, dep) (new_node (node_id,
727 (NONE, module', cat_lines xs ^ "\n")) gr'')))))
728 | SOME (_, module'', _) =>
729 (p module'', add_edge (node_id, dep) gr''))
733 | mk_tuple ps = Pretty.block (str "(" ::
734 flat (separate [str ",", Pretty.brk 1] (map single ps)) @ [str ")"]);
736 fun mk_let bindings body =
737 Pretty.blk (0, [str "let", Pretty.brk 1,
738 Pretty.blk (0, separate Pretty.fbrk (map (fn (pat, rhs) =>
739 Pretty.block [str "val ", pat, str " =", Pretty.brk 1,
740 rhs, str ";"]) bindings)),
741 Pretty.brk 1, str "in", Pretty.brk 1, body,
742 Pretty.brk 1, str "end"]);
744 fun mk_struct name s = "structure " ^ name ^ " =\nstruct\n\n" ^ s ^ "end;\n";
746 fun add_to_module name s = AList.map_entry (op =) (name : string) (suffix s);
748 fun output_code gr module xs =
750 val code = map_filter (fn s =>
751 let val c as (_, module', _) = Graph.get_node gr s
752 in if module = "" orelse module = module' then SOME (s, c) else NONE end)
753 (rev (Graph.all_preds gr xs));
754 fun string_of_cycle (a :: b :: cs) =
755 let val SOME (x, y) = get_first (fn (x, (_, a', _)) =>
756 if a = a' then Option.map (pair x)
757 (find_first ((fn (_, b', _) => b' = b) o Graph.get_node gr)
758 (Graph.imm_succs gr x))
760 in x ^ " called by " ^ y ^ "\n" ^ string_of_cycle (b :: cs) end
761 | string_of_cycle _ = ""
765 val modules = distinct (op =) (map (#2 o snd) code);
766 val mod_gr = fold_rev Graph.add_edge_acyclic
767 (maps (fn (s, (_, module, _)) => map (pair module)
768 (filter_out (fn s => s = module) (map (#2 o Graph.get_node gr)
769 (Graph.imm_succs gr s)))) code)
770 (fold_rev (Graph.new_node o rpair ()) modules Graph.empty);
772 rev (Graph.all_preds mod_gr (map (#2 o Graph.get_node gr) xs))
774 List.foldl (fn ((_, (_, module, s)), ms) => add_to_module module s ms)
775 (map (rpair "") modules') code
776 end handle Graph.CYCLES (cs :: _) =>
777 error ("Cyclic dependency of modules:\n" ^ commas cs ^
778 "\n" ^ string_of_cycle cs)
779 else [(module, implode (map (#3 o snd) code))]
782 fun gen_generate_code prep_term thy modules module xs =
784 val _ = (module <> "" orelse
785 member (op =) (!mode) "library" andalso forall (fn (s, _) => s = "") xs)
786 orelse error "missing module name";
787 val graphs = get_modules thy;
788 val defs = mk_deftab thy;
789 val gr = new_node ("<Top>", (NONE, module, ""))
790 (List.foldl (fn ((gr, (tab1, tab2)), (gr', (tab1', tab2'))) =>
791 (Graph.merge (fn ((_, module, _), (_, module', _)) =>
792 module = module') (gr, gr'),
793 (merge_nametabs (tab1, tab1'), merge_nametabs (tab2, tab2')))) emptygr
794 (map (fn s => case Symtab.lookup graphs s of
795 NONE => error ("Undefined code module: " ^ s)
796 | SOME gr => gr) modules))
797 handle Graph.DUP k => error ("Duplicate code for " ^ k);
798 fun expand (t as Abs _) = t
799 | expand t = (case fastype_of t of
800 Type ("fun", [T, U]) => Abs ("x", T, t $ Bound 0) | _ => t);
801 val (ps, gr') = fold_map (fn (s, t) => fn gr => apfst (pair s)
802 (invoke_codegen thy defs "<Top>" module false t gr))
803 (map (apsnd (expand o preprocess_term thy o prep_term thy)) xs) gr;
804 val code = map_filter
806 | (s', p) => SOME (string_of (Pretty.block
807 [str ("val " ^ s' ^ " ="), Pretty.brk 1, p, str ";"]))) ps;
808 val code' = space_implode "\n\n" code ^ "\n\n";
810 map_filter (fn (name, s) =>
811 if member (op =) (!mode) "library" andalso name = module andalso null code
813 else SOME (name, mk_struct name s))
814 ((if null code then I
815 else add_to_module module code')
816 (output_code (fst gr') (if_library "" module) ["<Top>"]))
818 (code'', del_nodes ["<Top>"] gr')
821 val generate_code_i = gen_generate_code Sign.cert_term;
823 gen_generate_code (Syntax.read_term o ProofContext.allow_dummies o ProofContext.init_global);
826 (**** Reflection ****)
828 val strip_tname = implode o tl o explode;
830 fun pretty_list xs = Pretty.block (str "[" ::
831 flat (separate [str ",", Pretty.brk 1] (map single xs)) @
834 fun mk_type p (TVar ((s, i), _)) = str
835 (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "T")
836 | mk_type p (TFree (s, _)) = str (strip_tname s ^ "T")
837 | mk_type p (Type (s, Ts)) = (if p then parens else I) (Pretty.block
838 [str "Type", Pretty.brk 1, str ("(\"" ^ s ^ "\","),
839 Pretty.brk 1, pretty_list (map (mk_type false) Ts), str ")"]);
841 fun mk_term_of gr module p (TVar ((s, i), _)) = str
842 (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "F")
843 | mk_term_of gr module p (TFree (s, _)) = str (strip_tname s ^ "F")
844 | mk_term_of gr module p (Type (s, Ts)) = (if p then parens else I)
845 (Pretty.block (separate (Pretty.brk 1)
846 (str (mk_qual_id module
847 (get_type_id' (fn s' => "term_of_" ^ s') gr s)) ::
849 [mk_term_of gr module true T, mk_type true T]) Ts)));
852 (**** Test data generators ****)
854 fun mk_gen gr module p xs a (TVar ((s, i), _)) = str
855 (strip_tname s ^ (if i = 0 then "" else string_of_int i) ^ "G")
856 | mk_gen gr module p xs a (TFree (s, _)) = str (strip_tname s ^ "G")
857 | mk_gen gr module p xs a (Type (tyc as (s, Ts))) = (if p then parens else I)
858 (Pretty.block (separate (Pretty.brk 1)
859 (str (mk_qual_id module (get_type_id' (fn s' => "gen_" ^ s') gr s) ^
860 (if member (op =) xs s then "'" else "")) ::
863 [mk_term_of gr module true T, mk_type true T,
864 mk_gen gr module true xs a U, mk_type true U]
866 [mk_gen gr module true xs a T, mk_type true T]) Ts) @
867 (if member (op =) xs s then [str a] else []))));
869 val test_fn : (int -> term list option) Unsynchronized.ref =
870 Unsynchronized.ref (fn _ => NONE);
872 fun test_term ctxt report t =
874 val thy = ProofContext.theory_of ctxt;
875 val (code, gr) = setmp_CRITICAL mode ["term_of", "test"]
876 (generate_code_i thy [] "Generated") [("testf", t)];
877 val Ts = map snd (fst (strip_abs t));
878 val args = map_index (fn (i, T) => ("arg" ^ string_of_int i, T)) Ts;
879 val s = "structure TestTerm =\nstruct\n\n" ^
880 cat_lines (map snd code) ^
881 "\nopen Generated;\n\n" ^ string_of
882 (Pretty.block [str "val () = Codegen.test_fn :=",
883 Pretty.brk 1, str ("(fn i =>"), Pretty.brk 1,
884 mk_let (map (fn (s, T) =>
885 (mk_tuple [str s, str (s ^ "_t")],
886 Pretty.block [mk_gen gr "Generated" false [] "" T, Pretty.brk 1,
888 (Pretty.block [str "if ",
889 mk_app false (str "testf") (map (str o fst) args),
890 Pretty.brk 1, str "then NONE",
891 Pretty.brk 1, str "else ",
892 Pretty.block [str "SOME ", Pretty.block (str "[" ::
893 Pretty.commas (map (fn (s, _) => str (s ^ "_t ()")) args) @
897 val _ = ML_Context.eval_text_in (SOME ctxt) false Position.none s;
898 val dummy_report = ([], false)
899 in (fn size => (! test_fn size, dummy_report)) end;
903 (**** Evaluator for terms ****)
905 val eval_result = Unsynchronized.ref (fn () => Bound 0);
907 fun eval_term thy t =
909 val ctxt = ProofContext.init_global thy;
912 val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
913 error "Term to be evaluated contains type variables";
914 val _ = (null (Term.add_vars t []) andalso null (Term.add_frees t [])) orelse
915 error "Term to be evaluated contains variables";
916 val (code, gr) = setmp_CRITICAL mode ["term_of"]
917 (generate_code_i thy [] "Generated")
918 [("result", Abs ("x", TFree ("'a", []), t))];
919 val s = "structure EvalTerm =\nstruct\n\n" ^
920 cat_lines (map snd code) ^
921 "\nopen Generated;\n\n" ^ string_of
922 (Pretty.block [str "val () = Codegen.eval_result := (fn () =>",
924 mk_app false (mk_term_of gr "Generated" false (fastype_of t))
928 val _ = NAMED_CRITICAL "codegen" (fn () => (* FIXME ??? *)
929 ML_Context.eval_text_in (SOME ctxt) false Position.none s);
933 val (_, evaluation_conv) = Context.>>> (Context.map_theory_result
934 (Thm.add_oracle (Binding.name "evaluation", fn ct =>
936 val thy = Thm.theory_of_cterm ct;
937 val t = Thm.term_of ct;
938 in Thm.cterm_of thy (Logic.mk_equals (t, eval_term thy t)) end)));
941 (**** Interface ****)
943 fun parse_mixfix rd s =
944 (case Scan.finite Symbol.stopper (Scan.repeat
946 || $$ "?" >> K Ignore
947 || $$ "\\<module>" >> K Module
948 || $$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length)
949 || $$ "{" |-- $$ "*" |-- Scan.repeat1
950 ( $$ "'" |-- Scan.one Symbol.is_regular
951 || Scan.unless ($$ "*" -- $$ "}") (Scan.one Symbol.is_regular)) --|
952 $$ "*" --| $$ "}" >> (Quote o rd o implode)
954 ( $$ "'" |-- Scan.one Symbol.is_regular
955 || Scan.unless ($$ "_" || $$ "?" || $$ "\\<module>" || $$ "/" || $$ "{" |-- $$ "*")
956 (Scan.one Symbol.is_regular)) >> (Pretty o str o implode)))
957 (Symbol.explode s) of
959 | _ => error ("Malformed annotation: " ^ quote s));
962 val _ = List.app Keyword.keyword ["attach", "file", "contains"];
964 fun strip_whitespace s = implode (fst (take_suffix (fn c => c = "\n" orelse c = " ")
965 (snd (take_prefix (fn c => c = "\n" orelse c = " ") (explode s))))) ^ "\n";
967 val parse_attach = Scan.repeat (Parse.$$$ "attach" |--
968 Scan.optional (Parse.$$$ "(" |-- Parse.xname --| Parse.$$$ ")") "" --
969 (Parse.verbatim >> strip_whitespace));
972 Outer_Syntax.command "types_code"
973 "associate types with target language types" Keyword.thy_decl
974 (Scan.repeat1 (Parse.xname --| Parse.$$$ "(" -- Parse.string --| Parse.$$$ ")" -- parse_attach) >>
975 (fn xs => Toplevel.theory (fn thy => fold (assoc_type o
976 (fn ((name, mfx), aux) => (name, (parse_mixfix
977 (Syntax.read_typ_global thy) mfx, aux)))) xs thy)));
980 Outer_Syntax.command "consts_code"
981 "associate constants with target language code" Keyword.thy_decl
984 Parse.$$$ "(" -- Parse.string --| Parse.$$$ ")" -- parse_attach) >>
985 (fn xs => Toplevel.theory (fn thy => fold (assoc_const o
986 (fn ((const, mfx), aux) =>
987 (const, (parse_mixfix (Syntax.read_term_global thy) mfx, aux)))) xs thy)));
990 Scan.optional (Parse.$$$ "(" |-- Parse.enum "," Parse.xname --| Parse.$$$ ")") (!mode) --
991 (if lib then Scan.optional Parse.name "" else Parse.name) --
992 Scan.option (Parse.$$$ "file" |-- Parse.name) --
993 (if lib then Scan.succeed []
994 else Scan.optional (Parse.$$$ "imports" |-- Scan.repeat1 Parse.name) []) --|
995 Parse.$$$ "contains" --
996 ( Scan.repeat1 (Parse.name --| Parse.$$$ "=" -- Parse.term)
997 || Scan.repeat1 (Parse.term >> pair "")) >>
998 (fn ((((mode', module), opt_fname), modules), xs) => Toplevel.theory (fn thy =>
1000 val mode'' = (if lib then insert (op =) "library" else I) (remove (op =) "library" mode');
1001 val (code, gr) = setmp_CRITICAL mode mode'' (generate_code thy modules module) xs;
1002 val thy' = thy |> Context.theory_map (ML_Context.exec (fn () =>
1004 NONE => ML_Context.eval_text false Position.none (cat_lines (map snd code))
1006 if lib then app (fn (name, s) => File.write
1007 (Path.append (Path.explode fname) (Path.basic (name ^ ".ML"))) s)
1008 (("ROOT", implode (map (fn (name, _) =>
1009 "use \"" ^ name ^ ".ML\";\n") code)) :: code)
1010 else File.write (Path.explode fname) (snd (hd code)))));
1013 else map_modules (Symtab.update (module, gr)) thy'
1016 val setup = add_codegen "default" default_codegen
1017 #> add_tycodegen "default" default_tycodegen
1018 #> add_preprocessor unfold_preprocessor;
1021 Outer_Syntax.command "code_library"
1022 "generates code for terms (one structure for each theory)" Keyword.thy_decl
1026 Outer_Syntax.command "code_module"
1027 "generates code for terms (single structure, incremental)" Keyword.thy_decl