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