src/Tools/Code/code_runtime.ML
author haftmann
Mon Feb 06 20:56:32 2017 +0100 (2017-02-06)
changeset 64988 93aaff2b0ae0
parent 64987 1985502518ce
child 64989 40c36a4aee1f
permissions -rw-r--r--
computations and partiality
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@40421
    31
  val code_reflect: (string * string list option) list -> string list -> string
haftmann@40421
    32
    -> string option -> theory -> theory
haftmann@39473
    33
  datatype truth = Holds
haftmann@39473
    34
  val put_truth: (unit -> truth) -> Proof.context -> Proof.context
haftmann@64987
    35
  val mount_computation: Proof.context -> (string * typ) list -> typ
haftmann@64988
    36
    -> (term -> 'ml) -> ((term -> term) -> 'ml option -> 'a) -> Proof.context -> term -> 'a
haftmann@64987
    37
  val polyml_as_definition: (binding * typ) list -> Path.T list -> theory -> theory
haftmann@57435
    38
  val trace: bool Config.T
haftmann@28054
    39
end;
haftmann@28054
    40
haftmann@39401
    41
structure Code_Runtime : CODE_RUNTIME =
haftmann@28054
    42
struct
haftmann@28054
    43
haftmann@55150
    44
open Basic_Code_Symbol;
haftmann@39473
    45
haftmann@64957
    46
(** ML compiler as evaluation environment **)
haftmann@33992
    47
haftmann@39473
    48
(* technical prerequisites *)
haftmann@39473
    49
haftmann@64959
    50
val thisN = "Code_Runtime";
haftmann@64987
    51
val prefix_this = Long_Name.append thisN;
haftmann@64987
    52
val truthN = prefix_this "truth";
haftmann@64987
    53
val HoldsN = prefix_this "Holds";
haftmann@39473
    54
haftmann@34028
    55
val target = "Eval";
haftmann@28054
    56
haftmann@39473
    57
datatype truth = Holds;
haftmann@39422
    58
wenzelm@53171
    59
val _ = Theory.setup
haftmann@59104
    60
  (Code_Target.add_derived_target (target, [(Code_ML.target_SML, I)])
haftmann@55150
    61
  #> Code_Target.set_printings (Type_Constructor (@{type_name prop},
haftmann@64959
    62
    [(target, SOME (0, (K o K o K) (Code_Printer.str truthN)))]))
haftmann@55150
    63
  #> Code_Target.set_printings (Constant (@{const_name Code_Generator.holds},
haftmann@64959
    64
    [(target, SOME (Code_Printer.plain_const_syntax HoldsN))]))
haftmann@64959
    65
  #> Code_Target.add_reserved target thisN
wenzelm@53171
    66
  #> fold (Code_Target.add_reserved target) ["oo", "ooo", "oooo", "upto", "downto", "orf", "andf"]);
haftmann@39485
    67
       (*avoid further pervasive infix names*)
haftmann@39473
    68
haftmann@57435
    69
val trace = Attrib.setup_config_bool @{binding "code_runtime_trace"} (K false);
haftmann@40150
    70
haftmann@63163
    71
fun compile_ML verbose code context =
haftmann@63163
    72
 (if Config.get_generic context trace then tracing code else ();
haftmann@63164
    73
  Code_Preproc.timed "compiling ML" Context.proof_of
haftmann@63164
    74
    (ML_Context.exec (fn () => ML_Compiler0.ML ML_Env.context
haftmann@63163
    75
    {line = 0, file = "generated code", verbose = verbose,
haftmann@63164
    76
       debug = false} code)) context);
haftmann@39912
    77
haftmann@39912
    78
fun value ctxt (get, put, put_ml) (prelude, value) =
haftmann@39912
    79
  let
wenzelm@62889
    80
    val code =
wenzelm@62889
    81
      prelude ^ "\nval _ = Context.put_generic_context (SOME (Context.map_proof (" ^
wenzelm@62889
    82
      put_ml ^ " (fn () => " ^ value ^ ")) (Context.the_generic_context ())))";
haftmann@39912
    83
    val ctxt' = ctxt
haftmann@64957
    84
      |> put (fn () => error ("Bad compilation for " ^ quote put_ml))
haftmann@63163
    85
      |> Context.proof_map (compile_ML false code);
haftmann@63164
    86
    val computator = get ctxt';
haftmann@63164
    87
  in Code_Preproc.timed_exec "running ML" computator ctxt' end;
haftmann@39912
    88
haftmann@39473
    89
haftmann@64957
    90
(* evaluation into ML language values *)
haftmann@39473
    91
haftmann@39473
    92
type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string;
haftmann@39473
    93
haftmann@55757
    94
fun reject_vars ctxt t =
haftmann@55757
    95
  ((Sign.no_frees ctxt o Sign.no_vars ctxt o map_types (K dummyT)) t; t);
haftmann@39605
    96
haftmann@64957
    97
fun build_compilation_text ctxt some_target program consts =
haftmann@64957
    98
  Code_Target.compilation_text ctxt (the_default target some_target) program consts false
haftmann@63157
    99
  #>> (fn ml_modules => space_implode "\n\n" (map snd ml_modules));
haftmann@63157
   100
haftmann@64957
   101
fun run_compilation_text cookie ctxt comp vs_t args =
haftmann@55757
   102
  let
haftmann@63157
   103
    val (program_code, value_name) = comp vs_t;
haftmann@39473
   104
    val value_code = space_implode " "
haftmann@41347
   105
      (value_name :: "()" :: map (enclose "(" ")") args);
wenzelm@40235
   106
  in Exn.interruptible_capture (value ctxt cookie) (program_code, value_code) end;
haftmann@39473
   107
haftmann@39473
   108
fun partiality_as_none e = SOME (Exn.release e)
haftmann@39473
   109
  handle General.Match => NONE
haftmann@39473
   110
    | General.Bind => NONE
haftmann@39473
   111
    | General.Fail _ => NONE;
haftmann@39473
   112
haftmann@55757
   113
fun dynamic_value_exn cookie ctxt some_target postproc t args =
haftmann@39473
   114
  let
haftmann@55757
   115
    val _ = reject_vars ctxt t;
haftmann@57435
   116
    val _ = if Config.get ctxt trace
haftmann@55757
   117
      then tracing ("Evaluation of term " ^ quote (Syntax.string_of_term ctxt t))
haftmann@41099
   118
      else ()
haftmann@63157
   119
    fun comp program _ vs_ty_t deps =
haftmann@64957
   120
      run_compilation_text cookie ctxt (build_compilation_text ctxt some_target program deps) vs_ty_t args;
haftmann@63157
   121
  in Code_Thingol.dynamic_value ctxt (Exn.map_res o postproc) comp t end;
haftmann@39473
   122
haftmann@55757
   123
fun dynamic_value_strict cookie ctxt some_target postproc t args =
haftmann@55757
   124
  Exn.release (dynamic_value_exn cookie ctxt some_target postproc t args);
haftmann@39473
   125
haftmann@55757
   126
fun dynamic_value cookie ctxt some_target postproc t args =
haftmann@55757
   127
  partiality_as_none (dynamic_value_exn cookie ctxt some_target postproc t args);
haftmann@39473
   128
haftmann@56973
   129
fun static_value_exn cookie { ctxt, target, lift_postproc, consts } =
haftmann@55757
   130
  let
haftmann@64957
   131
    fun compilation' { program, deps } =
haftmann@63157
   132
      let
haftmann@64957
   133
        val compilation'' = run_compilation_text cookie ctxt
haftmann@64957
   134
          (build_compilation_text ctxt target program (map Constant deps));
haftmann@64957
   135
      in fn _ => fn _ => fn vs_ty_t => fn _ => compilation'' vs_ty_t [] end;
haftmann@64957
   136
    val compilation = Code_Thingol.static_value { ctxt = ctxt,
wenzelm@61077
   137
      lift_postproc = Exn.map_res o lift_postproc, consts = consts }
haftmann@64957
   138
      compilation';
haftmann@64957
   139
  in fn ctxt' => compilation ctxt' o reject_vars ctxt' end;
haftmann@39473
   140
haftmann@64928
   141
fun static_value_strict cookie x = Exn.release oo static_value_exn cookie x;
haftmann@41347
   142
haftmann@64928
   143
fun static_value cookie x = partiality_as_none oo static_value_exn cookie x;
haftmann@39473
   144
haftmann@39473
   145
haftmann@39473
   146
(* evaluation for truth or nothing *)
haftmann@39473
   147
wenzelm@39820
   148
structure Truth_Result = Proof_Data
wenzelm@39820
   149
(
wenzelm@59155
   150
  type T = unit -> truth;
wenzelm@59155
   151
  val empty: T = fn () => raise Fail "Truth_Result";
wenzelm@59155
   152
  fun init _ = empty;
haftmann@39473
   153
);
haftmann@39473
   154
val put_truth = Truth_Result.put;
haftmann@64987
   155
val truth_cookie = (Truth_Result.get, put_truth, prefix_this "put_truth");
haftmann@39473
   156
haftmann@58558
   157
local
haftmann@39605
   158
haftmann@58558
   159
val reject_vars = fn ctxt => tap (reject_vars ctxt o Thm.term_of);
haftmann@41349
   160
haftmann@55757
   161
fun check_holds ctxt evaluator vs_t ct =
haftmann@39473
   162
  let
haftmann@39473
   163
    val t = Thm.term_of ct;
haftmann@39473
   164
    val _ = if fastype_of t <> propT
wenzelm@59633
   165
      then error ("Not a proposition: " ^ Syntax.string_of_term ctxt t)
haftmann@39473
   166
      else ();
wenzelm@59633
   167
    val iff = Thm.cterm_of ctxt (Term.Const (@{const_name Pure.eq}, propT --> propT --> propT));
haftmann@64957
   168
    val result = case partiality_as_none (run_compilation_text truth_cookie ctxt evaluator vs_t [])
haftmann@39473
   169
     of SOME Holds => true
haftmann@39473
   170
      | _ => false;
haftmann@39473
   171
  in
haftmann@39473
   172
    Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
haftmann@39473
   173
  end;
haftmann@39473
   174
haftmann@39473
   175
val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
wenzelm@43619
   176
  (Thm.add_oracle (@{binding holds_by_evaluation},
haftmann@55757
   177
  fn (ctxt, evaluator, vs_t, ct) => check_holds ctxt evaluator vs_t ct)));
haftmann@39473
   178
haftmann@56920
   179
fun check_holds_oracle ctxt evaluator vs_ty_t ct =
haftmann@56920
   180
  raw_check_holds_oracle (ctxt, evaluator, vs_ty_t, ct);
haftmann@41349
   181
haftmann@41349
   182
in
haftmann@39485
   183
haftmann@55757
   184
fun dynamic_holds_conv ctxt = Code_Thingol.dynamic_conv ctxt
haftmann@56969
   185
  (fn program => fn vs_t => fn deps =>
haftmann@64957
   186
    check_holds_oracle ctxt (build_compilation_text ctxt NONE program deps) vs_t)
haftmann@55757
   187
      o reject_vars ctxt;
haftmann@39473
   188
haftmann@56973
   189
fun static_holds_conv (ctxt_consts as { ctxt, ... }) =
haftmann@63156
   190
  Code_Thingol.static_conv_thingol ctxt_consts (fn { program, deps } => fn ctxt' => fn vs_t =>
haftmann@64957
   191
    K (check_holds_oracle ctxt' (build_compilation_text ctxt NONE program (map Constant deps)) vs_t o reject_vars ctxt'));
haftmann@41349
   192
haftmann@41349
   193
end; (*local*)
haftmann@39404
   194
haftmann@39404
   195
haftmann@64957
   196
(** generator for computations -- partial implementations of the universal morphism from Isabelle to ML terms **)
haftmann@64957
   197
haftmann@64957
   198
(* auxiliary *)
haftmann@64940
   199
haftmann@64957
   200
val generated_computationN = "Generated_Computation";
haftmann@64957
   201
haftmann@64957
   202
haftmann@64957
   203
(* possible type signatures of constants *)
haftmann@64943
   204
haftmann@64940
   205
fun typ_signatures_for T =
haftmann@64940
   206
  let
haftmann@64940
   207
    val (Ts, T') = strip_type T;
haftmann@64940
   208
  in map_range (fn n => (drop n Ts ---> T', take n Ts)) (length Ts + 1) end;
haftmann@64940
   209
haftmann@64940
   210
fun typ_signatures cTs =
haftmann@64940
   211
  let
haftmann@64940
   212
    fun add (c, T) =
haftmann@64940
   213
      fold (fn (T, Ts) => Typtab.map_default (T, []) (cons (c, Ts)))
haftmann@64940
   214
        (typ_signatures_for T);
haftmann@64940
   215
  in
haftmann@64940
   216
    Typtab.empty
haftmann@64940
   217
    |> fold add cTs
haftmann@64940
   218
    |> Typtab.lookup_list
haftmann@64940
   219
  end;
haftmann@64940
   220
haftmann@64957
   221
haftmann@64957
   222
(* name mangling *)
haftmann@64957
   223
haftmann@64957
   224
local
haftmann@64957
   225
haftmann@64957
   226
fun tycos_of (Type (tyco, Ts)) = maps tycos_of Ts @ [tyco]
haftmann@64957
   227
  | tycos_of _ = [];
haftmann@64957
   228
haftmann@64957
   229
val ml_name_of = Name.desymbolize NONE o Long_Name.base_name;
haftmann@64957
   230
haftmann@64957
   231
in
haftmann@64957
   232
haftmann@64959
   233
val covered_constsN = "covered_consts";
haftmann@64959
   234
haftmann@64957
   235
fun of_term_for_typ Ts =
haftmann@64957
   236
  let
haftmann@64957
   237
    val names = Ts
haftmann@64957
   238
      |> map (suffix "_of_term" o space_implode "_" o map ml_name_of o tycos_of)
haftmann@64957
   239
      |> Name.variant_list [];
haftmann@64957
   240
  in the o AList.lookup (op =) (Ts ~~ names) end;
haftmann@64957
   241
haftmann@64957
   242
fun eval_for_const ctxt cTs =
haftmann@64957
   243
  let
haftmann@64957
   244
    fun symbol_list (c, T) = c :: maps tycos_of (Sign.const_typargs (Proof_Context.theory_of ctxt) (c, T))
haftmann@64957
   245
    val names = cTs
haftmann@64957
   246
      |> map (prefix "eval_" o space_implode "_" o map ml_name_of o symbol_list)
haftmann@64957
   247
      |> Name.variant_list [];
haftmann@64957
   248
  in the o AList.lookup (op =) (cTs ~~ names) end;
haftmann@64957
   249
haftmann@64957
   250
end;
haftmann@64957
   251
haftmann@64957
   252
haftmann@64957
   253
(* checks for input terms *)
haftmann@64957
   254
haftmann@64957
   255
fun monomorphic T = fold_atyps ((K o K) false) T true;
haftmann@64957
   256
haftmann@64957
   257
fun check_typ ctxt T t =
haftmann@64957
   258
  Syntax.check_term ctxt (Type.constraint T t);
haftmann@64957
   259
haftmann@64957
   260
fun check_computation_input ctxt cTs t =
haftmann@64957
   261
  let
haftmann@64957
   262
    fun check t = check_comb (strip_comb t)
haftmann@64957
   263
    and check_comb (t as Abs _, _) =
haftmann@64957
   264
          error ("Bad term, contains abstraction: " ^ Syntax.string_of_term ctxt t)
haftmann@64957
   265
      | check_comb (t as Const (cT as (c, T)), ts) =
haftmann@64957
   266
          let
haftmann@64957
   267
            val _ = if not (member (op =) cTs cT)
haftmann@64957
   268
              then error ("Bad term, computation cannot proceed on constant " ^ Syntax.string_of_term ctxt t)
haftmann@64957
   269
              else ();
haftmann@64957
   270
            val _ = if not (monomorphic T)
haftmann@64957
   271
              then error ("Bad term, contains polymorphic constant " ^ Syntax.string_of_term ctxt t)
haftmann@64957
   272
              else ();
haftmann@64957
   273
            val _ = map check ts;
haftmann@64957
   274
          in () end;
haftmann@64957
   275
    val _ = check t;
haftmann@64957
   276
  in t end;
haftmann@64957
   277
haftmann@64957
   278
haftmann@64957
   279
(* code generation for of the universal morphism *)
haftmann@64957
   280
haftmann@64959
   281
val print_const = ML_Syntax.print_pair ML_Syntax.print_string ML_Syntax.print_typ;
haftmann@64959
   282
haftmann@64940
   283
fun print_of_term_funs { typ_sign_for, eval_for_const, of_term_for_typ } Ts =
haftmann@64940
   284
  let
haftmann@64940
   285
    val var_names = map_range (fn n => "t" ^ string_of_int (n + 1));
haftmann@64940
   286
    fun print_lhs c xs = "Const (" ^ quote c ^ ", _)"
haftmann@64940
   287
      |> fold (fn x => fn s => s ^ " $ " ^ x) xs
haftmann@64943
   288
      |> enclose "(" ")";
haftmann@64940
   289
    fun print_rhs c Ts T xs = eval_for_const (c, Ts ---> T)
haftmann@64940
   290
      |> fold2 (fn T' => fn x => fn s =>
haftmann@64943
   291
         s ^ (" (" ^ of_term_for_typ T' ^ " " ^ x ^ ")")) Ts xs
haftmann@64940
   292
    fun print_eq T (c, Ts) =
haftmann@64940
   293
      let
haftmann@64940
   294
        val xs = var_names (length Ts);
haftmann@64940
   295
      in print_lhs c xs ^ " = " ^ print_rhs c Ts T xs end;
haftmann@64940
   296
    fun print_eqs T =
haftmann@64940
   297
      let
haftmann@64940
   298
        val typ_signs = typ_sign_for T;
haftmann@64940
   299
        val name = of_term_for_typ T;
haftmann@64940
   300
      in
haftmann@64943
   301
        map (print_eq T) typ_signs
haftmann@64940
   302
        |> map (prefix (name ^ " "))
haftmann@64940
   303
        |> space_implode "\n  | "
haftmann@64940
   304
      end;
haftmann@64940
   305
  in
haftmann@64940
   306
    map print_eqs Ts
haftmann@64940
   307
    |> space_implode "\nand "
haftmann@64940
   308
    |> prefix "fun "
haftmann@64940
   309
  end;
haftmann@64940
   310
haftmann@64959
   311
fun print_computation_code ctxt compiled_value [] requested_Ts = ("", [])
haftmann@64959
   312
  | print_computation_code ctxt compiled_value cTs requested_Ts =
haftmann@64959
   313
      let
haftmann@64959
   314
        val proper_cTs = map_filter I cTs;
haftmann@64959
   315
        val typ_sign_for = typ_signatures proper_cTs;
haftmann@64959
   316
        fun add_typ T Ts =
haftmann@64959
   317
          if member (op =) Ts T
haftmann@64959
   318
          then Ts
haftmann@64959
   319
          else Ts
haftmann@64959
   320
            |> cons T
haftmann@64959
   321
            |> fold (fold add_typ o snd) (typ_sign_for T);
haftmann@64959
   322
        val required_Ts = fold add_typ requested_Ts [];
haftmann@64959
   323
        val of_term_for_typ' = of_term_for_typ required_Ts;
haftmann@64959
   324
        val eval_for_const' = eval_for_const ctxt proper_cTs;
haftmann@64959
   325
        val eval_for_const'' = the_default "_" o Option.map eval_for_const';
haftmann@64959
   326
        val eval_tuple = enclose "(" ")" (commas (map eval_for_const' proper_cTs));
haftmann@64959
   327
        fun mk_abs s = "fn " ^ s ^ " => ";
haftmann@64959
   328
        val eval_abs = space_implode ""
haftmann@64959
   329
          (map (mk_abs o eval_for_const'') cTs);
haftmann@64959
   330
        val of_term_code = print_of_term_funs {
haftmann@64959
   331
          typ_sign_for = typ_sign_for,
haftmann@64959
   332
          eval_for_const = eval_for_const',
haftmann@64959
   333
          of_term_for_typ = of_term_for_typ' } required_Ts;
haftmann@64959
   334
        val of_term_names = map (Long_Name.append generated_computationN
haftmann@64959
   335
          o of_term_for_typ') requested_Ts;
haftmann@64959
   336
      in
haftmann@64959
   337
        cat_lines [
haftmann@64959
   338
          "structure " ^ generated_computationN ^ " =",
haftmann@64959
   339
          "struct",
haftmann@64959
   340
          "",
haftmann@64959
   341
          "val " ^ covered_constsN ^ " = " ^ ML_Syntax.print_list print_const proper_cTs ^ ";",
haftmann@64959
   342
          "",
haftmann@64959
   343
          "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
haftmann@64959
   344
          "  (" ^ eval_abs,
haftmann@64959
   345
          "    " ^ eval_tuple ^ ");",
haftmann@64959
   346
          "",
haftmann@64959
   347
          of_term_code,
haftmann@64959
   348
          "",
haftmann@64959
   349
          "end"
haftmann@64959
   350
        ] |> rpair of_term_names
haftmann@64959
   351
      end;
haftmann@64940
   352
haftmann@64987
   353
fun checked_computation cTs T raw_computation ctxt =
haftmann@64987
   354
  check_typ ctxt T
haftmann@64987
   355
  #> reject_vars ctxt
haftmann@64987
   356
  #> check_computation_input ctxt cTs
haftmann@64988
   357
  #> Exn.capture raw_computation
haftmann@64988
   358
  #> partiality_as_none;
haftmann@64987
   359
haftmann@64957
   360
fun mount_computation ctxt cTs T raw_computation lift_postproc =
haftmann@64957
   361
  Code_Preproc.static_value { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
haftmann@64987
   362
    (K (checked_computation cTs T raw_computation));
haftmann@64943
   363
haftmann@64959
   364
haftmann@64959
   365
(** variants of universal runtime code generation **)
haftmann@64940
   366
haftmann@64959
   367
(*FIXME consolidate variants*)
haftmann@64940
   368
haftmann@64959
   369
fun runtime_code'' ctxt module_name program tycos consts =
haftmann@33992
   370
  let
haftmann@55757
   371
    val thy = Proof_Context.theory_of ctxt;
haftmann@48568
   372
    val (ml_modules, target_names) =
haftmann@55757
   373
      Code_Target.produce_code_for ctxt
haftmann@55683
   374
        target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
haftmann@48568
   375
    val ml_code = space_implode "\n\n" (map snd ml_modules);
haftmann@55147
   376
    val (consts', tycos') = chop (length consts) target_names;
wenzelm@42359
   377
    val consts_map = map2 (fn const =>
wenzelm@42359
   378
      fn NONE =>
wenzelm@42359
   379
          error ("Constant " ^ (quote o Code.string_of_const thy) const ^
wenzelm@42359
   380
            "\nhas a user-defined serialization")
haftmann@55147
   381
       | SOME const' => (const, const')) consts consts'
wenzelm@42359
   382
    val tycos_map = map2 (fn tyco =>
wenzelm@42359
   383
      fn NONE =>
wenzelm@55304
   384
          error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
wenzelm@42359
   385
            "\nhas a user-defined serialization")
haftmann@55147
   386
        | SOME tyco' => (tyco, tyco')) tycos tycos';
haftmann@34028
   387
  in (ml_code, (tycos_map, consts_map)) end;
haftmann@28054
   388
haftmann@64959
   389
fun runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
haftmann@64959
   390
  let
haftmann@64959
   391
    val thy = Proof_Context.theory_of ctxt;
haftmann@64959
   392
    fun the_const (Const cT) = cT
haftmann@64959
   393
      | the_const t = error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)
haftmann@64959
   394
    val raw_computation_cTs = case evals of
haftmann@64959
   395
        Abs (_, _, t) => (map the_const o snd o strip_comb) t
haftmann@64959
   396
      | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
haftmann@64959
   397
    val computation_cTs = fold_rev (fn cT => fn cTs =>
haftmann@64959
   398
      (if member (op =) cTs (SOME cT) then NONE else SOME cT) :: cTs) raw_computation_cTs [];
haftmann@64959
   399
    val consts' = fold (fn NONE => I | SOME (c, _) => insert (op =) c)
haftmann@64959
   400
      computation_cTs named_consts;
haftmann@64959
   401
    val program' = Code_Thingol.consts_program ctxt consts';
haftmann@64959
   402
      (*FIXME insufficient interfaces require double invocation of code generator*)
haftmann@64959
   403
    val ((ml_modules, compiled_value), deresolve) =
haftmann@64959
   404
      Code_Target.compilation_text' ctxt target some_module_name program'
haftmann@64959
   405
        (map Code_Symbol.Type_Constructor named_tycos @ map Code_Symbol.Constant consts' @ deps) true vs_ty_evals;
haftmann@64959
   406
        (*FIXME constrain signature*)
haftmann@64959
   407
    fun deresolve_const c = case (deresolve o Code_Symbol.Constant) c of
haftmann@64959
   408
          NONE => error ("Constant " ^ (quote o Code.string_of_const thy) c ^
haftmann@64959
   409
            "\nhas a user-defined serialization")
haftmann@64959
   410
        | SOME c' => c';
haftmann@64959
   411
    fun deresolve_tyco tyco = case (deresolve o Code_Symbol.Type_Constructor) tyco of
haftmann@64959
   412
          NONE => error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
haftmann@64959
   413
            "\nhas a user-defined serialization")
haftmann@64959
   414
        | SOME c' => c';
haftmann@64959
   415
    val tyco_names =  map deresolve_const named_tycos;
haftmann@64959
   416
    val const_names = map deresolve_const named_consts;
haftmann@64959
   417
    val generated_code = space_implode "\n\n" (map snd ml_modules);
haftmann@64959
   418
    val (of_term_code, of_term_names) =
haftmann@64959
   419
      print_computation_code ctxt compiled_value computation_cTs computation_Ts;
haftmann@64959
   420
    val compiled_computation = generated_code ^ "\n" ^ of_term_code;
haftmann@64959
   421
  in
haftmann@64959
   422
    compiled_computation
haftmann@64959
   423
    |> rpair { tyco_map = named_tycos ~~ tyco_names,
haftmann@64959
   424
      const_map = named_consts ~~ const_names,
haftmann@64959
   425
      of_term_map = computation_Ts ~~ of_term_names }
haftmann@64959
   426
  end;
haftmann@64959
   427
haftmann@64959
   428
fun funs_of_maps { tyco_map, const_map, of_term_map } =
haftmann@64959
   429
  { name_for_tyco = the o AList.lookup (op =) tyco_map,
haftmann@64959
   430
    name_for_const = the o AList.lookup (op =) const_map,
haftmann@64959
   431
    of_term_for_typ = the o AList.lookup (op =) of_term_map };
haftmann@64959
   432
haftmann@64959
   433
fun runtime_code ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
haftmann@64959
   434
  runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps
haftmann@64959
   435
  ||> funs_of_maps;
haftmann@64959
   436
haftmann@64959
   437
haftmann@64959
   438
(** code and computation antiquotations **)
haftmann@64959
   439
haftmann@64987
   440
val mount_computationN = prefix_this "mount_computation";
haftmann@64959
   441
haftmann@28054
   442
local
haftmann@28054
   443
haftmann@38930
   444
structure Code_Antiq_Data = Proof_Data
haftmann@28054
   445
(
haftmann@64955
   446
  type T = { named_consts: string list,
haftmann@64959
   447
    computation_Ts: typ list, computation_cTs: (string * typ) list,
haftmann@64959
   448
    position_index: int,
haftmann@64959
   449
    generated_code: (string * {
haftmann@64959
   450
      name_for_tyco: string -> string,
haftmann@64959
   451
      name_for_const: string -> string,
haftmann@64959
   452
      of_term_for_typ: typ -> string
haftmann@64959
   453
    }) lazy
haftmann@64955
   454
  };
haftmann@64955
   455
  val empty: T = { named_consts = [],
haftmann@64959
   456
    computation_Ts = [], computation_cTs = [],
haftmann@64959
   457
    position_index = 0,
haftmann@64959
   458
    generated_code = Lazy.lazy (fn () => raise Fail "empty")
haftmann@64955
   459
  };
wenzelm@59150
   460
  fun init _ = empty;
haftmann@28054
   461
);
haftmann@28054
   462
haftmann@64959
   463
val current_position_index = #position_index o Code_Antiq_Data.get;
haftmann@64955
   464
haftmann@64959
   465
fun register { named_consts, computation_Ts, computation_cTs } ctxt =
haftmann@64955
   466
  let
haftmann@64959
   467
    val data = Code_Antiq_Data.get ctxt;
haftmann@64959
   468
    val named_consts' = union (op =) named_consts (#named_consts data);
haftmann@64959
   469
    val computation_Ts' = union (op =) computation_Ts (#computation_Ts data);
haftmann@64959
   470
    val computation_cTs' = union (op =) computation_cTs (#computation_cTs data);
haftmann@64959
   471
    val position_index' = #position_index data + 1;
haftmann@64959
   472
    fun generated_code' () =
haftmann@64959
   473
      let
haftmann@64959
   474
        val evals = Abs ("eval", map snd computation_cTs' --->
haftmann@64959
   475
          TFree (Name.aT, []), list_comb (Bound 0, map Const computation_cTs'));
haftmann@64959
   476
      in Code_Thingol.dynamic_value ctxt
haftmann@64959
   477
        (K I) (runtime_code ctxt NONE [] named_consts' computation_Ts') evals
haftmann@64959
   478
      end;
haftmann@64955
   479
  in
haftmann@64955
   480
    ctxt
haftmann@64955
   481
    |> Code_Antiq_Data.put { 
haftmann@64959
   482
        named_consts = named_consts',
haftmann@64959
   483
        computation_Ts = computation_Ts',
haftmann@64959
   484
        computation_cTs = computation_cTs',
haftmann@64959
   485
        position_index = position_index',
haftmann@64959
   486
        generated_code = Lazy.lazy generated_code'
haftmann@64955
   487
      }
haftmann@64955
   488
  end;
haftmann@30962
   489
haftmann@64959
   490
fun register_const const =
haftmann@64959
   491
  register { named_consts = [const],
haftmann@64959
   492
    computation_Ts = [],
haftmann@64959
   493
    computation_cTs = [] };
haftmann@64959
   494
haftmann@64959
   495
fun register_computation cTs T =
haftmann@64959
   496
  register { named_consts = [],
haftmann@64959
   497
    computation_Ts = [T],
haftmann@64959
   498
    computation_cTs = cTs };
haftmann@64959
   499
haftmann@64959
   500
fun print body_code_for ctxt ctxt' =
haftmann@30962
   501
  let
haftmann@64959
   502
    val position_index = current_position_index ctxt;
haftmann@64959
   503
    val (code, name_ofs) = (Lazy.force o #generated_code o Code_Antiq_Data.get) ctxt';
haftmann@64959
   504
    val context_code = if position_index = 0 then code else "";
haftmann@64959
   505
    val body_code = body_code_for name_ofs (ML_Context.struct_name ctxt') position_index;
haftmann@64958
   506
  in (context_code, body_code) end;
haftmann@28054
   507
haftmann@64959
   508
fun print_code ctxt const =
haftmann@64959
   509
  print (fn { name_for_const, ... } => fn prfx => fn _ =>
haftmann@64959
   510
    Long_Name.append prfx (name_for_const const)) ctxt;
haftmann@64959
   511
haftmann@64959
   512
fun print_computation ctxt T =
haftmann@64959
   513
  print (fn { of_term_for_typ, ... } => fn prfx => fn _ =>
haftmann@64959
   514
    space_implode " " [
haftmann@64959
   515
      mount_computationN,
haftmann@64959
   516
      "(Context.proof_of (Context.the_generic_context ()))",
haftmann@64959
   517
      Long_Name.implode [prfx, generated_computationN, covered_constsN],
haftmann@64959
   518
      (ML_Syntax.atomic o ML_Syntax.print_typ) T,
haftmann@64959
   519
      Long_Name.append prfx (of_term_for_typ T)
haftmann@64959
   520
    ]) ctxt;
haftmann@64959
   521
haftmann@28054
   522
in
haftmann@28054
   523
wenzelm@56069
   524
fun ml_code_antiq raw_const ctxt =
haftmann@28054
   525
  let
wenzelm@53169
   526
    val thy = Proof_Context.theory_of ctxt;
wenzelm@53169
   527
    val const = Code.check_const thy raw_const;
haftmann@64959
   528
  in (print_code ctxt const, register_const const ctxt) end;
haftmann@64959
   529
haftmann@64959
   530
fun ml_computation_antiq (raw_ts, raw_T) ctxt =
haftmann@64959
   531
  let
haftmann@64959
   532
    val ts = map (Syntax.check_term ctxt) raw_ts;
haftmann@64987
   533
    val cTs = (fold o fold_aterms)
haftmann@64987
   534
      (fn (t as Const (cT as (_, T))) =>
haftmann@64987
   535
        if not (monomorphic T) then error ("Polymorphic constant: " ^ Syntax.string_of_term ctxt t)
haftmann@64987
   536
        else insert (op =) cT | _ => I) ts [];
haftmann@64959
   537
    val T = Syntax.check_typ ctxt raw_T;
haftmann@64959
   538
    val _ = if not (monomorphic T)
haftmann@64959
   539
      then error ("Polymorphic type: " ^ Syntax.string_of_typ ctxt T)
haftmann@64959
   540
      else ();
haftmann@64959
   541
  in (print_computation ctxt T, register_computation cTs T ctxt) end;
haftmann@30962
   542
haftmann@28054
   543
end; (*local*)
haftmann@28054
   544
haftmann@28054
   545
haftmann@58558
   546
(** reflection support **)
haftmann@36470
   547
haftmann@40421
   548
fun check_datatype thy tyco some_consts =
haftmann@36470
   549
  let
haftmann@63174
   550
    val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
haftmann@63174
   551
    val constrs = case some_consts
haftmann@63174
   552
     of SOME [] => []
haftmann@63174
   553
      | SOME consts =>
haftmann@40421
   554
          let
haftmann@63174
   555
            val missing_constrs = subtract (op =) consts declared_constrs;
haftmann@40421
   556
            val _ = if null missing_constrs then []
wenzelm@45430
   557
              else error ("Missing constructor(s) " ^ commas_quote missing_constrs
haftmann@40421
   558
                ^ " for datatype " ^ quote tyco);
haftmann@63174
   559
            val false_constrs = subtract (op =) declared_constrs consts;
haftmann@40421
   560
            val _ = if null false_constrs then []
wenzelm@45430
   561
              else error ("Non-constructor(s) " ^ commas_quote false_constrs
haftmann@40421
   562
                ^ " for datatype " ^ quote tyco)
haftmann@63174
   563
          in consts end
haftmann@63174
   564
      | NONE => declared_constrs;
haftmann@40421
   565
  in (tyco, constrs) end;
haftmann@36470
   566
haftmann@36470
   567
fun add_eval_tyco (tyco, tyco') thy =
haftmann@36470
   568
  let
haftmann@36470
   569
    val k = Sign.arity_number thy tyco;
haftmann@40421
   570
    fun pr pr' _ [] = tyco'
haftmann@40421
   571
      | pr pr' _ [ty] =
haftmann@36470
   572
          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
haftmann@40421
   573
      | pr pr' _ tys =
haftmann@36470
   574
          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
haftmann@36470
   575
  in
haftmann@36470
   576
    thy
haftmann@55150
   577
    |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
haftmann@36470
   578
  end;
haftmann@36470
   579
haftmann@36514
   580
fun add_eval_constr (const, const') thy =
haftmann@36514
   581
  let
haftmann@36514
   582
    val k = Code.args_number thy const;
haftmann@36514
   583
    fun pr pr' fxy ts = Code_Printer.brackify fxy
haftmann@38922
   584
      (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
haftmann@36514
   585
  in
haftmann@36514
   586
    thy
haftmann@55150
   587
    |> Code_Target.set_printings (Constant (const,
haftmann@52435
   588
      [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
haftmann@36514
   589
  end;
haftmann@36514
   590
haftmann@55150
   591
fun add_eval_const (const, const') = Code_Target.set_printings (Constant
haftmann@52435
   592
  (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
haftmann@36470
   593
haftmann@39912
   594
fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
haftmann@38935
   595
      thy
haftmann@38935
   596
      |> Code_Target.add_reserved target module_name
haftmann@63163
   597
      |> Context.theory_map (compile_ML true code)
haftmann@38935
   598
      |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
haftmann@38935
   599
      |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
haftmann@38935
   600
      |> fold (add_eval_const o apsnd Code_Printer.str) const_map
haftmann@39912
   601
  | process_reflection (code, _) _ (SOME file_name) thy =
haftmann@36470
   602
      let
wenzelm@37950
   603
        val preamble =
wenzelm@46737
   604
          "(* Generated from " ^
wenzelm@56208
   605
            Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
wenzelm@46737
   606
          "; DO NOT EDIT! *)";
haftmann@39912
   607
        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
haftmann@36470
   608
      in
haftmann@36470
   609
        thy
haftmann@36470
   610
      end;
haftmann@36470
   611
haftmann@36470
   612
fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
haftmann@36470
   613
  let
haftmann@55757
   614
    val ctxt = Proof_Context.init_global thy;
haftmann@36470
   615
    val datatypes = map (fn (raw_tyco, raw_cos) =>
haftmann@55757
   616
      (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
haftmann@40421
   617
    val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
haftmann@40421
   618
      |> apsnd flat;
haftmann@36470
   619
    val functions = map (prep_const thy) raw_functions;
haftmann@58557
   620
    val consts = constrs @ functions;
haftmann@63159
   621
    val program = Code_Thingol.consts_program ctxt consts;
haftmann@64959
   622
    val result = runtime_code'' ctxt module_name program tycos consts
haftmann@36514
   623
      |> (apsnd o apsnd) (chop (length constrs));
haftmann@36470
   624
  in
haftmann@36470
   625
    thy
haftmann@39485
   626
    |> process_reflection result module_name some_file
haftmann@36470
   627
  end;
haftmann@36470
   628
haftmann@39422
   629
val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
haftmann@36470
   630
val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
haftmann@36470
   631
haftmann@36470
   632
haftmann@28054
   633
(** Isar setup **)
haftmann@28054
   634
wenzelm@56069
   635
val _ =
haftmann@64959
   636
  Theory.setup (ML_Antiquotation.declaration @{binding code}
haftmann@64959
   637
    Args.term (fn _ => ml_code_antiq));
haftmann@64959
   638
haftmann@64959
   639
val _ =
haftmann@64959
   640
  Theory.setup (ML_Antiquotation.declaration @{binding computation}
haftmann@64987
   641
    (Scan.repeat Args.term --| Scan.lift (Args.$$$ "::") -- Args.typ)
haftmann@64987
   642
       (fn _ => ml_computation_antiq));
haftmann@28054
   643
haftmann@36470
   644
local
haftmann@36470
   645
wenzelm@36960
   646
val parse_datatype =
haftmann@63174
   647
  Parse.name -- Scan.optional (@{keyword "="} |--
haftmann@40711
   648
    (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
haftmann@63174
   649
    || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
haftmann@36470
   650
haftmann@36470
   651
in
haftmann@36470
   652
haftmann@36470
   653
val _ =
wenzelm@59936
   654
  Outer_Syntax.command @{command_keyword code_reflect}
wenzelm@46961
   655
    "enrich runtime environment with generated code"
haftmann@63174
   656
    (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
wenzelm@46949
   657
      ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
haftmann@52434
   658
    -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
haftmann@52434
   659
    -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
wenzelm@46961
   660
    >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
wenzelm@46961
   661
      (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
haftmann@36470
   662
haftmann@36470
   663
end; (*local*)
haftmann@36470
   664
haftmann@39816
   665
haftmann@39816
   666
(** using external SML files as substitute for proper definitions -- only for polyml!  **)
haftmann@39816
   667
haftmann@39816
   668
local
haftmann@39816
   669
wenzelm@39820
   670
structure Loaded_Values = Theory_Data
wenzelm@39820
   671
(
haftmann@39816
   672
  type T = string list
haftmann@39816
   673
  val empty = []
wenzelm@41472
   674
  val extend = I
wenzelm@39820
   675
  fun merge data : T = Library.merge (op =) data
haftmann@39816
   676
);
haftmann@39816
   677
haftmann@39816
   678
fun notify_val (string, value) = 
haftmann@39816
   679
  let
wenzelm@62495
   680
    val _ = #enterVal ML_Env.name_space (string, value);
wenzelm@53171
   681
    val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
haftmann@39816
   682
  in () end;
haftmann@39816
   683
haftmann@39816
   684
fun abort _ = error "Only value bindings allowed.";
haftmann@39816
   685
wenzelm@62494
   686
val notifying_context : ML_Compiler0.context =
wenzelm@62354
   687
 {name_space =
wenzelm@62495
   688
   {lookupVal    = #lookupVal ML_Env.name_space,
wenzelm@62495
   689
    lookupType   = #lookupType ML_Env.name_space,
wenzelm@62495
   690
    lookupFix    = #lookupFix ML_Env.name_space,
wenzelm@62495
   691
    lookupStruct = #lookupStruct ML_Env.name_space,
wenzelm@62495
   692
    lookupSig    = #lookupSig ML_Env.name_space,
wenzelm@62495
   693
    lookupFunct  = #lookupFunct ML_Env.name_space,
haftmann@39816
   694
    enterVal     = notify_val,
haftmann@39816
   695
    enterType    = abort,
haftmann@39816
   696
    enterFix     = abort,
haftmann@39816
   697
    enterStruct  = abort,
haftmann@39816
   698
    enterSig     = abort,
haftmann@39816
   699
    enterFunct   = abort,
wenzelm@62495
   700
    allVal       = #allVal ML_Env.name_space,
wenzelm@62495
   701
    allType      = #allType ML_Env.name_space,
wenzelm@62495
   702
    allFix       = #allFix ML_Env.name_space,
wenzelm@62495
   703
    allStruct    = #allStruct ML_Env.name_space,
wenzelm@62495
   704
    allSig       = #allSig ML_Env.name_space,
wenzelm@62495
   705
    allFunct     = #allFunct ML_Env.name_space},
wenzelm@62716
   706
  print_depth = NONE,
wenzelm@62495
   707
  here = #here ML_Env.context,
wenzelm@62495
   708
  print = #print ML_Env.context,
wenzelm@62495
   709
  error = #error ML_Env.context};
haftmann@39816
   710
haftmann@39816
   711
in
haftmann@39816
   712
haftmann@39816
   713
fun use_file filepath thy =
haftmann@39816
   714
  let
haftmann@39816
   715
    val thy' = Loaded_Values.put [] thy;
wenzelm@62889
   716
    val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
wenzelm@60956
   717
    val _ =
wenzelm@62902
   718
      ML_Compiler0.ML notifying_context
wenzelm@60956
   719
        {line = 0, file = Path.implode filepath, verbose = false, debug = false}
wenzelm@60956
   720
        (File.read filepath);
wenzelm@62876
   721
    val thy'' = Context.the_global_context ();
haftmann@39912
   722
    val names = Loaded_Values.get thy'';
haftmann@40320
   723
  in (names, thy'') end;
haftmann@39816
   724
haftmann@39816
   725
end;
haftmann@39816
   726
haftmann@39816
   727
fun add_definiendum (ml_name, (b, T)) thy =
haftmann@39816
   728
  thy
haftmann@39816
   729
  |> Code_Target.add_reserved target ml_name
wenzelm@63178
   730
  |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
haftmann@39816
   731
  |-> (fn ([Const (const, _)], _) =>
haftmann@55150
   732
    Code_Target.set_printings (Constant (const,
haftmann@52435
   733
      [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
haftmann@64940
   734
  #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
haftmann@39816
   735
haftmann@39816
   736
fun process_file filepath (definienda, thy) =
haftmann@39816
   737
  let
haftmann@39816
   738
    val (ml_names, thy') = use_file filepath thy;
haftmann@39816
   739
    val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
haftmann@39816
   740
    val _ = if null superfluous then ()
haftmann@39816
   741
      else error ("Value binding(s) " ^ commas_quote superfluous
wenzelm@41944
   742
        ^ " found in external file " ^ Path.print filepath
haftmann@39816
   743
        ^ " not present among the given contants binding(s).");
haftmann@39816
   744
    val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
haftmann@39816
   745
    val thy'' = fold add_definiendum these_definienda thy';
haftmann@39816
   746
    val definienda' = fold (AList.delete (op =)) ml_names definienda;
haftmann@39816
   747
  in (definienda', thy'') end;
haftmann@39816
   748
haftmann@39816
   749
fun polyml_as_definition bTs filepaths thy =
haftmann@39816
   750
  let
haftmann@39816
   751
    val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
haftmann@39816
   752
    val (remaining, thy') = fold process_file filepaths (definienda, thy);
haftmann@39816
   753
    val _ = if null remaining then ()
haftmann@39816
   754
      else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
haftmann@39816
   755
        ^ " not present in external file(s).");
haftmann@39816
   756
  in thy' end;
haftmann@39816
   757
haftmann@28054
   758
end; (*struct*)