src/Tools/Code/code_runtime.ML
author haftmann
Sun Jan 22 21:39:16 2017 +0100 (2017-01-22)
changeset 64940 19ca3644ec46
parent 64928 18a6b96f8b00
child 64943 c5618df67c2a
permissions -rw-r--r--
experimental computations: use arbitrary generated code for RHSs, not just constants
haftmann@39401
     1
(*  Title:      Tools/Code/code_runtime.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@34028
     4
Runtime services building on code generation into implementation language SML.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@39401
     7
signature CODE_RUNTIME =
haftmann@28054
     8
sig
haftmann@34028
     9
  val target: string
haftmann@39912
    10
  val value: Proof.context ->
haftmann@39912
    11
    (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string ->
haftmann@39912
    12
    string * string -> 'a
haftmann@39473
    13
  type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string
haftmann@55757
    14
  val dynamic_value: 'a cookie -> Proof.context -> string option
haftmann@39473
    15
    -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a option
haftmann@55757
    16
  val dynamic_value_strict: 'a cookie -> Proof.context -> string option
haftmann@39473
    17
    -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a
haftmann@55757
    18
  val dynamic_value_exn: 'a cookie -> Proof.context -> string option
haftmann@39473
    19
    -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a Exn.result
haftmann@56973
    20
  val static_value: 'a cookie -> { ctxt: Proof.context, target: string option,
haftmann@56973
    21
    lift_postproc: (term -> term) -> 'a -> 'a, consts: string list }
haftmann@56973
    22
    -> Proof.context -> term -> 'a option
haftmann@56973
    23
  val static_value_strict: 'a cookie -> { ctxt: Proof.context, target: string option,
haftmann@56973
    24
    lift_postproc: (term -> term) -> 'a -> 'a, consts: string list }
haftmann@56973
    25
    -> Proof.context -> term -> 'a
haftmann@56973
    26
  val static_value_exn: 'a cookie -> { ctxt: Proof.context, target: string option,
haftmann@56973
    27
    lift_postproc: (term -> term) -> 'a -> 'a, consts: string list }
haftmann@56973
    28
    -> Proof.context -> term -> 'a Exn.result
haftmann@55757
    29
  val dynamic_holds_conv: Proof.context -> conv
haftmann@56973
    30
  val static_holds_conv: { ctxt: Proof.context, consts: string list } -> Proof.context -> conv
haftmann@64940
    31
  val experimental_computation: (Proof.context -> term -> 'a) cookie
haftmann@58643
    32
    -> { ctxt: Proof.context, lift_postproc: (term -> term) -> 'a -> 'a,
haftmann@64940
    33
           terms: term list, T: typ }
haftmann@58643
    34
    -> Proof.context -> term -> 'a (*EXPERIMENTAL!*)
haftmann@40421
    35
  val code_reflect: (string * string list option) list -> string list -> string
haftmann@40421
    36
    -> string option -> theory -> theory
haftmann@39473
    37
  datatype truth = Holds
haftmann@39473
    38
  val put_truth: (unit -> truth) -> Proof.context -> Proof.context
haftmann@57435
    39
  val trace: bool Config.T
haftmann@39816
    40
  val polyml_as_definition: (binding * typ) list -> Path.T list -> theory -> theory
haftmann@28054
    41
end;
haftmann@28054
    42
haftmann@39401
    43
structure Code_Runtime : CODE_RUNTIME =
haftmann@28054
    44
struct
haftmann@28054
    45
haftmann@55150
    46
open Basic_Code_Symbol;
haftmann@39473
    47
haftmann@63157
    48
(** computation **)
haftmann@33992
    49
haftmann@39473
    50
(* technical prerequisites *)
haftmann@39473
    51
haftmann@39473
    52
val this = "Code_Runtime";
haftmann@39473
    53
val s_truth = Long_Name.append this "truth";
haftmann@39473
    54
val s_Holds = Long_Name.append this "Holds";
haftmann@39473
    55
haftmann@34028
    56
val target = "Eval";
haftmann@28054
    57
haftmann@39473
    58
datatype truth = Holds;
haftmann@39422
    59
wenzelm@53171
    60
val _ = Theory.setup
haftmann@59104
    61
  (Code_Target.add_derived_target (target, [(Code_ML.target_SML, I)])
haftmann@55150
    62
  #> Code_Target.set_printings (Type_Constructor (@{type_name prop},
haftmann@52435
    63
    [(target, SOME (0, (K o K o K) (Code_Printer.str s_truth)))]))
haftmann@55150
    64
  #> Code_Target.set_printings (Constant (@{const_name Code_Generator.holds},
haftmann@52435
    65
    [(target, SOME (Code_Printer.plain_const_syntax s_Holds))]))
haftmann@39473
    66
  #> Code_Target.add_reserved target this
wenzelm@53171
    67
  #> fold (Code_Target.add_reserved target) ["oo", "ooo", "oooo", "upto", "downto", "orf", "andf"]);
haftmann@39485
    68
       (*avoid further pervasive infix names*)
haftmann@39473
    69
haftmann@57435
    70
val trace = Attrib.setup_config_bool @{binding "code_runtime_trace"} (K false);
haftmann@40150
    71
haftmann@63163
    72
fun compile_ML verbose code context =
haftmann@63163
    73
 (if Config.get_generic context trace then tracing code else ();
haftmann@63164
    74
  Code_Preproc.timed "compiling ML" Context.proof_of
haftmann@63164
    75
    (ML_Context.exec (fn () => ML_Compiler0.ML ML_Env.context
haftmann@63163
    76
    {line = 0, file = "generated code", verbose = verbose,
haftmann@63164
    77
       debug = false} code)) context);
haftmann@39912
    78
haftmann@39912
    79
fun value ctxt (get, put, put_ml) (prelude, value) =
haftmann@39912
    80
  let
wenzelm@62889
    81
    val code =
wenzelm@62889
    82
      prelude ^ "\nval _ = Context.put_generic_context (SOME (Context.map_proof (" ^
wenzelm@62889
    83
      put_ml ^ " (fn () => " ^ value ^ ")) (Context.the_generic_context ())))";
haftmann@39912
    84
    val ctxt' = ctxt
haftmann@63157
    85
      |> put (fn () => error ("Bad computation for " ^ quote put_ml))
haftmann@63163
    86
      |> Context.proof_map (compile_ML false code);
haftmann@63164
    87
    val computator = get ctxt';
haftmann@63164
    88
  in Code_Preproc.timed_exec "running ML" computator ctxt' end;
haftmann@39912
    89
haftmann@39473
    90
haftmann@63157
    91
(* computation as evaluation into ML language values *)
haftmann@39473
    92
haftmann@39473
    93
type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string;
haftmann@39473
    94
haftmann@55757
    95
fun reject_vars ctxt t =
haftmann@55757
    96
  ((Sign.no_frees ctxt o Sign.no_vars ctxt o map_types (K dummyT)) t; t);
haftmann@39605
    97
haftmann@63157
    98
fun build_computation_text ctxt some_target program consts =
haftmann@63157
    99
  Code_Target.computation_text ctxt (the_default target some_target) program consts false
haftmann@63157
   100
  #>> (fn ml_modules => space_implode "\n\n" (map snd ml_modules));
haftmann@63157
   101
haftmann@63157
   102
fun run_computation_text cookie ctxt comp vs_t args =
haftmann@55757
   103
  let
haftmann@63157
   104
    val (program_code, value_name) = comp vs_t;
haftmann@39473
   105
    val value_code = space_implode " "
haftmann@41347
   106
      (value_name :: "()" :: map (enclose "(" ")") args);
wenzelm@40235
   107
  in Exn.interruptible_capture (value ctxt cookie) (program_code, value_code) end;
haftmann@39473
   108
haftmann@39473
   109
fun partiality_as_none e = SOME (Exn.release e)
haftmann@39473
   110
  handle General.Match => NONE
haftmann@39473
   111
    | General.Bind => NONE
haftmann@39473
   112
    | General.Fail _ => NONE;
haftmann@39473
   113
haftmann@55757
   114
fun dynamic_value_exn cookie ctxt some_target postproc t args =
haftmann@39473
   115
  let
haftmann@55757
   116
    val _ = reject_vars ctxt t;
haftmann@57435
   117
    val _ = if Config.get ctxt trace
haftmann@55757
   118
      then tracing ("Evaluation of term " ^ quote (Syntax.string_of_term ctxt t))
haftmann@41099
   119
      else ()
haftmann@63157
   120
    fun comp program _ vs_ty_t deps =
haftmann@63157
   121
      run_computation_text cookie ctxt (build_computation_text ctxt some_target program deps) vs_ty_t args;
haftmann@63157
   122
  in Code_Thingol.dynamic_value ctxt (Exn.map_res o postproc) comp t end;
haftmann@39473
   123
haftmann@55757
   124
fun dynamic_value_strict cookie ctxt some_target postproc t args =
haftmann@55757
   125
  Exn.release (dynamic_value_exn cookie ctxt some_target postproc t args);
haftmann@39473
   126
haftmann@55757
   127
fun dynamic_value cookie ctxt some_target postproc t args =
haftmann@55757
   128
  partiality_as_none (dynamic_value_exn cookie ctxt some_target postproc t args);
haftmann@39473
   129
haftmann@56973
   130
fun static_value_exn cookie { ctxt, target, lift_postproc, consts } =
haftmann@55757
   131
  let
haftmann@63157
   132
    fun computation' { program, deps } =
haftmann@63157
   133
      let
haftmann@63157
   134
        val computation'' = run_computation_text cookie ctxt
haftmann@63157
   135
          (build_computation_text ctxt target program (map Constant deps));
haftmann@63157
   136
      in fn _ => fn _ => fn vs_ty_t => fn _ => computation'' vs_ty_t [] end;
haftmann@63157
   137
    val computation = Code_Thingol.static_value { ctxt = ctxt,
wenzelm@61077
   138
      lift_postproc = Exn.map_res o lift_postproc, consts = consts }
haftmann@63157
   139
      computation';
haftmann@63157
   140
  in fn ctxt' => computation ctxt' o reject_vars ctxt' end;
haftmann@39473
   141
haftmann@64928
   142
fun static_value_strict cookie x = Exn.release oo static_value_exn cookie x;
haftmann@41347
   143
haftmann@64928
   144
fun static_value cookie x = partiality_as_none oo static_value_exn cookie x;
haftmann@39473
   145
haftmann@39473
   146
haftmann@39473
   147
(* evaluation for truth or nothing *)
haftmann@39473
   148
wenzelm@39820
   149
structure Truth_Result = Proof_Data
wenzelm@39820
   150
(
wenzelm@59155
   151
  type T = unit -> truth;
wenzelm@59155
   152
  val empty: T = fn () => raise Fail "Truth_Result";
wenzelm@59155
   153
  fun init _ = empty;
haftmann@39473
   154
);
haftmann@39473
   155
val put_truth = Truth_Result.put;
haftmann@39473
   156
val truth_cookie = (Truth_Result.get, put_truth, Long_Name.append this "put_truth");
haftmann@39473
   157
haftmann@58558
   158
local
haftmann@39605
   159
haftmann@58558
   160
val reject_vars = fn ctxt => tap (reject_vars ctxt o Thm.term_of);
haftmann@41349
   161
haftmann@55757
   162
fun check_holds ctxt evaluator vs_t ct =
haftmann@39473
   163
  let
haftmann@39473
   164
    val t = Thm.term_of ct;
haftmann@39473
   165
    val _ = if fastype_of t <> propT
wenzelm@59633
   166
      then error ("Not a proposition: " ^ Syntax.string_of_term ctxt t)
haftmann@39473
   167
      else ();
wenzelm@59633
   168
    val iff = Thm.cterm_of ctxt (Term.Const (@{const_name Pure.eq}, propT --> propT --> propT));
haftmann@63157
   169
    val result = case partiality_as_none (run_computation_text truth_cookie ctxt evaluator vs_t [])
haftmann@39473
   170
     of SOME Holds => true
haftmann@39473
   171
      | _ => false;
haftmann@39473
   172
  in
haftmann@39473
   173
    Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
haftmann@39473
   174
  end;
haftmann@39473
   175
haftmann@39473
   176
val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
wenzelm@43619
   177
  (Thm.add_oracle (@{binding holds_by_evaluation},
haftmann@55757
   178
  fn (ctxt, evaluator, vs_t, ct) => check_holds ctxt evaluator vs_t ct)));
haftmann@39473
   179
haftmann@56920
   180
fun check_holds_oracle ctxt evaluator vs_ty_t ct =
haftmann@56920
   181
  raw_check_holds_oracle (ctxt, evaluator, vs_ty_t, ct);
haftmann@41349
   182
haftmann@41349
   183
in
haftmann@39485
   184
haftmann@55757
   185
fun dynamic_holds_conv ctxt = Code_Thingol.dynamic_conv ctxt
haftmann@56969
   186
  (fn program => fn vs_t => fn deps =>
haftmann@63157
   187
    check_holds_oracle ctxt (build_computation_text ctxt NONE program deps) vs_t)
haftmann@55757
   188
      o reject_vars ctxt;
haftmann@39473
   189
haftmann@56973
   190
fun static_holds_conv (ctxt_consts as { ctxt, ... }) =
haftmann@63156
   191
  Code_Thingol.static_conv_thingol ctxt_consts (fn { program, deps } => fn ctxt' => fn vs_t =>
haftmann@63157
   192
    K (check_holds_oracle ctxt' (build_computation_text ctxt NONE program (map Constant deps)) vs_t o reject_vars ctxt'));
haftmann@41349
   193
haftmann@41349
   194
end; (*local*)
haftmann@39404
   195
haftmann@39404
   196
haftmann@64940
   197
(** computations -- experimental! **)
haftmann@64940
   198
haftmann@64940
   199
fun typ_signatures_for T =
haftmann@64940
   200
  let
haftmann@64940
   201
    val (Ts, T') = strip_type T;
haftmann@64940
   202
  in map_range (fn n => (drop n Ts ---> T', take n Ts)) (length Ts + 1) end;
haftmann@64940
   203
haftmann@64940
   204
fun typ_signatures cTs =
haftmann@64940
   205
  let
haftmann@64940
   206
    fun add (c, T) =
haftmann@64940
   207
      fold (fn (T, Ts) => Typtab.map_default (T, []) (cons (c, Ts)))
haftmann@64940
   208
        (typ_signatures_for T);
haftmann@64940
   209
  in
haftmann@64940
   210
    Typtab.empty
haftmann@64940
   211
    |> fold add cTs
haftmann@64940
   212
    |> Typtab.lookup_list
haftmann@64940
   213
  end;
haftmann@64940
   214
haftmann@64940
   215
fun print_of_term_funs { typ_sign_for, eval_for_const, of_term_for_typ } Ts =
haftmann@64940
   216
  let
haftmann@64940
   217
    val var_names = map_range (fn n => "t" ^ string_of_int (n + 1));
haftmann@64940
   218
    fun print_lhs c xs = "Const (" ^ quote c ^ ", _)"
haftmann@64940
   219
      |> fold (fn x => fn s => s ^ " $ " ^ x) xs
haftmann@64940
   220
      |> enclose "(" ")"
haftmann@64940
   221
      |> prefix "ctxt ";
haftmann@64940
   222
    fun print_rhs c Ts T xs = eval_for_const (c, Ts ---> T)
haftmann@64940
   223
      |> fold2 (fn T' => fn x => fn s =>
haftmann@64940
   224
         s ^ (" (" ^ of_term_for_typ T' ^ " ctxt " ^ x ^ ")")) Ts xs
haftmann@64940
   225
    fun print_eq T (c, Ts) =
haftmann@64940
   226
      let
haftmann@64940
   227
        val xs = var_names (length Ts);
haftmann@64940
   228
      in print_lhs c xs ^ " = " ^ print_rhs c Ts T xs end;
haftmann@64940
   229
    val err_eq =
haftmann@64940
   230
      "ctxt t = error (" ^ quote "Bad term: " ^ " ^ Syntax.string_of_term ctxt t)";
haftmann@64940
   231
    fun print_eqs T =
haftmann@64940
   232
      let
haftmann@64940
   233
        val typ_signs = typ_sign_for T;
haftmann@64940
   234
        val name = of_term_for_typ T;
haftmann@64940
   235
      in
haftmann@64940
   236
        (map (print_eq T) typ_signs @ [err_eq])
haftmann@64940
   237
        |> map (prefix (name ^ " "))
haftmann@64940
   238
        |> space_implode "\n  | "
haftmann@64940
   239
      end;
haftmann@64940
   240
  in
haftmann@64940
   241
    map print_eqs Ts
haftmann@64940
   242
    |> space_implode "\nand "
haftmann@64940
   243
    |> prefix "fun "
haftmann@64940
   244
  end;
haftmann@64940
   245
haftmann@64940
   246
local
haftmann@64940
   247
haftmann@64940
   248
fun tycos_of (Type (tyco, Ts)) = maps tycos_of Ts @ [tyco]
haftmann@64940
   249
  | tycos_of _ = [];
haftmann@64940
   250
haftmann@64940
   251
val ml_name_of = Name.desymbolize NONE o Long_Name.base_name;
haftmann@64940
   252
haftmann@64940
   253
in
haftmann@64940
   254
haftmann@64940
   255
fun of_term_for_typ Ts =
haftmann@64940
   256
  let
haftmann@64940
   257
    val names = Ts
haftmann@64940
   258
      |> map (suffix "_of_term" o space_implode "_" o map ml_name_of o tycos_of)
haftmann@64940
   259
      |> Name.variant_list [];
haftmann@64940
   260
  in the o AList.lookup (op =) (Ts ~~ names) end;
haftmann@64940
   261
haftmann@64940
   262
fun eval_for_const ctxt cTs =
haftmann@64940
   263
  let
haftmann@64940
   264
    fun symbol_list (c, T) = c :: maps tycos_of (Sign.const_typargs (Proof_Context.theory_of ctxt) (c, T))
haftmann@64940
   265
    val names = cTs
haftmann@64940
   266
      |> map (prefix "eval_" o space_implode "_" o map ml_name_of o symbol_list)
haftmann@64940
   267
      |> Name.variant_list [];
haftmann@64940
   268
  in the o AList.lookup (op =) (cTs ~~ names) end;
haftmann@64940
   269
haftmann@64940
   270
end;
haftmann@64940
   271
haftmann@64940
   272
val generated_computationN = "Generated_Computation";
haftmann@64940
   273
haftmann@64940
   274
fun print_computation_code ctxt compiled_value T cTs =
haftmann@64940
   275
  let
haftmann@64940
   276
    val typ_sign_for = typ_signatures cTs;
haftmann@64940
   277
    fun add_typ T Ts =
haftmann@64940
   278
      if member (op =) Ts T
haftmann@64940
   279
      then Ts
haftmann@64940
   280
      else Ts
haftmann@64940
   281
        |> cons T
haftmann@64940
   282
        |> fold (fold add_typ o snd) (typ_sign_for T);
haftmann@64940
   283
    val Ts = add_typ T [];
haftmann@64940
   284
    val of_term_for_typ' = of_term_for_typ Ts;
haftmann@64940
   285
    val of_terms = map of_term_for_typ' Ts;
haftmann@64940
   286
    val eval_for_const' = eval_for_const ctxt cTs;
haftmann@64940
   287
    val evals = map eval_for_const' cTs;
haftmann@64940
   288
    val eval_tuple = enclose "(" ")" (commas evals);
haftmann@64940
   289
    val eval_abs = space_implode "" (map (fn s => "fn " ^ s ^ " => ") evals);
haftmann@64940
   290
    val of_term_code = print_of_term_funs {
haftmann@64940
   291
      typ_sign_for = typ_sign_for,
haftmann@64940
   292
      eval_for_const = eval_for_const',
haftmann@64940
   293
      of_term_for_typ = of_term_for_typ' } Ts;
haftmann@64940
   294
  in
haftmann@64940
   295
    (cat_lines [
haftmann@64940
   296
      "structure " ^ generated_computationN ^ " =",
haftmann@64940
   297
      "struct",
haftmann@64940
   298
      "",
haftmann@64940
   299
      "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
haftmann@64940
   300
      "  (" ^ eval_abs,
haftmann@64940
   301
      "    " ^ eval_tuple ^ ");",
haftmann@64940
   302
      "",
haftmann@64940
   303
      of_term_code,
haftmann@64940
   304
      "",
haftmann@64940
   305
      "end"
haftmann@64940
   306
    ], map (prefix (generated_computationN ^ ".")) of_terms)
haftmann@64940
   307
  end;
haftmann@64940
   308
haftmann@64940
   309
fun compile_computation cookie ctxt T program evals vs_ty_evals deps =
haftmann@64940
   310
  let
haftmann@64940
   311
    val raw_cTs = case evals of
haftmann@64940
   312
        Abs (_, _, t) => (snd o strip_comb) t
haftmann@64940
   313
      | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
haftmann@64940
   314
    val cTs = map (fn Const cT => cT
haftmann@64940
   315
      | t => error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)) raw_cTs;
haftmann@64940
   316
    fun comp' vs_ty_evals =
haftmann@64940
   317
      let
haftmann@64940
   318
        val (generated_code, compiled_value) =
haftmann@64940
   319
          build_computation_text ctxt NONE program deps vs_ty_evals;
haftmann@64940
   320
        val (of_term_code, of_terms) = print_computation_code ctxt compiled_value T cTs;
haftmann@64940
   321
      in
haftmann@64940
   322
        (generated_code ^ "\n" ^ of_term_code,
haftmann@64940
   323
          enclose "(" ")" ("fn () => " ^ List.last of_terms))
haftmann@64940
   324
      end;
haftmann@64940
   325
    val compiled_computation =
haftmann@64940
   326
      Exn.release (run_computation_text cookie ctxt comp' vs_ty_evals []);
haftmann@64940
   327
  in fn ctxt' =>
haftmann@64940
   328
    compiled_computation ctxt' o reject_vars ctxt' o Syntax.check_term ctxt' o Type.constraint T
haftmann@64940
   329
  end;
haftmann@64940
   330
haftmann@64940
   331
fun experimental_computation cookie { ctxt, lift_postproc, terms = ts, T } =
haftmann@64940
   332
  let
haftmann@64940
   333
    val cTs = (fold o fold_aterms) (fn Const cT => insert (op =) cT | _ => I) ts [];
haftmann@64940
   334
    val vT = TFree (singleton (Name.variant_list
haftmann@64940
   335
      (fold (fn (_, T) => fold_atyps (fn TFree (v, _) => insert (op =) v | _ => I)
haftmann@64940
   336
        T) cTs [])) Name.aT, []);
haftmann@64940
   337
    val evals = Abs ("eval", map snd cTs ---> vT, list_comb (Bound 0, map Const cTs));
haftmann@64940
   338
    val computation = Code_Thingol.dynamic_value ctxt
haftmann@64940
   339
      (K I) (compile_computation cookie ctxt T) evals;
haftmann@64940
   340
  in
haftmann@64940
   341
    Code_Preproc.static_value { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
haftmann@64940
   342
      (K computation)
haftmann@64940
   343
  end;
haftmann@64940
   344
haftmann@64940
   345
haftmann@64940
   346
(** code antiquotation **)
haftmann@39404
   347
haftmann@58557
   348
fun evaluation_code ctxt module_name program tycos consts =
haftmann@33992
   349
  let
haftmann@55757
   350
    val thy = Proof_Context.theory_of ctxt;
haftmann@48568
   351
    val (ml_modules, target_names) =
haftmann@55757
   352
      Code_Target.produce_code_for ctxt
haftmann@55683
   353
        target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
haftmann@48568
   354
    val ml_code = space_implode "\n\n" (map snd ml_modules);
haftmann@55147
   355
    val (consts', tycos') = chop (length consts) target_names;
wenzelm@42359
   356
    val consts_map = map2 (fn const =>
wenzelm@42359
   357
      fn NONE =>
wenzelm@42359
   358
          error ("Constant " ^ (quote o Code.string_of_const thy) const ^
wenzelm@42359
   359
            "\nhas a user-defined serialization")
haftmann@55147
   360
       | SOME const' => (const, const')) consts consts'
wenzelm@42359
   361
    val tycos_map = map2 (fn tyco =>
wenzelm@42359
   362
      fn NONE =>
wenzelm@55304
   363
          error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
wenzelm@42359
   364
            "\nhas a user-defined serialization")
haftmann@55147
   365
        | SOME tyco' => (tyco, tyco')) tycos tycos';
haftmann@34028
   366
  in (ml_code, (tycos_map, consts_map)) end;
haftmann@28054
   367
haftmann@28054
   368
local
haftmann@28054
   369
haftmann@38930
   370
structure Code_Antiq_Data = Proof_Data
haftmann@28054
   371
(
haftmann@38930
   372
  type T = (string list * string list) * (bool
haftmann@40421
   373
    * (string * (string * string) list) lazy);
wenzelm@59150
   374
  val empty: T = (([], []), (true, (Lazy.value ("", []))));
wenzelm@59150
   375
  fun init _ = empty;
haftmann@28054
   376
);
haftmann@28054
   377
haftmann@38930
   378
val is_first_occ = fst o snd o Code_Antiq_Data.get;
haftmann@28054
   379
haftmann@30962
   380
fun register_code new_tycos new_consts ctxt =
haftmann@28054
   381
  let
haftmann@38930
   382
    val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
haftmann@30962
   383
    val tycos' = fold (insert (op =)) new_tycos tycos;
haftmann@30962
   384
    val consts' = fold (insert (op =)) new_consts consts;
haftmann@63159
   385
    val program = Code_Thingol.consts_program ctxt consts';
haftmann@38930
   386
    val acc_code = Lazy.lazy (fn () =>
haftmann@64940
   387
      evaluation_code ctxt Code_Target.generatedN program tycos' consts'
haftmann@40422
   388
      |> apsnd snd);
haftmann@38930
   389
  in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
haftmann@30962
   390
haftmann@30962
   391
fun register_const const = register_code [] [const];
haftmann@28054
   392
haftmann@40421
   393
fun print_code is_first const ctxt =
haftmann@30962
   394
  let
haftmann@38930
   395
    val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
haftmann@40421
   396
    val (ml_code, consts_map) = Lazy.force acc_code;
haftmann@40422
   397
    val ml_code = if is_first then ml_code else "";
wenzelm@59127
   398
    val body = ML_Context.struct_name ctxt ^ "." ^ the (AList.lookup (op =) consts_map const);
wenzelm@41376
   399
  in (ml_code, body) end;
haftmann@28054
   400
haftmann@28054
   401
in
haftmann@28054
   402
wenzelm@56069
   403
fun ml_code_antiq raw_const ctxt =
haftmann@28054
   404
  let
wenzelm@53169
   405
    val thy = Proof_Context.theory_of ctxt;
wenzelm@53169
   406
    val const = Code.check_const thy raw_const;
wenzelm@53169
   407
    val is_first = is_first_occ ctxt;
wenzelm@56069
   408
  in (print_code is_first const, register_const const ctxt) end;
haftmann@30962
   409
haftmann@28054
   410
end; (*local*)
haftmann@28054
   411
haftmann@28054
   412
haftmann@58558
   413
(** reflection support **)
haftmann@36470
   414
haftmann@40421
   415
fun check_datatype thy tyco some_consts =
haftmann@36470
   416
  let
haftmann@63174
   417
    val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
haftmann@63174
   418
    val constrs = case some_consts
haftmann@63174
   419
     of SOME [] => []
haftmann@63174
   420
      | SOME consts =>
haftmann@40421
   421
          let
haftmann@63174
   422
            val missing_constrs = subtract (op =) consts declared_constrs;
haftmann@40421
   423
            val _ = if null missing_constrs then []
wenzelm@45430
   424
              else error ("Missing constructor(s) " ^ commas_quote missing_constrs
haftmann@40421
   425
                ^ " for datatype " ^ quote tyco);
haftmann@63174
   426
            val false_constrs = subtract (op =) declared_constrs consts;
haftmann@40421
   427
            val _ = if null false_constrs then []
wenzelm@45430
   428
              else error ("Non-constructor(s) " ^ commas_quote false_constrs
haftmann@40421
   429
                ^ " for datatype " ^ quote tyco)
haftmann@63174
   430
          in consts end
haftmann@63174
   431
      | NONE => declared_constrs;
haftmann@40421
   432
  in (tyco, constrs) end;
haftmann@36470
   433
haftmann@36470
   434
fun add_eval_tyco (tyco, tyco') thy =
haftmann@36470
   435
  let
haftmann@36470
   436
    val k = Sign.arity_number thy tyco;
haftmann@40421
   437
    fun pr pr' _ [] = tyco'
haftmann@40421
   438
      | pr pr' _ [ty] =
haftmann@36470
   439
          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
haftmann@40421
   440
      | pr pr' _ tys =
haftmann@36470
   441
          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
haftmann@36470
   442
  in
haftmann@36470
   443
    thy
haftmann@55150
   444
    |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
haftmann@36470
   445
  end;
haftmann@36470
   446
haftmann@36514
   447
fun add_eval_constr (const, const') thy =
haftmann@36514
   448
  let
haftmann@36514
   449
    val k = Code.args_number thy const;
haftmann@36514
   450
    fun pr pr' fxy ts = Code_Printer.brackify fxy
haftmann@38922
   451
      (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
haftmann@36514
   452
  in
haftmann@36514
   453
    thy
haftmann@55150
   454
    |> Code_Target.set_printings (Constant (const,
haftmann@52435
   455
      [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
haftmann@36514
   456
  end;
haftmann@36514
   457
haftmann@55150
   458
fun add_eval_const (const, const') = Code_Target.set_printings (Constant
haftmann@52435
   459
  (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
haftmann@36470
   460
haftmann@39912
   461
fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
haftmann@38935
   462
      thy
haftmann@38935
   463
      |> Code_Target.add_reserved target module_name
haftmann@63163
   464
      |> Context.theory_map (compile_ML true code)
haftmann@38935
   465
      |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
haftmann@38935
   466
      |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
haftmann@38935
   467
      |> fold (add_eval_const o apsnd Code_Printer.str) const_map
haftmann@39912
   468
  | process_reflection (code, _) _ (SOME file_name) thy =
haftmann@36470
   469
      let
wenzelm@37950
   470
        val preamble =
wenzelm@46737
   471
          "(* Generated from " ^
wenzelm@56208
   472
            Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
wenzelm@46737
   473
          "; DO NOT EDIT! *)";
haftmann@39912
   474
        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
haftmann@36470
   475
      in
haftmann@36470
   476
        thy
haftmann@36470
   477
      end;
haftmann@36470
   478
haftmann@36470
   479
fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
haftmann@36470
   480
  let
haftmann@55757
   481
    val ctxt = Proof_Context.init_global thy;
haftmann@36470
   482
    val datatypes = map (fn (raw_tyco, raw_cos) =>
haftmann@55757
   483
      (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
haftmann@40421
   484
    val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
haftmann@40421
   485
      |> apsnd flat;
haftmann@36470
   486
    val functions = map (prep_const thy) raw_functions;
haftmann@58557
   487
    val consts = constrs @ functions;
haftmann@63159
   488
    val program = Code_Thingol.consts_program ctxt consts;
haftmann@58557
   489
    val result = evaluation_code ctxt module_name program tycos consts
haftmann@36514
   490
      |> (apsnd o apsnd) (chop (length constrs));
haftmann@36470
   491
  in
haftmann@36470
   492
    thy
haftmann@39485
   493
    |> process_reflection result module_name some_file
haftmann@36470
   494
  end;
haftmann@36470
   495
haftmann@39422
   496
val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
haftmann@36470
   497
val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
haftmann@36470
   498
haftmann@36470
   499
haftmann@28054
   500
(** Isar setup **)
haftmann@28054
   501
wenzelm@56069
   502
val _ =
wenzelm@56205
   503
  Theory.setup (ML_Antiquotation.declaration @{binding code} Args.term (fn _ => ml_code_antiq));
haftmann@28054
   504
haftmann@36470
   505
local
haftmann@36470
   506
wenzelm@36960
   507
val parse_datatype =
haftmann@63174
   508
  Parse.name -- Scan.optional (@{keyword "="} |--
haftmann@40711
   509
    (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
haftmann@63174
   510
    || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
haftmann@36470
   511
haftmann@36470
   512
in
haftmann@36470
   513
haftmann@36470
   514
val _ =
wenzelm@59936
   515
  Outer_Syntax.command @{command_keyword code_reflect}
wenzelm@46961
   516
    "enrich runtime environment with generated code"
haftmann@63174
   517
    (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
wenzelm@46949
   518
      ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
haftmann@52434
   519
    -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
haftmann@52434
   520
    -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
wenzelm@46961
   521
    >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
wenzelm@46961
   522
      (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
haftmann@36470
   523
haftmann@36470
   524
end; (*local*)
haftmann@36470
   525
haftmann@39816
   526
haftmann@39816
   527
(** using external SML files as substitute for proper definitions -- only for polyml!  **)
haftmann@39816
   528
haftmann@39816
   529
local
haftmann@39816
   530
wenzelm@39820
   531
structure Loaded_Values = Theory_Data
wenzelm@39820
   532
(
haftmann@39816
   533
  type T = string list
haftmann@39816
   534
  val empty = []
wenzelm@41472
   535
  val extend = I
wenzelm@39820
   536
  fun merge data : T = Library.merge (op =) data
haftmann@39816
   537
);
haftmann@39816
   538
haftmann@39816
   539
fun notify_val (string, value) = 
haftmann@39816
   540
  let
wenzelm@62495
   541
    val _ = #enterVal ML_Env.name_space (string, value);
wenzelm@53171
   542
    val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
haftmann@39816
   543
  in () end;
haftmann@39816
   544
haftmann@39816
   545
fun abort _ = error "Only value bindings allowed.";
haftmann@39816
   546
wenzelm@62494
   547
val notifying_context : ML_Compiler0.context =
wenzelm@62354
   548
 {name_space =
wenzelm@62495
   549
   {lookupVal    = #lookupVal ML_Env.name_space,
wenzelm@62495
   550
    lookupType   = #lookupType ML_Env.name_space,
wenzelm@62495
   551
    lookupFix    = #lookupFix ML_Env.name_space,
wenzelm@62495
   552
    lookupStruct = #lookupStruct ML_Env.name_space,
wenzelm@62495
   553
    lookupSig    = #lookupSig ML_Env.name_space,
wenzelm@62495
   554
    lookupFunct  = #lookupFunct ML_Env.name_space,
haftmann@39816
   555
    enterVal     = notify_val,
haftmann@39816
   556
    enterType    = abort,
haftmann@39816
   557
    enterFix     = abort,
haftmann@39816
   558
    enterStruct  = abort,
haftmann@39816
   559
    enterSig     = abort,
haftmann@39816
   560
    enterFunct   = abort,
wenzelm@62495
   561
    allVal       = #allVal ML_Env.name_space,
wenzelm@62495
   562
    allType      = #allType ML_Env.name_space,
wenzelm@62495
   563
    allFix       = #allFix ML_Env.name_space,
wenzelm@62495
   564
    allStruct    = #allStruct ML_Env.name_space,
wenzelm@62495
   565
    allSig       = #allSig ML_Env.name_space,
wenzelm@62495
   566
    allFunct     = #allFunct ML_Env.name_space},
wenzelm@62716
   567
  print_depth = NONE,
wenzelm@62495
   568
  here = #here ML_Env.context,
wenzelm@62495
   569
  print = #print ML_Env.context,
wenzelm@62495
   570
  error = #error ML_Env.context};
haftmann@39816
   571
haftmann@39816
   572
in
haftmann@39816
   573
haftmann@39816
   574
fun use_file filepath thy =
haftmann@39816
   575
  let
haftmann@39816
   576
    val thy' = Loaded_Values.put [] thy;
wenzelm@62889
   577
    val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
wenzelm@60956
   578
    val _ =
wenzelm@62902
   579
      ML_Compiler0.ML notifying_context
wenzelm@60956
   580
        {line = 0, file = Path.implode filepath, verbose = false, debug = false}
wenzelm@60956
   581
        (File.read filepath);
wenzelm@62876
   582
    val thy'' = Context.the_global_context ();
haftmann@39912
   583
    val names = Loaded_Values.get thy'';
haftmann@40320
   584
  in (names, thy'') end;
haftmann@39816
   585
haftmann@39816
   586
end;
haftmann@39816
   587
haftmann@39816
   588
fun add_definiendum (ml_name, (b, T)) thy =
haftmann@39816
   589
  thy
haftmann@39816
   590
  |> Code_Target.add_reserved target ml_name
wenzelm@63178
   591
  |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
haftmann@39816
   592
  |-> (fn ([Const (const, _)], _) =>
haftmann@55150
   593
    Code_Target.set_printings (Constant (const,
haftmann@52435
   594
      [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
haftmann@64940
   595
  #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
haftmann@39816
   596
haftmann@39816
   597
fun process_file filepath (definienda, thy) =
haftmann@39816
   598
  let
haftmann@39816
   599
    val (ml_names, thy') = use_file filepath thy;
haftmann@39816
   600
    val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
haftmann@39816
   601
    val _ = if null superfluous then ()
haftmann@39816
   602
      else error ("Value binding(s) " ^ commas_quote superfluous
wenzelm@41944
   603
        ^ " found in external file " ^ Path.print filepath
haftmann@39816
   604
        ^ " not present among the given contants binding(s).");
haftmann@39816
   605
    val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
haftmann@39816
   606
    val thy'' = fold add_definiendum these_definienda thy';
haftmann@39816
   607
    val definienda' = fold (AList.delete (op =)) ml_names definienda;
haftmann@39816
   608
  in (definienda', thy'') end;
haftmann@39816
   609
haftmann@39816
   610
fun polyml_as_definition bTs filepaths thy =
haftmann@39816
   611
  let
haftmann@39816
   612
    val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
haftmann@39816
   613
    val (remaining, thy') = fold process_file filepaths (definienda, thy);
haftmann@39816
   614
    val _ = if null remaining then ()
haftmann@39816
   615
      else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
haftmann@39816
   616
        ^ " not present in external file(s).");
haftmann@39816
   617
  in thy' end;
haftmann@39816
   618
haftmann@28054
   619
end; (*struct*)