src/Tools/Code/code_runtime.ML
author haftmann
Mon Sep 20 08:53:37 2010 +0200 (2010-09-20)
changeset 39537 41afe7124aa6
parent 39485 f7270a5e2550
child 39605 6dc866b9c548
permissions -rw-r--r--
made smlnj happy
     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   type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string
    11   val dynamic_value: 'a cookie -> theory -> string option
    12     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a option
    13   val dynamic_value_strict: 'a cookie -> theory -> string option
    14     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a
    15   val dynamic_value_exn: 'a cookie -> theory -> string option
    16     -> ((term -> term) -> 'a -> 'a) -> term -> string list -> 'a Exn.result
    17   val static_value: 'a cookie -> theory -> string option
    18     -> ((term -> term) -> 'a -> 'a) -> string list -> term -> 'a option
    19   val static_value_strict: 'a cookie -> theory -> string option
    20     -> ((term -> term) -> 'a -> 'a) -> string list -> term -> 'a
    21   val static_value_exn: 'a cookie -> theory -> string option
    22     -> ((term -> term) -> 'a -> 'a) -> string list -> term -> 'a Exn.result
    23   val dynamic_holds_conv: conv
    24   val static_holds_conv: theory -> string list -> conv
    25   val code_reflect: (string * string list) list -> string list -> string -> string option
    26     -> theory -> theory
    27   datatype truth = Holds
    28   val put_truth: (unit -> truth) -> Proof.context -> Proof.context
    29 end;
    30 
    31 structure Code_Runtime : CODE_RUNTIME =
    32 struct
    33 
    34 open Basic_Code_Thingol;
    35 
    36 (** evaluation **)
    37 
    38 (* technical prerequisites *)
    39 
    40 val this = "Code_Runtime";
    41 val s_truth = Long_Name.append this "truth";
    42 val s_Holds = Long_Name.append this "Holds";
    43 
    44 val target = "Eval";
    45 
    46 datatype truth = Holds;
    47 
    48 val _ = Context.>> (Context.map_theory
    49   (Code_Target.extend_target (target, (Code_ML.target_SML, K I))
    50   #> Code_Target.add_tyco_syntax target @{type_name prop}
    51        (SOME (0, (K o K o K) (Code_Printer.str s_truth)))
    52   #> Code_Target.add_const_syntax target @{const_name Code_Generator.holds}
    53        (SOME (Code_Printer.plain_const_syntax s_Holds))
    54   #> Code_Target.add_reserved target this
    55   #> fold (Code_Target.add_reserved target) ["oo", "ooo", "oooo", "upto", "downto", "orf", "andf"]));
    56        (*avoid further pervasive infix names*)
    57 
    58 
    59 (* evaluation into target language values *)
    60 
    61 type 'a cookie = (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string;
    62 
    63 fun obtain_serializer thy some_target = Code_Target.produce_code_for thy
    64   (the_default target some_target) NONE "Code" [];
    65 
    66 fun base_evaluator cookie serializer (naming : Code_Thingol.naming) thy program ((vs, ty), t) deps args =
    67   let
    68     val ctxt = ProofContext.init_global thy;
    69     val _ = if Code_Thingol.contains_dictvar t then
    70       error "Term to be evaluated contains free dictionaries" else ();
    71     val v' = Name.variant (map fst vs) "a";
    72     val vs' = (v', []) :: vs
    73     val ty' = Code_Thingol.fun_tyco `%% [ITyVar v', ty];
    74     val value_name = "Value.value.value"
    75     val program' = program
    76       |> Graph.new_node (value_name,
    77           Code_Thingol.Fun (Term.dummy_patternN, (((vs', ty'), [(([IVar NONE], t), (NONE, true))]), NONE)))
    78       |> fold (curry Graph.add_edge value_name) deps;
    79     val (program_code, [SOME value_name']) = serializer naming program' [value_name];
    80     val value_code = space_implode " "
    81       (value_name' :: "()" :: map (enclose "(" ")") args);
    82   in Exn.capture (ML_Context.value ctxt cookie) (program_code, value_code) end;
    83 
    84 fun partiality_as_none e = SOME (Exn.release e)
    85   handle General.Match => NONE
    86     | General.Bind => NONE
    87     | General.Fail _ => NONE;
    88 
    89 fun dynamic_value_exn cookie thy some_target postproc t args =
    90   let
    91     fun evaluator naming program ((_, vs_ty), t) deps =
    92       base_evaluator cookie (obtain_serializer thy some_target) naming thy program (vs_ty, t) deps args;
    93   in Code_Thingol.dynamic_eval_value thy (Exn.map_result o postproc) evaluator t end;
    94 
    95 fun dynamic_value_strict cookie thy some_target postproc t args =
    96   Exn.release (dynamic_value_exn cookie thy some_target postproc t args);
    97 
    98 fun dynamic_value cookie thy some_target postproc t args =
    99   partiality_as_none (dynamic_value_exn cookie thy some_target postproc t args);
   100 
   101 fun static_value_exn cookie thy some_target postproc consts =
   102   let
   103     val serializer = obtain_serializer thy some_target;
   104     fun evaluator naming program thy ((_, vs_ty), t) deps =
   105       base_evaluator cookie serializer naming thy program (vs_ty, t) deps [];
   106   in Code_Thingol.static_eval_value thy (Exn.map_result o postproc) consts evaluator end;
   107 
   108 fun static_value_strict cookie thy some_target postproc consts t =
   109   Exn.release (static_value_exn cookie thy some_target postproc consts t);
   110 
   111 fun static_value cookie thy some_target postproc consts t =
   112   partiality_as_none (static_value_exn cookie thy some_target postproc consts t);
   113 
   114 
   115 (* evaluation for truth or nothing *)
   116 
   117 structure Truth_Result = Proof_Data (
   118   type T = unit -> truth
   119   fun init _ () = error "Truth_Result"
   120 );
   121 val put_truth = Truth_Result.put;
   122 val truth_cookie = (Truth_Result.get, put_truth, Long_Name.append this "put_truth");
   123 
   124 fun check_holds serializer naming thy program vs_t deps ct =
   125   let
   126     val t = Thm.term_of ct;
   127     val _ = if fastype_of t <> propT
   128       then error ("Not a proposition: " ^ Syntax.string_of_term_global thy t)
   129       else ();
   130     val iff = Thm.cterm_of thy (Term.Const ("==", propT --> propT --> propT));
   131     val result = case partiality_as_none (base_evaluator truth_cookie serializer naming thy program vs_t deps [])
   132      of SOME Holds => true
   133       | _ => false;
   134   in
   135     Thm.mk_binop iff ct (if result then @{cprop "PROP Code_Generator.holds"} else ct)
   136   end;
   137 
   138 val (_, raw_check_holds_oracle) = Context.>>> (Context.map_theory_result
   139   (Thm.add_oracle (Binding.name "holds_by_evaluation",
   140   fn (serializer, naming, thy, program, vs_t, deps, ct) => check_holds serializer naming thy program vs_t deps ct)));
   141 
   142 fun check_holds_oracle serializer naming thy program ((_, vs_ty), t) deps ct =
   143   raw_check_holds_oracle (serializer, naming, thy, program, (vs_ty, t), deps, ct);
   144 
   145 val dynamic_holds_conv = Conv.tap_thy (fn thy => Code_Thingol.dynamic_eval_conv thy
   146   (fn naming => check_holds_oracle (obtain_serializer thy NONE) naming thy));
   147 
   148 fun static_holds_conv thy consts =
   149   let
   150     val serializer = obtain_serializer thy NONE;
   151   in
   152     Code_Thingol.static_eval_conv thy consts
   153       (fn naming => fn program => fn thy => check_holds_oracle serializer naming thy program)
   154   end;
   155 
   156 
   157 (** instrumentalization **)
   158 
   159 fun evaluation_code thy module_name tycos consts =
   160   let
   161     val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
   162     val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
   163     val (ml_code, target_names) = Code_Target.produce_code_for thy
   164       target NONE module_name [] naming program (consts' @ tycos');
   165     val (consts'', tycos'') = chop (length consts') target_names;
   166     val consts_map = map2 (fn const => fn NONE =>
   167         error ("Constant " ^ (quote o Code.string_of_const thy) const
   168           ^ "\nhas a user-defined serialization")
   169       | SOME const'' => (const, const'')) consts consts''
   170     val tycos_map = map2 (fn tyco => fn NONE =>
   171         error ("Type " ^ (quote o Sign.extern_type thy) tyco
   172           ^ "\nhas a user-defined serialization")
   173       | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
   174   in (ml_code, (tycos_map, consts_map)) end;
   175 
   176 
   177 (* by antiquotation *)
   178 
   179 local
   180 
   181 structure Code_Antiq_Data = Proof_Data
   182 (
   183   type T = (string list * string list) * (bool
   184     * (string * ((string * string) list * (string * string) list)) lazy);
   185   fun init _ = (([], []), (true, (Lazy.value ("", ([], [])))));
   186 );
   187 
   188 val is_first_occ = fst o snd o Code_Antiq_Data.get;
   189 
   190 fun register_code new_tycos new_consts ctxt =
   191   let
   192     val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
   193     val tycos' = fold (insert (op =)) new_tycos tycos;
   194     val consts' = fold (insert (op =)) new_consts consts;
   195     val acc_code = Lazy.lazy (fn () =>
   196       evaluation_code (ProofContext.theory_of ctxt) "Code" tycos' consts');
   197   in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
   198 
   199 fun register_const const = register_code [] [const];
   200 
   201 fun register_datatype tyco constrs = register_code [tyco] constrs;
   202 
   203 fun print_const const all_struct_name tycos_map consts_map =
   204   (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
   205 
   206 fun print_code is_first print_it ctxt =
   207   let
   208     val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
   209     val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
   210     val ml_code = if is_first then ml_code
   211       else "";
   212     val all_struct_name = "Isabelle";
   213   in (ml_code, print_it all_struct_name tycos_map consts_map) end;
   214 
   215 in
   216 
   217 fun ml_code_antiq raw_const background =
   218   let
   219     val const = Code.check_const (ProofContext.theory_of background) raw_const;
   220     val is_first = is_first_occ background;
   221     val background' = register_const const background;
   222   in (print_code is_first (print_const const), background') end;
   223 
   224 end; (*local*)
   225 
   226 
   227 (* reflection support *)
   228 
   229 fun check_datatype thy tyco consts =
   230   let
   231     val constrs = (map (fst o fst) o snd o Code.get_type thy) tyco;
   232     val missing_constrs = subtract (op =) consts constrs;
   233     val _ = if null missing_constrs then []
   234       else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
   235         ^ " for datatype " ^ quote tyco);
   236     val false_constrs = subtract (op =) constrs consts;
   237     val _ = if null false_constrs then []
   238       else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
   239         ^ " for datatype " ^ quote tyco);
   240   in () end;
   241 
   242 fun add_eval_tyco (tyco, tyco') thy =
   243   let
   244     val k = Sign.arity_number thy tyco;
   245     fun pr pr' fxy [] = tyco'
   246       | pr pr' fxy [ty] =
   247           Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   248       | pr pr' fxy tys =
   249           Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   250   in
   251     thy
   252     |> Code_Target.add_tyco_syntax target tyco (SOME (k, pr))
   253   end;
   254 
   255 fun add_eval_constr (const, const') thy =
   256   let
   257     val k = Code.args_number thy const;
   258     fun pr pr' fxy ts = Code_Printer.brackify fxy
   259       (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   260   in
   261     thy
   262     |> Code_Target.add_const_syntax target const (SOME (Code_Printer.simple_const_syntax (k, pr)))
   263   end;
   264 
   265 fun add_eval_const (const, const') = Code_Target.add_const_syntax target
   266   const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
   267 
   268 fun process_reflection (code_body, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   269       thy
   270       |> Code_Target.add_reserved target module_name
   271       |> Context.theory_map
   272         (ML_Context.exec (fn () => ML_Context.eval_text true Position.none code_body))
   273       |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   274       |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   275       |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   276   | process_reflection (code_body, _) _ (SOME file_name) thy =
   277       let
   278         val preamble =
   279           "(* Generated from " ^ Path.implode (Thy_Header.thy_path (Context.theory_name thy))
   280           ^ "; DO NOT EDIT! *)";
   281         val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code_body);
   282       in
   283         thy
   284       end;
   285 
   286 fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   287   let
   288     val datatypes = map (fn (raw_tyco, raw_cos) =>
   289       (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
   290     val _ = map (uncurry (check_datatype thy)) datatypes;
   291     val tycos = map fst datatypes;
   292     val constrs = maps snd datatypes;
   293     val functions = map (prep_const thy) raw_functions;
   294     val result = evaluation_code thy module_name tycos (constrs @ functions)
   295       |> (apsnd o apsnd) (chop (length constrs));
   296   in
   297     thy
   298     |> process_reflection result module_name some_file
   299   end;
   300 
   301 val code_reflect = gen_code_reflect Code_Target.cert_tyco (K I);
   302 val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   303 
   304 
   305 (** Isar setup **)
   306 
   307 val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
   308 
   309 local
   310 
   311 val datatypesK = "datatypes";
   312 val functionsK = "functions";
   313 val fileK = "file";
   314 val andK = "and"
   315 
   316 val _ = List.app Keyword.keyword [datatypesK, functionsK];
   317 
   318 val parse_datatype =
   319   Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
   320 
   321 in
   322 
   323 val _ =
   324   Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
   325     Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
   326       ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
   327     -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
   328     -- Scan.option (Parse.$$$ fileK |-- Parse.name)
   329   >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   330     (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   331 
   332 end; (*local*)
   333 
   334 end; (*struct*)