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