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