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