src/Tools/Code/code_target.ML
author haftmann
Thu Sep 23 13:23:22 2010 +0200 (2010-09-23)
changeset 39661 6381d18507ef
parent 39659 07549694e2f1
child 39679 d36864e3f06c
permissions -rw-r--r--
reverted cs 07549694e2f1 -- use re-printing with current print mode instead after code assembly, avoid Latex.output_typewriter
     1 (*  Title:      Tools/Code/code_target.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Generic infrastructure for target language data.
     5 *)
     6 
     7 signature CODE_TARGET =
     8 sig
     9   val cert_tyco: theory -> string -> string
    10   val read_tyco: theory -> string -> string
    11   val read_const_exprs: theory -> string list -> string list
    12 
    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 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
    21 
    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 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
    30 
    31   type serializer
    32   type literals = Code_Printer.literals
    33   val add_target: string * { serializer: serializer, literals: literals,
    34     check: { env_var: string, make_destination: Path.T -> Path.T,
    35       make_command: string -> string -> string } } -> theory -> theory
    36   val extend_target: string *
    37       (string * (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program))
    38     -> theory -> theory
    39   val assert_target: theory -> string -> string
    40   val the_literals: theory -> string -> literals
    41   type serialization
    42   val parse_args: 'a parser -> Token.T list -> 'a
    43   val serialization: (int -> Path.T option -> 'a -> unit)
    44     -> (string list -> int -> 'a -> string * (string -> string option))
    45     -> 'a -> serialization
    46   val set_default_code_width: int -> theory -> theory
    47 
    48   val allow_abort: string -> theory -> theory
    49   type tyco_syntax = Code_Printer.tyco_syntax
    50   type const_syntax = Code_Printer.const_syntax
    51   val add_class_syntax: string -> class -> string option -> theory -> theory
    52   val add_instance_syntax: string -> class * string -> unit option -> theory -> theory
    53   val add_tyco_syntax: string -> string -> tyco_syntax option -> theory -> theory
    54   val add_const_syntax: string -> string -> const_syntax option -> theory -> theory
    55   val add_reserved: string -> string -> theory -> theory
    56   val add_include: string -> string * (string * string list) option -> theory -> theory
    57 
    58   val codegen_tool: string (*theory name*) -> bool -> string (*export_code expr*) -> unit
    59 end;
    60 
    61 structure Code_Target : CODE_TARGET =
    62 struct
    63 
    64 open Basic_Code_Thingol;
    65 
    66 type literals = Code_Printer.literals;
    67 type tyco_syntax = Code_Printer.tyco_syntax;
    68 type const_syntax = Code_Printer.const_syntax;
    69 
    70 
    71 (** abstract nonsense **)
    72 
    73 datatype destination = Export of Path.T option | Produce | Present of string list;
    74 type serialization = int -> destination -> (string * (string -> string option)) option;
    75 
    76 fun serialization output _ content width (Export some_path) =
    77       (output width some_path content; NONE)
    78   | serialization _ string content width Produce =
    79       string [] width content |> SOME
    80   | serialization _ string content width (Present stmt_names) =
    81      string stmt_names width content
    82      |> apfst (Pretty.output (SOME width) o Pretty.str)
    83      |> SOME;
    84 
    85 fun export some_path f = (f (Export some_path); ());
    86 fun produce f = the (f Produce);
    87 fun present stmt_names f = fst (the (f (Present stmt_names)));
    88 
    89 
    90 (** theory data **)
    91 
    92 datatype symbol_syntax_data = Symbol_Syntax_Data of {
    93   class: string Symtab.table,
    94   instance: unit Symreltab.table,
    95   tyco: Code_Printer.tyco_syntax Symtab.table,
    96   const: Code_Printer.const_syntax Symtab.table
    97 };
    98 
    99 fun make_symbol_syntax_data ((class, instance), (tyco, const)) =
   100   Symbol_Syntax_Data { class = class, instance = instance, tyco = tyco, const = const };
   101 fun map_symbol_syntax_data f (Symbol_Syntax_Data { class, instance, tyco, const }) =
   102   make_symbol_syntax_data (f ((class, instance), (tyco, const)));
   103 fun merge_symbol_syntax_data
   104   (Symbol_Syntax_Data { class = class1, instance = instance1, tyco = tyco1, const = const1 },
   105     Symbol_Syntax_Data { class = class2, instance = instance2, tyco = tyco2, const = const2 }) =
   106   make_symbol_syntax_data (
   107     (Symtab.join (K snd) (class1, class2),
   108        Symreltab.join (K snd) (instance1, instance2)),
   109     (Symtab.join (K snd) (tyco1, tyco2),
   110        Symtab.join (K snd) (const1, const2))
   111   );
   112 
   113 type serializer = Token.T list
   114   -> {
   115     labelled_name: string -> string,
   116     reserved_syms: string list,
   117     includes: (string * Pretty.T) list,
   118     module_alias: string -> string option,
   119     class_syntax: string -> string option,
   120     tyco_syntax: string -> Code_Printer.tyco_syntax option,
   121     const_syntax: string -> Code_Printer.activated_const_syntax option,
   122     program: Code_Thingol.program }
   123   -> serialization;
   124 
   125 datatype description = Fundamental of { serializer: serializer,
   126       literals: literals,
   127       check: { env_var: string, make_destination: Path.T -> Path.T,
   128         make_command: string -> string -> string } }
   129   | Extension of string *
   130       (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program);
   131 
   132 datatype target = Target of {
   133   serial: serial,
   134   description: description,
   135   reserved: string list,
   136   includes: (Pretty.T * string list) Symtab.table,
   137   module_alias: string Symtab.table,
   138   symbol_syntax: symbol_syntax_data
   139 };
   140 
   141 fun make_target ((serial, description), ((reserved, includes), (module_alias, symbol_syntax))) =
   142   Target { serial = serial, description = description, reserved = reserved, 
   143     includes = includes, module_alias = module_alias, symbol_syntax = symbol_syntax };
   144 fun map_target f ( Target { serial, description, reserved, includes, module_alias, symbol_syntax } ) =
   145   make_target (f ((serial, description), ((reserved, includes), (module_alias, symbol_syntax))));
   146 fun merge_target strict target (Target { serial = serial1, description = description,
   147   reserved = reserved1, includes = includes1,
   148   module_alias = module_alias1, symbol_syntax = symbol_syntax1 },
   149     Target { serial = serial2, description = _,
   150       reserved = reserved2, includes = includes2,
   151       module_alias = module_alias2, symbol_syntax = symbol_syntax2 }) =
   152   if serial1 = serial2 orelse not strict then
   153     make_target ((serial1, description),
   154       ((merge (op =) (reserved1, reserved2), Symtab.join (K snd) (includes1, includes2)),
   155         (Symtab.join (K snd) (module_alias1, module_alias2),
   156           merge_symbol_syntax_data (symbol_syntax1, symbol_syntax2))
   157     ))
   158   else
   159     error ("Incompatible targets: " ^ quote target);
   160 
   161 fun the_description (Target { description, ... }) = description;
   162 fun the_reserved (Target { reserved, ... }) = reserved;
   163 fun the_includes (Target { includes, ... }) = includes;
   164 fun the_module_alias (Target { module_alias , ... }) = module_alias;
   165 fun the_symbol_syntax (Target { symbol_syntax = Symbol_Syntax_Data x, ... }) = x;
   166 
   167 structure Targets = Theory_Data
   168 (
   169   type T = (target Symtab.table * string list) * int;
   170   val empty = ((Symtab.empty, []), 80);
   171   val extend = I;
   172   fun merge (((target1, exc1), width1), ((target2, exc2), width2)) : T =
   173     ((Symtab.join (merge_target true) (target1, target2),
   174       Library.merge (op =) (exc1, exc2)), Int.max (width1, width2));
   175 );
   176 
   177 val abort_allowed = snd o fst o Targets.get;
   178 
   179 fun assert_target thy target = if Symtab.defined ((fst o fst) (Targets.get thy)) target
   180   then target
   181   else error ("Unknown code target language: " ^ quote target);
   182 
   183 fun put_target (target, seri) thy =
   184   let
   185     val lookup_target = Symtab.lookup ((fst o fst) (Targets.get thy));
   186     val _ = case seri
   187      of Extension (super, _) => if is_some (lookup_target super) then ()
   188           else error ("Unknown code target language: " ^ quote super)
   189       | _ => ();
   190     val overwriting = case (Option.map the_description o lookup_target) target
   191      of NONE => false
   192       | SOME (Extension _) => true
   193       | SOME (Fundamental _) => (case seri
   194          of Extension _ => error ("Will not overwrite existing target " ^ quote target)
   195           | _ => true);
   196     val _ = if overwriting
   197       then warning ("Overwriting existing target " ^ quote target)
   198       else (); 
   199   in
   200     thy
   201     |> (Targets.map o apfst o apfst o Symtab.update)
   202           (target, make_target ((serial (), seri), (([], Symtab.empty),
   203             (Symtab.empty, make_symbol_syntax_data ((Symtab.empty, Symreltab.empty),
   204               (Symtab.empty, Symtab.empty))))))
   205   end;
   206 
   207 fun add_target (target, seri) = put_target (target, Fundamental seri);
   208 fun extend_target (target, (super, modify)) =
   209   put_target (target, Extension (super, modify));
   210 
   211 fun map_target_data target f thy =
   212   let
   213     val _ = assert_target thy target;
   214   in
   215     thy
   216     |> (Targets.map o apfst o apfst o Symtab.map_entry target o map_target) f
   217   end;
   218 
   219 fun map_reserved target =
   220   map_target_data target o apsnd o apfst o apfst;
   221 fun map_includes target =
   222   map_target_data target o apsnd o apfst o apsnd;
   223 fun map_module_alias target =
   224   map_target_data target o apsnd o apsnd o apfst;
   225 fun map_symbol_syntax target =
   226   map_target_data target o apsnd o apsnd o apsnd o map_symbol_syntax_data;
   227 
   228 fun set_default_code_width k = (Targets.map o apsnd) (K k);
   229 
   230 
   231 (** serializer usage **)
   232 
   233 (* montage *)
   234 
   235 fun the_fundamental thy =
   236   let
   237     val ((targets, _), _) = Targets.get thy;
   238     fun fundamental target = case Symtab.lookup targets target
   239      of SOME data => (case the_description data
   240          of Fundamental data => data
   241           | Extension (super, _) => fundamental super)
   242       | NONE => error ("Unknown code target language: " ^ quote target);
   243   in fundamental end;
   244 
   245 fun the_literals thy = #literals o the_fundamental thy;
   246 
   247 local
   248 
   249 fun activate_target thy target =
   250   let
   251     val ((targets, abortable), default_width) = Targets.get thy;
   252     fun collapse_hierarchy target =
   253       let
   254         val data = case Symtab.lookup targets target
   255          of SOME data => data
   256           | NONE => error ("Unknown code target language: " ^ quote target);
   257       in case the_description data
   258        of Fundamental _ => (K I, data)
   259         | Extension (super, modify) => let
   260             val (modify', data') = collapse_hierarchy super
   261           in (fn naming => modify' naming #> modify naming, merge_target false target (data', data)) end
   262       end;
   263     val (modify, data) = collapse_hierarchy target;
   264   in (default_width, abortable, data, modify) end;
   265 
   266 fun activate_syntax lookup_name src_tab = Symtab.empty
   267   |> fold_map (fn thing_identifier => fn tab => case lookup_name thing_identifier
   268        of SOME name => (SOME name,
   269             Symtab.update_new (name, the (Symtab.lookup src_tab thing_identifier)) tab)
   270         | NONE => (NONE, tab)) (Symtab.keys src_tab)
   271   |>> map_filter I;
   272 
   273 fun activate_const_syntax thy literals src_tab naming = (Symtab.empty, naming)
   274   |> fold_map (fn c => fn (tab, naming) =>
   275       case Code_Thingol.lookup_const naming c
   276        of SOME name => let
   277               val (syn, naming') = Code_Printer.activate_const_syntax thy
   278                 literals c (the (Symtab.lookup src_tab c)) naming
   279             in (SOME name, (Symtab.update_new (name, syn) tab, naming')) end
   280         | NONE => (NONE, (tab, naming))) (Symtab.keys src_tab)
   281   |>> map_filter I;
   282 
   283 fun activate_symbol_syntax thy literals naming
   284     class_syntax instance_syntax tyco_syntax const_syntax =
   285   let
   286     val (names_class, class_syntax') =
   287       activate_syntax (Code_Thingol.lookup_class naming) class_syntax;
   288     val names_inst = map_filter (Code_Thingol.lookup_instance naming)
   289       (Symreltab.keys instance_syntax);
   290     val (names_tyco, tyco_syntax') =
   291       activate_syntax (Code_Thingol.lookup_tyco naming) tyco_syntax;
   292     val (names_const, (const_syntax', _)) =
   293       activate_const_syntax thy literals const_syntax naming;
   294   in
   295     (names_class @ names_inst @ names_tyco @ names_const,
   296       (class_syntax', tyco_syntax', const_syntax'))
   297   end;
   298 
   299 fun project_program thy abortable names_hidden names1 program2 =
   300   let
   301     val names2 = subtract (op =) names_hidden names1;
   302     val program3 = Graph.subgraph (not o member (op =) names_hidden) program2;
   303     val names4 = Graph.all_succs program3 names2;
   304     val empty_funs = filter_out (member (op =) abortable)
   305       (Code_Thingol.empty_funs program3);
   306     val _ = if null empty_funs then () else error ("No code equations for "
   307       ^ commas (map (Sign.extern_const thy) empty_funs));
   308     val program4 = Graph.subgraph (member (op =) names4) program3;
   309   in (names4, program4) end;
   310 
   311 fun invoke_serializer thy abortable serializer literals reserved all_includes
   312     module_alias proto_class_syntax proto_instance_syntax proto_tyco_syntax proto_const_syntax
   313     module_name args naming proto_program names =
   314   let
   315     val (names_hidden, (class_syntax, tyco_syntax, const_syntax)) =
   316       activate_symbol_syntax thy literals naming
   317         proto_class_syntax proto_instance_syntax proto_tyco_syntax proto_const_syntax;
   318     val (names_all, program) = project_program thy abortable names_hidden names proto_program;
   319     fun select_include (name, (content, cs)) =
   320       if null cs orelse exists (fn c => case Code_Thingol.lookup_const naming c
   321        of SOME name => member (op =) names_all name
   322         | NONE => false) cs
   323       then SOME (name, content) else NONE;
   324     val includes = map_filter select_include (Symtab.dest all_includes);
   325   in
   326     serializer args {
   327       labelled_name = Code_Thingol.labelled_name thy proto_program,
   328       reserved_syms = reserved,
   329       includes = includes,
   330       module_alias = if module_name = "" then Symtab.lookup module_alias else K (SOME module_name),
   331       class_syntax = Symtab.lookup class_syntax,
   332       tyco_syntax = Symtab.lookup tyco_syntax,
   333       const_syntax = Symtab.lookup const_syntax,
   334       program = program }
   335   end;
   336 
   337 fun mount_serializer thy target some_width module_name args =
   338   let
   339     val (default_width, abortable, data, modify) = activate_target thy target;
   340     val serializer = case the_description data
   341      of Fundamental seri => #serializer seri;
   342     val reserved = the_reserved data;
   343     val module_alias = the_module_alias data 
   344     val { class, instance, tyco, const } = the_symbol_syntax data;
   345     val literals = the_literals thy target;
   346     val width = the_default default_width some_width;
   347   in fn naming => fn program => fn names =>
   348     invoke_serializer thy abortable serializer literals reserved
   349       (the_includes data) module_alias class instance tyco const module_name args
   350         naming (modify naming program) names width
   351   end;
   352 
   353 fun assert_module_name "" = error ("Empty module name not allowed.")
   354   | assert_module_name module_name = module_name;
   355 
   356 in
   357 
   358 fun export_code_for thy some_path target some_width module_name args =
   359   export some_path ooo mount_serializer thy target some_width module_name args;
   360 
   361 fun produce_code_for thy target some_width module_name args =
   362   let
   363     val serializer = mount_serializer thy target some_width (assert_module_name module_name) args;
   364   in fn naming => fn program => fn names =>
   365     produce (serializer naming program names) |> apsnd (fn deresolve => map deresolve names)
   366   end;
   367 
   368 fun present_code_for thy target some_width module_name args =
   369   let
   370     val serializer = mount_serializer thy target some_width (assert_module_name module_name) args;
   371   in fn naming => fn program => fn (names, selects) =>
   372     present selects (serializer naming program names)
   373   end;
   374 
   375 fun check_code_for thy target strict args naming program names_cs =
   376   let
   377     val module_name = "Code";
   378     val { env_var, make_destination, make_command } =
   379       (#check o the_fundamental thy) target;
   380     val env_param = getenv env_var;
   381     fun ext_check env_param p =
   382       let 
   383         val destination = make_destination p;
   384         val _ = export (SOME destination) (mount_serializer thy target (SOME 80)
   385           module_name args naming program names_cs);
   386         val cmd = make_command env_param module_name;
   387       in if bash ("cd " ^ File.shell_path p ^ " && " ^ cmd ^ " 2>&1") <> 0
   388         then error ("Code check failed for " ^ target ^ ": " ^ cmd)
   389         else ()
   390       end;
   391   in if env_param = ""
   392     then if strict
   393       then error (env_var ^ " not set; cannot check code for " ^ target)
   394       else warning (env_var ^ " not set; skipped checking code for " ^ target)
   395     else Cache_IO.with_tmp_dir "Code_Test" (ext_check env_param)
   396   end;
   397 
   398 end; (* local *)
   399 
   400 
   401 (* code generation *)
   402 
   403 fun transitivly_non_empty_funs thy naming program =
   404   let
   405     val cs = subtract (op =) (abort_allowed thy) (Code_Thingol.empty_funs program);
   406     val names = map_filter (Code_Thingol.lookup_const naming) cs;
   407   in subtract (op =) (Graph.all_preds program names) (Graph.keys program) end;
   408 
   409 fun read_const_exprs thy cs =
   410   let
   411     val (cs1, cs2) = Code_Thingol.read_const_exprs thy cs;
   412     val (names2, (naming, program)) = Code_Thingol.consts_program thy true cs2;
   413     val names3 = transitivly_non_empty_funs thy naming program;
   414     val cs3 = map_filter (fn (c, name) =>
   415       if member (op =) names3 name then SOME c else NONE) (cs2 ~~ names2);
   416   in union (op =) cs3 cs1 end;
   417 
   418 fun prep_destination "" = NONE
   419   | prep_destination "-" = NONE
   420   | prep_destination s = SOME (Path.explode s);
   421 
   422 fun export_code thy cs seris =
   423   let
   424     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   425     val _ = map (fn (((target, module_name), some_path), args) =>
   426       export_code_for thy some_path target NONE module_name args naming program names_cs) seris;
   427   in () end;
   428 
   429 fun export_code_cmd raw_cs seris thy = export_code thy (read_const_exprs thy raw_cs)
   430   ((map o apfst o apsnd) prep_destination seris);
   431 
   432 fun produce_code thy cs target some_width some_module_name args =
   433   let
   434     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   435   in produce_code_for thy target some_width some_module_name args naming program names_cs end;
   436 
   437 fun present_code thy cs names_stmt target some_width some_module_name args =
   438   let
   439     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   440   in present_code_for thy target some_width some_module_name args naming program (names_cs, names_stmt naming) end;
   441 
   442 fun check_code thy cs seris =
   443   let
   444     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   445     val _ = map (fn ((target, strict), args) =>
   446       check_code_for thy target strict args naming program names_cs) seris;
   447   in () end;
   448 
   449 fun check_code_cmd raw_cs seris thy = check_code thy (read_const_exprs thy raw_cs) seris;
   450 
   451 local
   452 
   453 val parse_const_terms = Scan.repeat1 Args.term
   454   >> (fn ts => fn thy => map (Code.check_const thy) ts);
   455 
   456 fun parse_names category parse internalize lookup =
   457   Scan.lift (Args.parens (Args.$$$ category)) |-- Scan.repeat1 parse
   458   >> (fn xs => fn thy => fn naming => map_filter (lookup naming o internalize thy) xs);
   459   
   460 val parse_consts = parse_names "consts" Args.term
   461   Code.check_const Code_Thingol.lookup_const ;
   462 
   463 val parse_types = parse_names "types" (Scan.lift Args.name)
   464   Sign.intern_type Code_Thingol.lookup_tyco;
   465 
   466 val parse_classes = parse_names "classes" (Scan.lift Args.name)
   467   Sign.intern_class Code_Thingol.lookup_class;
   468 
   469 val parse_instances = parse_names "instances" (Scan.lift (Args.name --| Args.$$$ "::" -- Args.name))
   470   (fn thy => fn (raw_tyco, raw_class) => (Sign.intern_class thy raw_class, Sign.intern_type thy raw_tyco))
   471     Code_Thingol.lookup_instance;
   472 
   473 in
   474 
   475 val _ = Thy_Output.antiquotation "code_stmts"
   476   (parse_const_terms -- Scan.repeat (parse_consts || parse_types || parse_classes || parse_instances)
   477     -- Scan.lift (Args.parens (Args.name -- Scan.option Parse.int)))
   478   (fn {context = ctxt, ...} => fn ((mk_cs, mk_stmtss), (target, some_width)) =>
   479     let val thy = ProofContext.theory_of ctxt in
   480       present_code thy (mk_cs thy)
   481         (fn naming => maps (fn f => f thy naming) mk_stmtss)
   482         target some_width "Example" []
   483       (*|> Latex.output_typewriter*)
   484     end);
   485 
   486 end;
   487 
   488 
   489 (** serializer configuration **)
   490 
   491 (* data access *)
   492 
   493 fun cert_class thy class =
   494   let
   495     val _ = AxClass.get_info thy class;
   496   in class end;
   497 
   498 fun read_class thy = cert_class thy o Sign.intern_class thy;
   499 
   500 fun cert_tyco thy tyco =
   501   let
   502     val _ = if Sign.declared_tyname thy tyco then ()
   503       else error ("No such type constructor: " ^ quote tyco);
   504   in tyco end;
   505 
   506 fun read_tyco thy = cert_tyco thy o Sign.intern_type thy;
   507 
   508 fun cert_inst thy (class, tyco) =
   509   (cert_class thy class, cert_tyco thy tyco);
   510 
   511 fun read_inst thy (raw_tyco, raw_class) =
   512   (read_class thy raw_class, read_tyco thy raw_tyco);
   513 
   514 fun gen_add_syntax (mapp, upd, del) prep_x prep_syn target raw_x some_raw_syn thy =
   515   let
   516     val x = prep_x thy raw_x;
   517     val change = case some_raw_syn
   518      of SOME raw_syn => upd (x, prep_syn thy x raw_syn)
   519       | NONE => del x;
   520   in (map_symbol_syntax target o mapp) change thy end;
   521 
   522 fun gen_add_class_syntax prep_class =
   523   gen_add_syntax (apfst o apfst, Symtab.update, Symtab.delete_safe) prep_class ((K o K) I);
   524 
   525 fun gen_add_instance_syntax prep_inst =
   526   gen_add_syntax (apfst o apsnd, Symreltab.update, Symreltab.delete_safe) prep_inst ((K o K) I);
   527 
   528 fun gen_add_tyco_syntax prep_tyco =
   529   gen_add_syntax (apsnd o apfst, Symtab.update, Symtab.delete_safe) prep_tyco
   530     (fn thy => fn tyco => fn syn => if fst syn <> Sign.arity_number thy tyco
   531       then error ("Number of arguments mismatch in syntax for type constructor " ^ quote tyco)
   532       else syn);
   533 
   534 fun gen_add_const_syntax prep_const =
   535   gen_add_syntax (apsnd o apsnd, Symtab.update, Symtab.delete_safe) prep_const
   536     (fn thy => fn c => fn syn =>
   537       if Code_Printer.requires_args syn > Code.args_number thy c
   538       then error ("Too many arguments in syntax for constant " ^ quote c)
   539       else syn);
   540 
   541 fun add_reserved target =
   542   let
   543     fun add sym syms = if member (op =) syms sym
   544       then error ("Reserved symbol " ^ quote sym ^ " already declared")
   545       else insert (op =) sym syms
   546   in map_reserved target o add end;
   547 
   548 fun gen_add_include read_const target args thy =
   549   let
   550     fun add (name, SOME (content, raw_cs)) incls =
   551           let
   552             val _ = if Symtab.defined incls name
   553               then warning ("Overwriting existing include " ^ name)
   554               else ();
   555             val cs = map (read_const thy) raw_cs;
   556           in Symtab.update (name, (Code_Printer.str content, cs)) incls end
   557       | add (name, NONE) incls = Symtab.delete name incls;
   558   in map_includes target (add args) thy end;
   559 
   560 val add_include = gen_add_include (K I);
   561 val add_include_cmd = gen_add_include Code.read_const;
   562 
   563 fun add_module_alias target (thyname, "") =
   564       map_module_alias target (Symtab.delete thyname)
   565   | add_module_alias target (thyname, modlname) =
   566       let
   567         val xs = Long_Name.explode modlname;
   568         val xs' = map (Name.desymbolize true) xs;
   569       in if xs' = xs
   570         then map_module_alias target (Symtab.update (thyname, modlname))
   571         else error ("Invalid module name: " ^ quote modlname ^ "\n"
   572           ^ "perhaps try " ^ quote (Long_Name.implode xs'))
   573       end;
   574 
   575 fun gen_allow_abort prep_const raw_c thy =
   576   let
   577     val c = prep_const thy raw_c;
   578   in thy |> (Targets.map o apfst o apsnd) (insert (op =) c) end;
   579 
   580 
   581 (* concrete syntax *)
   582 
   583 local
   584 
   585 fun zip_list (x::xs) f g =
   586   f
   587   :|-- (fn y =>
   588     fold_map (fn x => g |-- f >> pair x) xs
   589     :|-- (fn xys => pair ((x, y) :: xys)));
   590 
   591 fun process_multi_syntax parse_thing parse_syntax change =
   592   (Parse.and_list1 parse_thing
   593   :|-- (fn things => Scan.repeat1 (Parse.$$$ "(" |-- Parse.name --
   594         (zip_list things parse_syntax (Parse.$$$ "and")) --| Parse.$$$ ")")))
   595   >> (Toplevel.theory oo fold)
   596     (fn (target, syns) => fold (fn (raw_x, syn) => change target raw_x syn) syns);
   597 
   598 in
   599 
   600 val add_class_syntax = gen_add_class_syntax cert_class;
   601 val add_instance_syntax = gen_add_instance_syntax cert_inst;
   602 val add_tyco_syntax = gen_add_tyco_syntax cert_tyco;
   603 val add_const_syntax = gen_add_const_syntax (K I);
   604 val allow_abort = gen_allow_abort (K I);
   605 val add_reserved = add_reserved;
   606 val add_include = add_include;
   607 
   608 val add_class_syntax_cmd = gen_add_class_syntax read_class;
   609 val add_instance_syntax_cmd = gen_add_instance_syntax read_inst;
   610 val add_tyco_syntax_cmd = gen_add_tyco_syntax read_tyco;
   611 val add_const_syntax_cmd = gen_add_const_syntax Code.read_const;
   612 val allow_abort_cmd = gen_allow_abort Code.read_const;
   613 
   614 fun parse_args f args =
   615   case Scan.read Token.stopper f args
   616    of SOME x => x
   617     | NONE => error "Bad serializer arguments";
   618 
   619 
   620 (** Isar setup **)
   621 
   622 val (inK, module_nameK, fileK, checkingK) = ("in", "module_name", "file", "checking");
   623 
   624 val code_expr_argsP = Scan.optional (Parse.$$$ "(" |-- Args.parse --| Parse.$$$ ")") [];
   625 
   626 val code_exprP =
   627   Scan.repeat1 Parse.term_group :|-- (fn raw_cs =>
   628     ((Parse.$$$ checkingK |-- Scan.repeat (Parse.name
   629       -- ((Parse.$$$ "?" |-- Scan.succeed false) || Scan.succeed true) -- code_expr_argsP))
   630       >> (fn seris => check_code_cmd raw_cs seris)
   631     || Scan.repeat (Parse.$$$ inK |-- Parse.name
   632        -- Scan.optional (Parse.$$$ module_nameK |-- Parse.name) ""
   633        -- Scan.optional (Parse.$$$ fileK |-- Parse.name) ""
   634        -- code_expr_argsP) >> (fn seris => export_code_cmd raw_cs seris)));
   635 
   636 val _ = List.app Keyword.keyword [inK, module_nameK, fileK, checkingK];
   637 
   638 val _ =
   639   Outer_Syntax.command "code_class" "define code syntax for class" Keyword.thy_decl (
   640     process_multi_syntax Parse.xname (Scan.option Parse.string)
   641     add_class_syntax_cmd);
   642 
   643 val _ =
   644   Outer_Syntax.command "code_instance" "define code syntax for instance" Keyword.thy_decl (
   645     process_multi_syntax (Parse.xname --| Parse.$$$ "::" -- Parse.xname)
   646       (Scan.option (Parse.minus >> K ()))
   647     add_instance_syntax_cmd);
   648 
   649 val _ =
   650   Outer_Syntax.command "code_type" "define code syntax for type constructor" Keyword.thy_decl (
   651     process_multi_syntax Parse.xname Code_Printer.parse_tyco_syntax
   652     add_tyco_syntax_cmd);
   653 
   654 val _ =
   655   Outer_Syntax.command "code_const" "define code syntax for constant" Keyword.thy_decl (
   656     process_multi_syntax Parse.term_group Code_Printer.parse_const_syntax
   657     add_const_syntax_cmd);
   658 
   659 val _ =
   660   Outer_Syntax.command "code_reserved" "declare words as reserved for target language"
   661     Keyword.thy_decl (
   662     Parse.name -- Scan.repeat1 Parse.name
   663     >> (fn (target, reserveds) => (Toplevel.theory o fold (add_reserved target)) reserveds)
   664   );
   665 
   666 val _ =
   667   Outer_Syntax.command "code_include" "declare piece of code to be included in generated code"
   668     Keyword.thy_decl (
   669     Parse.name -- Parse.name -- (Parse.text :|-- (fn "-" => Scan.succeed NONE
   670       | s => Scan.optional (Parse.$$$ "attach" |-- Scan.repeat1 Parse.term) [] >> pair s >> SOME))
   671     >> (fn ((target, name), content_consts) =>
   672         (Toplevel.theory o add_include_cmd target) (name, content_consts))
   673   );
   674 
   675 val _ =
   676   Outer_Syntax.command "code_modulename" "alias module to other name" Keyword.thy_decl (
   677     Parse.name -- Scan.repeat1 (Parse.name -- Parse.name)
   678     >> (fn (target, modlnames) => (Toplevel.theory o fold (add_module_alias target)) modlnames)
   679   );
   680 
   681 val _ =
   682   Outer_Syntax.command "code_abort" "permit constant to be implemented as program abort"
   683     Keyword.thy_decl (
   684     Scan.repeat1 Parse.term_group >> (Toplevel.theory o fold allow_abort_cmd)
   685   );
   686 
   687 val _ =
   688   Outer_Syntax.command "export_code" "generate executable code for constants"
   689     Keyword.diag (Parse.!!! code_exprP >> (fn f => Toplevel.keep (f o Toplevel.theory_of)));
   690 
   691 end; (*local*)
   692 
   693 
   694 (** external entrance point -- for codegen tool **)
   695 
   696 fun codegen_tool thyname qnd cmd_expr =
   697   let
   698     val thy = Thy_Info.get_theory thyname;
   699     val _ = quick_and_dirty := qnd;
   700     val parse = Scan.read Token.stopper (Parse.!!! code_exprP) o
   701       (filter Token.is_proper o Outer_Syntax.scan Position.none);
   702   in case parse cmd_expr
   703    of SOME f => (writeln "Now generating code..."; f thy)
   704     | NONE => error ("Bad directive " ^ quote cmd_expr)
   705   end;
   706 
   707 end; (*struct*)