fundamental treatment of undefined vs. universally partial replaces code_abort
1 (* Title: Tools/Code/code_target.ML
2 Author: Florian Haftmann, TU Muenchen
4 Generic infrastructure for target language data.
7 signature CODE_TARGET =
9 val cert_tyco: theory -> string -> string
10 val read_tyco: theory -> string -> string
11 val read_const_exprs: theory -> string list -> string list
13 val export_code_for: theory -> Path.T option -> string -> int option -> string -> Token.T list
14 -> Code_Thingol.naming -> Code_Thingol.program -> string list -> unit
15 val produce_code_for: theory -> string -> int option -> string -> Token.T list
16 -> Code_Thingol.naming -> Code_Thingol.program -> string list -> (string * string) list * string option list
17 val present_code_for: theory -> string -> int option -> string -> Token.T list
18 -> Code_Thingol.naming -> Code_Thingol.program -> string list * string list -> string
19 val check_code_for: theory -> string -> bool -> Token.T list
20 -> Code_Thingol.naming -> Code_Thingol.program -> string list -> unit
22 val export_code: theory -> string list
23 -> (((string * string) * Path.T option) * Token.T list) list -> unit
24 val produce_code: theory -> string list
25 -> string -> int option -> string -> Token.T list -> (string * string) list * string option list
26 val present_code: theory -> string list -> (Code_Thingol.naming -> string list)
27 -> string -> int option -> string -> Token.T list -> string
28 val check_code: theory -> string list
29 -> ((string * bool) * Token.T list) list -> unit
31 val generatedN: string
32 val evaluator: theory -> string -> Code_Thingol.naming -> Code_Thingol.program
33 -> string list -> ((string * class list) list * Code_Thingol.itype) * Code_Thingol.iterm
34 -> (string * string) list * string
37 type literals = Code_Printer.literals
38 val add_target: string * { serializer: serializer, literals: literals,
39 check: { env_var: string, make_destination: Path.T -> Path.T, make_command: string -> string } }
41 val extend_target: string *
42 (string * (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program))
44 val assert_target: theory -> string -> string
45 val the_literals: theory -> string -> literals
47 val parse_args: 'a parser -> Token.T list -> 'a
48 val serialization: (int -> Path.T option -> 'a -> unit)
49 -> (string list -> int -> 'a -> (string * string) list * (string -> string option))
50 -> 'a -> serialization
51 val set_default_code_width: int -> theory -> theory
53 type ('a, 'b, 'c, 'd, 'e, 'f) symbol_attr_decl
55 val set_identifiers: (string, string, string, string, string, string) symbol_attr_decl
57 type const_syntax = Code_Printer.const_syntax
58 type tyco_syntax = Code_Printer.tyco_syntax
59 val set_printings: (const_syntax, tyco_syntax, string, unit, unit, (string * string list)) symbol_attr_decl
61 val add_const_syntax: string -> string -> const_syntax option -> theory -> theory
62 val add_tyco_syntax: string -> string -> tyco_syntax option -> theory -> theory
63 val add_class_syntax: string -> class -> string option -> theory -> theory
64 val add_instance_syntax: string -> class * string -> unit option -> theory -> theory
65 val add_reserved: string -> string -> theory -> theory
66 val add_include: string -> string * (string * string list) option -> theory -> theory
68 val codegen_tool: string (*theory name*) -> string (*export_code expr*) -> unit
70 val setup: theory -> theory
73 structure Code_Target : CODE_TARGET =
76 open Basic_Code_Thingol;
78 type literals = Code_Printer.literals;
79 type ('a, 'b, 'c, 'd, 'e, 'f) symbol_attr_decl =
80 (string * (string * 'a option) list, string * (string * 'b option) list,
81 class * (string * 'c option) list, (class * class) * (string * 'd option) list,
82 (class * string) * (string * 'e option) list,
83 string * (string * 'f option) list) Code_Symbol.attr;
84 type identifier_data = (string, string, string, string, string, string) Code_Symbol.data;
86 type tyco_syntax = Code_Printer.tyco_syntax;
87 type const_syntax = Code_Printer.const_syntax;
90 (** checking and parsing of symbols **)
92 fun cert_const thy const =
94 val _ = if Sign.declared_const thy const then ()
95 else error ("No such constant: " ^ quote const);
98 fun cert_tyco thy tyco =
100 val _ = if Sign.declared_tyname thy tyco then ()
101 else error ("No such type constructor: " ^ quote tyco);
104 fun read_tyco thy = #1 o dest_Type
105 o Proof_Context.read_type_name_proper (Proof_Context.init_global thy) true;
107 fun cert_class thy class =
109 val _ = Axclass.get_info thy class;
112 fun read_class thy = Proof_Context.read_class (Proof_Context.init_global thy);
114 val parse_classrel_ident = Parse.class --| @{keyword "<"} -- Parse.class;
116 fun cert_inst thy (class, tyco) =
117 (cert_class thy class, cert_tyco thy tyco);
119 fun read_inst thy (raw_tyco, raw_class) =
120 (read_class thy raw_class, read_tyco thy raw_tyco);
122 val parse_inst_ident = Parse.xname --| @{keyword "::"} -- Parse.class;
125 Code_Symbol.map_attr (apfst (cert_const thy)) (apfst (cert_tyco thy))
126 (apfst (cert_class thy)) ((apfst o pairself) (cert_class thy)) (apfst (cert_inst thy)) I;
129 Code_Symbol.map_attr (apfst (Code.read_const thy)) (apfst (read_tyco thy))
130 (apfst (read_class thy)) ((apfst o pairself) (read_class thy)) (apfst (read_inst thy)) I;
132 fun check_name is_module s =
134 val _ = if s = "" then error "Bad empty code name" else ();
135 val xs = Long_Name.explode s;
136 val xs' = if is_module
137 then map (Name.desymbolize true) xs
138 else if length xs < 2
139 then error ("Bad code name without module component: " ^ quote s)
142 val (ys, y) = split_last xs;
143 val ys' = map (Name.desymbolize true) ys;
144 val y' = Name.desymbolize false y;
148 else error ("Invalid code name: " ^ quote s ^ "\n"
149 ^ "better try " ^ quote (Long_Name.implode xs'))
153 (** serializations and serializer **)
155 (* serialization: abstract nonsense to cover different destinies for generated code *)
157 datatype destination = Export of Path.T option | Produce | Present of string list;
158 type serialization = int -> destination -> ((string * string) list * (string -> string option)) option;
160 fun serialization output _ content width (Export some_path) =
161 (output width some_path content; NONE)
162 | serialization _ string content width Produce =
163 string [] width content |> SOME
164 | serialization _ string content width (Present stmt_names) =
165 string stmt_names width content
166 |> (apfst o map o apsnd) (Pretty.output (SOME width) o Pretty.str)
169 fun export some_path f = (f (Export some_path); ());
170 fun produce f = the (f Produce);
171 fun present stmt_names f = space_implode "\n\n" (map snd (fst (the (f (Present stmt_names)))));
174 (* serializers: functions producing serializations *)
176 type serializer = Token.T list
179 symbol_of: string -> Code_Symbol.symbol,
181 reserved_syms: string list,
182 identifiers: identifier_data,
183 includes: (string * Pretty.T) list,
184 class_syntax: string -> string option,
185 tyco_syntax: string -> Code_Printer.tyco_syntax option,
186 const_syntax: string -> Code_Printer.activated_const_syntax option }
187 -> Code_Thingol.program
190 datatype description =
191 Fundamental of { serializer: serializer,
193 check: { env_var: string, make_destination: Path.T -> Path.T,
194 make_command: string -> string } }
195 | Extension of string *
196 (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program);
201 datatype target = Target of {
203 description: description,
204 reserved: string list,
205 identifiers: identifier_data,
206 printings: (Code_Printer.const_syntax, Code_Printer.tyco_syntax, string, unit, unit,
207 (Pretty.T * string list)) Code_Symbol.data
210 fun make_target ((serial, description), (reserved, (identifiers, printings))) =
211 Target { serial = serial, description = description, reserved = reserved,
212 identifiers = identifiers, printings = printings };
213 fun map_target f (Target { serial, description, reserved, identifiers, printings }) =
214 make_target (f ((serial, description), (reserved, (identifiers, printings))));
215 fun merge_target strict target (Target { serial = serial1, description = description,
216 reserved = reserved1, identifiers = identifiers1, printings = printings1 },
217 Target { serial = serial2, description = _,
218 reserved = reserved2, identifiers = identifiers2, printings = printings2 }) =
219 if serial1 = serial2 orelse not strict then
220 make_target ((serial1, description), (merge (op =) (reserved1, reserved2),
221 (Code_Symbol.merge_data (identifiers1, identifiers2),
222 Code_Symbol.merge_data (printings1, printings2))))
224 error ("Incompatible targets: " ^ quote target);
226 fun the_description (Target { description, ... }) = description;
227 fun the_reserved (Target { reserved, ... }) = reserved;
228 fun the_identifiers (Target { identifiers , ... }) = identifiers;
229 fun the_printings (Target { printings, ... }) = printings;
231 structure Targets = Theory_Data
233 type T = target Symtab.table * int;
234 val empty = (Symtab.empty, 80);
236 fun merge ((target1, width1), (target2, width2)) : T =
237 (Symtab.join (merge_target true) (target1, target2), Int.max (width1, width2));
240 fun assert_target thy target = if Symtab.defined (fst (Targets.get thy)) target
242 else error ("Unknown code target language: " ^ quote target);
244 fun put_target (target, seri) thy =
246 val lookup_target = Symtab.lookup (fst (Targets.get thy));
248 of Extension (super, _) => if is_some (lookup_target super) then ()
249 else error ("Unknown code target language: " ^ quote super)
251 val overwriting = case (Option.map the_description o lookup_target) target
253 | SOME (Extension _) => true
254 | SOME (Fundamental _) => (case seri
255 of Extension _ => error ("Will not overwrite existing target " ^ quote target)
257 val _ = if overwriting
258 then warning ("Overwriting existing target " ^ quote target)
262 |> (Targets.map o apfst o Symtab.update)
263 (target, make_target ((serial (), seri),
264 ([], (Code_Symbol.empty_data, Code_Symbol.empty_data))))
267 fun add_target (target, seri) = put_target (target, Fundamental seri);
268 fun extend_target (target, (super, modify)) =
269 put_target (target, Extension (super, modify));
271 fun map_target_data target f thy =
273 val _ = assert_target thy target;
276 |> (Targets.map o apfst o Symtab.map_entry target o map_target o apsnd) f
279 fun map_reserved target =
280 map_target_data target o apfst;
281 fun map_identifiers target =
282 map_target_data target o apsnd o apfst;
283 fun map_printings target =
284 map_target_data target o apsnd o apsnd;
286 fun set_default_code_width k = (Targets.map o apsnd) (K k);
289 (** serializer usage **)
293 fun the_fundamental thy =
295 val (targets, _) = Targets.get thy;
296 fun fundamental target = case Symtab.lookup targets target
297 of SOME data => (case the_description data
298 of Fundamental data => data
299 | Extension (super, _) => fundamental super)
300 | NONE => error ("Unknown code target language: " ^ quote target);
303 fun the_literals thy = #literals o the_fundamental thy;
305 fun collapse_hierarchy thy =
307 val (targets, _) = Targets.get thy;
308 fun collapse target =
310 val data = case Symtab.lookup targets target
312 | NONE => error ("Unknown code target language: " ^ quote target);
313 in case the_description data
314 of Fundamental _ => (K I, data)
315 | Extension (super, modify) => let
316 val (modify', data') = collapse super
317 in (fn naming => modify' naming #> modify naming, merge_target false target (data', data)) end
323 fun activate_target thy target =
325 val (_, default_width) = Targets.get thy;
326 val (modify, data) = collapse_hierarchy thy target;
327 in (default_width, data, modify) end;
329 fun activate_const_syntax thy literals cs_data naming =
330 (Symtab.empty, naming)
331 |> fold_map (fn (c, data) => fn (tab, naming) =>
332 case Code_Thingol.lookup_const naming c
335 Code_Printer.activate_const_syntax thy literals c data naming
336 in (SOME name, (Symtab.update_new (name, syn) tab, naming')) end
337 | NONE => (NONE, (tab, naming))) cs_data
340 fun activate_syntax lookup_name things =
342 |> fold_map (fn (thing_identifier, data) => fn tab => case lookup_name thing_identifier
343 of SOME name => (SOME name, Symtab.update_new (name, data) tab)
344 | NONE => (NONE, tab)) things
347 fun activate_symbol_syntax thy literals naming printings =
349 val (names_const, (const_syntax, _)) =
350 activate_const_syntax thy literals (Code_Symbol.dest_constant_data printings) naming;
351 val (names_tyco, tyco_syntax) =
352 activate_syntax (Code_Thingol.lookup_tyco naming) (Code_Symbol.dest_type_constructor_data printings);
353 val (names_class, class_syntax) =
354 activate_syntax (Code_Thingol.lookup_class naming) (Code_Symbol.dest_type_class_data printings);
355 val names_inst = map_filter (Code_Thingol.lookup_instance naming o fst)
356 (Code_Symbol.dest_class_instance_data printings);
358 (names_const @ names_tyco @ names_class @ names_inst,
359 (const_syntax, tyco_syntax, class_syntax))
362 fun project_program thy names_hidden names1 program2 =
364 val ctxt = Proof_Context.init_global thy;
365 val names2 = subtract (op =) names_hidden names1;
366 val program3 = Graph.restrict (not o member (op =) names_hidden) program2;
367 val names4 = Graph.all_succs program3 names2;
368 val unimplemented = Code_Thingol.unimplemented program3;
370 if null unimplemented then ()
371 else error ("No code equations for " ^
372 commas (map (Proof_Context.extern_const ctxt) unimplemented));
373 val program4 = Graph.restrict (member (op =) names4) program3;
374 in (names4, program4) end;
376 fun prepare_serializer thy (serializer : serializer) literals reserved identifiers
377 printings module_name args naming proto_program names =
379 val (names_hidden, (const_syntax, tyco_syntax, class_syntax)) =
380 activate_symbol_syntax thy literals naming printings;
381 val (names_all, program) = project_program thy names_hidden names proto_program;
382 fun select_include (name, (content, cs)) =
383 if null cs orelse exists (fn c => case Code_Thingol.lookup_const naming c
384 of SOME name => member (op =) names_all name
386 then SOME (name, content) else NONE;
387 val includes = map_filter select_include (Code_Symbol.dest_module_data printings);
389 (serializer args (Proof_Context.init_global thy) {
390 symbol_of = Code_Thingol.symbol_of proto_program,
391 module_name = module_name,
392 reserved_syms = reserved,
393 identifiers = identifiers,
395 const_syntax = Symtab.lookup const_syntax,
396 tyco_syntax = Symtab.lookup tyco_syntax,
397 class_syntax = Symtab.lookup class_syntax },
401 fun mount_serializer thy target some_width module_name args naming program names =
403 val (default_width, data, modify) = activate_target thy target;
404 val serializer = case the_description data
405 of Fundamental seri => #serializer seri;
406 val (prepared_serializer, prepared_program) =
407 prepare_serializer thy serializer (the_literals thy target)
408 (the_reserved data) (the_identifiers data) (the_printings data)
409 module_name args naming (modify naming program) names
410 val width = the_default default_width some_width;
411 in (fn program => prepared_serializer program width, prepared_program) end;
413 fun invoke_serializer thy target some_width module_name args naming program names =
415 val check = if module_name = "" then I else check_name true;
416 val (mounted_serializer, prepared_program) = mount_serializer thy
417 target some_width (check module_name) args naming program names;
418 in mounted_serializer prepared_program end;
420 fun assert_module_name "" = error "Empty module name not allowed here"
421 | assert_module_name module_name = module_name;
423 fun using_master_directory thy =
424 Option.map (Path.append (File.pwd ()) o Path.append (Thy_Load.master_directory thy));
428 val generatedN = "Generated_Code";
430 fun export_code_for thy some_path target some_width module_name args =
431 export (using_master_directory thy some_path)
432 ooo invoke_serializer thy target some_width module_name args;
434 fun produce_code_for thy target some_width module_name args =
436 val serializer = invoke_serializer thy target some_width (assert_module_name module_name) args;
437 in fn naming => fn program => fn names =>
438 produce (serializer naming program names) |> apsnd (fn deresolve => map deresolve names)
441 fun present_code_for thy target some_width module_name args =
443 val serializer = invoke_serializer thy target some_width (assert_module_name module_name) args;
444 in fn naming => fn program => fn (names, selects) =>
445 present selects (serializer naming program names)
448 fun check_code_for thy target strict args naming program names_cs =
450 val { env_var, make_destination, make_command } =
451 (#check o the_fundamental thy) target;
454 val destination = make_destination p;
455 val _ = export (SOME destination) (invoke_serializer thy target (SOME 80)
456 generatedN args naming program names_cs);
457 val cmd = make_command generatedN;
459 if Isabelle_System.bash ("cd " ^ File.shell_path p ^ " && " ^ cmd ^ " 2>&1") <> 0
460 then error ("Code check failed for " ^ target ^ ": " ^ cmd)
464 if getenv env_var = ""
466 then error (env_var ^ " not set; cannot check code for " ^ target)
467 else warning (env_var ^ " not set; skipped checking code for " ^ target)
468 else Isabelle_System.with_tmp_dir "Code_Test" ext_check
471 fun evaluation mounted_serializer prepared_program consts ((vs, ty), t) =
473 val _ = if Code_Thingol.contains_dict_var t then
474 error "Term to be evaluated contains free dictionaries" else ();
475 val v' = singleton (Name.variant_list (map fst vs)) "a";
476 val vs' = (v', []) :: vs;
477 val ty' = Code_Thingol.fun_tyco `%% [ITyVar v', ty];
478 val value_name = "Value.value.value"
479 val program = prepared_program
480 |> Graph.new_node (value_name,
481 Code_Thingol.Fun (@{const_name dummy_pattern}, (((vs', ty'), [(([IVar NONE], t), (NONE, true))]), NONE)))
482 |> fold (curry (perhaps o try o Graph.add_edge) value_name) consts;
483 val (program_code, deresolve) = produce (mounted_serializer program);
484 val value_name' = the (deresolve value_name);
485 in (program_code, value_name') end;
487 fun evaluator thy target naming program consts =
489 val (mounted_serializer, prepared_program) = mount_serializer thy
490 target NONE generatedN [] naming program consts;
491 in evaluation mounted_serializer prepared_program consts end;
496 (* code generation *)
498 fun implemented_functions thy naming program =
500 val cs = Code_Thingol.unimplemented program;
501 val names = map_filter (Code_Thingol.lookup_const naming) cs;
502 in subtract (op =) (Graph.all_preds program names) (Graph.keys program) end;
504 fun read_const_exprs thy cs =
506 val (cs1, cs2) = Code_Thingol.read_const_exprs thy cs;
507 val (names2, (naming, program)) = Code_Thingol.consts_program thy true cs2;
508 val names3 = implemented_functions thy naming program;
509 val cs3 = map_filter (fn (c, name) =>
510 if member (op =) names3 name then SOME c else NONE) (cs2 ~~ names2);
511 in union (op =) cs3 cs1 end;
513 fun prep_destination "" = NONE
514 | prep_destination "-" = (legacy_feature "drop \"file\" argument entirely instead of \"-\""; NONE)
515 | prep_destination s = SOME (Path.explode s);
517 fun export_code thy cs seris =
519 val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
520 val _ = map (fn (((target, module_name), some_path), args) =>
521 export_code_for thy some_path target NONE module_name args naming program names_cs) seris;
524 fun export_code_cmd raw_cs seris thy = export_code thy (read_const_exprs thy raw_cs)
525 ((map o apfst o apsnd) prep_destination seris);
527 fun produce_code thy cs target some_width some_module_name args =
529 val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
530 in produce_code_for thy target some_width some_module_name args naming program names_cs end;
532 fun present_code thy cs names_stmt target some_width some_module_name args =
534 val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
535 in present_code_for thy target some_width some_module_name args naming program (names_cs, names_stmt naming) end;
537 fun check_code thy cs seris =
539 val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
540 val _ = map (fn ((target, strict), args) =>
541 check_code_for thy target strict args naming program names_cs) seris;
544 fun check_code_cmd raw_cs seris thy = check_code thy (read_const_exprs thy raw_cs) seris;
548 val parse_const_terms = Scan.repeat1 Args.term
549 >> (fn ts => fn thy => map (Code.check_const thy) ts);
551 fun parse_names category parse internalize lookup =
552 Scan.lift (Args.parens (Args.$$$ category)) |-- Scan.repeat1 parse
553 >> (fn xs => fn thy => fn naming => map_filter (lookup naming o internalize thy) xs);
555 val parse_consts = parse_names "consts" Args.term
556 Code.check_const Code_Thingol.lookup_const;
558 val parse_types = parse_names "types" (Scan.lift Args.name)
559 Sign.intern_type Code_Thingol.lookup_tyco;
561 val parse_classes = parse_names "classes" (Scan.lift Args.name)
562 Sign.intern_class Code_Thingol.lookup_class;
564 val parse_instances = parse_names "instances" (Scan.lift (Args.name --| Args.$$$ "::" -- Args.name))
565 (fn thy => fn (raw_tyco, raw_class) => (Sign.intern_class thy raw_class, Sign.intern_type thy raw_tyco))
566 Code_Thingol.lookup_instance;
571 Thy_Output.antiquotation @{binding code_stmts}
572 (parse_const_terms --
573 Scan.repeat (parse_consts || parse_types || parse_classes || parse_instances)
574 -- Scan.lift (Args.parens (Args.name -- Scan.option Parse.int)))
575 (fn {context = ctxt, ...} => fn ((mk_cs, mk_stmtss), (target, some_width)) =>
576 let val thy = Proof_Context.theory_of ctxt in
577 present_code thy (mk_cs thy)
578 (fn naming => maps (fn f => f thy naming) mk_stmtss)
579 target some_width "Example" []
585 (** serializer configuration **)
587 (* reserved symbol names *)
589 fun add_reserved target sym thy =
591 val (_, data) = collapse_hierarchy thy target;
592 val _ = if member (op =) (the_reserved data) sym
593 then error ("Reserved symbol " ^ quote sym ^ " already declared")
597 |> map_reserved target (insert (op =) sym)
601 (* checking of syntax *)
603 fun check_const_syntax thy c syn =
604 if Code_Printer.requires_args syn > Code.args_number thy c
605 then error ("Too many arguments in syntax for constant " ^ quote c)
608 fun check_tyco_syntax thy tyco syn =
609 if fst syn <> Sign.arity_number thy tyco
610 then error ("Number of arguments mismatch in syntax for type constructor " ^ quote tyco)
614 (* custom symbol names *)
616 fun arrange_name_decls x =
618 fun arrange is_module (sym, target_names) = map (fn (target, some_name) =>
619 (target, (sym, Option.map (check_name is_module) some_name))) target_names;
621 Code_Symbol.maps_attr' (arrange false) (arrange false) (arrange false)
622 (arrange false) (arrange false) (arrange true) x
625 fun cert_name_decls thy = cert_syms thy #> arrange_name_decls;
627 fun read_name_decls thy = read_syms thy #> arrange_name_decls;
629 fun set_identifier (target, sym_name) = map_identifiers target (Code_Symbol.set_data sym_name);
631 fun gen_set_identifiers prep_name_decl raw_name_decls thy =
632 fold set_identifier (prep_name_decl thy raw_name_decls) thy;
634 val set_identifiers = gen_set_identifiers cert_name_decls;
635 val set_identifiers_cmd = gen_set_identifiers read_name_decls;
637 fun add_module_alias_cmd target aliasses thy =
639 val _ = legacy_feature "prefer \"code_identifier\" over \"code_modulename\"";
641 fold (fn (sym, name) => set_identifier
642 (target, Code_Symbol.Module (sym, if name = "" then NONE else SOME (check_name true name))))
647 (* custom printings *)
649 fun arrange_printings prep_const thy =
651 fun arrange check (sym, target_syns) =
652 map (fn (target, some_syn) => (target, (sym, Option.map (check thy sym) some_syn))) target_syns;
654 Code_Symbol.maps_attr'
655 (arrange check_const_syntax) (arrange check_tyco_syntax)
656 (arrange ((K o K) I)) (arrange ((K o K) I)) (arrange ((K o K) I))
657 (arrange (fn thy => fn _ => fn (raw_content, raw_cs) =>
658 (Code_Printer.str raw_content, map (prep_const thy) raw_cs)))
661 fun cert_printings thy = cert_syms thy #> arrange_printings cert_const thy;
663 fun read_printings thy = read_syms thy #> arrange_printings Code.read_const thy;
665 fun set_printing (target, sym_syn) = map_printings target (Code_Symbol.set_data sym_syn);
667 fun gen_set_printings prep_print_decl raw_print_decls thy =
668 fold set_printing (prep_print_decl thy raw_print_decls) thy;
670 val set_printings = gen_set_printings cert_printings;
671 val set_printings_cmd = gen_set_printings read_printings;
673 fun gen_add_syntax Symbol prep_x prep_syn target raw_x some_raw_syn thy =
675 val _ = legacy_feature "prefer \"code_printing\" for custom serialisations"
676 val x = prep_x thy raw_x;
677 in set_printing (target, Symbol (x, Option.map (prep_syn thy x) some_raw_syn)) thy end;
679 fun gen_add_const_syntax prep_const =
680 gen_add_syntax Code_Symbol.Constant prep_const check_const_syntax;
682 fun gen_add_tyco_syntax prep_tyco =
683 gen_add_syntax Code_Symbol.Type_Constructor prep_tyco check_tyco_syntax;
685 fun gen_add_class_syntax prep_class =
686 gen_add_syntax Code_Symbol.Type_Class prep_class ((K o K) I);
688 fun gen_add_instance_syntax prep_inst =
689 gen_add_syntax Code_Symbol.Class_Instance prep_inst ((K o K) I);
691 fun gen_add_include prep_const target (name, some_content) thy =
692 gen_add_syntax Code_Symbol.Module (K I)
693 (fn thy => fn _ => fn (raw_content, raw_cs) => (Code_Printer.str raw_content, map (prep_const thy) raw_cs))
694 target name some_content thy;
697 (* concrete syntax *)
701 fun zip_list (x :: xs) f g =
704 fold_map (fn x => g |-- f >> pair x) xs
705 :|-- (fn xys => pair ((x, y) :: xys)));
707 fun process_multi_syntax parse_thing parse_syntax change =
708 (Parse.and_list1 parse_thing
709 :|-- (fn things => Scan.repeat1 (@{keyword "("} |-- Parse.name --
710 (zip_list things (Scan.option parse_syntax) @{keyword "and"}) --| @{keyword ")"})))
711 >> (Toplevel.theory oo fold)
712 (fn (target, syns) => fold (fn (raw_x, syn) => change target raw_x syn) syns);
716 val add_reserved = add_reserved;
717 val add_const_syntax = gen_add_const_syntax (K I);
718 val add_tyco_syntax = gen_add_tyco_syntax cert_tyco;
719 val add_class_syntax = gen_add_class_syntax cert_class;
720 val add_instance_syntax = gen_add_instance_syntax cert_inst;
721 val add_include = gen_add_include (K I);
723 val add_const_syntax_cmd = gen_add_const_syntax Code.read_const;
724 val add_tyco_syntax_cmd = gen_add_tyco_syntax read_tyco;
725 val add_class_syntax_cmd = gen_add_class_syntax read_class;
726 val add_instance_syntax_cmd = gen_add_instance_syntax read_inst;
727 val add_include_cmd = gen_add_include Code.read_const;
729 fun parse_args f args =
730 case Scan.read Token.stopper f args
732 | NONE => error "Bad serializer arguments";
737 fun parse_single_symbol_pragma parse_keyword parse_isa parse_target =
738 parse_keyword |-- Parse.!!! (parse_isa --| (@{keyword "\<rightharpoonup>"} || @{keyword "=>"})
739 -- Parse.and_list1 (@{keyword "("} |-- (Parse.name --| @{keyword ")"} -- Scan.option parse_target)));
741 fun parse_symbol_pragma parse_const parse_tyco parse_class parse_classrel parse_inst parse_module =
742 parse_single_symbol_pragma @{keyword "constant"} Parse.term parse_const
743 >> Code_Symbol.Constant
744 || parse_single_symbol_pragma @{keyword "type_constructor"} Parse.type_const parse_tyco
745 >> Code_Symbol.Type_Constructor
746 || parse_single_symbol_pragma @{keyword "type_class"} Parse.class parse_class
747 >> Code_Symbol.Type_Class
748 || parse_single_symbol_pragma @{keyword "class_relation"} parse_classrel_ident parse_classrel
749 >> Code_Symbol.Class_Relation
750 || parse_single_symbol_pragma @{keyword "class_instance"} parse_inst_ident parse_inst
751 >> Code_Symbol.Class_Instance
752 || parse_single_symbol_pragma @{keyword "code_module"} Parse.name parse_module
753 >> Code_Symbol.Module;
755 fun parse_symbol_pragmas parse_const parse_tyco parse_class parse_classrel parse_inst parse_module =
756 Parse.enum1 "|" (Parse.group (fn () => "code symbol pragma")
757 (parse_symbol_pragma parse_const parse_tyco parse_class parse_classrel parse_inst parse_module));
759 val code_expr_argsP = Scan.optional (@{keyword "("} |-- Args.parse --| @{keyword ")"}) [];
761 fun code_expr_inP raw_cs =
762 Scan.repeat (@{keyword "in"} |-- Parse.!!! (Parse.name
763 -- Scan.optional (@{keyword "module_name"} |-- Parse.name) ""
764 -- Scan.optional (@{keyword "file"} |-- Parse.name) ""
766 >> (fn seri_args => export_code_cmd raw_cs seri_args);
768 fun code_expr_checkingP raw_cs =
769 (@{keyword "checking"} |-- Parse.!!!
770 (Scan.repeat (Parse.name -- ((@{keyword "?"} |-- Scan.succeed false) || Scan.succeed true)
771 -- code_expr_argsP)))
772 >> (fn seri_args => check_code_cmd raw_cs seri_args);
774 val code_exprP = Scan.repeat1 Parse.term
775 :|-- (fn raw_cs => (code_expr_checkingP raw_cs || code_expr_inP raw_cs));
778 Outer_Syntax.command @{command_spec "code_reserved"}
779 "declare words as reserved for target language"
780 (Parse.name -- Scan.repeat1 Parse.name
781 >> (fn (target, reserveds) => (Toplevel.theory o fold (add_reserved target)) reserveds));
784 Outer_Syntax.command @{command_spec "code_identifier"} "declare mandatory names for code symbols"
785 (parse_symbol_pragmas Parse.name Parse.name Parse.name Parse.name Parse.name Parse.name
786 >> (Toplevel.theory o fold set_identifiers_cmd));
789 Outer_Syntax.command @{command_spec "code_modulename"} "alias module to other name"
790 (Parse.name -- Scan.repeat1 (Parse.name -- Parse.name)
791 >> (fn (target, modlnames) => (Toplevel.theory o add_module_alias_cmd target) modlnames));
794 Outer_Syntax.command @{command_spec "code_printing"} "declare dedicated printing for code symbols"
795 (parse_symbol_pragmas (Code_Printer.parse_const_syntax) (Code_Printer.parse_tyco_syntax)
796 Parse.string (Parse.minus >> K ()) (Parse.minus >> K ())
797 (Parse.text -- Scan.optional (@{keyword "attach"} |-- Scan.repeat1 Parse.term) [])
798 >> (Toplevel.theory o fold set_printings_cmd));
801 Outer_Syntax.command @{command_spec "code_const"} "define code syntax for constant"
802 (process_multi_syntax Parse.term Code_Printer.parse_const_syntax
803 add_const_syntax_cmd);
806 Outer_Syntax.command @{command_spec "code_type"} "define code syntax for type constructor"
807 (process_multi_syntax Parse.type_const Code_Printer.parse_tyco_syntax
808 add_tyco_syntax_cmd);
811 Outer_Syntax.command @{command_spec "code_class"} "define code syntax for class"
812 (process_multi_syntax Parse.class Parse.string
813 add_class_syntax_cmd);
816 Outer_Syntax.command @{command_spec "code_instance"} "define code syntax for instance"
817 (process_multi_syntax parse_inst_ident (Parse.minus >> K ())
818 add_instance_syntax_cmd);
821 Outer_Syntax.command @{command_spec "code_include"}
822 "declare piece of code to be included in generated code"
823 (Parse.name -- Parse.name -- (Parse.text :|--
824 (fn "-" => Scan.succeed NONE
825 | s => Scan.optional (@{keyword "attach"} |-- Scan.repeat1 Parse.term) [] >> pair s >> SOME))
826 >> (fn ((target, name), content_consts) =>
827 (Toplevel.theory o add_include_cmd target) (name, content_consts)));
830 Outer_Syntax.command @{command_spec "export_code"} "generate executable code for constants"
831 (Parse.!!! code_exprP >> (fn f => Toplevel.keep (f o Toplevel.theory_of)));
836 (** external entrance point -- for codegen tool **)
838 fun codegen_tool thyname cmd_expr =
840 val thy = Thy_Info.get_theory thyname;
841 val parse = Scan.read Token.stopper (Parse.!!! code_exprP) o
842 (filter Token.is_proper o Outer_Syntax.scan Position.none);
843 in case parse cmd_expr
844 of SOME f => (writeln "Now generating code..."; f thy)
845 | NONE => error ("Bad directive " ^ quote cmd_expr)
851 val setup = antiq_setup;