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