src/Tools/Code/code_runtime.ML
author haftmann
Fri Oct 01 22:44:36 2010 +0200 (2010-10-01)
changeset 39913 721ba2c1a799
parent 39820 cd691e2c7a1a
parent 39912 2ffe7060ca75
child 40150 1348d4982a17
permissions -rw-r--r--
merged
     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 (
   142   type T = unit -> truth
   143   fun init _ () = error "Truth_Result"
   144 );
   145 val put_truth = Truth_Result.put;
   146 val truth_cookie = (Truth_Result.get, put_truth, Long_Name.append this "put_truth");
   147 
   148 val reject_vars = fn thy => tap (reject_vars thy o Thm.term_of);
   149 
   150 fun check_holds serializer naming thy program vs_t deps ct =
   151   let
   152     val t = Thm.term_of ct;
   153     val _ = if fastype_of t <> propT
   154       then error ("Not a proposition: " ^ Syntax.string_of_term_global thy t)
   155       else ();
   156     val iff = Thm.cterm_of thy (Term.Const ("==", propT --> propT --> propT));
   157     val result = case partiality_as_none (base_evaluator truth_cookie serializer naming thy program vs_t deps [])
   158      of SOME Holds => true
   159       | _ => false;
   160   in
   161     Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
   162   end;
   163 
   164 val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
   165   (Thm.add_oracle (Binding.name "holds_by_evaluation",
   166   fn (serializer, naming, thy, program, vs_t, deps, ct) => check_holds serializer naming thy program vs_t deps ct)));
   167 
   168 fun check_holds_oracle serializer naming thy program ((_, vs_ty), t) deps ct =
   169   raw_check_holds_oracle (serializer, naming, thy, program, (vs_ty, t), deps, ct);
   170 
   171 val dynamic_holds_conv = Conv.tap_thy (fn thy => Code_Thingol.dynamic_eval_conv thy
   172   (fn naming => check_holds_oracle (obtain_serializer thy NONE) naming thy)
   173   o reject_vars thy);
   174 
   175 fun static_holds_conv thy consts =
   176   let
   177     val serializer = obtain_serializer thy NONE;
   178   in
   179     Code_Thingol.static_eval_conv thy consts
   180       (fn naming => fn program => fn thy => check_holds_oracle serializer naming thy program)
   181     o reject_vars thy
   182   end;
   183 
   184 
   185 (** instrumentalization **)
   186 
   187 fun evaluation_code thy module_name tycos consts =
   188   let
   189     val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
   190     val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
   191     val (ml_code, target_names) = Code_Target.produce_code_for thy
   192       target NONE module_name [] naming program (consts' @ tycos');
   193     val (consts'', tycos'') = chop (length consts') target_names;
   194     val consts_map = map2 (fn const => fn NONE =>
   195         error ("Constant " ^ (quote o Code.string_of_const thy) const
   196           ^ "\nhas a user-defined serialization")
   197       | SOME const'' => (const, const'')) consts consts''
   198     val tycos_map = map2 (fn tyco => fn NONE =>
   199         error ("Type " ^ (quote o Sign.extern_type thy) tyco
   200           ^ "\nhas a user-defined serialization")
   201       | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
   202   in (ml_code, (tycos_map, consts_map)) end;
   203 
   204 
   205 (* by antiquotation *)
   206 
   207 local
   208 
   209 structure Code_Antiq_Data = Proof_Data
   210 (
   211   type T = (string list * string list) * (bool
   212     * (string * ((string * string) list * (string * string) list)) lazy);
   213   fun init _ = (([], []), (true, (Lazy.value ("", ([], [])))));
   214 );
   215 
   216 val is_first_occ = fst o snd o Code_Antiq_Data.get;
   217 
   218 fun register_code new_tycos new_consts ctxt =
   219   let
   220     val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
   221     val tycos' = fold (insert (op =)) new_tycos tycos;
   222     val consts' = fold (insert (op =)) new_consts consts;
   223     val acc_code = Lazy.lazy (fn () =>
   224       evaluation_code (ProofContext.theory_of ctxt) "Code" tycos' consts');
   225   in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
   226 
   227 fun register_const const = register_code [] [const];
   228 
   229 fun register_datatype tyco constrs = register_code [tyco] constrs;
   230 
   231 fun print_const const all_struct_name tycos_map consts_map =
   232   (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
   233 
   234 fun print_code is_first print_it ctxt =
   235   let
   236     val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
   237     val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
   238     val ml_code = if is_first then ml_code
   239       else "";
   240     val all_struct_name = "Isabelle";
   241   in (ml_code, print_it all_struct_name tycos_map consts_map) end;
   242 
   243 in
   244 
   245 fun ml_code_antiq raw_const background =
   246   let
   247     val const = Code.check_const (ProofContext.theory_of background) raw_const;
   248     val is_first = is_first_occ background;
   249     val background' = register_const const background;
   250   in (print_code is_first (print_const const), background') end;
   251 
   252 end; (*local*)
   253 
   254 
   255 (* reflection support *)
   256 
   257 fun check_datatype thy tyco consts =
   258   let
   259     val constrs = (map (fst o fst) o snd o Code.get_type thy) tyco;
   260     val missing_constrs = subtract (op =) consts constrs;
   261     val _ = if null missing_constrs then []
   262       else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
   263         ^ " for datatype " ^ quote tyco);
   264     val false_constrs = subtract (op =) constrs consts;
   265     val _ = if null false_constrs then []
   266       else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
   267         ^ " for datatype " ^ quote tyco);
   268   in () end;
   269 
   270 fun add_eval_tyco (tyco, tyco') thy =
   271   let
   272     val k = Sign.arity_number thy tyco;
   273     fun pr pr' fxy [] = tyco'
   274       | pr pr' fxy [ty] =
   275           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   276       | pr pr' fxy tys =
   277           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   278   in
   279     thy
   280     |> Code_Target.add_tyco_syntax target tyco (SOME (k, pr))
   281   end;
   282 
   283 fun add_eval_constr (const, const') thy =
   284   let
   285     val k = Code.args_number thy const;
   286     fun pr pr' fxy ts = Code_Printer.brackify fxy
   287       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   288   in
   289     thy
   290     |> Code_Target.add_const_syntax target const (SOME (Code_Printer.simple_const_syntax (k, pr)))
   291   end;
   292 
   293 fun add_eval_const (const, const') = Code_Target.add_const_syntax target
   294   const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
   295 
   296 fun process_reflection (code, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   297       thy
   298       |> Code_Target.add_reserved target module_name
   299       |> Context.theory_map (exec true code)
   300       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   301       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   302       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   303   | process_reflection (code, _) _ (SOME file_name) thy =
   304       let
   305         val preamble =
   306           "(* Generated from " ^ Path.implode (Thy_Header.thy_path (Context.theory_name thy))
   307           ^ "; DO NOT EDIT! *)";
   308         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code);
   309       in
   310         thy
   311       end;
   312 
   313 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   314   let
   315     val datatypes = map (fn (raw_tyco, raw_cos) =>
   316       (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
   317     val _ = map (uncurry (check_datatype thy)) datatypes;
   318     val tycos = map fst datatypes;
   319     val constrs = maps snd datatypes;
   320     val functions = map (prep_const thy) raw_functions;
   321     val result = evaluation_code thy module_name tycos (constrs @ functions)
   322       |> (apsnd o apsnd) (chop (length constrs));
   323   in
   324     thy
   325     |> process_reflection result module_name some_file
   326   end;
   327 
   328 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   329 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   330 
   331 
   332 (** Isar setup **)
   333 
   334 val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
   335 
   336 local
   337 
   338 val datatypesK = "datatypes";
   339 val functionsK = "functions";
   340 val fileK = "file";
   341 val andK = "and"
   342 
   343 val _ = List.app Keyword.keyword [datatypesK, functionsK];
   344 
   345 val parse_datatype =
   346   Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
   347 
   348 in
   349 
   350 val _ =
   351   Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
   352     Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
   353       ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
   354     -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
   355     -- Scan.option (Parse.$$$ fileK |-- Parse.name)
   356   >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   357     (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   358 
   359 end; (*local*)
   360 
   361 
   362 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   363 
   364 local
   365 
   366 structure Loaded_Values = Theory_Data
   367 (
   368   type T = string list
   369   val empty = []
   370   fun merge data : T = Library.merge (op =) data
   371   val extend = I
   372 );
   373 
   374 fun notify_val (string, value) = 
   375   let
   376     val _ = #enterVal ML_Env.name_space (string, value);
   377     val _ = Context.>> ((Context.map_theory o Loaded_Values.map) (insert (op =) string));
   378   in () end;
   379 
   380 fun abort _ = error "Only value bindings allowed.";
   381 
   382 val notifying_context : use_context =
   383  {tune_source = #tune_source ML_Env.local_context,
   384   name_space =
   385    {lookupVal    = #lookupVal ML_Env.name_space,
   386     lookupType   = #lookupType ML_Env.name_space,
   387     lookupFix    = #lookupFix ML_Env.name_space,
   388     lookupStruct = #lookupStruct ML_Env.name_space,
   389     lookupSig    = #lookupSig ML_Env.name_space,
   390     lookupFunct  = #lookupFunct ML_Env.name_space,
   391     enterVal     = notify_val,
   392     enterType    = abort,
   393     enterFix     = abort,
   394     enterStruct  = abort,
   395     enterSig     = abort,
   396     enterFunct   = abort,
   397     allVal       = #allVal ML_Env.name_space,
   398     allType      = #allType ML_Env.name_space,
   399     allFix       = #allFix ML_Env.name_space,
   400     allStruct    = #allStruct ML_Env.name_space,
   401     allSig       = #allSig ML_Env.name_space,
   402     allFunct     = #allFunct ML_Env.name_space},
   403   str_of_pos = #str_of_pos ML_Env.local_context,
   404   print = #print ML_Env.local_context,
   405   error = #error ML_Env.local_context};
   406 
   407 in
   408 
   409 fun use_file filepath thy =
   410   let
   411     val thy' = Loaded_Values.put [] thy;
   412     val _ = Context.set_thread_data ((SOME o Context.Theory) thy');
   413     val _ = Secure.use_text notifying_context
   414       (0, Path.implode filepath) false (File.read filepath);
   415     val thy'' = (Context.the_theory o the) (Context.thread_data ());
   416     val names = Loaded_Values.get thy'';
   417     val thy''' = Thy_Load.provide_file filepath thy'';
   418   in (names, thy''') end;
   419 
   420 end;
   421 
   422 fun add_definiendum (ml_name, (b, T)) thy =
   423   thy
   424   |> Code_Target.add_reserved target ml_name
   425   |> Specification.axiomatization [(b, SOME T, NoSyn)] []
   426   |-> (fn ([Const (const, _)], _) =>
   427      Code_Target.add_const_syntax target const
   428        (SOME (Code_Printer.simple_const_syntax (0, (K o K o K o Code_Printer.str) ml_name)))
   429   #> tap (fn thy => Code_Target.produce_code thy [const] target NONE "Code" []));
   430 
   431 fun process_file filepath (definienda, thy) =
   432   let
   433     val (ml_names, thy') = use_file filepath thy;
   434     val superfluous = subtract (fn ((name1, _), name2) => name1 = name2) definienda ml_names;
   435     val _ = if null superfluous then ()
   436       else error ("Value binding(s) " ^ commas_quote superfluous
   437         ^ " found in external file " ^ quote (Path.implode filepath)
   438         ^ " not present among the given contants binding(s).");
   439     val these_definienda = AList.make (the o AList.lookup (op =) definienda) ml_names;
   440     val thy'' = fold add_definiendum these_definienda thy';
   441     val definienda' = fold (AList.delete (op =)) ml_names definienda;
   442   in (definienda', thy'') end;
   443 
   444 fun polyml_as_definition bTs filepaths thy =
   445   let
   446     val definienda = map (fn bT => ((Binding.name_of o fst) bT, bT)) bTs;
   447     val (remaining, thy') = fold process_file filepaths (definienda, thy);
   448     val _ = if null remaining then ()
   449       else error ("Constant binding(s) " ^ commas_quote (map fst remaining)
   450         ^ " not present in external file(s).");
   451   in thy' end;
   452 
   453 end; (*struct*)