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