src/Tools/Code/code_runtime.ML
author wenzelm
Thu Oct 28 22:04:00 2010 +0200 (2010-10-28)
changeset 40235 87998864284e
parent 40150 1348d4982a17
child 40257 323f7aad54b0
permissions -rw-r--r--
use Exn.interruptible_capture to keep user-code interruptible (Exn.capture not immediately followed by Exn.release here);
     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 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") false 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_serializer thy some_target = Code_Target.produce_code_for thy
    90   (the_default target some_target) NONE "Code" [];
    91 
    92 fun base_evaluator cookie serializer (naming : Code_Thingol.naming) thy program ((vs, ty), t) deps args =
    93   let
    94     val ctxt = ProofContext.init_global thy;
    95     val _ = if Code_Thingol.contains_dictvar t then
    96       error "Term to be evaluated contains free dictionaries" else ();
    97     val v' = Name.variant (map fst vs) "a";
    98     val vs' = (v', []) :: vs
    99     val ty' = Code_Thingol.fun_tyco `%% [ITyVar v', ty];
   100     val value_name = "Value.value.value"
   101     val program' = program
   102       |> Graph.new_node (value_name,
   103           Code_Thingol.Fun (Term.dummy_patternN, (((vs', ty'), [(([IVar NONE], t), (NONE, true))]), NONE)))
   104       |> fold (curry Graph.add_edge value_name) deps;
   105     val (program_code, [SOME value_name']) = serializer naming program' [value_name];
   106     val value_code = space_implode " "
   107       (value_name' :: "()" :: map (enclose "(" ")") args);
   108   in Exn.interruptible_capture (value ctxt cookie) (program_code, value_code) end;
   109 
   110 fun partiality_as_none e = SOME (Exn.release e)
   111   handle General.Match => NONE
   112     | General.Bind => NONE
   113     | General.Fail _ => NONE;
   114 
   115 fun dynamic_value_exn cookie thy some_target postproc t args =
   116   let
   117     val _ = reject_vars thy t;
   118     fun evaluator naming program ((_, vs_ty), t) deps =
   119       base_evaluator cookie (obtain_serializer thy some_target) naming thy program (vs_ty, t) deps args;
   120   in Code_Thingol.dynamic_eval_value thy (Exn.map_result o postproc) evaluator t end;
   121 
   122 fun dynamic_value_strict cookie thy some_target postproc t args =
   123   Exn.release (dynamic_value_exn cookie thy some_target postproc t args);
   124 
   125 fun dynamic_value cookie thy some_target postproc t args =
   126   partiality_as_none (dynamic_value_exn cookie thy some_target postproc t args);
   127 
   128 fun static_value_exn cookie thy some_target postproc consts =
   129   let
   130     val serializer = obtain_serializer thy some_target;
   131     fun evaluator naming program thy ((_, vs_ty), t) deps =
   132       base_evaluator cookie serializer naming thy program (vs_ty, t) deps [];
   133   in Code_Thingol.static_eval_value thy (Exn.map_result o postproc) consts evaluator o reject_vars thy end;
   134 
   135 fun static_value_strict cookie thy some_target postproc consts t =
   136   Exn.release (static_value_exn cookie thy some_target postproc consts t);
   137 
   138 fun static_value cookie thy some_target postproc consts t =
   139   partiality_as_none (static_value_exn cookie thy some_target postproc consts t);
   140 
   141 
   142 (* evaluation for truth or nothing *)
   143 
   144 structure Truth_Result = Proof_Data
   145 (
   146   type T = unit -> truth
   147   fun init _ () = error "Truth_Result"
   148 );
   149 val put_truth = Truth_Result.put;
   150 val truth_cookie = (Truth_Result.get, put_truth, Long_Name.append this "put_truth");
   151 
   152 val reject_vars = fn thy => tap (reject_vars thy o Thm.term_of);
   153 
   154 fun check_holds serializer naming thy program vs_t deps ct =
   155   let
   156     val t = Thm.term_of ct;
   157     val _ = if fastype_of t <> propT
   158       then error ("Not a proposition: " ^ Syntax.string_of_term_global thy t)
   159       else ();
   160     val iff = Thm.cterm_of thy (Term.Const ("==", propT --> propT --> propT));
   161     val result = case partiality_as_none (base_evaluator truth_cookie serializer naming thy program vs_t deps [])
   162      of SOME Holds => true
   163       | _ => false;
   164   in
   165     Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
   166   end;
   167 
   168 val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
   169   (Thm.add_oracle (Binding.name "holds_by_evaluation",
   170   fn (serializer, naming, thy, program, vs_t, deps, ct) => check_holds serializer naming thy program vs_t deps ct)));
   171 
   172 fun check_holds_oracle serializer naming thy program ((_, vs_ty), t) deps ct =
   173   raw_check_holds_oracle (serializer, naming, thy, program, (vs_ty, t), deps, ct);
   174 
   175 val dynamic_holds_conv = Conv.tap_thy (fn thy => Code_Thingol.dynamic_eval_conv thy
   176   (fn naming => check_holds_oracle (obtain_serializer thy NONE) naming thy)
   177   o reject_vars thy);
   178 
   179 fun static_holds_conv thy consts =
   180   let
   181     val serializer = obtain_serializer thy NONE;
   182   in
   183     Code_Thingol.static_eval_conv thy consts
   184       (fn naming => fn program => fn thy => check_holds_oracle serializer naming thy program)
   185     o reject_vars thy
   186   end;
   187 
   188 
   189 (** instrumentalization **)
   190 
   191 fun evaluation_code thy module_name tycos consts =
   192   let
   193     val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
   194     val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
   195     val (ml_code, target_names) = Code_Target.produce_code_for thy
   196       target NONE module_name [] naming program (consts' @ tycos');
   197     val (consts'', tycos'') = chop (length consts') target_names;
   198     val consts_map = map2 (fn const => fn NONE =>
   199         error ("Constant " ^ (quote o Code.string_of_const thy) const
   200           ^ "\nhas a user-defined serialization")
   201       | SOME const'' => (const, const'')) consts consts''
   202     val tycos_map = map2 (fn tyco => fn NONE =>
   203         error ("Type " ^ (quote o Sign.extern_type thy) tyco
   204           ^ "\nhas a user-defined serialization")
   205       | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
   206   in (ml_code, (tycos_map, consts_map)) end;
   207 
   208 
   209 (* by antiquotation *)
   210 
   211 local
   212 
   213 structure Code_Antiq_Data = Proof_Data
   214 (
   215   type T = (string list * string list) * (bool
   216     * (string * ((string * string) list * (string * string) list)) lazy);
   217   fun init _ = (([], []), (true, (Lazy.value ("", ([], [])))));
   218 );
   219 
   220 val is_first_occ = fst o snd o Code_Antiq_Data.get;
   221 
   222 fun register_code new_tycos new_consts ctxt =
   223   let
   224     val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
   225     val tycos' = fold (insert (op =)) new_tycos tycos;
   226     val consts' = fold (insert (op =)) new_consts consts;
   227     val acc_code = Lazy.lazy (fn () =>
   228       evaluation_code (ProofContext.theory_of ctxt) "Code" tycos' consts');
   229   in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
   230 
   231 fun register_const const = register_code [] [const];
   232 
   233 fun register_datatype tyco constrs = register_code [tyco] constrs;
   234 
   235 fun print_const const all_struct_name tycos_map consts_map =
   236   (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
   237 
   238 fun print_code is_first print_it ctxt =
   239   let
   240     val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
   241     val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
   242     val ml_code = if is_first then ml_code
   243       else "";
   244     val all_struct_name = "Isabelle";
   245   in (ml_code, print_it all_struct_name tycos_map consts_map) end;
   246 
   247 in
   248 
   249 fun ml_code_antiq raw_const background =
   250   let
   251     val const = Code.check_const (ProofContext.theory_of background) raw_const;
   252     val is_first = is_first_occ background;
   253     val background' = register_const const background;
   254   in (print_code is_first (print_const const), background') end;
   255 
   256 end; (*local*)
   257 
   258 
   259 (* reflection support *)
   260 
   261 fun check_datatype thy tyco consts =
   262   let
   263     val constrs = (map (fst o fst) o snd o Code.get_type thy) tyco;
   264     val missing_constrs = subtract (op =) consts constrs;
   265     val _ = if null missing_constrs then []
   266       else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
   267         ^ " for datatype " ^ quote tyco);
   268     val false_constrs = subtract (op =) constrs consts;
   269     val _ = if null false_constrs then []
   270       else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
   271         ^ " for datatype " ^ quote tyco);
   272   in () end;
   273 
   274 fun add_eval_tyco (tyco, tyco') thy =
   275   let
   276     val k = Sign.arity_number thy tyco;
   277     fun pr pr' fxy [] = tyco'
   278       | pr pr' fxy [ty] =
   279           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   280       | pr pr' fxy 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, map (prep_const thy) raw_cos)) raw_datatypes;
   321     val _ = map (uncurry (check_datatype thy)) datatypes;
   322     val tycos = map fst datatypes;
   323     val constrs = maps snd datatypes;
   324     val functions = map (prep_const thy) raw_functions;
   325     val result = evaluation_code thy module_name tycos (constrs @ functions)
   326       |> (apsnd o apsnd) (chop (length constrs));
   327   in
   328     thy
   329     |> process_reflection result module_name some_file
   330   end;
   331 
   332 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   333 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   334 
   335 
   336 (** Isar setup **)
   337 
   338 val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
   339 
   340 local
   341 
   342 val datatypesK = "datatypes";
   343 val functionsK = "functions";
   344 val fileK = "file";
   345 val andK = "and"
   346 
   347 val _ = List.app Keyword.keyword [datatypesK, functionsK];
   348 
   349 val parse_datatype =
   350   Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
   351 
   352 in
   353 
   354 val _ =
   355   Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
   356     Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
   357       ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
   358     -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
   359     -- Scan.option (Parse.$$$ fileK |-- Parse.name)
   360   >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   361     (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   362 
   363 end; (*local*)
   364 
   365 
   366 (** using external SML files as substitute for proper definitions -- only for polyml!  **)
   367 
   368 local
   369 
   370 structure Loaded_Values = Theory_Data
   371 (
   372   type T = string list
   373   val empty = []
   374   fun merge data : T = Library.merge (op =) data
   375   val extend = I
   376 );
   377 
   378 fun notify_val (string, value) = 
   379   let
   380     val _ = #enterVal ML_Env.name_space (string, value);
   381     val _ = Context.>> ((Context.map_theory o Loaded_Values.map) (insert (op =) string));
   382   in () end;
   383 
   384 fun abort _ = error "Only value bindings allowed.";
   385 
   386 val notifying_context : use_context =
   387  {tune_source = #tune_source ML_Env.local_context,
   388   name_space =
   389    {lookupVal    = #lookupVal ML_Env.name_space,
   390     lookupType   = #lookupType ML_Env.name_space,
   391     lookupFix    = #lookupFix ML_Env.name_space,
   392     lookupStruct = #lookupStruct ML_Env.name_space,
   393     lookupSig    = #lookupSig ML_Env.name_space,
   394     lookupFunct  = #lookupFunct ML_Env.name_space,
   395     enterVal     = notify_val,
   396     enterType    = abort,
   397     enterFix     = abort,
   398     enterStruct  = abort,
   399     enterSig     = abort,
   400     enterFunct   = abort,
   401     allVal       = #allVal ML_Env.name_space,
   402     allType      = #allType ML_Env.name_space,
   403     allFix       = #allFix ML_Env.name_space,
   404     allStruct    = #allStruct ML_Env.name_space,
   405     allSig       = #allSig ML_Env.name_space,
   406     allFunct     = #allFunct ML_Env.name_space},
   407   str_of_pos = #str_of_pos ML_Env.local_context,
   408   print = #print ML_Env.local_context,
   409   error = #error ML_Env.local_context};
   410 
   411 in
   412 
   413 fun use_file filepath thy =
   414   let
   415     val thy' = Loaded_Values.put [] thy;
   416     val _ = Context.set_thread_data ((SOME o Context.Theory) thy');
   417     val _ = Secure.use_text notifying_context
   418       (0, Path.implode filepath) false (File.read filepath);
   419     val thy'' = (Context.the_theory o the) (Context.thread_data ());
   420     val names = Loaded_Values.get thy'';
   421     val thy''' = Thy_Load.provide_file filepath 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*)