src/Tools/Code/code_target.ML
author wenzelm
Fri Sep 01 12:47:23 2017 +0200 (2017-09-01)
changeset 66586 e5e56c330976
parent 64959 9ca021bd718d
child 67207 ad538f6c5d2f
permissions -rw-r--r--
more PIDE markup;
     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: Proof.context -> string -> string
    10   val read_tyco: Proof.context -> string -> string
    11 
    12   val export_code_for: Proof.context -> Path.T option -> string -> int option -> string -> Token.T list
    13     -> Code_Thingol.program -> bool -> Code_Symbol.T list -> unit
    14   val produce_code_for: Proof.context -> string -> int option -> string -> Token.T list
    15     -> Code_Thingol.program -> bool -> Code_Symbol.T list -> (string * string) list * string option list
    16   val present_code_for: Proof.context -> string -> int option -> string -> Token.T list
    17     -> Code_Thingol.program -> Code_Symbol.T list * Code_Symbol.T list -> string
    18   val check_code_for: Proof.context -> string -> bool -> Token.T list
    19     -> Code_Thingol.program -> bool -> Code_Symbol.T list -> unit
    20 
    21   val export_code: Proof.context -> bool -> string list
    22     -> (((string * string) * Path.T option) * Token.T list) list -> unit
    23   val produce_code: Proof.context -> bool -> string list
    24     -> string -> int option -> string -> Token.T list -> (string * string) list * string option list
    25   val present_code: Proof.context -> string list -> Code_Symbol.T list
    26     -> string -> int option -> string -> Token.T list -> string
    27   val check_code: Proof.context -> bool -> string list
    28     -> ((string * bool) * Token.T list) list -> unit
    29 
    30   val generatedN: string
    31   val compilation_text: Proof.context -> string -> Code_Thingol.program
    32     -> Code_Symbol.T list -> bool -> ((string * class list) list * Code_Thingol.itype) * Code_Thingol.iterm
    33     -> (string * string) list * string
    34   val compilation_text': Proof.context -> string -> string option -> Code_Thingol.program
    35     -> Code_Symbol.T list -> bool -> ((string * class list) list * Code_Thingol.itype) * Code_Thingol.iterm
    36     -> ((string * string) list * string) * (Code_Symbol.T -> string option)
    37 
    38   type serializer
    39   type literals = Code_Printer.literals
    40   type language
    41   type ancestry
    42   val assert_target: theory -> string -> string
    43   val add_language: string * language -> theory -> theory
    44   val add_derived_target: string * ancestry -> theory -> theory
    45   val the_literals: Proof.context -> 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     -> (Code_Symbol.T list -> int -> 'a -> (string * string) list * (Code_Symbol.T -> string option))
    50     -> 'a -> serialization
    51   val default_code_width: int Config.T
    52 
    53   type ('a, 'b, 'c, 'd, 'e, 'f) symbol_attr_decl
    54   val set_identifiers: (string, string, string, string, string, string) symbol_attr_decl
    55     -> theory -> theory
    56   val set_printings: (Code_Printer.raw_const_syntax, Code_Printer.tyco_syntax, string, unit, unit, (string * string list)) symbol_attr_decl
    57     -> theory -> theory
    58   val add_reserved: string -> string -> theory -> theory
    59 end;
    60 
    61 structure Code_Target : CODE_TARGET =
    62 struct
    63 
    64 open Basic_Code_Symbol;
    65 open Basic_Code_Thingol;
    66 
    67 type literals = Code_Printer.literals;
    68 type ('a, 'b, 'c, 'd, 'e, 'f) symbol_attr_decl =
    69   (string * (string * 'a option) list, string * (string * 'b option) list,
    70     class * (string * 'c option) list, (class * class) * (string * 'd option) list,
    71     (class * string) * (string * 'e option) list,
    72     string * (string * 'f option) list) Code_Symbol.attr;
    73 
    74 type tyco_syntax = Code_Printer.tyco_syntax;
    75 type raw_const_syntax = Code_Printer.raw_const_syntax;
    76 
    77 
    78 (** checking and parsing of symbols **)
    79 
    80 fun cert_const ctxt const =
    81   let
    82     val _ = if Sign.declared_const (Proof_Context.theory_of ctxt) const then ()
    83       else error ("No such constant: " ^ quote const);
    84   in const end;
    85 
    86 fun read_const ctxt = Code.read_const (Proof_Context.theory_of ctxt);
    87 
    88 fun cert_tyco ctxt tyco =
    89   let
    90     val _ = if Sign.declared_tyname (Proof_Context.theory_of ctxt) tyco then ()
    91       else error ("No such type constructor: " ^ quote tyco);
    92   in tyco end;
    93 
    94 fun read_tyco ctxt =
    95   #1 o dest_Type o Proof_Context.read_type_name {proper = true, strict = true} ctxt;
    96 
    97 fun cert_class ctxt class =
    98   let
    99     val _ = Axclass.get_info (Proof_Context.theory_of ctxt) class;
   100   in class end;
   101 
   102 val parse_classrel_ident = Parse.class --| @{keyword "<"} -- Parse.class;
   103 
   104 fun cert_inst ctxt (class, tyco) =
   105   (cert_class ctxt class, cert_tyco ctxt tyco);
   106 
   107 fun read_inst ctxt (raw_tyco, raw_class) =
   108   (read_tyco ctxt raw_tyco, Proof_Context.read_class ctxt raw_class);
   109 
   110 val parse_inst_ident = Parse.name --| @{keyword "::"} -- Parse.class;
   111 
   112 fun cert_syms ctxt =
   113   Code_Symbol.map_attr (apfst (cert_const ctxt)) (apfst (cert_tyco ctxt))
   114     (apfst (cert_class ctxt)) ((apfst o apply2) (cert_class ctxt)) (apfst (cert_inst ctxt)) I;
   115 
   116 fun read_syms ctxt =
   117   Code_Symbol.map_attr (apfst (read_const ctxt)) (apfst (read_tyco ctxt))
   118     (apfst (Proof_Context.read_class ctxt)) ((apfst o apply2) (Proof_Context.read_class ctxt)) (apfst (read_inst ctxt)) I;
   119 
   120 fun check_name is_module s =
   121   let
   122     val _ = if s = "" then error "Bad empty code name" else ();
   123     val xs = Long_Name.explode s;
   124     val xs' = if is_module
   125         then map (Name.desymbolize NONE) xs
   126       else if length xs < 2
   127         then error ("Bad code name without module component: " ^ quote s)
   128       else
   129         let
   130           val (ys, y) = split_last xs;
   131           val ys' = map (Name.desymbolize NONE) ys;
   132           val y' = Name.desymbolize NONE y;
   133         in ys' @ [y'] end;
   134   in if xs' = xs
   135     then if is_module then (xs, "") else split_last xs
   136     else error ("Invalid code name: " ^ quote s ^ "\n"
   137       ^ "better try " ^ quote (Long_Name.implode xs'))
   138   end;
   139 
   140 
   141 (** serializations and serializer **)
   142 
   143 (* serialization: abstract nonsense to cover different destinies for generated code *)
   144 
   145 datatype destination = Export of Path.T option | Produce | Present of Code_Symbol.T list;
   146 type serialization = int -> destination -> ((string * string) list * (Code_Symbol.T -> string option)) option;
   147 
   148 fun serialization output _ content width (Export some_path) =
   149       (output width some_path content; NONE)
   150   | serialization _ string content width Produce =
   151       string [] width content |> SOME
   152   | serialization _ string content width (Present syms) =
   153      string syms width content
   154      |> (apfst o map o apsnd) Output.output
   155      |> SOME;
   156 
   157 fun export some_path f = (f (Export some_path); ());
   158 fun produce f = the (f Produce);
   159 fun present syms f = space_implode "\n\n" (map snd (fst (the (f (Present syms)))));
   160 
   161 
   162 (* serializers: functions producing serializations *)
   163 
   164 type serializer = Token.T list
   165   -> Proof.context
   166   -> {
   167     module_name: string,
   168     reserved_syms: string list,
   169     identifiers: Code_Printer.identifiers,
   170     includes: (string * Pretty.T) list,
   171     class_syntax: string -> string option,
   172     tyco_syntax: string -> Code_Printer.tyco_syntax option,
   173     const_syntax: string -> Code_Printer.const_syntax option }
   174   -> Code_Symbol.T list
   175   -> Code_Thingol.program
   176   -> serialization;
   177 
   178   
   179 (** theory data **)
   180 
   181 type language = { serializer: serializer, literals: literals,
   182   check: { env_var: string, make_destination: Path.T -> Path.T, make_command: string -> string } }; 
   183 
   184 type ancestry = (string * (Code_Thingol.program -> Code_Thingol.program)) list;
   185 
   186 val merge_ancestry : ancestry * ancestry -> ancestry = AList.join (op =) (K snd);
   187 
   188 type target = { serial: serial, language: language, ancestry: ancestry };
   189 
   190 structure Targets = Theory_Data
   191 (
   192   type T = (target * Code_Printer.data) Symtab.table;
   193   val empty = Symtab.empty;
   194   val extend = I;
   195   fun merge (targets1, targets2) : T =
   196     Symtab.join (fn target_name => fn ((target1, data1), (target2, data2)) =>
   197       if #serial target1 = #serial target2 then
   198       ({ serial = #serial target1, language = #language target1,
   199         ancestry = merge_ancestry (#ancestry target1, #ancestry target2)},
   200         Code_Printer.merge_data (data1, data2))
   201       else error ("Incompatible targets: " ^ quote target_name) 
   202     ) (targets1, targets2)
   203 );
   204 
   205 fun exists_target thy = Symtab.defined (Targets.get thy);
   206 fun lookup_target_data thy = Symtab.lookup (Targets.get thy);
   207 fun assert_target thy target_name =
   208   if exists_target thy target_name
   209   then target_name
   210   else error ("Unknown code target language: " ^ quote target_name);
   211 
   212 fun fold1 f xs = fold f (tl xs) (hd xs);
   213 
   214 fun join_ancestry thy target_name =
   215   let
   216     val _ = assert_target thy target_name; 
   217     val the_target_data = the o lookup_target_data thy;
   218     val (target, this_data) = the_target_data target_name;
   219     val ancestry = #ancestry target;
   220     val modifies = rev (map snd ancestry);
   221     val modify = fold (curry (op o)) modifies I;
   222     val datas = rev (map (snd o the_target_data o fst) ancestry) @ [this_data];
   223     val data = fold1 (fn data' => fn data => Code_Printer.merge_data (data, data')) datas;
   224   in (modify, (target, data)) end;
   225 
   226   fun allocate_target target_name target thy =
   227   let
   228     val _ = if exists_target thy target_name
   229       then error ("Attempt to overwrite existing target " ^ quote target_name)
   230       else ();
   231   in
   232     thy
   233     |> (Targets.map o Symtab.update) (target_name, (target, Code_Printer.empty_data))  
   234   end;
   235 
   236 fun add_language (target_name, language) =
   237   allocate_target target_name { serial = serial (), language = language, ancestry = [] };
   238 
   239 fun add_derived_target (target_name, initial_ancestry) thy =
   240   let
   241     val _ = if null initial_ancestry
   242       then error "Must derive from existing target(s)" else ();
   243     fun the_target_data target_name' = case lookup_target_data thy target_name' of
   244       NONE => error ("Unknown code target language: " ^ quote target_name')
   245     | SOME target_data' => target_data';
   246     val targets = rev (map (fst o the_target_data o fst) initial_ancestry);
   247     val supremum = fold1 (fn target' => fn target =>
   248       if #serial target = #serial target'
   249       then target else error "Incompatible targets") targets;
   250     val ancestries = map #ancestry targets @ [initial_ancestry];
   251     val ancestry = fold1 (fn ancestry' => fn ancestry =>
   252       merge_ancestry (ancestry, ancestry')) ancestries;
   253   in
   254     allocate_target target_name { serial = #serial supremum, language = #language supremum,
   255       ancestry = ancestry } thy 
   256   end;
   257   
   258 fun map_data target_name f thy =
   259   let
   260     val _ = assert_target thy target_name;
   261   in
   262     thy
   263     |> (Targets.map o Symtab.map_entry target_name o apsnd o Code_Printer.map_data) f
   264   end;
   265 
   266 fun map_reserved target_name =
   267   map_data target_name o @{apply 3 (1)};
   268 fun map_identifiers target_name =
   269   map_data target_name o @{apply 3 (2)};
   270 fun map_printings target_name =
   271   map_data target_name o @{apply 3 (3)};
   272 
   273 
   274 (** serializer usage **)
   275 
   276 (* technical aside: pretty printing width *)
   277 
   278 val default_code_width = Attrib.setup_config_int @{binding "default_code_width"} (K 80);
   279 
   280 
   281 (* montage *)
   282 
   283 fun the_language ctxt =
   284   #language o fst o the o lookup_target_data (Proof_Context.theory_of ctxt);
   285 
   286 fun the_literals ctxt = #literals o the_language ctxt;
   287 
   288 local
   289 
   290 fun activate_target ctxt target_name =
   291   let
   292     val thy = Proof_Context.theory_of ctxt;
   293     val (modify, target_data) = join_ancestry thy target_name;
   294   in (target_data, modify) end;
   295 
   296 fun project_program ctxt syms_hidden syms1 program2 =
   297   let
   298     val syms2 = subtract (op =) syms_hidden syms1;
   299     val program3 = Code_Symbol.Graph.restrict (not o member (op =) syms_hidden) program2;
   300     val syms4 = Code_Symbol.Graph.all_succs program3 syms2;
   301     val unimplemented = Code_Thingol.unimplemented program3;
   302     val _ =
   303       if null unimplemented then ()
   304       else error ("No code equations for " ^
   305         commas (map (Proof_Context.markup_const ctxt) unimplemented));
   306     val program4 = Code_Symbol.Graph.restrict (member (op =) syms4) program3;
   307   in (syms4, program4) end;
   308 
   309 fun prepare_serializer ctxt (serializer : serializer) reserved identifiers
   310     printings module_name args proto_program syms =
   311   let
   312     val syms_hidden = Code_Symbol.symbols_of printings;
   313     val (syms_all, program) = project_program ctxt syms_hidden syms proto_program;
   314     fun select_include (name, (content, cs)) =
   315       if null cs orelse exists (fn c => member (op =) syms_all (Constant c)) cs
   316       then SOME (name, content) else NONE;
   317     val includes = map_filter select_include (Code_Symbol.dest_module_data printings);
   318   in
   319     (serializer args ctxt {
   320       module_name = module_name,
   321       reserved_syms = reserved,
   322       identifiers = identifiers,
   323       includes = includes,
   324       const_syntax = Code_Symbol.lookup_constant_data printings,
   325       tyco_syntax = Code_Symbol.lookup_type_constructor_data printings,
   326       class_syntax = Code_Symbol.lookup_type_class_data printings },
   327       (subtract (op =) syms_hidden syms, program))
   328   end;
   329 
   330 fun mount_serializer ctxt target_name some_width module_name args program syms =
   331   let
   332     val default_width = Config.get ctxt default_code_width;
   333     val ((target, data), modify) = activate_target ctxt target_name;
   334     val serializer = (#serializer o #language) target;
   335     val (prepared_serializer, (prepared_syms, prepared_program)) =
   336       prepare_serializer ctxt serializer
   337         (Code_Printer.the_reserved data) (Code_Printer.the_identifiers data)
   338         (Code_Printer.the_printings data)
   339         module_name args (modify program) syms
   340     val width = the_default default_width some_width;
   341   in (fn program => fn syms => prepared_serializer syms program width, (prepared_syms, prepared_program)) end;
   342 
   343 fun invoke_serializer ctxt target_name some_width raw_module_name args program all_public syms =
   344   let
   345     val module_name = if raw_module_name = "" then ""
   346       else (check_name true raw_module_name; raw_module_name)
   347     val (mounted_serializer, (prepared_syms, prepared_program)) =
   348       mount_serializer ctxt target_name some_width module_name args program syms;
   349   in
   350     Code_Preproc.timed_exec "serializing"
   351       (fn () => mounted_serializer prepared_program (if all_public then [] else prepared_syms)) ctxt
   352   end;
   353 
   354 fun assert_module_name "" = error "Empty module name not allowed here"
   355   | assert_module_name module_name = module_name;
   356 
   357 val using_master_directory =
   358   Option.map o File.full_path o Resources.master_directory o Proof_Context.theory_of;
   359 
   360 in
   361 
   362 val generatedN = "Generated_Code";
   363 
   364 fun export_code_for ctxt some_path target_name some_width module_name args =
   365   export (using_master_directory ctxt some_path)
   366   ooo invoke_serializer ctxt target_name some_width module_name args;
   367 
   368 fun produce_code_for ctxt target_name some_width module_name args =
   369   let
   370     val serializer = invoke_serializer ctxt target_name some_width (assert_module_name module_name) args;
   371   in fn program => fn all_public => fn syms =>
   372     produce (serializer program all_public syms) |> apsnd (fn deresolve => map deresolve syms)
   373   end;
   374 
   375 fun present_code_for ctxt target_name some_width module_name args =
   376   let
   377     val serializer = invoke_serializer ctxt target_name some_width (assert_module_name module_name) args;
   378   in fn program => fn (syms, selects) =>
   379     present selects (serializer program false syms)
   380   end;
   381 
   382 fun check_code_for ctxt target_name strict args program all_public syms =
   383   let
   384     val { env_var, make_destination, make_command } =
   385       (#check o the_language ctxt) target_name;
   386     fun ext_check p =
   387       let
   388         val destination = make_destination p;
   389         val _ = export (SOME destination) (invoke_serializer ctxt target_name (SOME 80)
   390           generatedN args program all_public syms);
   391         val cmd = make_command generatedN;
   392       in
   393         if Isabelle_System.bash ("cd " ^ File.bash_path p ^ " && " ^ cmd ^ " 2>&1") <> 0
   394         then error ("Code check failed for " ^ target_name ^ ": " ^ cmd)
   395         else ()
   396       end;
   397   in
   398     if not (env_var = "") andalso getenv env_var = ""
   399     then if strict
   400       then error (env_var ^ " not set; cannot check code for " ^ target_name)
   401       else warning (env_var ^ " not set; skipped checking code for " ^ target_name)
   402     else Isabelle_System.with_tmp_dir "Code_Test" ext_check
   403   end;
   404 
   405 fun dynamic_compilation_text mounted_serializer prepared_program syms all_public ((vs, ty), t) =
   406   let
   407     val _ = if Code_Thingol.contains_dict_var t then
   408       error "Term to be evaluated contains free dictionaries" else ();
   409     val v' = singleton (Name.variant_list (map fst vs)) "a";
   410     val vs' = (v', []) :: vs;
   411     val ty' = ITyVar v' `-> ty;
   412     val program = prepared_program
   413       |> Code_Symbol.Graph.new_node (Code_Symbol.value,
   414           Code_Thingol.Fun (((vs', ty'), [(([IVar (SOME "dummy")], t), (NONE, true))]), NONE))
   415       |> fold (curry (perhaps o try o
   416           Code_Symbol.Graph.add_edge) Code_Symbol.value) syms;
   417     val (program_code, deresolve) =
   418       produce (mounted_serializer program (if all_public then [] else [Code_Symbol.value]));
   419     val value_name = the (deresolve Code_Symbol.value);
   420   in ((program_code, value_name), deresolve) end;
   421 
   422 fun compilation_text' ctxt target_name some_module_name program syms =
   423   let
   424     val (mounted_serializer, (_, prepared_program)) =
   425       mount_serializer ctxt target_name NONE (the_default generatedN some_module_name) [] program syms;
   426   in
   427     Code_Preproc.timed_exec "serializing"
   428     (fn () => dynamic_compilation_text mounted_serializer prepared_program syms) ctxt
   429   end;
   430 
   431 fun compilation_text ctxt target_name program syms =
   432   fst oo compilation_text' ctxt target_name NONE program syms
   433   
   434 end; (* local *)
   435 
   436 
   437 (* code generation *)
   438 
   439 fun prep_destination (s, pos) =
   440   if s = "" then NONE
   441   else
   442     let
   443       val _ = Position.report pos Markup.language_path;
   444       val path = Path.explode s;
   445       val _ = Position.report pos (Markup.path (Path.smart_implode path));
   446     in SOME path end;
   447 
   448 fun export_code ctxt all_public cs seris =
   449   let
   450     val program = Code_Thingol.consts_program ctxt cs;
   451     val _ = map (fn (((target_name, module_name), some_path), args) =>
   452       export_code_for ctxt some_path target_name NONE module_name args program all_public (map Constant cs)) seris;
   453   in () end;
   454 
   455 fun export_code_cmd all_public raw_cs seris ctxt =
   456   export_code ctxt all_public
   457     (Code_Thingol.read_const_exprs ctxt raw_cs)
   458     ((map o apfst o apsnd) prep_destination seris);
   459 
   460 fun produce_code ctxt all_public cs target_name some_width some_module_name args =
   461   let
   462     val program = Code_Thingol.consts_program ctxt cs;
   463   in produce_code_for ctxt target_name some_width some_module_name args program all_public (map Constant cs) end;
   464 
   465 fun present_code ctxt cs syms target_name some_width some_module_name args =
   466   let
   467     val program = Code_Thingol.consts_program ctxt cs;
   468   in present_code_for ctxt target_name some_width some_module_name args program (map Constant cs, syms) end;
   469 
   470 fun check_code ctxt all_public cs seris =
   471   let
   472     val program = Code_Thingol.consts_program ctxt cs;
   473     val _ = map (fn ((target_name, strict), args) =>
   474       check_code_for ctxt target_name strict args program all_public (map Constant cs)) seris;
   475   in () end;
   476 
   477 fun check_code_cmd all_public raw_cs seris ctxt =
   478   check_code ctxt all_public
   479     (Code_Thingol.read_const_exprs ctxt raw_cs) seris;
   480 
   481 local
   482 
   483 val parse_const_terms = Scan.repeat1 Args.term
   484   >> (fn ts => fn ctxt => map (Code.check_const (Proof_Context.theory_of ctxt)) ts);
   485 
   486 fun parse_names category parse internalize mark_symbol =
   487   Scan.lift (Args.parens (Args.$$$ category)) |-- Scan.repeat1 parse
   488   >> (fn xs => fn ctxt => map (mark_symbol o internalize ctxt) xs);
   489 
   490 val parse_consts = parse_names "consts" Args.term
   491   (Code.check_const o Proof_Context.theory_of) Constant;
   492 
   493 val parse_types = parse_names "types" (Scan.lift Args.name)
   494   (Sign.intern_type o Proof_Context.theory_of) Type_Constructor;
   495 
   496 val parse_classes = parse_names "classes" (Scan.lift Args.name)
   497   (Sign.intern_class o Proof_Context.theory_of) Type_Class;
   498 
   499 val parse_instances = parse_names "instances" (Scan.lift (Args.name --| Args.$$$ "::" -- Args.name))
   500   (fn ctxt => fn (raw_tyco, raw_class) =>
   501     let
   502       val thy = Proof_Context.theory_of ctxt;
   503     in (Sign.intern_class thy raw_tyco, Sign.intern_type thy raw_class) end) Class_Instance;
   504 
   505 in
   506 
   507 val _ = Theory.setup
   508   (Thy_Output.antiquotation @{binding code_stmts}
   509     (parse_const_terms --
   510       Scan.repeat (parse_consts || parse_types || parse_classes || parse_instances)
   511       -- Scan.lift (Args.parens (Args.name -- Scan.option Parse.int)))
   512     (fn {context = ctxt, ...} => fn ((mk_cs, mk_stmtss), (target_name, some_width)) =>
   513         present_code ctxt (mk_cs ctxt)
   514           (maps (fn f => f ctxt) mk_stmtss)
   515           target_name some_width "Example" []));
   516 
   517 end;
   518 
   519 
   520 (** serializer configuration **)
   521 
   522 (* reserved symbol names *)
   523 
   524 fun add_reserved target_name sym thy =
   525   let
   526     val (_, (_, data)) = join_ancestry thy target_name;
   527     val _ = if member (op =) (Code_Printer.the_reserved data) sym
   528       then error ("Reserved symbol " ^ quote sym ^ " already declared")
   529       else ();
   530   in
   531     thy
   532     |> map_reserved target_name (insert (op =) sym)
   533   end;
   534 
   535 
   536 (* checking of syntax *)
   537 
   538 fun check_const_syntax ctxt target_name c syn =
   539   if Code_Printer.requires_args syn > Code.args_number (Proof_Context.theory_of ctxt) c
   540   then error ("Too many arguments in syntax for constant " ^ quote c)
   541   else Code_Printer.prep_const_syntax (Proof_Context.theory_of ctxt) (the_literals ctxt target_name) c syn;
   542 
   543 fun check_tyco_syntax ctxt target_name tyco syn =
   544   if fst syn <> Sign.arity_number (Proof_Context.theory_of ctxt) tyco
   545   then error ("Number of arguments mismatch in syntax for type constructor " ^ quote tyco)
   546   else syn;
   547 
   548 
   549 (* custom symbol names *)
   550 
   551 fun arrange_name_decls x =
   552   let
   553     fun arrange is_module (sym, target_names) = map (fn (target, some_name) =>
   554       (target, (sym, Option.map (check_name is_module) some_name))) target_names;
   555   in
   556     Code_Symbol.maps_attr' (arrange false) (arrange false) (arrange false)
   557       (arrange false) (arrange false) (arrange true) x
   558   end;
   559 
   560 fun cert_name_decls ctxt = cert_syms ctxt #> arrange_name_decls;
   561 
   562 fun read_name_decls ctxt = read_syms ctxt #> arrange_name_decls;
   563 
   564 fun set_identifier (target_name, sym_name) = map_identifiers target_name (Code_Symbol.set_data sym_name);
   565 
   566 fun gen_set_identifiers prep_name_decl raw_name_decls thy =
   567   fold set_identifier (prep_name_decl (Proof_Context.init_global thy) raw_name_decls) thy;
   568 
   569 val set_identifiers = gen_set_identifiers cert_name_decls;
   570 val set_identifiers_cmd = gen_set_identifiers read_name_decls;
   571 
   572 
   573 (* custom printings *)
   574 
   575 fun arrange_printings prep_const ctxt =
   576   let
   577     fun arrange check (sym, target_syns) =
   578       map (fn (target_name, some_syn) =>
   579         (target_name, (sym, Option.map (check ctxt target_name sym) some_syn))) target_syns;
   580   in
   581     Code_Symbol.maps_attr'
   582       (arrange check_const_syntax) (arrange check_tyco_syntax)
   583         (arrange ((K o K o K) I)) (arrange ((K o K o K) I)) (arrange ((K o K o K) I))
   584         (arrange (fn ctxt => fn _ => fn _ => fn (raw_content, raw_cs) =>
   585           (Pretty.blk (0, Pretty.fbreaks (map Code_Printer.str (split_lines raw_content))),
   586             map (prep_const ctxt) raw_cs)))
   587   end;
   588 
   589 fun cert_printings ctxt = cert_syms ctxt #> arrange_printings cert_const ctxt;
   590 
   591 fun read_printings ctxt = read_syms ctxt #> arrange_printings read_const ctxt;
   592 
   593 fun set_printing (target_name, sym_syn) = map_printings target_name (Code_Symbol.set_data sym_syn);
   594 
   595 fun gen_set_printings prep_print_decl raw_print_decls thy =
   596   fold set_printing (prep_print_decl (Proof_Context.init_global thy) raw_print_decls) thy;
   597 
   598 val set_printings = gen_set_printings cert_printings;
   599 val set_printings_cmd = gen_set_printings read_printings;
   600 
   601 
   602 (* concrete syntax *)
   603 
   604 fun parse_args f args =
   605   case Scan.read Token.stopper f args
   606    of SOME x => x
   607     | NONE => error "Bad serializer arguments";
   608 
   609 
   610 (** Isar setup **)
   611 
   612 fun parse_single_symbol_pragma parse_keyword parse_isa parse_target =
   613   parse_keyword |-- Parse.!!! (parse_isa --| (@{keyword "\<rightharpoonup>"} || @{keyword "=>"})
   614     -- Parse.and_list1 (@{keyword "("} |-- (Parse.name --| @{keyword ")"} -- Scan.option parse_target)));
   615 
   616 fun parse_symbol_pragma parse_const parse_tyco parse_class parse_classrel parse_inst parse_module =
   617   parse_single_symbol_pragma @{keyword "constant"} Parse.term parse_const
   618     >> Constant
   619   || parse_single_symbol_pragma @{keyword "type_constructor"} Parse.type_const parse_tyco
   620     >> Type_Constructor
   621   || parse_single_symbol_pragma @{keyword "type_class"} Parse.class parse_class
   622     >> Type_Class
   623   || parse_single_symbol_pragma @{keyword "class_relation"} parse_classrel_ident parse_classrel
   624     >> Class_Relation
   625   || parse_single_symbol_pragma @{keyword "class_instance"} parse_inst_ident parse_inst
   626     >> Class_Instance
   627   || parse_single_symbol_pragma @{keyword "code_module"} Parse.name parse_module
   628     >> Code_Symbol.Module;
   629 
   630 fun parse_symbol_pragmas parse_const parse_tyco parse_class parse_classrel parse_inst parse_module =
   631   Parse.enum1 "|" (Parse.group (fn () => "code symbol pragma")
   632     (parse_symbol_pragma parse_const parse_tyco parse_class parse_classrel parse_inst parse_module));
   633 
   634 val code_expr_argsP = Scan.optional (@{keyword "("} |-- Parse.args --| @{keyword ")"}) [];
   635 
   636 fun code_expr_inP all_public raw_cs =
   637   Scan.repeat (@{keyword "in"} |-- Parse.!!! (Parse.name
   638     -- Scan.optional (@{keyword "module_name"} |-- Parse.name) ""
   639     -- Scan.optional (@{keyword "file"} |-- Parse.position Parse.path) ("", Position.none)
   640     -- code_expr_argsP))
   641       >> (fn seri_args => export_code_cmd all_public raw_cs seri_args);
   642 
   643 fun code_expr_checkingP all_public raw_cs =
   644   (@{keyword "checking"} |-- Parse.!!!
   645     (Scan.repeat (Parse.name -- ((@{keyword "?"} |-- Scan.succeed false) || Scan.succeed true)
   646     -- code_expr_argsP)))
   647       >> (fn seri_args => check_code_cmd all_public raw_cs seri_args);
   648 
   649 val code_exprP = (Scan.optional (@{keyword "open"} |-- Scan.succeed true) false
   650   -- Scan.repeat1 Parse.term)
   651   :|-- (fn (all_public, raw_cs) => (code_expr_checkingP all_public raw_cs || code_expr_inP all_public raw_cs));
   652 
   653 val _ =
   654   Outer_Syntax.command @{command_keyword code_reserved}
   655     "declare words as reserved for target language"
   656     (Parse.name -- Scan.repeat1 Parse.name
   657       >> (fn (target, reserveds) => (Toplevel.theory o fold (add_reserved target)) reserveds));
   658 
   659 val _ =
   660   Outer_Syntax.command @{command_keyword code_identifier} "declare mandatory names for code symbols"
   661     (parse_symbol_pragmas Parse.name Parse.name Parse.name Parse.name Parse.name Parse.name
   662       >> (Toplevel.theory o fold set_identifiers_cmd));
   663 
   664 val _ =
   665   Outer_Syntax.command @{command_keyword code_printing} "declare dedicated printing for code symbols"
   666     (parse_symbol_pragmas (Code_Printer.parse_const_syntax) (Code_Printer.parse_tyco_syntax)
   667       Parse.string (Parse.minus >> K ()) (Parse.minus >> K ())
   668       (Parse.text -- Scan.optional (@{keyword "attach"} |-- Scan.repeat1 Parse.term) [])
   669       >> (Toplevel.theory o fold set_printings_cmd));
   670 
   671 val _ =
   672   Outer_Syntax.command @{command_keyword export_code} "generate executable code for constants"
   673     (Parse.!!! code_exprP >> (fn f => Toplevel.keep (f o Toplevel.context_of)));
   674 
   675 end; (*struct*)