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