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