src/Tools/Code/code_runtime.ML
author haftmann
Mon Feb 06 20:56:33 2017 +0100 (2017-02-06)
changeset 64989 40c36a4aee1f
parent 64988 93aaff2b0ae0
child 64990 c6a7de505796
permissions -rw-r--r--
more computation antiquotations
     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_for 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_for 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_sign_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_sign_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   | print_computation_code ctxt compiled_value cTs requested_Ts =
   317       let
   318         val proper_cTs = map_filter I cTs;
   319         val typ_sign_for = typ_signatures proper_cTs;
   320         fun add_typ T Ts =
   321           if member (op =) Ts T
   322           then Ts
   323           else Ts
   324             |> cons T
   325             |> fold (fold add_typ o snd) (typ_sign_for T);
   326         val required_Ts = fold add_typ requested_Ts [];
   327         val of_term_for_typ' = of_term_for_typ required_Ts;
   328         val eval_for_const' = eval_for_const ctxt proper_cTs;
   329         val eval_for_const'' = the_default "_" o Option.map eval_for_const';
   330         val eval_tuple = enclose "(" ")" (commas (map eval_for_const' proper_cTs));
   331         fun mk_abs s = "fn " ^ s ^ " => ";
   332         val eval_abs = space_implode ""
   333           (map (mk_abs o eval_for_const'') cTs);
   334         val of_term_code = print_of_term_funs {
   335           typ_sign_for = typ_sign_for,
   336           eval_for_const = eval_for_const',
   337           of_term_for_typ = of_term_for_typ' } required_Ts;
   338         val of_term_names = map (Long_Name.append generated_computationN
   339           o of_term_for_typ') requested_Ts;
   340       in
   341         cat_lines [
   342           "structure " ^ generated_computationN ^ " =",
   343           "struct",
   344           "",
   345           "val " ^ covered_constsN ^ " = " ^ ML_Syntax.print_list print_const proper_cTs ^ ";",
   346           "",
   347           "val " ^ eval_tuple ^ " = " ^ compiled_value ^ " ()",
   348           "  (" ^ eval_abs,
   349           "    " ^ eval_tuple ^ ");",
   350           "",
   351           of_term_code,
   352           "",
   353           "end"
   354         ] |> rpair of_term_names
   355       end;
   356 
   357 fun checked_computation cTs T raw_computation ctxt =
   358   check_typ ctxt T
   359   #> reject_vars ctxt
   360   #> check_computation_input ctxt cTs
   361   #> Exn.capture raw_computation
   362   #> partiality_as_none;
   363 
   364 fun mount_computation ctxt cTs T raw_computation lift_postproc =
   365   Code_Preproc.static_value { ctxt = ctxt, lift_postproc = lift_postproc, consts = [] }
   366     (K (checked_computation cTs T raw_computation));
   367 
   368 fun mount_computation_conv ctxt cTs T raw_computation conv =
   369   Code_Preproc.static_conv { ctxt = ctxt, consts = [] }
   370     (K (fn ctxt' => fn t =>
   371       case checked_computation cTs T raw_computation ctxt' t of
   372         SOME x => conv x
   373       | NONE => Conv.all_conv));
   374 
   375 local
   376 
   377 fun holds ct = Thm.mk_binop @{cterm "Pure.eq :: prop \<Rightarrow> prop \<Rightarrow> prop"}
   378   ct @{cprop "PROP Code_Generator.holds"};
   379 
   380 val (_, holds_oracle) = Context.>>> (Context.map_theory_result
   381   (Thm.add_oracle (@{binding holds}, holds)));
   382 
   383 in
   384 
   385 fun mount_computation_check ctxt cTs raw_computation =
   386   mount_computation_conv ctxt cTs @{typ prop} raw_computation
   387     (K holds_oracle);
   388 
   389 end;
   390 
   391 
   392 (** variants of universal runtime code generation **)
   393 
   394 (*FIXME consolidate variants*)
   395 
   396 fun runtime_code'' ctxt module_name program tycos consts =
   397   let
   398     val thy = Proof_Context.theory_of ctxt;
   399     val (ml_modules, target_names) =
   400       Code_Target.produce_code_for ctxt
   401         target NONE module_name [] program false (map Constant consts @ map Type_Constructor tycos);
   402     val ml_code = space_implode "\n\n" (map snd ml_modules);
   403     val (consts', tycos') = chop (length consts) target_names;
   404     val consts_map = map2 (fn const =>
   405       fn NONE =>
   406           error ("Constant " ^ (quote o Code.string_of_const thy) const ^
   407             "\nhas a user-defined serialization")
   408        | SOME const' => (const, const')) consts consts'
   409     val tycos_map = map2 (fn tyco =>
   410       fn NONE =>
   411           error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   412             "\nhas a user-defined serialization")
   413         | SOME tyco' => (tyco, tyco')) tycos tycos';
   414   in (ml_code, (tycos_map, consts_map)) end;
   415 
   416 fun runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
   417   let
   418     val thy = Proof_Context.theory_of ctxt;
   419     fun the_const (Const cT) = cT
   420       | the_const t = error ("No constant after preprocessing: " ^ Syntax.string_of_term ctxt t)
   421     val raw_computation_cTs = case evals of
   422         Abs (_, _, t) => (map the_const o snd o strip_comb) t
   423       | _ => error ("Bad term after preprocessing: " ^ Syntax.string_of_term ctxt evals);
   424     val computation_cTs = fold_rev (fn cT => fn cTs =>
   425       (if member (op =) cTs (SOME cT) then NONE else SOME cT) :: cTs) raw_computation_cTs [];
   426     val consts' = fold (fn NONE => I | SOME (c, _) => insert (op =) c)
   427       computation_cTs named_consts;
   428     val program' = Code_Thingol.consts_program ctxt consts';
   429       (*FIXME insufficient interfaces require double invocation of code generator*)
   430     val ((ml_modules, compiled_value), deresolve) =
   431       Code_Target.compilation_text' ctxt target some_module_name program'
   432         (map Code_Symbol.Type_Constructor named_tycos @ map Code_Symbol.Constant consts' @ deps) true vs_ty_evals;
   433         (*FIXME constrain signature*)
   434     fun deresolve_const c = case (deresolve o Code_Symbol.Constant) c of
   435           NONE => error ("Constant " ^ (quote o Code.string_of_const thy) c ^
   436             "\nhas a user-defined serialization")
   437         | SOME c' => c';
   438     fun deresolve_tyco tyco = case (deresolve o Code_Symbol.Type_Constructor) tyco of
   439           NONE => error ("Type " ^ quote (Proof_Context.markup_type ctxt tyco) ^
   440             "\nhas a user-defined serialization")
   441         | SOME c' => c';
   442     val tyco_names =  map deresolve_const named_tycos;
   443     val const_names = map deresolve_const named_consts;
   444     val generated_code = space_implode "\n\n" (map snd ml_modules);
   445     val (of_term_code, of_term_names) =
   446       print_computation_code ctxt compiled_value computation_cTs computation_Ts;
   447     val compiled_computation = generated_code ^ "\n" ^ of_term_code;
   448   in
   449     compiled_computation
   450     |> rpair { tyco_map = named_tycos ~~ tyco_names,
   451       const_map = named_consts ~~ const_names,
   452       of_term_map = computation_Ts ~~ of_term_names }
   453   end;
   454 
   455 fun funs_of_maps { tyco_map, const_map, of_term_map } =
   456   { name_for_tyco = the o AList.lookup (op =) tyco_map,
   457     name_for_const = the o AList.lookup (op =) const_map,
   458     of_term_for_typ = the o AList.lookup (op =) of_term_map };
   459 
   460 fun runtime_code ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps =
   461   runtime_code' ctxt some_module_name named_tycos named_consts computation_Ts program evals vs_ty_evals deps
   462   ||> funs_of_maps;
   463 
   464 
   465 (** code and computation antiquotations **)
   466 
   467 local
   468 
   469 val mount_computationN = prefix_this "mount_computation";
   470 val mount_computation_convN = prefix_this "mount_computation_conv";
   471 val mount_computation_checkN = prefix_this "mount_computation_check";
   472 
   473 structure Code_Antiq_Data = Proof_Data
   474 (
   475   type T = { named_consts: string list,
   476     computation_Ts: typ list, computation_cTs: (string * typ) list,
   477     position_index: int,
   478     generated_code: (string * {
   479       name_for_tyco: string -> string,
   480       name_for_const: string -> string,
   481       of_term_for_typ: typ -> string
   482     }) lazy
   483   };
   484   val empty: T = { named_consts = [],
   485     computation_Ts = [], computation_cTs = [],
   486     position_index = 0,
   487     generated_code = Lazy.lazy (fn () => raise Fail "empty")
   488   };
   489   fun init _ = empty;
   490 );
   491 
   492 val current_position_index = #position_index o Code_Antiq_Data.get;
   493 
   494 fun register { named_consts, computation_Ts, computation_cTs } ctxt =
   495   let
   496     val data = Code_Antiq_Data.get ctxt;
   497     val named_consts' = union (op =) named_consts (#named_consts data);
   498     val computation_Ts' = union (op =) computation_Ts (#computation_Ts data);
   499     val computation_cTs' = union (op =) computation_cTs (#computation_cTs data);
   500     val position_index' = #position_index data + 1;
   501     fun generated_code' () =
   502       let
   503         val evals = Abs ("eval", map snd computation_cTs' --->
   504           TFree (Name.aT, []), list_comb (Bound 0, map Const computation_cTs'));
   505       in Code_Thingol.dynamic_value ctxt
   506         (K I) (runtime_code ctxt NONE [] named_consts' computation_Ts') evals
   507       end;
   508   in
   509     ctxt
   510     |> Code_Antiq_Data.put { 
   511         named_consts = named_consts',
   512         computation_Ts = computation_Ts',
   513         computation_cTs = computation_cTs',
   514         position_index = position_index',
   515         generated_code = Lazy.lazy generated_code'
   516       }
   517   end;
   518 
   519 fun register_const const =
   520   register { named_consts = [const],
   521     computation_Ts = [],
   522     computation_cTs = [] };
   523 
   524 fun register_computation cTs T =
   525   register { named_consts = [],
   526     computation_Ts = [T],
   527     computation_cTs = cTs };
   528 
   529 fun print body_code_for ctxt ctxt' =
   530   let
   531     val position_index = current_position_index ctxt;
   532     val (code, name_ofs) = (Lazy.force o #generated_code o Code_Antiq_Data.get) ctxt';
   533     val context_code = if position_index = 0 then code else "";
   534     val body_code = body_code_for name_ofs (ML_Context.struct_name ctxt');
   535   in (context_code, body_code) end;
   536 
   537 fun print_code ctxt const =
   538   print (fn { name_for_const, ... } => fn prfx =>
   539     Long_Name.append prfx (name_for_const const)) ctxt;
   540 
   541 fun print_computation kind ctxt T =
   542   print (fn { of_term_for_typ, ... } => fn prfx =>
   543     space_implode " " [
   544       kind,
   545       "(Context.proof_of (Context.the_generic_context ()))",
   546       Long_Name.implode [prfx, generated_computationN, covered_constsN],
   547       (ML_Syntax.atomic o ML_Syntax.print_typ) T,
   548       Long_Name.append prfx (of_term_for_typ T)
   549     ]) ctxt;
   550 
   551 fun print_computation_check ctxt =
   552   print (fn { of_term_for_typ, ... } => fn prfx =>
   553     space_implode " " [
   554       mount_computation_checkN,
   555       "(Context.proof_of (Context.the_generic_context ()))",
   556       Long_Name.implode [prfx, generated_computationN, covered_constsN],
   557       Long_Name.append prfx (of_term_for_typ @{typ prop})
   558     ]) ctxt;
   559 
   560 fun prep_terms ctxt raw_ts =
   561   let
   562     val ts = map (Syntax.check_term ctxt) raw_ts;
   563   in
   564     (fold o fold_aterms)
   565       (fn (t as Const (cT as (_, T))) =>
   566         if not (monomorphic T) then error ("Polymorphic constant: " ^ Syntax.string_of_term ctxt t)
   567         else insert (op =) cT | _ => I) ts []
   568   end;
   569 
   570 in
   571 
   572 fun ml_code_antiq raw_const ctxt =
   573   let
   574     val thy = Proof_Context.theory_of ctxt;
   575     val const = Code.check_const thy raw_const;
   576   in (print_code ctxt const, register_const const ctxt) end;
   577 
   578 fun gen_ml_computation_antiq kind (raw_ts, raw_T) ctxt =
   579   let
   580     val cTs = prep_terms ctxt raw_ts;
   581     val T = Syntax.check_typ ctxt raw_T;
   582     val _ = if not (monomorphic T)
   583       then error ("Polymorphic type: " ^ Syntax.string_of_typ ctxt T)
   584       else ();
   585   in (print_computation kind ctxt T, register_computation cTs T ctxt) end;
   586 
   587 val ml_computation_antiq = gen_ml_computation_antiq mount_computationN;
   588 
   589 val ml_computation_conv_antiq = gen_ml_computation_antiq mount_computation_convN;
   590 
   591 fun ml_computation_check_antiq raw_ts ctxt =
   592   let
   593     val cTs = insert (op =) (dest_Const @{const holds}) (prep_terms ctxt raw_ts);
   594   in (print_computation_check ctxt, register_computation cTs @{typ prop} ctxt) end;
   595 
   596 end; (*local*)
   597 
   598 
   599 (** reflection support **)
   600 
   601 fun check_datatype thy tyco some_consts =
   602   let
   603     val declared_constrs = (map fst o snd o fst o Code.get_type thy) tyco;
   604     val constrs = case some_consts
   605      of SOME [] => []
   606       | SOME consts =>
   607           let
   608             val missing_constrs = subtract (op =) consts declared_constrs;
   609             val _ = if null missing_constrs then []
   610               else error ("Missing constructor(s) " ^ commas_quote missing_constrs
   611                 ^ " for datatype " ^ quote tyco);
   612             val false_constrs = subtract (op =) declared_constrs consts;
   613             val _ = if null false_constrs then []
   614               else error ("Non-constructor(s) " ^ commas_quote false_constrs
   615                 ^ " for datatype " ^ quote tyco)
   616           in consts end
   617       | NONE => declared_constrs;
   618   in (tyco, constrs) end;
   619 
   620 fun add_eval_tyco (tyco, tyco') thy =
   621   let
   622     val k = Sign.arity_number thy tyco;
   623     fun pr pr' _ [] = tyco'
   624       | pr pr' _ [ty] =
   625           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   626       | pr pr' _ tys =
   627           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   628   in
   629     thy
   630     |> Code_Target.set_printings (Type_Constructor (tyco, [(target, SOME (k, pr))]))
   631   end;
   632 
   633 fun add_eval_constr (const, const') thy =
   634   let
   635     val k = Code.args_number thy const;
   636     fun pr pr' fxy ts = Code_Printer.brackify fxy
   637       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   638   in
   639     thy
   640     |> Code_Target.set_printings (Constant (const,
   641       [(target, SOME (Code_Printer.simple_const_syntax (k, pr)))]))
   642   end;
   643 
   644 fun add_eval_const (const, const') = Code_Target.set_printings (Constant
   645   (const, [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')))]));
   646 
   647 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   648       thy
   649       |> Code_Target.add_reserved target module_name
   650       |> Context.theory_map (compile_ML true code)
   651       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   652       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   653       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   654   | process_reflection (code, _) _ (SOME file_name) thy =
   655       let
   656         val preamble =
   657           "(* Generated from " ^
   658             Path.implode (Resources.thy_path (Path.basic (Context.theory_name thy))) ^
   659           "; DO NOT EDIT! *)";
   660         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   661       in
   662         thy
   663       end;
   664 
   665 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   666   let
   667     val ctxt = Proof_Context.init_global thy;
   668     val datatypes = map (fn (raw_tyco, raw_cos) =>
   669       (prep_type ctxt raw_tyco, (Option.map o map) (prep_const thy) raw_cos)) raw_datatypes;
   670     val (tycos, constrs) = map_split (uncurry (check_datatype thy)) datatypes
   671       |> apsnd flat;
   672     val functions = map (prep_const thy) raw_functions;
   673     val consts = constrs @ functions;
   674     val program = Code_Thingol.consts_program ctxt consts;
   675     val result = runtime_code'' ctxt module_name program tycos consts
   676       |> (apsnd o apsnd) (chop (length constrs));
   677   in
   678     thy
   679     |> process_reflection result module_name some_file
   680   end;
   681 
   682 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   683 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   684 
   685 
   686 (** Isar setup **)
   687 
   688 val _ =
   689   Theory.setup (ML_Antiquotation.declaration @{binding code}
   690     Args.term (fn _ => ml_code_antiq));
   691 
   692 val _ =
   693   Theory.setup (ML_Antiquotation.declaration @{binding computation}
   694     (Scan.repeat Args.term --| Scan.lift (Args.$$$ "::") -- Args.typ)
   695        (fn _ => ml_computation_antiq));
   696 
   697 val _ =
   698   Theory.setup (ML_Antiquotation.declaration @{binding computation_conv}
   699     (Scan.repeat Args.term --| Scan.lift (Args.$$$ "::") -- Args.typ)
   700        (fn _ => ml_computation_conv_antiq));
   701 
   702 val _ =
   703   Theory.setup (ML_Antiquotation.declaration @{binding computation_check}
   704     (Scan.repeat Args.term) 
   705        (fn _ => ml_computation_check_antiq));
   706 
   707 local
   708 
   709 val parse_datatype =
   710   Parse.name -- Scan.optional (@{keyword "="} |--
   711     (((Parse.sym_ident || Parse.string) >> (fn "_" => NONE | _ => Scan.fail ()))
   712     || ((Parse.term ::: (Scan.repeat (@{keyword "|"} |-- Parse.term))) >> SOME))) (SOME []);
   713 
   714 in
   715 
   716 val _ =
   717   Outer_Syntax.command @{command_keyword code_reflect}
   718     "enrich runtime environment with generated code"
   719     (Parse.name -- Scan.optional (@{keyword "datatypes"} |-- Parse.!!! (parse_datatype
   720       ::: Scan.repeat (@{keyword "and"} |-- parse_datatype))) []
   721     -- Scan.optional (@{keyword "functions"} |-- Parse.!!!  (Scan.repeat1 Parse.name)) []
   722     -- Scan.option (@{keyword "file"} |-- Parse.!!! Parse.name)
   723     >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   724       (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   725 
   726 end; (*local*)
   727 
   728 
   729 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   730 
   731 local
   732 
   733 structure Loaded_Values = Theory_Data
   734 (
   735   type T = string list
   736   val empty = []
   737   val extend = I
   738   fun merge data : T = Library.merge (op =) data
   739 );
   740 
   741 fun notify_val (string, value) = 
   742   let
   743     val _ = #enterVal ML_Env.name_space (string, value);
   744     val _ = Theory.setup (Loaded_Values.map (insert (op =) string));
   745   in () end;
   746 
   747 fun abort _ = error "Only value bindings allowed.";
   748 
   749 val notifying_context : ML_Compiler0.context =
   750  {name_space =
   751    {lookupVal    = #lookupVal ML_Env.name_space,
   752     lookupType   = #lookupType ML_Env.name_space,
   753     lookupFix    = #lookupFix ML_Env.name_space,
   754     lookupStruct = #lookupStruct ML_Env.name_space,
   755     lookupSig    = #lookupSig ML_Env.name_space,
   756     lookupFunct  = #lookupFunct ML_Env.name_space,
   757     enterVal     = notify_val,
   758     enterType    = abort,
   759     enterFix     = abort,
   760     enterStruct  = abort,
   761     enterSig     = abort,
   762     enterFunct   = abort,
   763     allVal       = #allVal ML_Env.name_space,
   764     allType      = #allType ML_Env.name_space,
   765     allFix       = #allFix ML_Env.name_space,
   766     allStruct    = #allStruct ML_Env.name_space,
   767     allSig       = #allSig ML_Env.name_space,
   768     allFunct     = #allFunct ML_Env.name_space},
   769   print_depth = NONE,
   770   here = #here ML_Env.context,
   771   print = #print ML_Env.context,
   772   error = #error ML_Env.context};
   773 
   774 in
   775 
   776 fun use_file filepath thy =
   777   let
   778     val thy' = Loaded_Values.put [] thy;
   779     val _ = Context.put_generic_context ((SOME o Context.Theory) thy');
   780     val _ =
   781       ML_Compiler0.ML notifying_context
   782         {line = 0, file = Path.implode filepath, verbose = false, debug = false}
   783         (File.read filepath);
   784     val thy'' = Context.the_global_context ();
   785     val names = Loaded_Values.get thy'';
   786   in (names, thy'') end;
   787 
   788 end;
   789 
   790 fun add_definiendum (ml_name, (b, T)) thy =
   791   thy
   792   |> Code_Target.add_reserved target ml_name
   793   |> Specification.axiomatization [(b, SOME T, NoSyn)] [] [] []
   794   |-> (fn ([Const (const, _)], _) =>
   795     Code_Target.set_printings (Constant (const,
   796       [(target, SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))]))
   797   #> tap (fn thy => Code_Target.produce_code (Proof_Context.init_global thy) false [const] target NONE Code_Target.generatedN []));
   798 
   799 fun process_file filepath (definienda, thy) =
   800   let
   801     val (ml_names, thy') = use_file filepath thy;
   802     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   803     val _ = if null superfluous then ()
   804       else error ("Value binding(s) " ^ commas_quote superfluous
   805         ^ " found in external file " ^ Path.print filepath
   806         ^ " not present among the given contants binding(s).");
   807     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   808     val thy'' = fold add_definiendum these_definienda thy';
   809     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   810   in (definienda', thy'') end;
   811 
   812 fun polyml_as_definition bTs filepaths thy =
   813   let
   814     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   815     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   816     val _ = if null remaining then ()
   817       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   818         ^ " not present in external file(s).");
   819   in thy' end;
   820 
   821 end; (*struct*)