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