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