src/Tools/Code/code_target.ML
author haftmann
Mon Aug 30 15:01:32 2010 +0200 (2010-08-30)
changeset 38909 919c924067f3
parent 38908 732149f6ebf9
child 38910 6af1d8673cbf
permissions -rw-r--r--
whitespace tuning
     1 (*  Title:      Tools/Code/code_target.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Generic infrastructure for serializers from intermediate language ("Thin-gol"
     5 to target languages.
     6 *)
     7 
     8 signature CODE_TARGET =
     9 sig
    10   val cert_tyco: theory -> string -> string
    11   val read_tyco: theory -> string -> string
    12 
    13   type serializer
    14   type literals = Code_Printer.literals
    15   val add_target: string * { serializer: serializer, literals: literals,
    16     check: { env_var: string, make_destination: Path.T -> Path.T,
    17       make_command: string -> string -> string } } -> theory -> theory
    18   val extend_target: string *
    19       (string * (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program))
    20     -> theory -> theory
    21   val assert_target: theory -> string -> string
    22 
    23   type destination
    24   type serialization
    25   val parse_args: 'a parser -> Token.T list -> 'a
    26   val stmt_names_of_destination: destination -> string list
    27   val mk_serialization: string -> (Path.T option -> 'a -> unit)
    28     -> ('a -> string * string option list)
    29     -> 'a -> serialization
    30   val serialize: theory -> string -> int option -> string option -> Token.T list
    31     -> Code_Thingol.naming -> Code_Thingol.program -> string list -> serialization
    32   val serialize_custom: theory -> string * serializer -> string option
    33     -> Code_Thingol.naming -> Code_Thingol.program -> string list
    34     -> string * string option list
    35   val the_literals: theory -> string -> literals
    36   val export: serialization -> unit
    37   val file: Path.T -> serialization -> unit
    38   val string: string list -> serialization -> string
    39   val code_of: theory -> string -> int option -> string
    40     -> string list -> (Code_Thingol.naming -> string list) -> string
    41   val set_default_code_width: int -> theory -> theory
    42   val shell_command: string (*theory name*) -> string (*export_code expr*) -> unit
    43 
    44   val allow_abort: string -> theory -> theory
    45   type tyco_syntax = Code_Printer.tyco_syntax
    46   type const_syntax = Code_Printer.const_syntax
    47   val add_syntax_class: string -> class -> string option -> theory -> theory
    48   val add_syntax_inst: string -> class * string -> unit option -> theory -> theory
    49   val add_syntax_tyco: string -> string -> tyco_syntax option -> theory -> theory
    50   val add_syntax_const: string -> string -> const_syntax option -> theory -> theory
    51   val add_reserved: string -> string -> theory -> theory
    52   val add_include: string -> string * (string * string list) option -> theory -> theory
    53 end;
    54 
    55 structure Code_Target : CODE_TARGET =
    56 struct
    57 
    58 open Basic_Code_Thingol;
    59 
    60 type literals = Code_Printer.literals;
    61 type tyco_syntax = Code_Printer.tyco_syntax;
    62 type const_syntax = Code_Printer.const_syntax;
    63 
    64 
    65 (** basics **)
    66 
    67 datatype destination = Export | File of Path.T | String of string list;
    68 type serialization = destination -> (string * string option list) option;
    69 
    70 fun export f = (f Export; ());
    71 fun file p f = (f (File p); ());
    72 fun string stmts f = fst (the (f (String stmts)));
    73 
    74 fun stmt_names_of_destination (String stmts) = stmts
    75   | stmt_names_of_destination _ = [];
    76 
    77 fun mk_serialization target output _ code Export = (output NONE code ; NONE)
    78   | mk_serialization target output _ code (File file) = (output (SOME file) code; NONE)
    79   | mk_serialization target _ string code (String _) = SOME (string code);
    80 
    81 
    82 (** theory data **)
    83 
    84 datatype name_syntax_table = NameSyntaxTable of {
    85   class: string Symtab.table,
    86   instance: unit Symreltab.table,
    87   tyco: Code_Printer.tyco_syntax Symtab.table,
    88   const: Code_Printer.const_syntax Symtab.table
    89 };
    90 
    91 fun mk_name_syntax_table ((class, instance), (tyco, const)) =
    92   NameSyntaxTable { class = class, instance = instance, tyco = tyco, const = const };
    93 fun map_name_syntax_table f (NameSyntaxTable { class, instance, tyco, const }) =
    94   mk_name_syntax_table (f ((class, instance), (tyco, const)));
    95 fun merge_name_syntax_table
    96   (NameSyntaxTable { class = class1, instance = instance1, tyco = tyco1, const = const1 },
    97     NameSyntaxTable { class = class2, instance = instance2, tyco = tyco2, const = const2 }) =
    98   mk_name_syntax_table (
    99     (Symtab.join (K snd) (class1, class2),
   100        Symreltab.join (K snd) (instance1, instance2)),
   101     (Symtab.join (K snd) (tyco1, tyco2),
   102        Symtab.join (K snd) (const1, const2))
   103   );
   104 
   105 type serializer =
   106   string option                         (*module name*)
   107   -> Token.T list                       (*arguments*)
   108   -> (string -> string)                 (*labelled_name*)
   109   -> string list                        (*reserved symbols*)
   110   -> (string * Pretty.T) list           (*includes*)
   111   -> (string -> string option)          (*module aliasses*)
   112   -> (string -> string option)          (*class syntax*)
   113   -> (string -> Code_Printer.tyco_syntax option)
   114   -> (string -> Code_Printer.activated_const_syntax option)
   115   -> ((Pretty.T -> string) * (Pretty.T -> unit))
   116   -> Code_Thingol.program
   117   -> (string list * string list)        (*selected statements*)
   118   -> serialization;
   119 
   120 datatype description = Fundamental of { serializer: serializer,
   121       literals: Code_Printer.literals,
   122       check: { env_var: string, make_destination: Path.T -> Path.T,
   123         make_command: string -> string -> string } }
   124   | Extension of string *
   125       (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program);
   126 
   127 datatype target = Target of {
   128   serial: serial,
   129   description: description,
   130   reserved: string list,
   131   includes: (Pretty.T * string list) Symtab.table,
   132   name_syntax_table: name_syntax_table,
   133   module_alias: string Symtab.table
   134 };
   135 
   136 fun make_target ((serial, description), ((reserved, includes), (name_syntax_table, module_alias))) =
   137   Target { serial = serial, description = description, reserved = reserved, 
   138     includes = includes, name_syntax_table = name_syntax_table, module_alias = module_alias };
   139 fun map_target f ( Target { serial, description, reserved, includes, name_syntax_table, module_alias } ) =
   140   make_target (f ((serial, description), ((reserved, includes), (name_syntax_table, module_alias))));
   141 fun merge_target strict target (Target { serial = serial1, description = description,
   142   reserved = reserved1, includes = includes1,
   143   name_syntax_table = name_syntax_table1, module_alias = module_alias1 },
   144     Target { serial = serial2, description = _,
   145       reserved = reserved2, includes = includes2,
   146       name_syntax_table = name_syntax_table2, module_alias = module_alias2 }) =
   147   if serial1 = serial2 orelse not strict then
   148     make_target ((serial1, description),
   149       ((merge (op =) (reserved1, reserved2), Symtab.join (K snd) (includes1, includes2)),
   150         (merge_name_syntax_table (name_syntax_table1, name_syntax_table2),
   151           Symtab.join (K snd) (module_alias1, module_alias2))
   152     ))
   153   else
   154     error ("Incompatible targets: " ^ quote target);
   155 
   156 fun the_description (Target { description, ... }) = description;
   157 fun the_reserved (Target { reserved, ... }) = reserved;
   158 fun the_includes (Target { includes, ... }) = includes;
   159 fun the_name_syntax (Target { name_syntax_table = NameSyntaxTable x, ... }) = x;
   160 fun the_module_alias (Target { module_alias , ... }) = module_alias;
   161 
   162 structure Targets = Theory_Data
   163 (
   164   type T = (target Symtab.table * string list) * int;
   165   val empty = ((Symtab.empty, []), 80);
   166   val extend = I;
   167   fun merge (((target1, exc1), width1), ((target2, exc2), width2)) : T =
   168     ((Symtab.join (merge_target true) (target1, target2),
   169       Library.merge (op =) (exc1, exc2)), Int.max (width1, width2));
   170 );
   171 
   172 val abort_allowed = snd o fst o Targets.get;
   173 
   174 fun assert_target thy target = if Symtab.defined ((fst o fst) (Targets.get thy)) target
   175   then target
   176   else error ("Unknown code target language: " ^ quote target);
   177 
   178 fun put_target (target, seri) thy =
   179   let
   180     val lookup_target = Symtab.lookup ((fst o fst) (Targets.get thy));
   181     val _ = case seri
   182      of Extension (super, _) => if is_some (lookup_target super) then ()
   183           else error ("Unknown code target language: " ^ quote super)
   184       | _ => ();
   185     val overwriting = case (Option.map the_description o lookup_target) target
   186      of NONE => false
   187       | SOME (Extension _) => true
   188       | SOME (Fundamental _) => (case seri
   189          of Extension _ => error ("Will not overwrite existing target " ^ quote target)
   190           | _ => true);
   191     val _ = if overwriting
   192       then warning ("Overwriting existing target " ^ quote target)
   193       else (); 
   194   in
   195     thy
   196     |> (Targets.map o apfst o apfst o Symtab.update)
   197           (target, make_target ((serial (), seri), (([], Symtab.empty),
   198             (mk_name_syntax_table ((Symtab.empty, Symreltab.empty),
   199               (Symtab.empty, Symtab.empty)), Symtab.empty))))
   200   end;
   201 
   202 fun add_target (target, seri) = put_target (target, Fundamental seri);
   203 fun extend_target (target, (super, modify)) =
   204   put_target (target, Extension (super, modify));
   205 
   206 fun map_target_data target f thy =
   207   let
   208     val _ = assert_target thy target;
   209   in
   210     thy
   211     |> (Targets.map o apfst o apfst o Symtab.map_entry target o map_target) f
   212   end;
   213 
   214 fun map_reserved target =
   215   map_target_data target o apsnd o apfst o apfst;
   216 fun map_includes target =
   217   map_target_data target o apsnd o apfst o apsnd;
   218 fun map_name_syntax target =
   219   map_target_data target o apsnd o apsnd o apfst o map_name_syntax_table;
   220 fun map_module_alias target =
   221   map_target_data target o apsnd o apsnd o apsnd;
   222 
   223 fun set_default_code_width k = (Targets.map o apsnd) (K k);
   224 
   225 
   226 (** serializer usage **)
   227 
   228 (* montage *)
   229 
   230 fun the_fundamental thy =
   231   let
   232     val ((targets, _), _) = Targets.get thy;
   233     fun fundamental target = case Symtab.lookup targets target
   234      of SOME data => (case the_description data
   235          of Fundamental data => data
   236           | Extension (super, _) => fundamental super)
   237       | NONE => error ("Unknown code target language: " ^ quote target);
   238   in fundamental end;
   239 
   240 fun the_literals thy = #literals o the_fundamental thy;
   241 
   242 local
   243 
   244 fun activate_syntax lookup_name src_tab = Symtab.empty
   245   |> fold_map (fn thing_identifier => fn tab => case lookup_name thing_identifier
   246        of SOME name => (SOME name,
   247             Symtab.update_new (name, the (Symtab.lookup src_tab thing_identifier)) tab)
   248         | NONE => (NONE, tab)) (Symtab.keys src_tab)
   249   |>> map_filter I;
   250 
   251 fun activate_const_syntax thy literals src_tab naming = (Symtab.empty, naming)
   252   |> fold_map (fn c => fn (tab, naming) =>
   253       case Code_Thingol.lookup_const naming c
   254        of SOME name => let
   255               val (syn, naming') = Code_Printer.activate_const_syntax thy
   256                 literals c (the (Symtab.lookup src_tab c)) naming
   257             in (SOME name, (Symtab.update_new (name, syn) tab, naming')) end
   258         | NONE => (NONE, (tab, naming))) (Symtab.keys src_tab)
   259   |>> map_filter I;
   260 
   261 fun invoke_serializer thy abortable serializer literals reserved abs_includes 
   262     module_alias class instance tyco const module_name width args naming program2 (names1, presentation_names) =
   263   let
   264     val (names_class, class') =
   265       activate_syntax (Code_Thingol.lookup_class naming) class;
   266     val names_inst = map_filter (Code_Thingol.lookup_instance naming)
   267       (Symreltab.keys instance);
   268     val (names_tyco, tyco') =
   269       activate_syntax (Code_Thingol.lookup_tyco naming) tyco;
   270     val (names_const, (const', _)) =
   271       activate_const_syntax thy literals const naming;
   272     val names_hidden = names_class @ names_inst @ names_tyco @ names_const;
   273     val names2 = subtract (op =) names_hidden names1;
   274     val program3 = Graph.subgraph (not o member (op =) names_hidden) program2;
   275     val names_all = Graph.all_succs program3 names2;
   276     val includes = abs_includes names_all;
   277     val program4 = Graph.subgraph (member (op =) names_all) program3;
   278     val empty_funs = filter_out (member (op =) abortable)
   279       (Code_Thingol.empty_funs program3);
   280     val _ = if null empty_funs then () else error ("No code equations for "
   281       ^ commas (map (Sign.extern_const thy) empty_funs));
   282   in
   283     serializer module_name args (Code_Thingol.labelled_name thy program2) reserved includes
   284       (if is_some module_name then K module_name else Symtab.lookup module_alias)
   285       (Symtab.lookup class') (Symtab.lookup tyco') (Symtab.lookup const')
   286       (Code_Printer.string_of_pretty width, Code_Printer.writeln_pretty width)
   287       program4 (names1, presentation_names)
   288   end;
   289 
   290 fun mount_serializer thy alt_serializer target some_width raw_module_name args naming program names destination =
   291   let
   292     val ((targets, abortable), default_width) = Targets.get thy;
   293     fun collapse_hierarchy target =
   294       let
   295         val data = case Symtab.lookup targets target
   296          of SOME data => data
   297           | NONE => error ("Unknown code target language: " ^ quote target);
   298       in case the_description data
   299        of Fundamental _ => (I, data)
   300         | Extension (super, modify) => let
   301             val (modify', data') = collapse_hierarchy super
   302           in (modify' #> modify naming, merge_target false target (data', data)) end
   303       end;
   304     val (modify, data) = collapse_hierarchy target;
   305     val serializer = the_default (case the_description data
   306      of Fundamental seri => #serializer seri) alt_serializer;
   307     val presentation_names = stmt_names_of_destination destination;
   308     val module_name = if null presentation_names
   309       then raw_module_name else SOME "Code";
   310     val reserved = the_reserved data;
   311     fun select_include names_all (name, (content, cs)) =
   312       if null cs then SOME (name, content)
   313       else if exists (fn c => case Code_Thingol.lookup_const naming c
   314        of SOME name => member (op =) names_all name
   315         | NONE => false) cs
   316       then SOME (name, content) else NONE;
   317     fun includes names_all = map_filter (select_include names_all)
   318       ((Symtab.dest o the_includes) data);
   319     val module_alias = the_module_alias data 
   320     val { class, instance, tyco, const } = the_name_syntax data;
   321     val literals = the_literals thy target;
   322     val width = the_default default_width some_width;
   323   in
   324     invoke_serializer thy abortable serializer literals reserved
   325       includes module_alias class instance tyco const module_name width args
   326         naming (modify program) (names, presentation_names) destination
   327   end;
   328 
   329 in
   330 
   331 fun serialize thy = mount_serializer thy NONE;
   332 
   333 fun check thy names_cs naming program target strict args =
   334   let
   335     val module_name = "Code_Test";
   336     val { env_var, make_destination, make_command } =
   337       (#check o the_fundamental thy) target;
   338     val env_param = getenv env_var;
   339     fun ext_check env_param p =
   340       let 
   341         val destination = make_destination p;
   342         val _ = file destination (serialize thy target (SOME 80)
   343           (SOME module_name) args naming program names_cs);
   344         val cmd = make_command env_param module_name;
   345       in if bash ("cd " ^ File.shell_path p ^ " && " ^ cmd ^ " 2>&1") <> 0
   346         then error ("Code check failed for " ^ target ^ ": " ^ cmd)
   347         else ()
   348       end;
   349   in if env_param = ""
   350     then if strict
   351       then error (env_var ^ " not set; cannot check code for " ^ target)
   352       else warning (env_var ^ " not set; skipped checking code for " ^ target)
   353     else Cache_IO.with_tmp_dir "Code_Test" (ext_check env_param)
   354   end;
   355 
   356 fun serialize_custom thy (target_name, seri) module_name naming program names =
   357   mount_serializer thy (SOME seri) target_name NONE module_name [] naming program names (String [])
   358   |> the;
   359 
   360 end; (* local *)
   361 
   362 
   363 (* code presentation *)
   364 
   365 fun code_of thy target some_width module_name cs names_stmt =
   366   let
   367     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   368   in
   369     string (names_stmt naming)
   370       (serialize thy target some_width (SOME module_name) [] naming program names_cs)
   371   end;
   372 
   373 
   374 (* code generation *)
   375 
   376 fun transitivly_non_empty_funs thy naming program =
   377   let
   378     val cs = subtract (op =) (abort_allowed thy) (Code_Thingol.empty_funs program);
   379     val names = map_filter (Code_Thingol.lookup_const naming) cs;
   380   in subtract (op =) (Graph.all_preds program names) (Graph.keys program) end;
   381 
   382 fun read_const_exprs thy cs =
   383   let
   384     val (cs1, cs2) = Code_Thingol.read_const_exprs thy cs;
   385     val (names2, (naming, program)) = Code_Thingol.consts_program thy true cs2;
   386     val names3 = transitivly_non_empty_funs thy naming program;
   387     val cs3 = map_filter (fn (c, name) =>
   388       if member (op =) names3 name then SOME c else NONE) (cs2 ~~ names2);
   389   in union (op =) cs3 cs1 end;
   390 
   391 fun export_code thy cs seris =
   392   let
   393     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   394     fun mk_seri_dest dest = if dest = "" orelse dest = "-" then export
   395       else file (Path.explode dest);
   396     val _ = map (fn (((target, module), dest), args) =>
   397       (mk_seri_dest dest (serialize thy target NONE module args naming program names_cs))) seris;
   398   in () end;
   399 
   400 fun export_code_cmd raw_cs seris thy = export_code thy (read_const_exprs thy raw_cs) seris;
   401 
   402 fun check_code thy cs seris =
   403   let
   404     val (names_cs, (naming, program)) = Code_Thingol.consts_program thy false cs;
   405     val _ = map (fn ((target, strict), args) => check thy names_cs naming program
   406       target strict args) seris;
   407   in () end;
   408 
   409 fun check_code_cmd raw_cs seris thy = check_code thy (read_const_exprs thy raw_cs) seris;
   410 
   411 
   412 (** serializer configuration **)
   413 
   414 (* data access *)
   415 
   416 fun cert_class thy class =
   417   let
   418     val _ = AxClass.get_info thy class;
   419   in class end;
   420 
   421 fun read_class thy = cert_class thy o Sign.intern_class thy;
   422 
   423 fun cert_tyco thy tyco =
   424   let
   425     val _ = if Sign.declared_tyname thy tyco then ()
   426       else error ("No such type constructor: " ^ quote tyco);
   427   in tyco end;
   428 
   429 fun read_tyco thy = cert_tyco thy o Sign.intern_type thy;
   430 
   431 fun cert_inst thy (class, tyco) =
   432   (cert_class thy class, cert_tyco thy tyco);
   433 
   434 fun read_inst thy (raw_tyco, raw_class) =
   435   (read_class thy raw_class, read_tyco thy raw_tyco);
   436 
   437 fun gen_add_syntax (mapp, upd, del) prep_x prep_syn target raw_x some_raw_syn thy =
   438   let
   439     val x = prep_x thy raw_x;
   440     val change = case some_raw_syn
   441      of SOME raw_syn => upd (x, prep_syn thy x raw_syn)
   442       | NONE => del x;
   443   in (map_name_syntax target o mapp) change thy end;
   444 
   445 fun gen_add_syntax_class prep_class =
   446   gen_add_syntax (apfst o apfst, Symtab.update, Symtab.delete_safe) prep_class ((K o K) I);
   447 
   448 fun gen_add_syntax_inst prep_inst =
   449   gen_add_syntax (apfst o apsnd, Symreltab.update, Symreltab.delete_safe) prep_inst ((K o K) I);
   450 
   451 fun gen_add_syntax_tyco prep_tyco =
   452   gen_add_syntax (apsnd o apfst, Symtab.update, Symtab.delete_safe) prep_tyco
   453     (fn thy => fn tyco => fn syn => if fst syn <> Sign.arity_number thy tyco
   454       then error ("Number of arguments mismatch in syntax for type constructor " ^ quote tyco)
   455       else syn);
   456 
   457 fun gen_add_syntax_const prep_const =
   458   gen_add_syntax (apsnd o apsnd, Symtab.update, Symtab.delete_safe) prep_const
   459     (fn thy => fn c => fn syn =>
   460       if Code_Printer.requires_args syn > Code.args_number thy c
   461       then error ("Too many arguments in syntax for constant " ^ quote c)
   462       else syn);
   463 
   464 fun add_reserved target =
   465   let
   466     fun add sym syms = if member (op =) syms sym
   467       then error ("Reserved symbol " ^ quote sym ^ " already declared")
   468       else insert (op =) sym syms
   469   in map_reserved target o add end;
   470 
   471 fun gen_add_include read_const target args thy =
   472   let
   473     fun add (name, SOME (content, raw_cs)) incls =
   474           let
   475             val _ = if Symtab.defined incls name
   476               then warning ("Overwriting existing include " ^ name)
   477               else ();
   478             val cs = map (read_const thy) raw_cs;
   479           in Symtab.update (name, (Code_Printer.str content, cs)) incls end
   480       | add (name, NONE) incls = Symtab.delete name incls;
   481   in map_includes target (add args) thy end;
   482 
   483 val add_include = gen_add_include (K I);
   484 val add_include_cmd = gen_add_include Code.read_const;
   485 
   486 fun add_module_alias target (thyname, modlname) =
   487   let
   488     val xs = Long_Name.explode modlname;
   489     val xs' = map (Name.desymbolize true) xs;
   490   in if xs' = xs
   491     then map_module_alias target (Symtab.update (thyname, modlname))
   492     else error ("Invalid module name: " ^ quote modlname ^ "\n"
   493       ^ "perhaps try " ^ quote (Long_Name.implode xs'))
   494   end;
   495 
   496 fun gen_allow_abort prep_const raw_c thy =
   497   let
   498     val c = prep_const thy raw_c;
   499   in thy |> (Targets.map o apfst o apsnd) (insert (op =) c) end;
   500 
   501 
   502 (* concrete syntax *)
   503 
   504 local
   505 
   506 fun zip_list (x::xs) f g =
   507   f
   508   :|-- (fn y =>
   509     fold_map (fn x => g |-- f >> pair x) xs
   510     :|-- (fn xys => pair ((x, y) :: xys)));
   511 
   512 fun process_multi_syntax parse_thing parse_syntax change =
   513   (Parse.and_list1 parse_thing
   514   :|-- (fn things => Scan.repeat1 (Parse.$$$ "(" |-- Parse.name --
   515         (zip_list things parse_syntax (Parse.$$$ "and")) --| Parse.$$$ ")")))
   516   >> (Toplevel.theory oo fold)
   517     (fn (target, syns) => fold (fn (raw_x, syn) => change target raw_x syn) syns);
   518 
   519 in
   520 
   521 val add_syntax_class = gen_add_syntax_class cert_class;
   522 val add_syntax_inst = gen_add_syntax_inst cert_inst;
   523 val add_syntax_tyco = gen_add_syntax_tyco cert_tyco;
   524 val add_syntax_const = gen_add_syntax_const (K I);
   525 val allow_abort = gen_allow_abort (K I);
   526 val add_reserved = add_reserved;
   527 val add_include = add_include;
   528 
   529 val add_syntax_class_cmd = gen_add_syntax_class read_class;
   530 val add_syntax_inst_cmd = gen_add_syntax_inst read_inst;
   531 val add_syntax_tyco_cmd = gen_add_syntax_tyco read_tyco;
   532 val add_syntax_const_cmd = gen_add_syntax_const Code.read_const;
   533 val allow_abort_cmd = gen_allow_abort Code.read_const;
   534 
   535 fun parse_args f args =
   536   case Scan.read Token.stopper f args
   537    of SOME x => x
   538     | NONE => error "Bad serializer arguments";
   539 
   540 
   541 (** Isar setup **)
   542 
   543 val (inK, module_nameK, fileK, checkingK) = ("in", "module_name", "file", "checking");
   544 
   545 val code_expr_argsP = Scan.optional (Parse.$$$ "(" |-- Args.parse --| Parse.$$$ ")") [];
   546 
   547 val code_exprP =
   548   Scan.repeat1 Parse.term_group :|-- (fn raw_cs =>
   549     ((Parse.$$$ checkingK |-- Scan.repeat (Parse.name
   550       -- ((Parse.$$$ "?" |-- Scan.succeed false) || Scan.succeed true) -- code_expr_argsP))
   551       >> (fn seris => check_code_cmd raw_cs seris)
   552     || Scan.repeat (Parse.$$$ inK |-- Parse.name
   553        -- Scan.option (Parse.$$$ module_nameK |-- Parse.name)
   554        -- Scan.optional (Parse.$$$ fileK |-- Parse.name) ""
   555        -- code_expr_argsP) >> (fn seris => export_code_cmd raw_cs seris)));
   556 
   557 val _ = List.app Keyword.keyword [inK, module_nameK, fileK, checkingK];
   558 
   559 val _ =
   560   Outer_Syntax.command "code_class" "define code syntax for class" Keyword.thy_decl (
   561     process_multi_syntax Parse.xname (Scan.option Parse.string)
   562     add_syntax_class_cmd);
   563 
   564 val _ =
   565   Outer_Syntax.command "code_instance" "define code syntax for instance" Keyword.thy_decl (
   566     process_multi_syntax (Parse.xname --| Parse.$$$ "::" -- Parse.xname)
   567       (Scan.option (Parse.minus >> K ()))
   568     add_syntax_inst_cmd);
   569 
   570 val _ =
   571   Outer_Syntax.command "code_type" "define code syntax for type constructor" Keyword.thy_decl (
   572     process_multi_syntax Parse.xname Code_Printer.parse_tyco_syntax
   573     add_syntax_tyco_cmd);
   574 
   575 val _ =
   576   Outer_Syntax.command "code_const" "define code syntax for constant" Keyword.thy_decl (
   577     process_multi_syntax Parse.term_group Code_Printer.parse_const_syntax
   578     add_syntax_const_cmd);
   579 
   580 val _ =
   581   Outer_Syntax.command "code_reserved" "declare words as reserved for target language"
   582     Keyword.thy_decl (
   583     Parse.name -- Scan.repeat1 Parse.name
   584     >> (fn (target, reserveds) => (Toplevel.theory o fold (add_reserved target)) reserveds)
   585   );
   586 
   587 val _ =
   588   Outer_Syntax.command "code_include" "declare piece of code to be included in generated code"
   589     Keyword.thy_decl (
   590     Parse.name -- Parse.name -- (Parse.text :|-- (fn "-" => Scan.succeed NONE
   591       | s => Scan.optional (Parse.$$$ "attach" |-- Scan.repeat1 Parse.term) [] >> pair s >> SOME))
   592     >> (fn ((target, name), content_consts) =>
   593         (Toplevel.theory o add_include_cmd target) (name, content_consts))
   594   );
   595 
   596 val _ =
   597   Outer_Syntax.command "code_modulename" "alias module to other name" Keyword.thy_decl (
   598     Parse.name -- Scan.repeat1 (Parse.name -- Parse.name)
   599     >> (fn (target, modlnames) => (Toplevel.theory o fold (add_module_alias target)) modlnames)
   600   );
   601 
   602 val _ =
   603   Outer_Syntax.command "code_abort" "permit constant to be implemented as program abort"
   604     Keyword.thy_decl (
   605     Scan.repeat1 Parse.term_group >> (Toplevel.theory o fold allow_abort_cmd)
   606   );
   607 
   608 val _ =
   609   Outer_Syntax.command "export_code" "generate executable code for constants"
   610     Keyword.diag (Parse.!!! code_exprP >> (fn f => Toplevel.keep (f o Toplevel.theory_of)));
   611 
   612 fun shell_command thyname cmd = Toplevel.program (fn _ =>
   613   (use_thy thyname; case Scan.read Token.stopper (Parse.!!! code_exprP)
   614     ((filter Token.is_proper o Outer_Syntax.scan Position.none) cmd)
   615    of SOME f => (writeln "Now generating code..."; f (Thy_Info.get_theory thyname))
   616     | NONE => error ("Bad directive " ^ quote cmd)))
   617   handle Runtime.TOPLEVEL_ERROR => OS.Process.exit OS.Process.failure;
   618 
   619 end; (*local*)
   620 
   621 end; (*struct*)