src/Tools/Code/code_target.ML
author haftmann
Wed, 01 Jan 2014 01:05:48 +0100
changeset 56232 cb892d835803
parent 56231 4121d64fde90
child 56329 3f561ee3d998
permissions -rw-r--r--
fundamental treatment of undefined vs. universally partial replaces code_abort
     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) 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
    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) 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
    30 
    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
    35 
    36   type serializer
    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 } }
    40     -> theory -> theory
    41   val extend_target: string *
    42       (string * (Code_Thingol.naming -> Code_Thingol.program -> Code_Thingol.program))
    43     -> theory -> theory
    44   val assert_target: theory -> string -> string
    45   val the_literals: theory -> string -> literals
    46   type serialization
    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
    52 
    53   type ('a, 'b, 'c, 'd, 'e, 'f) symbol_attr_decl
    54   type identifier_data
    55   val set_identifiers: (string, string, string, string, string, string) symbol_attr_decl
    56     -> theory -> theory
    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
    60     -> theory -> theory
    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
    67 
    68   val codegen_tool: string (*theory name*) -> string (*export_code expr*) -> unit
    69 
    70   val setup: theory -> theory
    71 end;
    72 
    73 structure Code_Target : CODE_TARGET =
    74 struct
    75 
    76 open Basic_Code_Thingol;
    77 
    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;
    85 
    86 type tyco_syntax = Code_Printer.tyco_syntax;
    87 type const_syntax = Code_Printer.const_syntax;
    88 
    89 
    90 (** checking and parsing of symbols **)
    91 
    92 fun cert_const thy const =
    93   let
    94     val _ = if Sign.declared_const thy const then ()
    95       else error ("No such constant: " ^ quote const);
    96   in const end;
    97 
    98 fun cert_tyco thy tyco =
    99   let
   100     val _ = if Sign.declared_tyname thy tyco then ()
   101       else error ("No such type constructor: " ^ quote tyco);
   102   in tyco end;
   103 
   104 fun read_tyco thy = #1 o dest_Type
   105   o Proof_Context.read_type_name_proper (Proof_Context.init_global thy) true;
   106 
   107 fun cert_class thy class =
   108   let
   109     val _ = Axclass.get_info thy class;
   110   in class end;
   111 
   112 fun read_class thy = Proof_Context.read_class (Proof_Context.init_global thy);
   113 
   114 val parse_classrel_ident = Parse.class --| @{keyword "<"} -- Parse.class;
   115 
   116 fun cert_inst thy (class, tyco) =
   117   (cert_class thy class, cert_tyco thy tyco);
   118 
   119 fun read_inst thy (raw_tyco, raw_class) =
   120   (read_class thy raw_class, read_tyco thy raw_tyco);
   121 
   122 val parse_inst_ident = Parse.xname --| @{keyword "::"} -- Parse.class;
   123 
   124 fun cert_syms thy =
   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;
   127 
   128 fun read_syms thy =
   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;
   131 
   132 fun check_name is_module s =
   133   let
   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)
   140       else
   141         let
   142           val (ys, y) = split_last xs;
   143           val ys' = map (Name.desymbolize true) ys;
   144           val y' = Name.desymbolize false y;
   145         in ys' @ [y'] end;
   146   in if xs' = xs
   147     then s
   148     else error ("Invalid code name: " ^ quote s ^ "\n"
   149       ^ "better try " ^ quote (Long_Name.implode xs'))
   150   end;
   151 
   152 
   153 (** serializations and serializer **)
   154 
   155 (* serialization: abstract nonsense to cover different destinies for generated code *)
   156 
   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;
   159 
   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)
   167      |> SOME;
   168 
   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)))));
   172 
   173 
   174 (* serializers: functions producing serializations *)
   175 
   176 type serializer = Token.T list
   177   -> Proof.context
   178   -> {
   179     symbol_of: string -> Code_Symbol.symbol,
   180     module_name: string,
   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
   188   -> serialization;
   189 
   190 datatype description =
   191     Fundamental of { serializer: serializer,
   192       literals: literals,
   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);
   197 
   198 
   199 (** theory data **)
   200 
   201 datatype target = Target of {
   202   serial: serial,
   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
   208 };
   209 
   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))))
   223   else
   224     error ("Incompatible targets: " ^ quote target);
   225 
   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;
   230 
   231 structure Targets = Theory_Data
   232 (
   233   type T = target Symtab.table * int;
   234   val empty = (Symtab.empty, 80);
   235   val extend = I;
   236   fun merge ((target1, width1), (target2, width2)) : T =
   237     (Symtab.join (merge_target true) (target1, target2), Int.max (width1, width2));
   238 );
   239 
   240 fun assert_target thy target = if Symtab.defined (fst (Targets.get thy)) target
   241   then target
   242   else error ("Unknown code target language: " ^ quote target);
   243 
   244 fun put_target (target, seri) thy =
   245   let
   246     val lookup_target = Symtab.lookup (fst (Targets.get thy));
   247     val _ = case seri
   248      of Extension (super, _) => if is_some (lookup_target super) then ()
   249           else error ("Unknown code target language: " ^ quote super)
   250       | _ => ();
   251     val overwriting = case (Option.map the_description o lookup_target) target
   252      of NONE => false
   253       | SOME (Extension _) => true
   254       | SOME (Fundamental _) => (case seri
   255          of Extension _ => error ("Will not overwrite existing target " ^ quote target)
   256           | _ => true);
   257     val _ = if overwriting
   258       then warning ("Overwriting existing target " ^ quote target)
   259       else ();
   260   in
   261     thy
   262     |> (Targets.map o apfst o Symtab.update)
   263         (target, make_target ((serial (), seri),
   264           ([], (Code_Symbol.empty_data, Code_Symbol.empty_data))))
   265   end;
   266 
   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));
   270 
   271 fun map_target_data target f thy =
   272   let
   273     val _ = assert_target thy target;
   274   in
   275     thy
   276     |> (Targets.map o apfst o Symtab.map_entry target o map_target o apsnd) f
   277   end;
   278 
   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;
   285 
   286 fun set_default_code_width k = (Targets.map o apsnd) (K k);
   287 
   288 
   289 (** serializer usage **)
   290 
   291 (* montage *)
   292 
   293 fun the_fundamental thy =
   294   let
   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);
   301   in fundamental end;
   302 
   303 fun the_literals thy = #literals o the_fundamental thy;
   304 
   305 fun collapse_hierarchy thy =
   306   let
   307     val (targets, _) = Targets.get thy;
   308     fun collapse target =
   309       let
   310         val data = case Symtab.lookup targets target
   311          of SOME data => data
   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
   318       end;
   319   in collapse end;
   320 
   321 local
   322 
   323 fun activate_target thy target =
   324   let
   325     val (_, default_width) = Targets.get thy;
   326     val (modify, data) = collapse_hierarchy thy target;
   327   in (default_width, data, modify) end;
   328 
   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
   333        of SOME name => let
   334               val (syn, naming') =
   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
   338   |>> map_filter I;
   339 
   340 fun activate_syntax lookup_name things =
   341   Symtab.empty
   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
   345   |>> map_filter I;
   346 
   347 fun activate_symbol_syntax thy literals naming printings =
   348   let
   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);
   357   in
   358     (names_const @ names_tyco @ names_class @ names_inst,
   359       (const_syntax, tyco_syntax, class_syntax))
   360   end;
   361 
   362 fun project_program thy names_hidden names1 program2 =
   363   let
   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;
   369     val _ =
   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;
   375 
   376 fun prepare_serializer thy (serializer : serializer) literals reserved identifiers
   377     printings module_name args naming proto_program names =
   378   let
   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
   385         | NONE => false) cs
   386       then SOME (name, content) else NONE;
   387     val includes = map_filter select_include (Code_Symbol.dest_module_data printings);
   388   in
   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,
   394       includes = includes,
   395       const_syntax = Symtab.lookup const_syntax,
   396       tyco_syntax = Symtab.lookup tyco_syntax,
   397       class_syntax = Symtab.lookup class_syntax },
   398       program)
   399   end;
   400 
   401 fun mount_serializer thy target some_width module_name args naming program names =
   402   let
   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;
   412 
   413 fun invoke_serializer thy target some_width module_name args naming program names =
   414   let
   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;
   419 
   420 fun assert_module_name "" = error "Empty module name not allowed here"
   421   | assert_module_name module_name = module_name;
   422 
   423 fun using_master_directory thy =
   424   Option.map (Path.append (File.pwd ()) o Path.append (Thy_Load.master_directory thy));
   425 
   426 in
   427 
   428 val generatedN = "Generated_Code";
   429 
   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;
   433 
   434 fun produce_code_for thy target some_width module_name args =
   435   let
   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)
   439   end;
   440 
   441 fun present_code_for thy target some_width module_name args =
   442   let
   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)
   446   end;
   447 
   448 fun check_code_for thy target strict args naming program names_cs =
   449   let
   450     val { env_var, make_destination, make_command } =
   451       (#check o the_fundamental thy) target;
   452     fun ext_check p =
   453       let
   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;
   458       in
   459         if Isabelle_System.bash ("cd " ^ File.shell_path p ^ " && " ^ cmd ^ " 2>&1") <> 0
   460         then error ("Code check failed for " ^ target ^ ": " ^ cmd)
   461         else ()
   462       end;
   463   in
   464     if getenv env_var = ""
   465     then if strict
   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
   469   end;
   470 
   471 fun evaluation mounted_serializer prepared_program consts ((vs, ty), t) =
   472   let
   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;
   486 
   487 fun evaluator thy target naming program consts =
   488   let
   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;
   492 
   493 end; (* local *)
   494 
   495 
   496 (* code generation *)
   497 
   498 fun implemented_functions thy naming program =
   499   let
   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;
   503 
   504 fun read_const_exprs thy cs =
   505   let
   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;
   512 
   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);
   516 
   517 fun export_code thy cs seris =
   518   let
   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;
   522   in () end;
   523 
   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);
   526 
   527 fun produce_code thy cs target some_width some_module_name args =
   528   let
   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;
   531 
   532 fun present_code thy cs names_stmt target some_width some_module_name args =
   533   let
   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;
   536 
   537 fun check_code thy cs seris =
   538   let
   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;
   542   in () end;
   543 
   544 fun check_code_cmd raw_cs seris thy = check_code thy (read_const_exprs thy raw_cs) seris;
   545 
   546 local
   547 
   548 val parse_const_terms = Scan.repeat1 Args.term
   549   >> (fn ts => fn thy => map (Code.check_const thy) ts);
   550 
   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);
   554 
   555 val parse_consts = parse_names "consts" Args.term
   556   Code.check_const Code_Thingol.lookup_const;
   557 
   558 val parse_types = parse_names "types" (Scan.lift Args.name)
   559   Sign.intern_type Code_Thingol.lookup_tyco;
   560 
   561 val parse_classes = parse_names "classes" (Scan.lift Args.name)
   562   Sign.intern_class Code_Thingol.lookup_class;
   563 
   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;
   567 
   568 in
   569 
   570 val antiq_setup =
   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" []
   580       end);
   581 
   582 end;
   583 
   584 
   585 (** serializer configuration **)
   586 
   587 (* reserved symbol names *)
   588 
   589 fun add_reserved target sym thy =
   590   let
   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")
   594       else ();
   595   in
   596     thy
   597     |> map_reserved target (insert (op =) sym)
   598   end;
   599 
   600 
   601 (* checking of syntax *)
   602 
   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)
   606   else syn;
   607 
   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)
   611   else syn;
   612 
   613 
   614 (* custom symbol names *)
   615 
   616 fun arrange_name_decls x =
   617   let
   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;
   620   in
   621     Code_Symbol.maps_attr' (arrange false) (arrange false) (arrange false)
   622       (arrange false) (arrange false) (arrange true) x
   623   end;
   624 
   625 fun cert_name_decls thy = cert_syms thy #> arrange_name_decls;
   626 
   627 fun read_name_decls thy = read_syms thy #> arrange_name_decls;
   628 
   629 fun set_identifier (target, sym_name) = map_identifiers target (Code_Symbol.set_data sym_name);
   630 
   631 fun gen_set_identifiers prep_name_decl raw_name_decls thy =
   632   fold set_identifier (prep_name_decl thy raw_name_decls) thy;
   633 
   634 val set_identifiers = gen_set_identifiers cert_name_decls;
   635 val set_identifiers_cmd = gen_set_identifiers read_name_decls;
   636 
   637 fun add_module_alias_cmd target aliasses thy =
   638   let
   639     val _ = legacy_feature "prefer \"code_identifier\" over \"code_modulename\"";
   640   in
   641     fold (fn (sym, name) => set_identifier
   642       (target, Code_Symbol.Module (sym, if name = "" then NONE else SOME (check_name true name))))
   643       aliasses thy
   644   end;
   645 
   646 
   647 (* custom printings *)
   648 
   649 fun arrange_printings prep_const thy =
   650   let
   651     fun arrange check (sym, target_syns) =
   652       map (fn (target, some_syn) => (target, (sym, Option.map (check thy sym) some_syn))) target_syns;
   653   in
   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)))
   659   end;
   660 
   661 fun cert_printings thy = cert_syms thy #> arrange_printings cert_const thy;
   662 
   663 fun read_printings thy = read_syms thy #> arrange_printings Code.read_const thy;
   664 
   665 fun set_printing (target, sym_syn) = map_printings target (Code_Symbol.set_data sym_syn);
   666 
   667 fun gen_set_printings prep_print_decl raw_print_decls thy =
   668   fold set_printing (prep_print_decl thy raw_print_decls) thy;
   669 
   670 val set_printings = gen_set_printings cert_printings;
   671 val set_printings_cmd = gen_set_printings read_printings;
   672 
   673 fun gen_add_syntax Symbol prep_x prep_syn target raw_x some_raw_syn thy =
   674   let
   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;
   678 
   679 fun gen_add_const_syntax prep_const =
   680   gen_add_syntax Code_Symbol.Constant prep_const check_const_syntax;
   681 
   682 fun gen_add_tyco_syntax prep_tyco =
   683   gen_add_syntax Code_Symbol.Type_Constructor prep_tyco check_tyco_syntax;
   684 
   685 fun gen_add_class_syntax prep_class =
   686   gen_add_syntax Code_Symbol.Type_Class prep_class ((K o K) I);
   687 
   688 fun gen_add_instance_syntax prep_inst =
   689   gen_add_syntax Code_Symbol.Class_Instance prep_inst ((K o K) I);
   690 
   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;
   695 
   696 
   697 (* concrete syntax *)
   698 
   699 local
   700 
   701 fun zip_list (x :: xs) f g =
   702   f
   703   :|-- (fn y =>
   704     fold_map (fn x => g |-- f >> pair x) xs
   705     :|-- (fn xys => pair ((x, y) :: xys)));
   706 
   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);
   713 
   714 in
   715 
   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);
   722 
   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;
   728 
   729 fun parse_args f args =
   730   case Scan.read Token.stopper f args
   731    of SOME x => x
   732     | NONE => error "Bad serializer arguments";
   733 
   734 
   735 (** Isar setup **)
   736 
   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)));
   740 
   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;
   754 
   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));
   758 
   759 val code_expr_argsP = Scan.optional (@{keyword "("} |-- Args.parse --| @{keyword ")"}) [];
   760 
   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) ""
   765     -- code_expr_argsP))
   766       >> (fn seri_args => export_code_cmd raw_cs seri_args);
   767 
   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);
   773 
   774 val code_exprP = Scan.repeat1 Parse.term
   775   :|-- (fn raw_cs => (code_expr_checkingP raw_cs || code_expr_inP raw_cs));
   776 
   777 val _ =
   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));
   782 
   783 val _ =
   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));
   787 
   788 val _ =
   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));
   792 
   793 val _ =
   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));
   799 
   800 val _ =
   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);
   804 
   805 val _ =
   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);
   809 
   810 val _ =
   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);
   814 
   815 val _ =
   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);
   819 
   820 val _ =
   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)));
   828 
   829 val _ =
   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)));
   832 
   833 end; (*local*)
   834 
   835 
   836 (** external entrance point -- for codegen tool **)
   837 
   838 fun codegen_tool thyname cmd_expr =
   839   let
   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)
   846   end;
   847 
   848 
   849 (** theory setup **)
   850 
   851 val setup = antiq_setup;
   852 
   853 end; (*struct*)