src/Tools/Code/code_runtime.ML
changeset 39401 887f4218a39a
parent 39388 fdbb2c55ffc2
child 39404 a8c337299bc1
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/Tools/Code/code_runtime.ML	Wed Sep 15 15:31:32 2010 +0200
     1.3 @@ -0,0 +1,222 @@
     1.4 +(*  Title:      Tools/Code/code_runtime.ML
     1.5 +    Author:     Florian Haftmann, TU Muenchen
     1.6 +
     1.7 +Runtime services building on code generation into implementation language SML.
     1.8 +*)
     1.9 +
    1.10 +signature CODE_RUNTIME =
    1.11 +sig
    1.12 +  val target: string
    1.13 +  val eval: string option
    1.14 +    -> (Proof.context -> unit -> 'a) * ((unit -> 'a) -> Proof.context -> Proof.context) * string
    1.15 +    -> ((term -> term) -> 'a -> 'a) -> theory -> term -> string list -> 'a
    1.16 +  val setup: theory -> theory
    1.17 +end;
    1.18 +
    1.19 +structure Code_Runtime : CODE_RUNTIME =
    1.20 +struct
    1.21 +
    1.22 +(** generic **)
    1.23 +
    1.24 +val target = "Eval";
    1.25 +
    1.26 +fun evaluation_code thy module_name tycos consts =
    1.27 +  let
    1.28 +    val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
    1.29 +    val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
    1.30 +    val (ml_code, target_names) = Code_Target.produce_code_for thy
    1.31 +      target NONE module_name [] naming program (consts' @ tycos');
    1.32 +    val (consts'', tycos'') = chop (length consts') target_names;
    1.33 +    val consts_map = map2 (fn const => fn NONE =>
    1.34 +        error ("Constant " ^ (quote o Code.string_of_const thy) const
    1.35 +          ^ "\nhas a user-defined serialization")
    1.36 +      | SOME const'' => (const, const'')) consts consts''
    1.37 +    val tycos_map = map2 (fn tyco => fn NONE =>
    1.38 +        error ("Type " ^ (quote o Sign.extern_type thy) tyco
    1.39 +          ^ "\nhas a user-defined serialization")
    1.40 +      | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
    1.41 +  in (ml_code, (tycos_map, consts_map)) end;
    1.42 +
    1.43 +
    1.44 +(** evaluation **)
    1.45 +
    1.46 +fun eval some_target cookie postproc thy t args =
    1.47 +  let
    1.48 +    val ctxt = ProofContext.init_global thy;
    1.49 +    fun evaluator naming program ((_, (_, ty)), t) deps =
    1.50 +      let
    1.51 +        val _ = if Code_Thingol.contains_dictvar t then
    1.52 +          error "Term to be evaluated contains free dictionaries" else ();
    1.53 +        val value_name = "Value.VALUE.value"
    1.54 +        val program' = program
    1.55 +          |> Graph.new_node (value_name,
    1.56 +              Code_Thingol.Fun (Term.dummy_patternN, ((([], ty), [(([], t), (NONE, true))]), NONE)))
    1.57 +          |> fold (curry Graph.add_edge value_name) deps;
    1.58 +        val (program_code, [SOME value_name']) = Code_Target.produce_code_for thy
    1.59 +          (the_default target some_target) NONE "Code" [] naming program' [value_name];
    1.60 +        val value_code = space_implode " "
    1.61 +          (value_name' :: map (enclose "(" ")") args);
    1.62 +      in ML_Context.value ctxt cookie (program_code, value_code) end;
    1.63 +  in Code_Thingol.dynamic_eval_value thy postproc evaluator t end;
    1.64 +
    1.65 +
    1.66 +(** instrumentalization by antiquotation **)
    1.67 +
    1.68 +local
    1.69 +
    1.70 +structure Code_Antiq_Data = Proof_Data
    1.71 +(
    1.72 +  type T = (string list * string list) * (bool
    1.73 +    * (string * ((string * string) list * (string * string) list)) lazy);
    1.74 +  fun init _ = (([], []), (true, (Lazy.value ("", ([], [])))));
    1.75 +);
    1.76 +
    1.77 +val is_first_occ = fst o snd o Code_Antiq_Data.get;
    1.78 +
    1.79 +fun register_code new_tycos new_consts ctxt =
    1.80 +  let
    1.81 +    val ((tycos, consts), _) = Code_Antiq_Data.get ctxt;
    1.82 +    val tycos' = fold (insert (op =)) new_tycos tycos;
    1.83 +    val consts' = fold (insert (op =)) new_consts consts;
    1.84 +    val acc_code = Lazy.lazy (fn () =>
    1.85 +      evaluation_code (ProofContext.theory_of ctxt) "Code" tycos' consts');
    1.86 +  in Code_Antiq_Data.put ((tycos', consts'), (false, acc_code)) ctxt end;
    1.87 +
    1.88 +fun register_const const = register_code [] [const];
    1.89 +
    1.90 +fun register_datatype tyco constrs = register_code [tyco] constrs;
    1.91 +
    1.92 +fun print_const const all_struct_name tycos_map consts_map =
    1.93 +  (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
    1.94 +
    1.95 +fun print_code is_first print_it ctxt =
    1.96 +  let
    1.97 +    val (_, (_, acc_code)) = Code_Antiq_Data.get ctxt;
    1.98 +    val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
    1.99 +    val ml_code = if is_first then ml_code
   1.100 +      else "";
   1.101 +    val all_struct_name = "Isabelle";
   1.102 +  in (ml_code, print_it all_struct_name tycos_map consts_map) end;
   1.103 +
   1.104 +in
   1.105 +
   1.106 +fun ml_code_antiq raw_const background =
   1.107 +  let
   1.108 +    val const = Code.check_const (ProofContext.theory_of background) raw_const;
   1.109 +    val is_first = is_first_occ background;
   1.110 +    val background' = register_const const background;
   1.111 +  in (print_code is_first (print_const const), background') end;
   1.112 +
   1.113 +end; (*local*)
   1.114 +
   1.115 +
   1.116 +(** reflection support **)
   1.117 +
   1.118 +fun check_datatype thy tyco consts =
   1.119 +  let
   1.120 +    val constrs = (map (fst o fst) o snd o Code.get_type thy) tyco;
   1.121 +    val missing_constrs = subtract (op =) consts constrs;
   1.122 +    val _ = if null missing_constrs then []
   1.123 +      else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
   1.124 +        ^ " for datatype " ^ quote tyco);
   1.125 +    val false_constrs = subtract (op =) constrs consts;
   1.126 +    val _ = if null false_constrs then []
   1.127 +      else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
   1.128 +        ^ " for datatype " ^ quote tyco);
   1.129 +  in () end;
   1.130 +
   1.131 +fun add_eval_tyco (tyco, tyco') thy =
   1.132 +  let
   1.133 +    val k = Sign.arity_number thy tyco;
   1.134 +    fun pr pr' fxy [] = tyco'
   1.135 +      | pr pr' fxy [ty] =
   1.136 +          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
   1.137 +      | pr pr' fxy tys =
   1.138 +          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
   1.139 +  in
   1.140 +    thy
   1.141 +    |> Code_Target.add_tyco_syntax target tyco (SOME (k, pr))
   1.142 +  end;
   1.143 +
   1.144 +fun add_eval_constr (const, const') thy =
   1.145 +  let
   1.146 +    val k = Code.args_number thy const;
   1.147 +    fun pr pr' fxy ts = Code_Printer.brackify fxy
   1.148 +      (const' :: the_list (Code_Printer.tuplify pr' Code_Printer.BR (map fst ts)));
   1.149 +  in
   1.150 +    thy
   1.151 +    |> Code_Target.add_const_syntax target const (SOME (Code_Printer.simple_const_syntax (k, pr)))
   1.152 +  end;
   1.153 +
   1.154 +fun add_eval_const (const, const') = Code_Target.add_const_syntax target
   1.155 +  const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
   1.156 +
   1.157 +fun process (code_body, (tyco_map, (constr_map, const_map))) module_name NONE thy =
   1.158 +      thy
   1.159 +      |> Code_Target.add_reserved target module_name
   1.160 +      |> Context.theory_map
   1.161 +        (ML_Context.exec (fn () => ML_Context.eval_text true Position.none code_body))
   1.162 +      |> fold (add_eval_tyco o apsnd Code_Printer.str) tyco_map
   1.163 +      |> fold (add_eval_constr o apsnd Code_Printer.str) constr_map
   1.164 +      |> fold (add_eval_const o apsnd Code_Printer.str) const_map
   1.165 +  | process (code_body, _) _ (SOME file_name) thy =
   1.166 +      let
   1.167 +        val preamble =
   1.168 +          "(* Generated from " ^ Path.implode (Thy_Header.thy_path (Context.theory_name thy))
   1.169 +          ^ "; DO NOT EDIT! *)";
   1.170 +        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code_body);
   1.171 +      in
   1.172 +        thy
   1.173 +      end;
   1.174 +
   1.175 +fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
   1.176 +  let
   1.177 +    val datatypes = map (fn (raw_tyco, raw_cos) =>
   1.178 +      (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
   1.179 +    val _ = map (uncurry (check_datatype thy)) datatypes;
   1.180 +    val tycos = map fst datatypes;
   1.181 +    val constrs = maps snd datatypes;
   1.182 +    val functions = map (prep_const thy) raw_functions;
   1.183 +    val result = evaluation_code thy module_name tycos (constrs @ functions)
   1.184 +      |> (apsnd o apsnd) (chop (length constrs));
   1.185 +  in
   1.186 +    thy
   1.187 +    |> process result module_name some_file
   1.188 +  end;
   1.189 +
   1.190 +val code_reflect = gen_code_reflect Code_Target.cert_tyco Code.check_const;
   1.191 +val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
   1.192 +
   1.193 +
   1.194 +(** Isar setup **)
   1.195 +
   1.196 +val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
   1.197 +
   1.198 +local
   1.199 +
   1.200 +val datatypesK = "datatypes";
   1.201 +val functionsK = "functions";
   1.202 +val fileK = "file";
   1.203 +val andK = "and"
   1.204 +
   1.205 +val _ = List.app Keyword.keyword [datatypesK, functionsK];
   1.206 +
   1.207 +val parse_datatype =
   1.208 +  Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
   1.209 +
   1.210 +in
   1.211 +
   1.212 +val _ =
   1.213 +  Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
   1.214 +    Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
   1.215 +      ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
   1.216 +    -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
   1.217 +    -- Scan.option (Parse.$$$ fileK |-- Parse.name)
   1.218 +  >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
   1.219 +    (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
   1.220 +
   1.221 +end; (*local*)
   1.222 +
   1.223 +val setup = Code_Target.extend_target (target, (Code_ML.target_SML, K I));
   1.224 +
   1.225 +end; (*struct*)