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