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