src/Tools/Code/code_runtime.ML
author haftmann
Thu Jan 26 16:06:18 2017 +0100 (2017-01-26)
changeset 64954 e5f535f90d61
parent 64946 03b5f4e7f4a6
child 64955 25281bee02ac
permissions -rw-r--r--
dropped dead code
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@64943
    31
  val experimental_computation: (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@64943
   199
fun monomorphic T = fold_atyps ((K o K) false) T true;
haftmann@64943
   200
haftmann@64940
   201
fun typ_signatures_for T =
haftmann@64940
   202
  let
haftmann@64940
   203
    val (Ts, T') = strip_type T;
haftmann@64940
   204
  in map_range (fn n => (drop n Ts ---> T', take n Ts)) (length Ts + 1) end;
haftmann@64940
   205
haftmann@64940
   206
fun typ_signatures cTs =
haftmann@64940
   207
  let
haftmann@64940
   208
    fun add (c, T) =
haftmann@64940
   209
      fold (fn (T, Ts) => Typtab.map_default (T, []) (cons (c, Ts)))
haftmann@64940
   210
        (typ_signatures_for T);
haftmann@64940
   211
  in
haftmann@64940
   212
    Typtab.empty
haftmann@64940
   213
    |> fold add cTs
haftmann@64940
   214
    |> Typtab.lookup_list
haftmann@64940
   215
  end;
haftmann@64940
   216
haftmann@64940
   217
fun print_of_term_funs { typ_sign_for, eval_for_const, of_term_for_typ } Ts =
haftmann@64940
   218
  let
haftmann@64940
   219
    val var_names = map_range (fn n => "t" ^ string_of_int (n + 1));
haftmann@64940
   220
    fun print_lhs c xs = "Const (" ^ quote c ^ ", _)"
haftmann@64940
   221
      |> fold (fn x => fn s => s ^ " $ " ^ x) xs
haftmann@64943
   222
      |> enclose "(" ")";
haftmann@64940
   223
    fun print_rhs c Ts T xs = eval_for_const (c, Ts ---> T)
haftmann@64940
   224
      |> fold2 (fn T' => fn x => fn s =>
haftmann@64943
   225
         s ^ (" (" ^ of_term_for_typ T' ^ " " ^ x ^ ")")) Ts xs
haftmann@64940
   226
    fun print_eq T (c, Ts) =
haftmann@64940
   227
      let
haftmann@64940
   228
        val xs = var_names (length Ts);
haftmann@64940
   229
      in print_lhs c xs ^ " = " ^ print_rhs c Ts T xs end;
haftmann@64940
   230
    fun print_eqs T =
haftmann@64940
   231
      let
haftmann@64940
   232
        val typ_signs = typ_sign_for T;
haftmann@64940
   233
        val name = of_term_for_typ T;
haftmann@64940
   234
      in
haftmann@64943
   235
        map (print_eq T) typ_signs
haftmann@64940
   236
        |> map (prefix (name ^ " "))
haftmann@64940
   237
        |> space_implode "\n  | "
haftmann@64940
   238
      end;
haftmann@64940
   239
  in
haftmann@64940
   240
    map print_eqs Ts
haftmann@64940
   241
    |> space_implode "\nand "
haftmann@64940
   242
    |> prefix "fun "
haftmann@64940
   243
  end;
haftmann@64940
   244
haftmann@64940
   245
local
haftmann@64940
   246
haftmann@64940
   247
fun tycos_of (Type (tyco, Ts)) = maps tycos_of Ts @ [tyco]
haftmann@64940
   248
  | tycos_of _ = [];
haftmann@64940
   249
haftmann@64940
   250
val ml_name_of = Name.desymbolize NONE o Long_Name.base_name;
haftmann@64940
   251
haftmann@64940
   252
in
haftmann@64940
   253
haftmann@64940
   254
fun of_term_for_typ Ts =
haftmann@64940
   255
  let
haftmann@64940
   256
    val names = Ts
haftmann@64940
   257
      |> map (suffix "_of_term" o space_implode "_" o map ml_name_of o tycos_of)
haftmann@64940
   258
      |> Name.variant_list [];
haftmann@64940
   259
  in the o AList.lookup (op =) (Ts ~~ names) end;
haftmann@64940
   260
haftmann@64940
   261
fun eval_for_const ctxt cTs =
haftmann@64940
   262
  let
haftmann@64940
   263
    fun symbol_list (c, T) = c :: maps tycos_of (Sign.const_typargs (Proof_Context.theory_of ctxt) (c, T))
haftmann@64940
   264
    val names = cTs
haftmann@64940
   265
      |> map (prefix "eval_" o space_implode "_" o map ml_name_of o symbol_list)
haftmann@64940
   266
      |> Name.variant_list [];
haftmann@64940
   267
  in the o AList.lookup (op =) (cTs ~~ names) end;
haftmann@64940
   268
haftmann@64940
   269
end;
haftmann@64940
   270
haftmann@64940
   271
val generated_computationN = "Generated_Computation";
haftmann@64940
   272
haftmann@64944
   273
fun print_computation_code ctxt compiled_value requested_Ts cTs =
haftmann@64940
   274
  let
haftmann@64945
   275
    val proper_cTs = map_filter I cTs;
haftmann@64945
   276
    val typ_sign_for = typ_signatures proper_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@64944
   283
    val required_Ts = fold add_typ requested_Ts [];
haftmann@64944
   284
    val of_term_for_typ' = of_term_for_typ required_Ts;
haftmann@64945
   285
    val eval_for_const' = eval_for_const ctxt proper_cTs;
haftmann@64945
   286
    val eval_for_const'' = the_default "_" o Option.map eval_for_const';
haftmann@64945
   287
    val eval_tuple = enclose "(" ")" (commas (map eval_for_const' proper_cTs));
haftmann@64945
   288
    fun mk_abs s = "fn " ^ s ^ " => ";
haftmann@64945
   289
    val eval_abs = space_implode ""
haftmann@64945
   290
      (map (mk_abs o eval_for_const'') cTs);
haftmann@64940
   291
    val of_term_code = print_of_term_funs {
haftmann@64940
   292
      typ_sign_for = typ_sign_for,
haftmann@64940
   293
      eval_for_const = eval_for_const',
haftmann@64944
   294
      of_term_for_typ = of_term_for_typ' } required_Ts;
haftmann@64940
   295
  in
haftmann@64940
   296
    (cat_lines [
haftmann@64940
   297
      "structure " ^ generated_computationN ^ " =",
haftmann@64940
   298
      "struct",
haftmann@64940
   299
      "",
haftmann@64940
   300
      "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
haftmann@64940
   301
      "  (" ^ eval_abs,
haftmann@64940
   302
      "    " ^ eval_tuple ^ ");",
haftmann@64940
   303
      "",
haftmann@64940
   304
      of_term_code,
haftmann@64940
   305
      "",
haftmann@64940
   306
      "end"
haftmann@64944
   307
    ], map (prefix (generated_computationN ^ ".") o of_term_for_typ') requested_Ts)
haftmann@64940
   308
  end;
haftmann@64940
   309
haftmann@64943
   310
fun check_typ ctxt T t =
haftmann@64943
   311
  Syntax.check_term ctxt (Type.constraint T t);
haftmann@64943
   312
haftmann@64943
   313
fun check_computation_input ctxt cTs t =
haftmann@64943
   314
  let
haftmann@64943
   315
    fun check t = check_comb (strip_comb t)
haftmann@64943
   316
    and check_comb (t as Abs _, _) =
haftmann@64943
   317
          error ("Bad term, contains abstraction: " ^ Syntax.string_of_term ctxt t)
haftmann@64943
   318
      | check_comb (t as Const (cT as (c, T)), ts) =
haftmann@64943
   319
          let
haftmann@64943
   320
            val _ = if not (member (op =) cTs cT)
haftmann@64943
   321
              then error ("Bad term, computation cannot proceed on constant " ^ Syntax.string_of_term ctxt t)
haftmann@64943
   322
              else ();
haftmann@64943
   323
            val _ = if not (monomorphic T)
haftmann@64943
   324
              then error ("Bad term, contains polymorphic constant " ^ Syntax.string_of_term ctxt t)
haftmann@64943
   325
              else ();
haftmann@64943
   326
            val _ = map check ts;
haftmann@64943
   327
          in () end;
haftmann@64943
   328
    val _ = check t;
haftmann@64943
   329
  in t end;
haftmann@64943
   330
haftmann@64940
   331
fun compile_computation cookie ctxt T program evals vs_ty_evals deps =
haftmann@64940
   332
  let
haftmann@64945
   333
    fun the_const (Const cT) = cT
haftmann@64945
   334
      | the_const t = error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)
haftmann@64940
   335
    val raw_cTs = case evals of
haftmann@64945
   336
        Abs (_, _, t) => (map the_const o snd o strip_comb) t
haftmann@64940
   337
      | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
haftmann@64945
   338
    val cTs = fold_rev (fn cT => fn cTs =>
haftmann@64945
   339
      (if member (op =) cTs (SOME cT) then NONE else SOME cT) :: cTs) raw_cTs [];
haftmann@64940
   340
    fun comp' vs_ty_evals =
haftmann@64940
   341
      let
haftmann@64940
   342
        val (generated_code, compiled_value) =
haftmann@64940
   343
          build_computation_text ctxt NONE program deps vs_ty_evals;
haftmann@64944
   344
        val (of_term_code, [of_term]) = print_computation_code ctxt compiled_value [T] cTs;
haftmann@64940
   345
      in
haftmann@64940
   346
        (generated_code ^ "\n" ^ of_term_code,
haftmann@64944
   347
          enclose "(" ")" ("fn () => " ^ of_term))
haftmann@64940
   348
      end;
haftmann@64940
   349
    val compiled_computation =
haftmann@64940
   350
      Exn.release (run_computation_text cookie ctxt comp' vs_ty_evals []);
haftmann@64940
   351
  in fn ctxt' =>
haftmann@64943
   352
    check_typ ctxt' T
haftmann@64943
   353
    #> reject_vars ctxt'
haftmann@64945
   354
    #> check_computation_input ctxt (map_filter I cTs)
haftmann@64943
   355
    #> compiled_computation
haftmann@64940
   356
  end;
haftmann@64940
   357
haftmann@64940
   358
fun experimental_computation cookie { ctxt, lift_postproc, terms = ts, T } =
haftmann@64940
   359
  let
haftmann@64944
   360
    val _ = if not (monomorphic T)
haftmann@64944
   361
      then error ("Polymorphic type: " ^ Syntax.string_of_typ ctxt T)
haftmann@64944
   362
      else ();
haftmann@64943
   363
    val cTs = (fold o fold_aterms)
haftmann@64943
   364
      (fn (t as Const (cT as (_, T))) =>
haftmann@64943
   365
        if not (monomorphic T) then error ("Polymorphic constant:" ^ Syntax.string_of_term ctxt t)
haftmann@64943
   366
        else insert (op =) cT | _ => I) ts [];
haftmann@64944
   367
    val evals = Abs ("eval", map snd cTs ---> TFree (Name.aT, []), list_comb (Bound 0, map Const cTs));
haftmann@64940
   368
    val computation = Code_Thingol.dynamic_value ctxt
haftmann@64940
   369
      (K I) (compile_computation cookie ctxt T) evals;
haftmann@64940
   370
  in
haftmann@64940
   371
    Code_Preproc.static_value { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
haftmann@64940
   372
      (K computation)
haftmann@64940
   373
  end;
haftmann@64940
   374
haftmann@64940
   375
haftmann@64940
   376
(** code antiquotation **)
haftmann@39404
   377
haftmann@58557
   378
fun evaluation_code ctxt module_name program tycos consts =
haftmann@33992
   379
  let
haftmann@55757
   380
    val thy = Proof_Context.theory_of ctxt;
haftmann@48568
   381
    val (ml_modules, target_names) =
haftmann@55757
   382
      Code_Target.produce_code_for ctxt
haftmann@55683
   383
        target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
haftmann@48568
   384
    val ml_code = space_implode "\n\n" (map snd ml_modules);
haftmann@55147
   385
    val (consts', tycos') = chop (length consts) target_names;
wenzelm@42359
   386
    val consts_map = map2 (fn const =>
wenzelm@42359
   387
      fn NONE =>
wenzelm@42359
   388
          error ("Constant " ^ (quote o Code.string_of_const thy) const ^
wenzelm@42359
   389
            "\nhas a user-defined serialization")
haftmann@55147
   390
       | SOME const' => (const, const')) consts consts'
wenzelm@42359
   391
    val tycos_map = map2 (fn tyco =>
wenzelm@42359
   392
      fn NONE =>
wenzelm@55304
   393
          error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
wenzelm@42359
   394
            "\nhas a user-defined serialization")
haftmann@55147
   395
        | SOME tyco' => (tyco, tyco')) tycos tycos';
haftmann@34028
   396
  in (ml_code, (tycos_map, consts_map)) end;
haftmann@28054
   397
haftmann@28054
   398
local
haftmann@28054
   399
haftmann@38930
   400
structure Code_Antiq_Data = Proof_Data
haftmann@28054
   401
(
haftmann@64946
   402
  type T = string list * (bool
haftmann@40421
   403
    * (string * (string * string) list) lazy);
haftmann@64946
   404
  val empty: T = ([], (true, (Lazy.value ("", []))));
wenzelm@59150
   405
  fun init _ = empty;
haftmann@28054
   406
);
haftmann@28054
   407
haftmann@38930
   408
val is_first_occ = fst o snd o Code_Antiq_Data.get;
haftmann@28054
   409
haftmann@64954
   410
fun register_const const ctxt =
haftmann@28054
   411
  let
haftmann@64946
   412
    val (consts, _) = Code_Antiq_Data.get ctxt;
haftmann@64954
   413
    val consts' = insert (op =) const consts;
haftmann@63159
   414
    val program = Code_Thingol.consts_program ctxt consts';
haftmann@38930
   415
    val acc_code = Lazy.lazy (fn () =>
haftmann@64946
   416
      evaluation_code ctxt Code_Target.generatedN program [] consts'
haftmann@40422
   417
      |> apsnd snd);
haftmann@64946
   418
  in Code_Antiq_Data.put (consts', (false, acc_code)) ctxt end;
haftmann@30962
   419
haftmann@40421
   420
fun print_code is_first const ctxt =
haftmann@30962
   421
  let
haftmann@38930
   422
    val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
haftmann@40421
   423
    val (ml_code, consts_map) = Lazy.force acc_code;
haftmann@40422
   424
    val ml_code = if is_first then ml_code else "";
wenzelm@59127
   425
    val body = ML_Context.struct_name ctxt ^ "." ^ the (AList.lookup (op =) consts_map const);
wenzelm@41376
   426
  in (ml_code, body) end;
haftmann@28054
   427
haftmann@28054
   428
in
haftmann@28054
   429
wenzelm@56069
   430
fun ml_code_antiq raw_const ctxt =
haftmann@28054
   431
  let
wenzelm@53169
   432
    val thy = Proof_Context.theory_of ctxt;
wenzelm@53169
   433
    val const = Code.check_const thy raw_const;
wenzelm@53169
   434
    val is_first = is_first_occ ctxt;
wenzelm@56069
   435
  in (print_code is_first const, register_const const ctxt) end;
haftmann@30962
   436
haftmann@28054
   437
end; (*local*)
haftmann@28054
   438
haftmann@28054
   439
haftmann@58558
   440
(** reflection support **)
haftmann@36470
   441
haftmann@40421
   442
fun check_datatype thy tyco some_consts =
haftmann@36470
   443
  let
haftmann@63174
   444
    val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
haftmann@63174
   445
    val constrs = case some_consts
haftmann@63174
   446
     of SOME [] => []
haftmann@63174
   447
      | SOME consts =>
haftmann@40421
   448
          let
haftmann@63174
   449
            val missing_constrs = subtract (op =) consts declared_constrs;
haftmann@40421
   450
            val _ = if null missing_constrs then []
wenzelm@45430
   451
              else error ("Missing constructor(s) " ^ commas_quote missing_constrs
haftmann@40421
   452
                ^ " for datatype " ^ quote tyco);
haftmann@63174
   453
            val false_constrs = subtract (op =) declared_constrs consts;
haftmann@40421
   454
            val _ = if null false_constrs then []
wenzelm@45430
   455
              else error ("Non-constructor(s) " ^ commas_quote false_constrs
haftmann@40421
   456
                ^ " for datatype " ^ quote tyco)
haftmann@63174
   457
          in consts end
haftmann@63174
   458
      | NONE => declared_constrs;
haftmann@40421
   459
  in (tyco, constrs) end;
haftmann@36470
   460
haftmann@36470
   461
fun add_eval_tyco (tyco, tyco') thy =
haftmann@36470
   462
  let
haftmann@36470
   463
    val k = Sign.arity_number thy tyco;
haftmann@40421
   464
    fun pr pr' _ [] = tyco'
haftmann@40421
   465
      | pr pr' _ [ty] =
haftmann@36470
   466
          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
haftmann@40421
   467
      | pr pr' _ tys =
haftmann@36470
   468
          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
haftmann@36470
   469
  in
haftmann@36470
   470
    thy
haftmann@55150
   471
    |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
haftmann@36470
   472
  end;
haftmann@36470
   473
haftmann@36514
   474
fun add_eval_constr (const, const') thy =
haftmann@36514
   475
  let
haftmann@36514
   476
    val k = Code.args_number thy const;
haftmann@36514
   477
    fun pr pr' fxy ts = Code_Printer.brackify fxy
haftmann@38922
   478
      (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
haftmann@36514
   479
  in
haftmann@36514
   480
    thy
haftmann@55150
   481
    |> Code_Target.set_printings (Constant (const,
haftmann@52435
   482
      [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
haftmann@36514
   483
  end;
haftmann@36514
   484
haftmann@55150
   485
fun add_eval_const (const, const') = Code_Target.set_printings (Constant
haftmann@52435
   486
  (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
haftmann@36470
   487
haftmann@39912
   488
fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
haftmann@38935
   489
      thy
haftmann@38935
   490
      |> Code_Target.add_reserved target module_name
haftmann@63163
   491
      |> Context.theory_map (compile_ML true code)
haftmann@38935
   492
      |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
haftmann@38935
   493
      |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
haftmann@38935
   494
      |> fold (add_eval_const o apsnd Code_Printer.str) const_map
haftmann@39912
   495
  | process_reflection (code, _) _ (SOME file_name) thy =
haftmann@36470
   496
      let
wenzelm@37950
   497
        val preamble =
wenzelm@46737
   498
          "(* Generated from " ^
wenzelm@56208
   499
            Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
wenzelm@46737
   500
          "; DO NOT EDIT! *)";
haftmann@39912
   501
        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
haftmann@36470
   502
      in
haftmann@36470
   503
        thy
haftmann@36470
   504
      end;
haftmann@36470
   505
haftmann@36470
   506
fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
haftmann@36470
   507
  let
haftmann@55757
   508
    val ctxt = Proof_Context.init_global thy;
haftmann@36470
   509
    val datatypes = map (fn (raw_tyco, raw_cos) =>
haftmann@55757
   510
      (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
haftmann@40421
   511
    val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
haftmann@40421
   512
      |> apsnd flat;
haftmann@36470
   513
    val functions = map (prep_const thy) raw_functions;
haftmann@58557
   514
    val consts = constrs @ functions;
haftmann@63159
   515
    val program = Code_Thingol.consts_program ctxt consts;
haftmann@58557
   516
    val result = evaluation_code ctxt module_name program tycos consts
haftmann@36514
   517
      |> (apsnd o apsnd) (chop (length constrs));
haftmann@36470
   518
  in
haftmann@36470
   519
    thy
haftmann@39485
   520
    |> process_reflection result module_name some_file
haftmann@36470
   521
  end;
haftmann@36470
   522
haftmann@39422
   523
val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
haftmann@36470
   524
val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
haftmann@36470
   525
haftmann@36470
   526
haftmann@28054
   527
(** Isar setup **)
haftmann@28054
   528
wenzelm@56069
   529
val _ =
wenzelm@56205
   530
  Theory.setup (ML_Antiquotation.declaration @{binding code} Args.term (fn _ => ml_code_antiq));
haftmann@28054
   531
haftmann@36470
   532
local
haftmann@36470
   533
wenzelm@36960
   534
val parse_datatype =
haftmann@63174
   535
  Parse.name -- Scan.optional (@{keyword "="} |--
haftmann@40711
   536
    (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
haftmann@63174
   537
    || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
haftmann@36470
   538
haftmann@36470
   539
in
haftmann@36470
   540
haftmann@36470
   541
val _ =
wenzelm@59936
   542
  Outer_Syntax.command @{command_keyword code_reflect}
wenzelm@46961
   543
    "enrich runtime environment with generated code"
haftmann@63174
   544
    (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
wenzelm@46949
   545
      ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
haftmann@52434
   546
    -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
haftmann@52434
   547
    -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
wenzelm@46961
   548
    >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
wenzelm@46961
   549
      (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
haftmann@36470
   550
haftmann@36470
   551
end; (*local*)
haftmann@36470
   552
haftmann@39816
   553
haftmann@39816
   554
(** using external SML files as substitute for proper definitions -- only for polyml!  **)
haftmann@39816
   555
haftmann@39816
   556
local
haftmann@39816
   557
wenzelm@39820
   558
structure Loaded_Values = Theory_Data
wenzelm@39820
   559
(
haftmann@39816
   560
  type T = string list
haftmann@39816
   561
  val empty = []
wenzelm@41472
   562
  val extend = I
wenzelm@39820
   563
  fun merge data : T = Library.merge (op =) data
haftmann@39816
   564
);
haftmann@39816
   565
haftmann@39816
   566
fun notify_val (string, value) = 
haftmann@39816
   567
  let
wenzelm@62495
   568
    val _ = #enterVal ML_Env.name_space (string, value);
wenzelm@53171
   569
    val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
haftmann@39816
   570
  in () end;
haftmann@39816
   571
haftmann@39816
   572
fun abort _ = error "Only value bindings allowed.";
haftmann@39816
   573
wenzelm@62494
   574
val notifying_context : ML_Compiler0.context =
wenzelm@62354
   575
 {name_space =
wenzelm@62495
   576
   {lookupVal    = #lookupVal ML_Env.name_space,
wenzelm@62495
   577
    lookupType   = #lookupType ML_Env.name_space,
wenzelm@62495
   578
    lookupFix    = #lookupFix ML_Env.name_space,
wenzelm@62495
   579
    lookupStruct = #lookupStruct ML_Env.name_space,
wenzelm@62495
   580
    lookupSig    = #lookupSig ML_Env.name_space,
wenzelm@62495
   581
    lookupFunct  = #lookupFunct ML_Env.name_space,
haftmann@39816
   582
    enterVal     = notify_val,
haftmann@39816
   583
    enterType    = abort,
haftmann@39816
   584
    enterFix     = abort,
haftmann@39816
   585
    enterStruct  = abort,
haftmann@39816
   586
    enterSig     = abort,
haftmann@39816
   587
    enterFunct   = abort,
wenzelm@62495
   588
    allVal       = #allVal ML_Env.name_space,
wenzelm@62495
   589
    allType      = #allType ML_Env.name_space,
wenzelm@62495
   590
    allFix       = #allFix ML_Env.name_space,
wenzelm@62495
   591
    allStruct    = #allStruct ML_Env.name_space,
wenzelm@62495
   592
    allSig       = #allSig ML_Env.name_space,
wenzelm@62495
   593
    allFunct     = #allFunct ML_Env.name_space},
wenzelm@62716
   594
  print_depth = NONE,
wenzelm@62495
   595
  here = #here ML_Env.context,
wenzelm@62495
   596
  print = #print ML_Env.context,
wenzelm@62495
   597
  error = #error ML_Env.context};
haftmann@39816
   598
haftmann@39816
   599
in
haftmann@39816
   600
haftmann@39816
   601
fun use_file filepath thy =
haftmann@39816
   602
  let
haftmann@39816
   603
    val thy' = Loaded_Values.put [] thy;
wenzelm@62889
   604
    val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
wenzelm@60956
   605
    val _ =
wenzelm@62902
   606
      ML_Compiler0.ML notifying_context
wenzelm@60956
   607
        {line = 0, file = Path.implode filepath, verbose = false, debug = false}
wenzelm@60956
   608
        (File.read filepath);
wenzelm@62876
   609
    val thy'' = Context.the_global_context ();
haftmann@39912
   610
    val names = Loaded_Values.get thy'';
haftmann@40320
   611
  in (names, thy'') end;
haftmann@39816
   612
haftmann@39816
   613
end;
haftmann@39816
   614
haftmann@39816
   615
fun add_definiendum (ml_name, (b, T)) thy =
haftmann@39816
   616
  thy
haftmann@39816
   617
  |> Code_Target.add_reserved target ml_name
wenzelm@63178
   618
  |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
haftmann@39816
   619
  |-> (fn ([Const (const, _)], _) =>
haftmann@55150
   620
    Code_Target.set_printings (Constant (const,
haftmann@52435
   621
      [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
haftmann@64940
   622
  #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
haftmann@39816
   623
haftmann@39816
   624
fun process_file filepath (definienda, thy) =
haftmann@39816
   625
  let
haftmann@39816
   626
    val (ml_names, thy') = use_file filepath thy;
haftmann@39816
   627
    val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
haftmann@39816
   628
    val _ = if null superfluous then ()
haftmann@39816
   629
      else error ("Value binding(s) " ^ commas_quote superfluous
wenzelm@41944
   630
        ^ " found in external file " ^ Path.print filepath
haftmann@39816
   631
        ^ " not present among the given contants binding(s).");
haftmann@39816
   632
    val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
haftmann@39816
   633
    val thy'' = fold add_definiendum these_definienda thy';
haftmann@39816
   634
    val definienda' = fold (AList.delete (op =)) ml_names definienda;
haftmann@39816
   635
  in (definienda', thy'') end;
haftmann@39816
   636
haftmann@39816
   637
fun polyml_as_definition bTs filepaths thy =
haftmann@39816
   638
  let
haftmann@39816
   639
    val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
haftmann@39816
   640
    val (remaining, thy') = fold process_file filepaths (definienda, thy);
haftmann@39816
   641
    val _ = if null remaining then ()
haftmann@39816
   642
      else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
haftmann@39816
   643
        ^ " not present in external file(s).");
haftmann@39816
   644
  in thy' end;
haftmann@39816
   645
haftmann@28054
   646
end; (*struct*)