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