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