src/Tools/Code/code_runtime.ML
author haftmann
Fri Oct 01 17:06:49 2010 +0200 (2010-10-01)
changeset 39912 2ffe7060ca75
parent 39816 c7cec137c48a
child 39913 721ba2c1a799
permissions -rw-r--r--
avoid antiquotation processing for code_reflect; moved ML_Context.value to Code_Runtime
     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 -> theory -> string option
    15     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a option
    16   val dynamic_value_strict: 'a cookie -> theory -> string option
    17     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a
    18   val dynamic_value_exn: 'a cookie -> theory -> string option
    19     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a Exn.result
    20   val static_value: 'a cookie -> theory -> string option
    21     -> ((term -> term) -> 'a -> 'a) -> string list -> term -> 'a option
    22   val static_value_strict: 'a cookie -> theory -> string option
    23     -> ((term -> term) -> 'a -> 'a) -> string list -> term -> 'a
    24   val static_value_exn: 'a cookie -> theory -> string option
    25     -> ((term -> term) -> 'a -> 'a) -> string list -> term -> 'a Exn.result
    26   val dynamic_holds_conv: conv
    27   val static_holds_conv: theory -> string list -> conv
    28   val code_reflect: (string * string list) list -> string list -> string -> string option
    29     -> theory -> theory
    30   datatype truth = Holds
    31   val put_truth: (unit -> truth) -> Proof.context -> Proof.context
    32   val polyml_as_definition: (binding * typ) list -> Path.T list -> theory -> theory
    33 end;
    34 
    35 structure Code_Runtime : CODE_RUNTIME =
    36 struct
    37 
    38 open Basic_Code_Thingol;
    39 
    40 (** evaluation **)
    41 
    42 (* technical prerequisites *)
    43 
    44 val this = "Code_Runtime";
    45 val s_truth = Long_Name.append this "truth";
    46 val s_Holds = Long_Name.append this "Holds";
    47 
    48 val target = "Eval";
    49 
    50 datatype truth = Holds;
    51 
    52 val _ = Context.>> (Context.map_theory
    53   (Code_Target.extend_target (target, (Code_ML.target_SML, K I))
    54   #> Code_Target.add_tyco_syntax target @{type_name prop}
    55        (SOME (0, (K o K o K) (Code_Printer.str s_truth)))
    56   #> Code_Target.add_const_syntax target @{const_name Code_Generator.holds}
    57        (SOME (Code_Printer.plain_const_syntax s_Holds))
    58   #> Code_Target.add_reserved target this
    59   #> fold (Code_Target.add_reserved target) ["oo", "ooo", "oooo", "upto", "downto", "orf", "andf"]));
    60        (*avoid further pervasive infix names*)
    61 
    62 fun exec verbose code =
    63   ML_Context.exec (fn () => Secure.use_text ML_Env.local_context (0, "generated code") false code);
    64 
    65 fun value ctxt (get, put, put_ml) (prelude, value) =
    66   let
    67     val code = (prelude
    68       ^ "\nval _ = Context.set_thread_data (SOME (Context.map_proof (" ^ put_ml
    69       ^ " (fn () => " ^ value ^ ")) (ML_Context.the_generic_context ())))");
    70     val ctxt' = ctxt
    71       |> put (fn () => error ("Bad evaluation for " ^ quote put_ml))
    72       |> Context.proof_map (exec false code);
    73   in get ctxt' () end;
    74 
    75 
    76 (* evaluation into target language values *)
    77 
    78 type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string;
    79 
    80 fun reject_vars thy t =
    81   let
    82     val ctxt = ProofContext.init_global thy;
    83   in ((Sign.no_frees ctxt o Sign.no_vars ctxt o map_types (K dummyT)) t; t) end;
    84 
    85 fun obtain_serializer thy some_target = Code_Target.produce_code_for thy
    86   (the_default target some_target) NONE "Code" [];
    87 
    88 fun base_evaluator cookie serializer (naming : Code_Thingol.naming) thy program ((vs, ty), t) deps args =
    89   let
    90     val ctxt = ProofContext.init_global thy;
    91     val _ = if Code_Thingol.contains_dictvar t then
    92       error "Term to be evaluated contains free dictionaries" else ();
    93     val v' = Name.variant (map fst vs) "a";
    94     val vs' = (v', []) :: vs
    95     val ty' = Code_Thingol.fun_tyco `%% [ITyVar v', ty];
    96     val value_name = "Value.value.value"
    97     val program' = program
    98       |> Graph.new_node (value_name,
    99           Code_Thingol.Fun (Term.dummy_patternN, (((vs', ty'), [(([IVar NONE], t), (NONE, true))]), NONE)))
   100       |> fold (curry Graph.add_edge value_name) deps;
   101     val (program_code, [SOME value_name']) = serializer naming program' [value_name];
   102     val value_code = space_implode " "
   103       (value_name' :: "()" :: map (enclose "(" ")") args);
   104   in Exn.capture (value ctxt cookie) (program_code, value_code) end;
   105 
   106 fun partiality_as_none e = SOME (Exn.release e)
   107   handle General.Match => NONE
   108     | General.Bind => NONE
   109     | General.Fail _ => NONE;
   110 
   111 fun dynamic_value_exn cookie thy some_target postproc t args =
   112   let
   113     val _ = reject_vars thy t;
   114     fun evaluator naming program ((_, vs_ty), t) deps =
   115       base_evaluator cookie (obtain_serializer thy some_target) naming thy program (vs_ty, t) deps args;
   116   in Code_Thingol.dynamic_eval_value thy (Exn.map_result o postproc) evaluator t end;
   117 
   118 fun dynamic_value_strict cookie thy some_target postproc t args =
   119   Exn.release (dynamic_value_exn cookie thy some_target postproc t args);
   120 
   121 fun dynamic_value cookie thy some_target postproc t args =
   122   partiality_as_none (dynamic_value_exn cookie thy some_target postproc t args);
   123 
   124 fun static_value_exn cookie thy some_target postproc consts =
   125   let
   126     val serializer = obtain_serializer thy some_target;
   127     fun evaluator naming program thy ((_, vs_ty), t) deps =
   128       base_evaluator cookie serializer naming thy program (vs_ty, t) deps [];
   129   in Code_Thingol.static_eval_value thy (Exn.map_result o postproc) consts evaluator o reject_vars thy end;
   130 
   131 fun static_value_strict cookie thy some_target postproc consts t =
   132   Exn.release (static_value_exn cookie thy some_target postproc consts t);
   133 
   134 fun static_value cookie thy some_target postproc consts t =
   135   partiality_as_none (static_value_exn cookie thy some_target postproc consts t);
   136 
   137 
   138 (* evaluation for truth or nothing *)
   139 
   140 structure Truth_Result = Proof_Data (
   141   type T = unit -> truth
   142   fun init _ () = error "Truth_Result"
   143 );
   144 val put_truth = Truth_Result.put;
   145 val truth_cookie = (Truth_Result.get, put_truth, Long_Name.append this "put_truth");
   146 
   147 val reject_vars = fn thy => tap (reject_vars thy o Thm.term_of);
   148 
   149 fun check_holds serializer naming thy program vs_t deps ct =
   150   let
   151     val t = Thm.term_of ct;
   152     val _ = if fastype_of t <> propT
   153       then error ("Not a proposition: " ^ Syntax.string_of_term_global thy t)
   154       else ();
   155     val iff = Thm.cterm_of thy (Term.Const ("==", propT --> propT --> propT));
   156     val result = case partiality_as_none (base_evaluator truth_cookie serializer naming thy program vs_t deps [])
   157      of SOME Holds => true
   158       | _ => false;
   159   in
   160     Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
   161   end;
   162 
   163 val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
   164   (Thm.add_oracle (Binding.name "holds_by_evaluation",
   165   fn (serializer, naming, thy, program, vs_t, deps, ct) => check_holds serializer naming thy program vs_t deps ct)));
   166 
   167 fun check_holds_oracle serializer naming thy program ((_, vs_ty), t) deps ct =
   168   raw_check_holds_oracle (serializer, naming, thy, program, (vs_ty, t), deps, ct);
   169 
   170 val dynamic_holds_conv = Conv.tap_thy (fn thy => Code_Thingol.dynamic_eval_conv thy
   171   (fn naming => check_holds_oracle (obtain_serializer thy NONE) naming thy)
   172   o reject_vars thy);
   173 
   174 fun static_holds_conv thy consts =
   175   let
   176     val serializer = obtain_serializer thy NONE;
   177   in
   178     Code_Thingol.static_eval_conv thy consts
   179       (fn naming => fn program => fn thy => check_holds_oracle serializer naming thy program)
   180     o reject_vars thy
   181   end;
   182 
   183 
   184 (** instrumentalization **)
   185 
   186 fun evaluation_code thy module_name tycos consts =
   187   let
   188     val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
   189     val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
   190     val (ml_code, target_names) = Code_Target.produce_code_for thy
   191       target NONE module_name [] naming program (consts' @ tycos');
   192     val (consts'', tycos'') = chop (length consts') target_names;
   193     val consts_map = map2 (fn const => fn NONE =>
   194         error ("Constant " ^ (quote o Code.string_of_const thy) const
   195           ^ "\nhas a user-defined serialization")
   196       | SOME const'' => (const, const'')) consts consts''
   197     val tycos_map = map2 (fn tyco => fn NONE =>
   198         error ("Type " ^ (quote o Sign.extern_type thy) tyco
   199           ^ "\nhas a user-defined serialization")
   200       | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
   201   in (ml_code, (tycos_map, consts_map)) end;
   202 
   203 
   204 (* by antiquotation *)
   205 
   206 local
   207 
   208 structure Code_Antiq_Data = Proof_Data
   209 (
   210   type T = (string list * string list) * (bool
   211     * (string * ((string * string) list * (string * string) list)) lazy);
   212   fun init _ = (([], []), (true, (Lazy.value ("", ([], [])))));
   213 );
   214 
   215 val is_first_occ = fst o snd o Code_Antiq_Data.get;
   216 
   217 fun register_code new_tycos new_consts ctxt =
   218   let
   219     val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
   220     val tycos' = fold (insert (op =)) new_tycos tycos;
   221     val consts' = fold (insert (op =)) new_consts consts;
   222     val acc_code = Lazy.lazy (fn () =>
   223       evaluation_code (ProofContext.theory_of ctxt) "Code" tycos' consts');
   224   in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
   225 
   226 fun register_const const = register_code [] [const];
   227 
   228 fun register_datatype tyco constrs = register_code [tyco] constrs;
   229 
   230 fun print_const const all_struct_name tycos_map consts_map =
   231   (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
   232 
   233 fun print_code is_first print_it ctxt =
   234   let
   235     val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
   236     val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
   237     val ml_code = if is_first then ml_code
   238       else "";
   239     val all_struct_name = "Isabelle";
   240   in (ml_code, print_it all_struct_name tycos_map consts_map) end;
   241 
   242 in
   243 
   244 fun ml_code_antiq raw_const background =
   245   let
   246     val const = Code.check_const (ProofContext.theory_of background) raw_const;
   247     val is_first = is_first_occ background;
   248     val background' = register_const const background;
   249   in (print_code is_first (print_const const), background') end;
   250 
   251 end; (*local*)
   252 
   253 
   254 (* reflection support *)
   255 
   256 fun check_datatype thy tyco consts =
   257   let
   258     val constrs = (map (fst o fst) o snd o Code.get_type thy) tyco;
   259     val missing_constrs = subtract (op =) consts constrs;
   260     val _ = if null missing_constrs then []
   261       else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
   262         ^ " for datatype " ^ quote tyco);
   263     val false_constrs = subtract (op =) constrs consts;
   264     val _ = if null false_constrs then []
   265       else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
   266         ^ " for datatype " ^ quote tyco);
   267   in () end;
   268 
   269 fun add_eval_tyco (tyco, tyco') thy =
   270   let
   271     val k = Sign.arity_number thy tyco;
   272     fun pr pr' fxy [] = tyco'
   273       | pr pr' fxy [ty] =
   274           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   275       | pr pr' fxy tys =
   276           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   277   in
   278     thy
   279     |> Code_Target.add_tyco_syntax target tyco (SOME (k, pr))
   280   end;
   281 
   282 fun add_eval_constr (const, const') thy =
   283   let
   284     val k = Code.args_number thy const;
   285     fun pr pr' fxy ts = Code_Printer.brackify fxy
   286       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   287   in
   288     thy
   289     |> Code_Target.add_const_syntax target const (SOME (Code_Printer.simple_const_syntax (k, pr)))
   290   end;
   291 
   292 fun add_eval_const (const, const') = Code_Target.add_const_syntax target
   293   const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
   294 
   295 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   296       thy
   297       |> Code_Target.add_reserved target module_name
   298       |> Context.theory_map (exec true code)
   299       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   300       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   301       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   302   | process_reflection (code, _) _ (SOME file_name) thy =
   303       let
   304         val preamble =
   305           "(* Generated from " ^ Path.implode (Thy_Header.thy_path (Context.theory_name thy))
   306           ^ "; DO NOT EDIT! *)";
   307         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   308       in
   309         thy
   310       end;
   311 
   312 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   313   let
   314     val datatypes = map (fn (raw_tyco, raw_cos) =>
   315       (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
   316     val _ = map (uncurry (check_datatype thy)) datatypes;
   317     val tycos = map fst datatypes;
   318     val constrs = maps snd datatypes;
   319     val functions = map (prep_const thy) raw_functions;
   320     val result = evaluation_code thy module_name tycos (constrs @ functions)
   321       |> (apsnd o apsnd) (chop (length constrs));
   322   in
   323     thy
   324     |> process_reflection result module_name some_file
   325   end;
   326 
   327 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   328 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   329 
   330 
   331 (** Isar setup **)
   332 
   333 val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
   334 
   335 local
   336 
   337 val datatypesK = "datatypes";
   338 val functionsK = "functions";
   339 val fileK = "file";
   340 val andK = "and"
   341 
   342 val _ = List.app Keyword.keyword [datatypesK, functionsK];
   343 
   344 val parse_datatype =
   345   Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
   346 
   347 in
   348 
   349 val _ =
   350   Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
   351     Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
   352       ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
   353     -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
   354     -- Scan.option (Parse.$$$ fileK |-- Parse.name)
   355   >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   356     (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   357 
   358 end; (*local*)
   359 
   360 
   361 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   362 
   363 local
   364 
   365 structure Loaded_Values = Theory_Data(
   366   type T = string list
   367   val empty = []
   368   val merge = merge (op =)
   369   val extend = I
   370 );
   371 
   372 fun notify_val (string, value) = 
   373   let
   374     val _ = #enterVal ML_Env.name_space (string, value);
   375     val _ = Context.>> ((Context.map_theory o Loaded_Values.map) (insert (op =) string));
   376   in () end;
   377 
   378 fun abort _ = error "Only value bindings allowed.";
   379 
   380 val notifying_context : use_context =
   381  {tune_source = #tune_source ML_Env.local_context,
   382   name_space =
   383    {lookupVal    = #lookupVal ML_Env.name_space,
   384     lookupType   = #lookupType ML_Env.name_space,
   385     lookupFix    = #lookupFix ML_Env.name_space,
   386     lookupStruct = #lookupStruct ML_Env.name_space,
   387     lookupSig    = #lookupSig ML_Env.name_space,
   388     lookupFunct  = #lookupFunct ML_Env.name_space,
   389     enterVal     = notify_val,
   390     enterType    = abort,
   391     enterFix     = abort,
   392     enterStruct  = abort,
   393     enterSig     = abort,
   394     enterFunct   = abort,
   395     allVal       = #allVal ML_Env.name_space,
   396     allType      = #allType ML_Env.name_space,
   397     allFix       = #allFix ML_Env.name_space,
   398     allStruct    = #allStruct ML_Env.name_space,
   399     allSig       = #allSig ML_Env.name_space,
   400     allFunct     = #allFunct ML_Env.name_space},
   401   str_of_pos = #str_of_pos ML_Env.local_context,
   402   print = #print ML_Env.local_context,
   403   error = #error ML_Env.local_context};
   404 
   405 in
   406 
   407 fun use_file filepath thy =
   408   let
   409     val thy' = Loaded_Values.put [] thy;
   410     val _ = Context.set_thread_data ((SOME o Context.Theory) thy');
   411     val _ = Secure.use_text notifying_context
   412       (0, Path.implode filepath) false (File.read filepath);
   413     val thy'' = (Context.the_theory o the) (Context.thread_data ());
   414     val names = Loaded_Values.get thy'';
   415     val thy''' = Thy_Load.provide_file filepath thy'';
   416   in (names, thy''') end;
   417 
   418 end;
   419 
   420 fun add_definiendum (ml_name, (b, T)) thy =
   421   thy
   422   |> Code_Target.add_reserved target ml_name
   423   |> Specification.axiomatization [(b, SOME T, NoSyn)] []
   424   |-> (fn ([Const (const, _)], _) =>
   425      Code_Target.add_const_syntax target const
   426        (SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))
   427   #> tap (fn thy => Code_Target.produce_code thy [const] target NONE "Code" []));
   428 
   429 fun process_file filepath (definienda, thy) =
   430   let
   431     val (ml_names, thy') = use_file filepath thy;
   432     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   433     val _ = if null superfluous then ()
   434       else error ("Value binding(s) " ^ commas_quote superfluous
   435         ^ " found in external file " ^ quote (Path.implode filepath)
   436         ^ " not present among the given contants binding(s).");
   437     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   438     val thy'' = fold add_definiendum these_definienda thy';
   439     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   440   in (definienda', thy'') end;
   441 
   442 fun polyml_as_definition bTs filepaths thy =
   443   let
   444     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   445     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   446     val _ = if null remaining then ()
   447       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   448         ^ " not present in external file(s).");
   449   in thy' end;
   450 
   451 end; (*struct*)