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