src/Tools/Code/code_runtime.ML
author haftmann
Mon Feb 06 20:56:36 2017 +0100 (2017-02-06)
changeset 64992 41e2c3617582
parent 64991 d2c79b16e133
child 64993 4fb84597ec5a
permissions -rw-r--r--
extended syntax allows to include datatype constructors directly in 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 code_reflect: (string * string list option) list -> string list -> string
    32     -> string option -> theory -> theory
    33   datatype truth = Holds
    34   val put_truth: (unit -> truth) -> Proof.context -> Proof.context
    35   val mount_computation: Proof.context -> (string * typ) list -> typ
    36     -> (term -> 'ml) -> ((term -> term) -> 'ml option -> 'a) -> Proof.context -> term -> 'a
    37   val mount_computation_conv: Proof.context -> (string * typ) list -> typ
    38     -> (term -> 'ml) -> ('ml -> conv) -> Proof.context -> conv
    39   val mount_computation_check: Proof.context -> (string * typ) list
    40     -> (term -> truth) -> Proof.context -> conv
    41   val polyml_as_definition: (binding * typ) list -> Path.T list -> theory -> theory
    42   val trace: bool Config.T
    43 end;
    44 
    45 structure Code_Runtime : CODE_RUNTIME =
    46 struct
    47 
    48 open Basic_Code_Symbol;
    49 
    50 (** ML compiler as evaluation environment **)
    51 
    52 (* technical prerequisites *)
    53 
    54 val thisN = "Code_Runtime";
    55 val prefix_this = Long_Name.append thisN;
    56 val truthN = prefix_this "truth";
    57 val HoldsN = prefix_this "Holds";
    58 
    59 val target = "Eval";
    60 
    61 datatype truth = Holds;
    62 
    63 val _ = Theory.setup
    64   (Code_Target.add_derived_target (target, [(Code_ML.target_SML, I)])
    65   #> Code_Target.set_printings (Type_Constructor (@{type_name prop},
    66     [(target, SOME (0, (K o K o K) (Code_Printer.str truthN)))]))
    67   #> Code_Target.set_printings (Constant (@{const_name Code_Generator.holds},
    68     [(target, SOME (Code_Printer.plain_const_syntax HoldsN))]))
    69   #> Code_Target.add_reserved target thisN
    70   #> fold (Code_Target.add_reserved target) ["oo", "ooo", "oooo", "upto", "downto", "orf", "andf"]);
    71        (*avoid further pervasive infix names*)
    72 
    73 val trace = Attrib.setup_config_bool @{binding "code_runtime_trace"} (K false);
    74 
    75 fun compile_ML verbose code context =
    76  (if Config.get_generic context trace then tracing code else ();
    77   Code_Preproc.timed "compiling ML" Context.proof_of
    78     (ML_Context.exec (fn () => ML_Compiler0.ML ML_Env.context
    79     {line = 0, file = "generated code", verbose = verbose,
    80        debug = false} code)) context);
    81 
    82 fun value ctxt (get, put, put_ml) (prelude, value) =
    83   let
    84     val code =
    85       prelude ^ "\nval _ = Context.put_generic_context (SOME (Context.map_proof (" ^
    86       put_ml ^ " (fn () => " ^ value ^ ")) (Context.the_generic_context ())))";
    87     val ctxt' = ctxt
    88       |> put (fn () => error ("Bad compilation for " ^ quote put_ml))
    89       |> Context.proof_map (compile_ML false code);
    90     val computator = get ctxt';
    91   in Code_Preproc.timed_exec "running ML" computator ctxt' end;
    92 
    93 
    94 (* evaluation into ML language values *)
    95 
    96 type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string;
    97 
    98 fun reject_vars ctxt t =
    99   ((Sign.no_frees ctxt o Sign.no_vars ctxt o map_types (K dummyT)) t; t);
   100 
   101 fun build_compilation_text ctxt some_target program consts =
   102   Code_Target.compilation_text ctxt (the_default target some_target) program consts false
   103   #>> (fn ml_modules => space_implode "\n\n" (map snd ml_modules));
   104 
   105 fun run_compilation_text cookie ctxt comp vs_t args =
   106   let
   107     val (program_code, value_name) = comp vs_t;
   108     val value_code = space_implode " "
   109       (value_name :: "()" :: map (enclose "(" ")") args);
   110   in Exn.interruptible_capture (value ctxt cookie) (program_code, value_code) end;
   111 
   112 fun partiality_as_none e = SOME (Exn.release e)
   113   handle General.Match => NONE
   114     | General.Bind => NONE
   115     | General.Fail _ => NONE;
   116 
   117 fun dynamic_value_exn cookie ctxt some_target postproc t args =
   118   let
   119     val _ = reject_vars ctxt t;
   120     val _ = if Config.get ctxt trace
   121       then tracing ("Evaluation of term " ^ quote (Syntax.string_of_term ctxt t))
   122       else ()
   123     fun comp program _ vs_ty_t deps =
   124       run_compilation_text cookie ctxt (build_compilation_text ctxt some_target program deps) vs_ty_t args;
   125   in Code_Thingol.dynamic_value ctxt (Exn.map_res o postproc) comp t end;
   126 
   127 fun dynamic_value_strict cookie ctxt some_target postproc t args =
   128   Exn.release (dynamic_value_exn cookie ctxt some_target postproc t args);
   129 
   130 fun dynamic_value cookie ctxt some_target postproc t args =
   131   partiality_as_none (dynamic_value_exn cookie ctxt some_target postproc t args);
   132 
   133 fun static_value_exn cookie { ctxt, target, lift_postproc, consts } =
   134   let
   135     fun compilation' { program, deps } =
   136       let
   137         val compilation'' = run_compilation_text cookie ctxt
   138           (build_compilation_text ctxt target program (map Constant deps));
   139       in fn _ => fn _ => fn vs_ty_t => fn _ => compilation'' vs_ty_t [] end;
   140     val compilation = Code_Thingol.static_value { ctxt = ctxt,
   141       lift_postproc = Exn.map_res o lift_postproc, consts = consts }
   142       compilation';
   143   in fn ctxt' => compilation ctxt' o reject_vars ctxt' end;
   144 
   145 fun static_value_strict cookie x = Exn.release oo static_value_exn cookie x;
   146 
   147 fun static_value cookie x = partiality_as_none oo static_value_exn cookie x;
   148 
   149 
   150 (* evaluation for truth or nothing *)
   151 
   152 structure Truth_Result = Proof_Data
   153 (
   154   type T = unit -> truth;
   155   val empty: T = fn () => raise Fail "Truth_Result";
   156   fun init _ = empty;
   157 );
   158 val put_truth = Truth_Result.put;
   159 val truth_cookie = (Truth_Result.get, put_truth, prefix_this "put_truth");
   160 
   161 local
   162 
   163 val reject_vars = fn ctxt => tap (reject_vars ctxt o Thm.term_of);
   164 
   165 fun check_holds ctxt evaluator vs_t ct =
   166   let
   167     val t = Thm.term_of ct;
   168     val _ = if fastype_of t <> propT
   169       then error ("Not a proposition: " ^ Syntax.string_of_term ctxt t)
   170       else ();
   171     val iff = Thm.cterm_of ctxt (Term.Const (@{const_name Pure.eq}, propT --> propT --> propT));
   172     val result = case partiality_as_none (run_compilation_text truth_cookie ctxt evaluator vs_t [])
   173      of SOME Holds => true
   174       | _ => false;
   175   in
   176     Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
   177   end;
   178 
   179 val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
   180   (Thm.add_oracle (@{binding holds_by_evaluation},
   181   fn (ctxt, evaluator, vs_t, ct) => check_holds ctxt evaluator vs_t ct)));
   182 
   183 fun check_holds_oracle ctxt evaluator vs_ty_t ct =
   184   raw_check_holds_oracle (ctxt, evaluator, vs_ty_t, ct);
   185 
   186 in
   187 
   188 fun dynamic_holds_conv ctxt = Code_Thingol.dynamic_conv ctxt
   189   (fn program => fn vs_t => fn deps =>
   190     check_holds_oracle ctxt (build_compilation_text ctxt NONE program deps) vs_t)
   191       o reject_vars ctxt;
   192 
   193 fun static_holds_conv (ctxt_consts as { ctxt, ... }) =
   194   Code_Thingol.static_conv_thingol ctxt_consts (fn { program, deps } => fn ctxt' => fn vs_t =>
   195     K (check_holds_oracle ctxt' (build_compilation_text ctxt NONE program (map Constant deps)) vs_t o reject_vars ctxt'));
   196 
   197 end; (*local*)
   198 
   199 
   200 (** generator for computations -- partial implementations of the universal morphism from Isabelle to ML terms **)
   201 
   202 (* auxiliary *)
   203 
   204 val generated_computationN = "Generated_Computation";
   205 
   206 
   207 (* possible type signatures of constants *)
   208 
   209 fun typ_signatures' T =
   210   let
   211     val (Ts, T') = strip_type T;
   212   in map_range (fn n => (drop n Ts ---> T', take n Ts)) (length Ts + 1) end;
   213 
   214 fun typ_signatures cTs =
   215   let
   216     fun add (c, T) =
   217       fold (fn (T, Ts) => Typtab.map_default (T, []) (cons (c, Ts)))
   218         (typ_signatures' T);
   219   in
   220     Typtab.empty
   221     |> fold add cTs
   222     |> Typtab.lookup_list
   223   end;
   224 
   225 
   226 (* name mangling *)
   227 
   228 local
   229 
   230 fun tycos_of (Type (tyco, Ts)) = maps tycos_of Ts @ [tyco]
   231   | tycos_of _ = [];
   232 
   233 val ml_name_of = Name.desymbolize NONE o Long_Name.base_name;
   234 
   235 in
   236 
   237 val covered_constsN = "covered_consts";
   238 
   239 fun of_term_for_typ Ts =
   240   let
   241     val names = Ts
   242       |> map (suffix "_of_term" o space_implode "_" o map ml_name_of o tycos_of)
   243       |> Name.variant_list [];
   244   in the o AList.lookup (op =) (Ts ~~ names) end;
   245 
   246 fun eval_for_const ctxt cTs =
   247   let
   248     fun symbol_list (c, T) = c :: maps tycos_of (Sign.const_typargs (Proof_Context.theory_of ctxt) (c, T))
   249     val names = cTs
   250       |> map (prefix "eval_" o space_implode "_" o map ml_name_of o symbol_list)
   251       |> Name.variant_list [];
   252   in the o AList.lookup (op =) (cTs ~~ names) end;
   253 
   254 end;
   255 
   256 
   257 (* checks for input terms *)
   258 
   259 fun monomorphic T = fold_atyps ((K o K) false) T true;
   260 
   261 fun check_typ ctxt T t =
   262   Syntax.check_term ctxt (Type.constraint T t);
   263 
   264 fun check_computation_input ctxt cTs t =
   265   let
   266     fun check t = check_comb (strip_comb t)
   267     and check_comb (t as Abs _, _) =
   268           error ("Bad term, contains abstraction: " ^ Syntax.string_of_term ctxt t)
   269       | check_comb (t as Const (cT as (c, T)), ts) =
   270           let
   271             val _ = if not (member (op =) cTs cT)
   272               then error ("Bad term, computation cannot proceed on constant " ^ Syntax.string_of_term ctxt t)
   273               else ();
   274             val _ = if not (monomorphic T)
   275               then error ("Bad term, contains polymorphic constant " ^ Syntax.string_of_term ctxt t)
   276               else ();
   277             val _ = map check ts;
   278           in () end;
   279     val _ = check t;
   280   in t end;
   281 
   282 
   283 (* code generation for of the universal morphism *)
   284 
   285 val print_const = ML_Syntax.print_pair ML_Syntax.print_string ML_Syntax.print_typ;
   286 
   287 fun print_of_term_funs { typ_signatures_for, eval_for_const, of_term_for_typ } Ts =
   288   let
   289     val var_names = map_range (fn n => "t" ^ string_of_int (n + 1));
   290     fun print_lhs c xs = "Const (" ^ quote c ^ ", _)"
   291       |> fold (fn x => fn s => s ^ " $ " ^ x) xs
   292       |> enclose "(" ")";
   293     fun print_rhs c Ts T xs = eval_for_const (c, Ts ---> T)
   294       |> fold2 (fn T' => fn x => fn s =>
   295          s ^ (" (" ^ of_term_for_typ T' ^ " " ^ x ^ ")")) Ts xs
   296     fun print_eq T (c, Ts) =
   297       let
   298         val xs = var_names (length Ts);
   299       in print_lhs c xs ^ " = " ^ print_rhs c Ts T xs end;
   300     fun print_eqs T =
   301       let
   302         val typ_signs = typ_signatures_for T;
   303         val name = of_term_for_typ T;
   304       in
   305         map (print_eq T) typ_signs
   306         |> map (prefix (name ^ " "))
   307         |> space_implode "\n  | "
   308       end;
   309   in
   310     map print_eqs Ts
   311     |> space_implode "\nand "
   312     |> prefix "fun "
   313   end;
   314 
   315 fun print_computation_code ctxt compiled_value [] requested_Ts =
   316       if null requested_Ts then ("", [])
   317       else error ("No equation available for requested type "
   318         ^ Syntax.string_of_typ ctxt (hd requested_Ts))
   319   | print_computation_code ctxt compiled_value cTs requested_Ts =
   320       let
   321         val proper_cTs = map_filter I cTs;
   322         val typ_signatures_for = typ_signatures proper_cTs;
   323         fun add_typ T Ts =
   324           if member (op =) Ts T
   325           then Ts
   326           else case typ_signatures_for T of
   327             [] => error ("No equation available for requested type "
   328               ^ Syntax.string_of_typ ctxt T)
   329           | typ_signs =>
   330               Ts
   331               |> cons T
   332               |> fold (fold add_typ o snd) typ_signs;
   333         val required_Ts = fold add_typ requested_Ts [];
   334         val of_term_for_typ' = of_term_for_typ required_Ts;
   335         val eval_for_const' = eval_for_const ctxt proper_cTs;
   336         val eval_for_const'' = the_default "_" o Option.map eval_for_const';
   337         val eval_tuple = enclose "(" ")" (commas (map eval_for_const' proper_cTs));
   338         fun mk_abs s = "fn " ^ s ^ " => ";
   339         val eval_abs = space_implode ""
   340           (map (mk_abs o eval_for_const'') cTs);
   341         val of_term_code = print_of_term_funs {
   342           typ_signatures_for = typ_signatures_for,
   343           eval_for_const = eval_for_const',
   344           of_term_for_typ = of_term_for_typ' } required_Ts;
   345         val of_term_names = map (Long_Name.append generated_computationN
   346           o of_term_for_typ') requested_Ts;
   347       in
   348         cat_lines [
   349           "structure " ^ generated_computationN ^ " =",
   350           "struct",
   351           "",
   352           "val " ^ covered_constsN ^ " = " ^ ML_Syntax.print_list print_const proper_cTs ^ ";",
   353           "",
   354           "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
   355           "  (" ^ eval_abs,
   356           "    " ^ eval_tuple ^ ");",
   357           "",
   358           of_term_code,
   359           "",
   360           "end"
   361         ] |> rpair of_term_names
   362       end;
   363 
   364 fun prechecked_computation T raw_computation ctxt =
   365   check_typ ctxt T
   366   #> reject_vars ctxt
   367   #> raw_computation ctxt;
   368 
   369 fun prechecked_conv T raw_conv ctxt =
   370   tap (check_typ ctxt T o reject_vars ctxt o Thm.term_of)
   371   #> raw_conv ctxt;
   372 
   373 fun checked_computation cTs raw_computation ctxt =
   374   check_computation_input ctxt cTs
   375   #> Exn.capture raw_computation
   376   #> partiality_as_none;
   377 
   378 fun mount_computation ctxt cTs T raw_computation lift_postproc =
   379   prechecked_computation T (Code_Preproc.static_value
   380     { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
   381     (K (checked_computation cTs raw_computation)));
   382 
   383 fun mount_computation_conv ctxt cTs T raw_computation conv =
   384   prechecked_conv T (Code_Preproc.static_conv
   385     { ctxt = ctxt, consts = [] }
   386     (K (fn ctxt' => fn t =>
   387       case checked_computation cTs raw_computation ctxt' t of
   388         SOME x => conv x
   389       | NONE => Conv.all_conv)));
   390 
   391 local
   392 
   393 fun holds ct = Thm.mk_binop @{cterm "Pure.eq :: prop \<Rightarrow> prop \<Rightarrow> prop"}
   394   ct @{cprop "PROP Code_Generator.holds"};
   395 
   396 val (_, holds_oracle) = Context.>>> (Context.map_theory_result
   397   (Thm.add_oracle (@{binding holds}, holds)));
   398 
   399 in
   400 
   401 fun mount_computation_check ctxt cTs raw_computation =
   402   mount_computation_conv ctxt cTs @{typ prop} raw_computation
   403     (K holds_oracle);
   404 
   405 end;
   406 
   407 
   408 (** variants of universal runtime code generation **)
   409 
   410 (*FIXME consolidate variants*)
   411 
   412 fun runtime_code'' ctxt module_name program tycos consts =
   413   let
   414     val thy = Proof_Context.theory_of ctxt;
   415     val (ml_modules, target_names) =
   416       Code_Target.produce_code_for ctxt
   417         target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
   418     val ml_code = space_implode "\n\n" (map snd ml_modules);
   419     val (consts', tycos') = chop (length consts) target_names;
   420     val consts_map = map2 (fn const =>
   421       fn NONE =>
   422           error ("Constant " ^ (quote o Code.string_of_const thy) const ^
   423             "\nhas a user-defined serialization")
   424        | SOME const' => (const, const')) consts consts'
   425     val tycos_map = map2 (fn tyco =>
   426       fn NONE =>
   427           error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   428             "\nhas a user-defined serialization")
   429         | SOME tyco' => (tyco, tyco')) tycos tycos';
   430   in (ml_code, (tycos_map, consts_map)) end;
   431 
   432 fun runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
   433   let
   434     val thy = Proof_Context.theory_of ctxt;
   435     fun the_const (Const cT) = cT
   436       | the_const t = error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)
   437     val raw_computation_cTs = case evals of
   438         Abs (_, _, t) => (map the_const o snd o strip_comb) t
   439       | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
   440     val computation_cTs = fold_rev (fn cT => fn cTs =>
   441       (if member (op =) cTs (SOME cT) then NONE else SOME cT) :: cTs) raw_computation_cTs [];
   442     val consts' = fold (fn NONE => I | SOME (c, _) => insert (op =) c)
   443       computation_cTs named_consts;
   444     val program' = Code_Thingol.consts_program ctxt consts';
   445       (*FIXME insufficient interfaces require double invocation of code generator*)
   446     val ((ml_modules, compiled_value), deresolve) =
   447       Code_Target.compilation_text' ctxt target some_module_name program'
   448         (map Code_Symbol.Type_Constructor named_tycos @ map Code_Symbol.Constant consts' @ deps) true vs_ty_evals;
   449         (*FIXME constrain signature*)
   450     fun deresolve_const c = case (deresolve o Code_Symbol.Constant) c of
   451           NONE => error ("Constant " ^ (quote o Code.string_of_const thy) c ^
   452             "\nhas a user-defined serialization")
   453         | SOME c' => c';
   454     fun deresolve_tyco tyco = case (deresolve o Code_Symbol.Type_Constructor) tyco of
   455           NONE => error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   456             "\nhas a user-defined serialization")
   457         | SOME c' => c';
   458     val tyco_names =  map deresolve_const named_tycos;
   459     val const_names = map deresolve_const named_consts;
   460     val generated_code = space_implode "\n\n" (map snd ml_modules);
   461     val (of_term_code, of_term_names) =
   462       print_computation_code ctxt compiled_value computation_cTs computation_Ts;
   463     val compiled_computation = generated_code ^ "\n" ^ of_term_code;
   464   in
   465     compiled_computation
   466     |> rpair { tyco_map = named_tycos ~~ tyco_names,
   467       const_map = named_consts ~~ const_names,
   468       of_term_map = computation_Ts ~~ of_term_names }
   469   end;
   470 
   471 fun funs_of_maps { tyco_map, const_map, of_term_map } =
   472   { name_for_tyco = the o AList.lookup (op =) tyco_map,
   473     name_for_const = the o AList.lookup (op =) const_map,
   474     of_term_for_typ = the o AList.lookup (op =) of_term_map };
   475 
   476 fun runtime_code ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
   477   runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps
   478   ||> funs_of_maps;
   479 
   480 
   481 (** code and computation antiquotations **)
   482 
   483 local
   484 
   485 val mount_computationN = prefix_this "mount_computation";
   486 val mount_computation_convN = prefix_this "mount_computation_conv";
   487 val mount_computation_checkN = prefix_this "mount_computation_check";
   488 
   489 structure Code_Antiq_Data = Proof_Data
   490 (
   491   type T = { named_consts: string list,
   492     computation_Ts: typ list, computation_cTs: (string * typ) list,
   493     position_index: int,
   494     generated_code: (string * {
   495       name_for_tyco: string -> string,
   496       name_for_const: string -> string,
   497       of_term_for_typ: typ -> string
   498     }) lazy
   499   };
   500   val empty: T = { named_consts = [],
   501     computation_Ts = [], computation_cTs = [],
   502     position_index = 0,
   503     generated_code = Lazy.lazy (fn () => raise Fail "empty")
   504   };
   505   fun init _ = empty;
   506 );
   507 
   508 val current_position_index = #position_index o Code_Antiq_Data.get;
   509 
   510 fun register { named_consts, computation_Ts, computation_cTs } ctxt =
   511   let
   512     val data = Code_Antiq_Data.get ctxt;
   513     val named_consts' = union (op =) named_consts (#named_consts data);
   514     val computation_Ts' = union (op =) computation_Ts (#computation_Ts data);
   515     val computation_cTs' = union (op =) computation_cTs (#computation_cTs data);
   516     val position_index' = #position_index data + 1;
   517     fun generated_code' () =
   518       let
   519         val evals = Abs ("eval", map snd computation_cTs' --->
   520           TFree (Name.aT, []), list_comb (Bound 0, map Const computation_cTs'));
   521       in Code_Thingol.dynamic_value ctxt
   522         (K I) (runtime_code ctxt NONE [] named_consts' computation_Ts') evals
   523       end;
   524   in
   525     ctxt
   526     |> Code_Antiq_Data.put { 
   527         named_consts = named_consts',
   528         computation_Ts = computation_Ts',
   529         computation_cTs = computation_cTs',
   530         position_index = position_index',
   531         generated_code = Lazy.lazy generated_code'
   532       }
   533   end;
   534 
   535 fun register_const const =
   536   register { named_consts = [const],
   537     computation_Ts = [],
   538     computation_cTs = [] };
   539 
   540 fun register_computation cTs T =
   541   register { named_consts = [],
   542     computation_Ts = [T],
   543     computation_cTs = cTs };
   544 
   545 fun print body_code_for ctxt ctxt' =
   546   let
   547     val position_index = current_position_index ctxt;
   548     val (code, name_ofs) = (Lazy.force o #generated_code o Code_Antiq_Data.get) ctxt';
   549     val context_code = if position_index = 0 then code else "";
   550     val body_code = body_code_for name_ofs (ML_Context.struct_name ctxt');
   551   in (context_code, body_code) end;
   552 
   553 fun print_code ctxt const =
   554   print (fn { name_for_const, ... } => fn prfx =>
   555     Long_Name.append prfx (name_for_const const)) ctxt;
   556 
   557 fun print_computation kind ctxt T =
   558   print (fn { of_term_for_typ, ... } => fn prfx =>
   559     space_implode " " [
   560       kind,
   561       "(Context.proof_of (Context.the_generic_context ()))",
   562       Long_Name.implode [prfx, generated_computationN, covered_constsN],
   563       (ML_Syntax.atomic o ML_Syntax.print_typ) T,
   564       Long_Name.append prfx (of_term_for_typ T)
   565     ]) ctxt;
   566 
   567 fun print_computation_check ctxt =
   568   print (fn { of_term_for_typ, ... } => fn prfx =>
   569     space_implode " " [
   570       mount_computation_checkN,
   571       "(Context.proof_of (Context.the_generic_context ()))",
   572       Long_Name.implode [prfx, generated_computationN, covered_constsN],
   573       Long_Name.append prfx (of_term_for_typ @{typ prop})
   574     ]) ctxt;
   575 
   576 
   577 fun add_all_constrs ctxt (dT as Type (tyco, Ts)) =
   578   let
   579     val ((vs, constrs), _) = Code.get_type (Proof_Context.theory_of ctxt) tyco;
   580     val subst_TFree = the o AList.lookup (op =) (map fst vs ~~ Ts);
   581     val cs = map (fn (c, (_, Ts')) =>
   582       (c, (map o map_atyps) (fn TFree (v, _) => subst_TFree v) Ts'
   583         ---> dT)) constrs;
   584   in
   585     union (op =) cs
   586     #> fold (add_all_constrs ctxt) Ts
   587   end;
   588 
   589 fun prep_spec ctxt (raw_ts, raw_dTs) =
   590   let
   591     val ts = map (Syntax.check_term ctxt) raw_ts;
   592     val dTs = map (Syntax.check_typ ctxt) raw_dTs;
   593   in
   594     []
   595     |> (fold o fold_aterms)
   596       (fn (t as Const (cT as (_, T))) =>
   597         if not (monomorphic T) then error ("Polymorphic constant: " ^ Syntax.string_of_term ctxt t)
   598         else insert (op =) cT | _ => I) ts
   599     |> fold (fn dT =>
   600         if not (monomorphic dT) then error ("Polymorphic datatype: " ^ Syntax.string_of_typ ctxt dT)
   601         else add_all_constrs ctxt dT) dTs
   602   end;
   603 
   604 in
   605 
   606 fun ml_code_antiq raw_const ctxt =
   607   let
   608     val thy = Proof_Context.theory_of ctxt;
   609     val const = Code.check_const thy raw_const;
   610   in (print_code ctxt const, register_const const ctxt) end;
   611 
   612 fun gen_ml_computation_antiq kind (raw_T, raw_spec) ctxt =
   613   let
   614     val cTs = prep_spec ctxt raw_spec;
   615     val T = Syntax.check_typ ctxt raw_T;
   616     val _ = if not (monomorphic T)
   617       then error ("Polymorphic type: " ^ Syntax.string_of_typ ctxt T)
   618       else ();
   619   in (print_computation kind ctxt T, register_computation cTs T ctxt) end;
   620 
   621 val ml_computation_antiq = gen_ml_computation_antiq mount_computationN;
   622 
   623 val ml_computation_conv_antiq = gen_ml_computation_antiq mount_computation_convN;
   624 
   625 fun ml_computation_check_antiq raw_spec ctxt =
   626   let
   627     val cTs = insert (op =) (dest_Const @{const holds}) (prep_spec ctxt raw_spec);
   628   in (print_computation_check ctxt, register_computation cTs @{typ prop} ctxt) end;
   629 
   630 end; (*local*)
   631 
   632 
   633 (** reflection support **)
   634 
   635 fun check_datatype thy tyco some_consts =
   636   let
   637     val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
   638     val constrs = case some_consts
   639      of SOME [] => []
   640       | SOME consts =>
   641           let
   642             val missing_constrs = subtract (op =) consts declared_constrs;
   643             val _ = if null missing_constrs then []
   644               else error ("Missing constructor(s) " ^ commas_quote missing_constrs
   645                 ^ " for datatype " ^ quote tyco);
   646             val false_constrs = subtract (op =) declared_constrs consts;
   647             val _ = if null false_constrs then []
   648               else error ("Non-constructor(s) " ^ commas_quote false_constrs
   649                 ^ " for datatype " ^ quote tyco)
   650           in consts end
   651       | NONE => declared_constrs;
   652   in (tyco, constrs) end;
   653 
   654 fun add_eval_tyco (tyco, tyco') thy =
   655   let
   656     val k = Sign.arity_number thy tyco;
   657     fun pr pr' _ [] = tyco'
   658       | pr pr' _ [ty] =
   659           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   660       | pr pr' _ tys =
   661           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   662   in
   663     thy
   664     |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
   665   end;
   666 
   667 fun add_eval_constr (const, const') thy =
   668   let
   669     val k = Code.args_number thy const;
   670     fun pr pr' fxy ts = Code_Printer.brackify fxy
   671       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   672   in
   673     thy
   674     |> Code_Target.set_printings (Constant (const,
   675       [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
   676   end;
   677 
   678 fun add_eval_const (const, const') = Code_Target.set_printings (Constant
   679   (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
   680 
   681 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   682       thy
   683       |> Code_Target.add_reserved target module_name
   684       |> Context.theory_map (compile_ML true code)
   685       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   686       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   687       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   688   | process_reflection (code, _) _ (SOME file_name) thy =
   689       let
   690         val preamble =
   691           "(* Generated from " ^
   692             Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
   693           "; DO NOT EDIT! *)";
   694         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   695       in
   696         thy
   697       end;
   698 
   699 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   700   let
   701     val ctxt = Proof_Context.init_global thy;
   702     val datatypes = map (fn (raw_tyco, raw_cos) =>
   703       (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
   704     val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
   705       |> apsnd flat;
   706     val functions = map (prep_const thy) raw_functions;
   707     val consts = constrs @ functions;
   708     val program = Code_Thingol.consts_program ctxt consts;
   709     val result = runtime_code'' ctxt module_name program tycos consts
   710       |> (apsnd o apsnd) (chop (length constrs));
   711   in
   712     thy
   713     |> process_reflection result module_name some_file
   714   end;
   715 
   716 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   717 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   718 
   719 
   720 (** Isar setup **)
   721 
   722 local
   723 
   724 val parse_consts_spec =
   725   Scan.optional (Scan.lift (Args.$$$ "terms" -- Args.colon) |-- Scan.repeat1 Args.term) []
   726   -- Scan.optional (Scan.lift (Args.$$$ "datatypes"  -- Args.colon) |-- Scan.repeat1 Args.typ) [];
   727 
   728 in
   729 
   730 val _ =
   731   Theory.setup (ML_Antiquotation.declaration @{binding code}
   732     Args.term (fn _ => ml_code_antiq));
   733 
   734 val _ =
   735   Theory.setup (ML_Antiquotation.declaration @{binding computation}
   736     (Args.typ -- parse_consts_spec)
   737        (fn _ => ml_computation_antiq));
   738 
   739 val _ =
   740   Theory.setup (ML_Antiquotation.declaration @{binding computation_conv}
   741     (Args.typ -- parse_consts_spec)
   742        (fn _ => ml_computation_conv_antiq));
   743 
   744 val _ =
   745   Theory.setup (ML_Antiquotation.declaration @{binding computation_check}
   746     parse_consts_spec 
   747        (fn _ => ml_computation_check_antiq));
   748 
   749 end;
   750 
   751 local
   752 
   753 val parse_datatype =
   754   Parse.name -- Scan.optional (@{keyword "="} |--
   755     (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
   756     || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
   757 
   758 in
   759 
   760 val _ =
   761   Outer_Syntax.command @{command_keyword code_reflect}
   762     "enrich runtime environment with generated code"
   763     (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
   764       ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
   765     -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
   766     -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
   767     >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   768       (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   769 
   770 end; (*local*)
   771 
   772 
   773 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   774 
   775 local
   776 
   777 structure Loaded_Values = Theory_Data
   778 (
   779   type T = string list
   780   val empty = []
   781   val extend = I
   782   fun merge data : T = Library.merge (op =) data
   783 );
   784 
   785 fun notify_val (string, value) = 
   786   let
   787     val _ = #enterVal ML_Env.name_space (string, value);
   788     val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
   789   in () end;
   790 
   791 fun abort _ = error "Only value bindings allowed.";
   792 
   793 val notifying_context : ML_Compiler0.context =
   794  {name_space =
   795    {lookupVal    = #lookupVal ML_Env.name_space,
   796     lookupType   = #lookupType ML_Env.name_space,
   797     lookupFix    = #lookupFix ML_Env.name_space,
   798     lookupStruct = #lookupStruct ML_Env.name_space,
   799     lookupSig    = #lookupSig ML_Env.name_space,
   800     lookupFunct  = #lookupFunct ML_Env.name_space,
   801     enterVal     = notify_val,
   802     enterType    = abort,
   803     enterFix     = abort,
   804     enterStruct  = abort,
   805     enterSig     = abort,
   806     enterFunct   = abort,
   807     allVal       = #allVal ML_Env.name_space,
   808     allType      = #allType ML_Env.name_space,
   809     allFix       = #allFix ML_Env.name_space,
   810     allStruct    = #allStruct ML_Env.name_space,
   811     allSig       = #allSig ML_Env.name_space,
   812     allFunct     = #allFunct ML_Env.name_space},
   813   print_depth = NONE,
   814   here = #here ML_Env.context,
   815   print = #print ML_Env.context,
   816   error = #error ML_Env.context};
   817 
   818 in
   819 
   820 fun use_file filepath thy =
   821   let
   822     val thy' = Loaded_Values.put [] thy;
   823     val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
   824     val _ =
   825       ML_Compiler0.ML notifying_context
   826         {line = 0, file = Path.implode filepath, verbose = false, debug = false}
   827         (File.read filepath);
   828     val thy'' = Context.the_global_context ();
   829     val names = Loaded_Values.get thy'';
   830   in (names, thy'') end;
   831 
   832 end;
   833 
   834 fun add_definiendum (ml_name, (b, T)) thy =
   835   thy
   836   |> Code_Target.add_reserved target ml_name
   837   |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
   838   |-> (fn ([Const (const, _)], _) =>
   839     Code_Target.set_printings (Constant (const,
   840       [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
   841   #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
   842 
   843 fun process_file filepath (definienda, thy) =
   844   let
   845     val (ml_names, thy') = use_file filepath thy;
   846     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   847     val _ = if null superfluous then ()
   848       else error ("Value binding(s) " ^ commas_quote superfluous
   849         ^ " found in external file " ^ Path.print filepath
   850         ^ " not present among the given contants binding(s).");
   851     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   852     val thy'' = fold add_definiendum these_definienda thy';
   853     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   854   in (definienda', thy'') end;
   855 
   856 fun polyml_as_definition bTs filepaths thy =
   857   let
   858     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   859     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   860     val _ = if null remaining then ()
   861       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   862         ^ " not present in external file(s).");
   863   in thy' end;
   864 
   865 end; (*struct*)