src/Tools/Code/code_runtime.ML
author haftmann
Tue Jan 24 22:29:36 2017 +0100 (2017-01-24)
changeset 64943 c5618df67c2a
parent 64940 19ca3644ec46
child 64944 27b1ba3ef778
permissions -rw-r--r--
explicit a-priori detection of unsuitable terms for computations
     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 T 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 Ts = add_typ T [];
   283     val of_term_for_typ' = of_term_for_typ Ts;
   284     val of_terms = map of_term_for_typ' Ts;
   285     val eval_for_const' = eval_for_const ctxt cTs;
   286     val evals = map eval_for_const' cTs;
   287     val eval_tuple = enclose "(" ")" (commas evals);
   288     val eval_abs = space_implode "" (map (fn s => "fn " ^ s ^ " => ") evals);
   289     val of_term_code = print_of_term_funs {
   290       typ_sign_for = typ_sign_for,
   291       eval_for_const = eval_for_const',
   292       of_term_for_typ = of_term_for_typ' } Ts;
   293   in
   294     (cat_lines [
   295       "structure " ^ generated_computationN ^ " =",
   296       "struct",
   297       "",
   298       "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
   299       "  (" ^ eval_abs,
   300       "    " ^ eval_tuple ^ ");",
   301       "",
   302       of_term_code,
   303       "",
   304       "end"
   305     ], map (prefix (generated_computationN ^ ".")) of_terms)
   306   end;
   307 
   308 fun check_typ ctxt T t =
   309   Syntax.check_term ctxt (Type.constraint T t);
   310 
   311 fun check_computation_input ctxt cTs t =
   312   let
   313     fun check t = check_comb (strip_comb t)
   314     and check_comb (t as Abs _, _) =
   315           error ("Bad term, contains abstraction: " ^ Syntax.string_of_term ctxt t)
   316       | check_comb (t as Const (cT as (c, T)), ts) =
   317           let
   318             val _ = if not (member (op =) cTs cT)
   319               then error ("Bad term, computation cannot proceed on constant " ^ Syntax.string_of_term ctxt t)
   320               else ();
   321             val _ = if not (monomorphic T)
   322               then error ("Bad term, contains polymorphic constant " ^ Syntax.string_of_term ctxt t)
   323               else ();
   324             val _ = map check ts;
   325           in () end;
   326     val _ = check t;
   327   in t end;
   328 
   329 fun compile_computation cookie ctxt T program evals vs_ty_evals deps =
   330   let
   331     val raw_cTs = case evals of
   332         Abs (_, _, t) => (snd o strip_comb) t
   333       | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
   334     val cTs = map (fn Const cT => cT
   335       | t => error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)) raw_cTs;
   336     fun comp' vs_ty_evals =
   337       let
   338         val (generated_code, compiled_value) =
   339           build_computation_text ctxt NONE program deps vs_ty_evals;
   340         val (of_term_code, of_terms) = print_computation_code ctxt compiled_value T cTs;
   341       in
   342         (generated_code ^ "\n" ^ of_term_code,
   343           enclose "(" ")" ("fn () => " ^ List.last of_terms))
   344       end;
   345     val compiled_computation =
   346       Exn.release (run_computation_text cookie ctxt comp' vs_ty_evals []);
   347   in fn ctxt' =>
   348     check_typ ctxt' T
   349     #> reject_vars ctxt'
   350     #> check_computation_input ctxt cTs
   351     #> compiled_computation
   352   end;
   353 
   354 fun experimental_computation cookie { ctxt, lift_postproc, terms = ts, T } =
   355   let
   356     val cTs = (fold o fold_aterms)
   357       (fn (t as Const (cT as (_, T))) =>
   358         if not (monomorphic T) then error ("Polymorphic constant:" ^ Syntax.string_of_term ctxt t)
   359         else insert (op =) cT | _ => I) ts [];
   360     val vT = TFree (singleton (Name.variant_list
   361       (fold (fn (_, T) => fold_atyps (fn TFree (v, _) => insert (op =) v | _ => I)
   362         T) cTs [])) Name.aT, []);
   363     val evals = Abs ("eval", map snd cTs ---> vT, list_comb (Bound 0, map Const cTs));
   364     val computation = Code_Thingol.dynamic_value ctxt
   365       (K I) (compile_computation cookie ctxt T) evals;
   366   in
   367     Code_Preproc.static_value { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
   368       (K computation)
   369   end;
   370 
   371 
   372 (** code antiquotation **)
   373 
   374 fun evaluation_code ctxt module_name program tycos consts =
   375   let
   376     val thy = Proof_Context.theory_of ctxt;
   377     val (ml_modules, target_names) =
   378       Code_Target.produce_code_for ctxt
   379         target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
   380     val ml_code = space_implode "\n\n" (map snd ml_modules);
   381     val (consts', tycos') = chop (length consts) target_names;
   382     val consts_map = map2 (fn const =>
   383       fn NONE =>
   384           error ("Constant " ^ (quote o Code.string_of_const thy) const ^
   385             "\nhas a user-defined serialization")
   386        | SOME const' => (const, const')) consts consts'
   387     val tycos_map = map2 (fn tyco =>
   388       fn NONE =>
   389           error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   390             "\nhas a user-defined serialization")
   391         | SOME tyco' => (tyco, tyco')) tycos tycos';
   392   in (ml_code, (tycos_map, consts_map)) end;
   393 
   394 local
   395 
   396 structure Code_Antiq_Data = Proof_Data
   397 (
   398   type T = (string list * string list) * (bool
   399     * (string * (string * string) list) lazy);
   400   val empty: T = (([], []), (true, (Lazy.value ("", []))));
   401   fun init _ = empty;
   402 );
   403 
   404 val is_first_occ = fst o snd o Code_Antiq_Data.get;
   405 
   406 fun register_code new_tycos new_consts ctxt =
   407   let
   408     val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
   409     val tycos' = fold (insert (op =)) new_tycos tycos;
   410     val consts' = fold (insert (op =)) new_consts consts;
   411     val program = Code_Thingol.consts_program ctxt consts';
   412     val acc_code = Lazy.lazy (fn () =>
   413       evaluation_code ctxt Code_Target.generatedN program tycos' consts'
   414       |> apsnd snd);
   415   in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
   416 
   417 fun register_const const = register_code [] [const];
   418 
   419 fun print_code is_first const ctxt =
   420   let
   421     val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
   422     val (ml_code, consts_map) = Lazy.force acc_code;
   423     val ml_code = if is_first then ml_code else "";
   424     val body = ML_Context.struct_name ctxt ^ "." ^ the (AList.lookup (op =) consts_map const);
   425   in (ml_code, body) end;
   426 
   427 in
   428 
   429 fun ml_code_antiq raw_const ctxt =
   430   let
   431     val thy = Proof_Context.theory_of ctxt;
   432     val const = Code.check_const thy raw_const;
   433     val is_first = is_first_occ ctxt;
   434   in (print_code is_first const, register_const const ctxt) end;
   435 
   436 end; (*local*)
   437 
   438 
   439 (** reflection support **)
   440 
   441 fun check_datatype thy tyco some_consts =
   442   let
   443     val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
   444     val constrs = case some_consts
   445      of SOME [] => []
   446       | SOME consts =>
   447           let
   448             val missing_constrs = subtract (op =) consts declared_constrs;
   449             val _ = if null missing_constrs then []
   450               else error ("Missing constructor(s) " ^ commas_quote missing_constrs
   451                 ^ " for datatype " ^ quote tyco);
   452             val false_constrs = subtract (op =) declared_constrs consts;
   453             val _ = if null false_constrs then []
   454               else error ("Non-constructor(s) " ^ commas_quote false_constrs
   455                 ^ " for datatype " ^ quote tyco)
   456           in consts end
   457       | NONE => declared_constrs;
   458   in (tyco, constrs) end;
   459 
   460 fun add_eval_tyco (tyco, tyco') thy =
   461   let
   462     val k = Sign.arity_number thy tyco;
   463     fun pr pr' _ [] = tyco'
   464       | pr pr' _ [ty] =
   465           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   466       | pr pr' _ tys =
   467           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   468   in
   469     thy
   470     |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
   471   end;
   472 
   473 fun add_eval_constr (const, const') thy =
   474   let
   475     val k = Code.args_number thy const;
   476     fun pr pr' fxy ts = Code_Printer.brackify fxy
   477       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   478   in
   479     thy
   480     |> Code_Target.set_printings (Constant (const,
   481       [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
   482   end;
   483 
   484 fun add_eval_const (const, const') = Code_Target.set_printings (Constant
   485   (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
   486 
   487 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   488       thy
   489       |> Code_Target.add_reserved target module_name
   490       |> Context.theory_map (compile_ML true code)
   491       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   492       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   493       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   494   | process_reflection (code, _) _ (SOME file_name) thy =
   495       let
   496         val preamble =
   497           "(* Generated from " ^
   498             Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
   499           "; DO NOT EDIT! *)";
   500         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   501       in
   502         thy
   503       end;
   504 
   505 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   506   let
   507     val ctxt = Proof_Context.init_global thy;
   508     val datatypes = map (fn (raw_tyco, raw_cos) =>
   509       (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
   510     val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
   511       |> apsnd flat;
   512     val functions = map (prep_const thy) raw_functions;
   513     val consts = constrs @ functions;
   514     val program = Code_Thingol.consts_program ctxt consts;
   515     val result = evaluation_code ctxt module_name program tycos consts
   516       |> (apsnd o apsnd) (chop (length constrs));
   517   in
   518     thy
   519     |> process_reflection result module_name some_file
   520   end;
   521 
   522 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   523 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   524 
   525 
   526 (** Isar setup **)
   527 
   528 val _ =
   529   Theory.setup (ML_Antiquotation.declaration @{binding code} Args.term (fn _ => ml_code_antiq));
   530 
   531 local
   532 
   533 val parse_datatype =
   534   Parse.name -- Scan.optional (@{keyword "="} |--
   535     (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
   536     || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
   537 
   538 in
   539 
   540 val _ =
   541   Outer_Syntax.command @{command_keyword code_reflect}
   542     "enrich runtime environment with generated code"
   543     (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
   544       ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
   545     -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
   546     -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
   547     >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   548       (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   549 
   550 end; (*local*)
   551 
   552 
   553 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   554 
   555 local
   556 
   557 structure Loaded_Values = Theory_Data
   558 (
   559   type T = string list
   560   val empty = []
   561   val extend = I
   562   fun merge data : T = Library.merge (op =) data
   563 );
   564 
   565 fun notify_val (string, value) = 
   566   let
   567     val _ = #enterVal ML_Env.name_space (string, value);
   568     val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
   569   in () end;
   570 
   571 fun abort _ = error "Only value bindings allowed.";
   572 
   573 val notifying_context : ML_Compiler0.context =
   574  {name_space =
   575    {lookupVal    = #lookupVal ML_Env.name_space,
   576     lookupType   = #lookupType ML_Env.name_space,
   577     lookupFix    = #lookupFix ML_Env.name_space,
   578     lookupStruct = #lookupStruct ML_Env.name_space,
   579     lookupSig    = #lookupSig ML_Env.name_space,
   580     lookupFunct  = #lookupFunct ML_Env.name_space,
   581     enterVal     = notify_val,
   582     enterType    = abort,
   583     enterFix     = abort,
   584     enterStruct  = abort,
   585     enterSig     = abort,
   586     enterFunct   = abort,
   587     allVal       = #allVal ML_Env.name_space,
   588     allType      = #allType ML_Env.name_space,
   589     allFix       = #allFix ML_Env.name_space,
   590     allStruct    = #allStruct ML_Env.name_space,
   591     allSig       = #allSig ML_Env.name_space,
   592     allFunct     = #allFunct ML_Env.name_space},
   593   print_depth = NONE,
   594   here = #here ML_Env.context,
   595   print = #print ML_Env.context,
   596   error = #error ML_Env.context};
   597 
   598 in
   599 
   600 fun use_file filepath thy =
   601   let
   602     val thy' = Loaded_Values.put [] thy;
   603     val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
   604     val _ =
   605       ML_Compiler0.ML notifying_context
   606         {line = 0, file = Path.implode filepath, verbose = false, debug = false}
   607         (File.read filepath);
   608     val thy'' = Context.the_global_context ();
   609     val names = Loaded_Values.get thy'';
   610   in (names, thy'') end;
   611 
   612 end;
   613 
   614 fun add_definiendum (ml_name, (b, T)) thy =
   615   thy
   616   |> Code_Target.add_reserved target ml_name
   617   |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
   618   |-> (fn ([Const (const, _)], _) =>
   619     Code_Target.set_printings (Constant (const,
   620       [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
   621   #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
   622 
   623 fun process_file filepath (definienda, thy) =
   624   let
   625     val (ml_names, thy') = use_file filepath thy;
   626     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   627     val _ = if null superfluous then ()
   628       else error ("Value binding(s) " ^ commas_quote superfluous
   629         ^ " found in external file " ^ Path.print filepath
   630         ^ " not present among the given contants binding(s).");
   631     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   632     val thy'' = fold add_definiendum these_definienda thy';
   633     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   634   in (definienda', thy'') end;
   635 
   636 fun polyml_as_definition bTs filepaths thy =
   637   let
   638     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   639     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   640     val _ = if null remaining then ()
   641       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   642         ^ " not present in external file(s).");
   643   in thy' end;
   644 
   645 end; (*struct*)