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