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