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