src/Tools/Code/code_runtime.ML
author wenzelm
Sat May 28 21:38:58 2016 +0200 (2016-05-28)
changeset 63178 b9e1d53124f5
parent 63164 72aaf69328fc
child 63184 dd6cd88cebd9
permissions -rw-r--r--
clarified 'axiomatization';
     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 = Exn.release ooo static_value_exn cookie;
   152 
   153 fun static_value cookie = partiality_as_none ooo static_value_exn cookie;
   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 = Exn.release ooo fully_static_value_exn cookie;
   323 
   324 fun fully_static_value cookie = partiality_as_none ooo fully_static_value_exn cookie;
   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 constrs = (map fst o snd o fst o Code.get_type thy) tyco;
   379     val _ = case some_consts
   380      of SOME consts =>
   381           let
   382             val missing_constrs = subtract (op =) consts constrs;
   383             val _ = if null missing_constrs then []
   384               else error ("Missing constructor(s) " ^ commas_quote missing_constrs
   385                 ^ " for datatype " ^ quote tyco);
   386             val false_constrs = subtract (op =) constrs consts;
   387             val _ = if null false_constrs then []
   388               else error ("Non-constructor(s) " ^ commas_quote false_constrs
   389                 ^ " for datatype " ^ quote tyco)
   390           in () end
   391       | NONE => ();
   392   in (tyco, constrs) end;
   393 
   394 fun add_eval_tyco (tyco, tyco') thy =
   395   let
   396     val k = Sign.arity_number thy tyco;
   397     fun pr pr' _ [] = tyco'
   398       | pr pr' _ [ty] =
   399           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   400       | pr pr' _ tys =
   401           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   402   in
   403     thy
   404     |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
   405   end;
   406 
   407 fun add_eval_constr (const, const') thy =
   408   let
   409     val k = Code.args_number thy const;
   410     fun pr pr' fxy ts = Code_Printer.brackify fxy
   411       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   412   in
   413     thy
   414     |> Code_Target.set_printings (Constant (const,
   415       [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
   416   end;
   417 
   418 fun add_eval_const (const, const') = Code_Target.set_printings (Constant
   419   (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
   420 
   421 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   422       thy
   423       |> Code_Target.add_reserved target module_name
   424       |> Context.theory_map (compile_ML true code)
   425       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   426       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   427       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   428   | process_reflection (code, _) _ (SOME file_name) thy =
   429       let
   430         val preamble =
   431           "(* Generated from " ^
   432             Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
   433           "; DO NOT EDIT! *)";
   434         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   435       in
   436         thy
   437       end;
   438 
   439 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   440   let
   441     val ctxt = Proof_Context.init_global thy;
   442     val datatypes = map (fn (raw_tyco, raw_cos) =>
   443       (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
   444     val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
   445       |> apsnd flat;
   446     val functions = map (prep_const thy) raw_functions;
   447     val consts = constrs @ functions;
   448     val program = Code_Thingol.consts_program ctxt consts;
   449     val result = evaluation_code ctxt module_name program tycos consts
   450       |> (apsnd o apsnd) (chop (length constrs));
   451   in
   452     thy
   453     |> process_reflection result module_name some_file
   454   end;
   455 
   456 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   457 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   458 
   459 
   460 (** Isar setup **)
   461 
   462 val _ =
   463   Theory.setup (ML_Antiquotation.declaration @{binding code} Args.term (fn _ => ml_code_antiq));
   464 
   465 local
   466 
   467 val parse_datatype =
   468   Parse.name --| @{keyword "="} --
   469     (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
   470     || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME));
   471 
   472 in
   473 
   474 val _ =
   475   Outer_Syntax.command @{command_keyword code_reflect}
   476     "enrich runtime environment with generated code"
   477     (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!!  (parse_datatype
   478       ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
   479     -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
   480     -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
   481     >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   482       (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   483 
   484 end; (*local*)
   485 
   486 
   487 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   488 
   489 local
   490 
   491 structure Loaded_Values = Theory_Data
   492 (
   493   type T = string list
   494   val empty = []
   495   val extend = I
   496   fun merge data : T = Library.merge (op =) data
   497 );
   498 
   499 fun notify_val (string, value) = 
   500   let
   501     val _ = #enterVal ML_Env.name_space (string, value);
   502     val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
   503   in () end;
   504 
   505 fun abort _ = error "Only value bindings allowed.";
   506 
   507 val notifying_context : ML_Compiler0.context =
   508  {name_space =
   509    {lookupVal    = #lookupVal ML_Env.name_space,
   510     lookupType   = #lookupType ML_Env.name_space,
   511     lookupFix    = #lookupFix ML_Env.name_space,
   512     lookupStruct = #lookupStruct ML_Env.name_space,
   513     lookupSig    = #lookupSig ML_Env.name_space,
   514     lookupFunct  = #lookupFunct ML_Env.name_space,
   515     enterVal     = notify_val,
   516     enterType    = abort,
   517     enterFix     = abort,
   518     enterStruct  = abort,
   519     enterSig     = abort,
   520     enterFunct   = abort,
   521     allVal       = #allVal ML_Env.name_space,
   522     allType      = #allType ML_Env.name_space,
   523     allFix       = #allFix ML_Env.name_space,
   524     allStruct    = #allStruct ML_Env.name_space,
   525     allSig       = #allSig ML_Env.name_space,
   526     allFunct     = #allFunct ML_Env.name_space},
   527   print_depth = NONE,
   528   here = #here ML_Env.context,
   529   print = #print ML_Env.context,
   530   error = #error ML_Env.context};
   531 
   532 in
   533 
   534 fun use_file filepath thy =
   535   let
   536     val thy' = Loaded_Values.put [] thy;
   537     val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
   538     val _ =
   539       ML_Compiler0.ML notifying_context
   540         {line = 0, file = Path.implode filepath, verbose = false, debug = false}
   541         (File.read filepath);
   542     val thy'' = Context.the_global_context ();
   543     val names = Loaded_Values.get thy'';
   544   in (names, thy'') end;
   545 
   546 end;
   547 
   548 fun add_definiendum (ml_name, (b, T)) thy =
   549   thy
   550   |> Code_Target.add_reserved target ml_name
   551   |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
   552   |-> (fn ([Const (const, _)], _) =>
   553     Code_Target.set_printings (Constant (const,
   554       [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
   555   #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE structure_generated []));
   556 
   557 fun process_file filepath (definienda, thy) =
   558   let
   559     val (ml_names, thy') = use_file filepath thy;
   560     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   561     val _ = if null superfluous then ()
   562       else error ("Value binding(s) " ^ commas_quote superfluous
   563         ^ " found in external file " ^ Path.print filepath
   564         ^ " not present among the given contants binding(s).");
   565     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   566     val thy'' = fold add_definiendum these_definienda thy';
   567     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   568   in (definienda', thy'') end;
   569 
   570 fun polyml_as_definition bTs filepaths thy =
   571   let
   572     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   573     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   574     val _ = if null remaining then ()
   575       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   576         ^ " not present in external file(s).");
   577   in thy' end;
   578 
   579 end; (*struct*)