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