src/Tools/Code/code_eval.ML
author wenzelm
Mon, 31 May 2010 21:06:57 +0200
changeset 37216 3165bc303f66
parent 37199 3af985b10550
child 37412 4202e11ae7dc
permissions -rw-r--r--
modernized some structure names, keeping a few legacy aliases;
haftmann@36534
     1
(*  Title:      Tools/code/code_eval.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@34026
     4
Runtime services building on code generation into implementation language SML.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@34026
     7
signature CODE_EVAL =
haftmann@28054
     8
sig
haftmann@34026
     9
  val target: string
wenzelm@32740
    10
  val eval: string option -> string * (unit -> 'a) option Unsynchronized.ref
haftmann@30970
    11
    -> ((term -> term) -> 'a -> 'a) -> theory -> term -> string list -> 'a
haftmann@36466
    12
  val evaluation_code: theory -> string -> string list -> string list
haftmann@34026
    13
    -> string * ((string * string) list * (string * string) list)
haftmann@28054
    14
  val setup: theory -> theory
haftmann@28054
    15
end;
haftmann@28054
    16
haftmann@34026
    17
structure Code_Eval : CODE_EVAL =
haftmann@28054
    18
struct
haftmann@28054
    19
haftmann@33989
    20
(** generic **)
haftmann@33989
    21
haftmann@34026
    22
val target = "Eval";
haftmann@28054
    23
haftmann@34030
    24
val eval_struct_name = "Code";
haftmann@33989
    25
haftmann@36466
    26
fun evaluation_code thy struct_name_hint tycos consts =
haftmann@33989
    27
  let
haftmann@36271
    28
    val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
haftmann@34026
    29
    val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
haftmann@36466
    30
    val struct_name = if struct_name_hint = "" then eval_struct_name
haftmann@36466
    31
      else struct_name_hint;
haftmann@34026
    32
    val (ml_code, target_names) = Code_ML.evaluation_code_of thy target
haftmann@36466
    33
      struct_name naming program (consts' @ tycos');
haftmann@34026
    34
    val (consts'', tycos'') = chop (length consts') target_names;
haftmann@34026
    35
    val consts_map = map2 (fn const => fn NONE =>
haftmann@34026
    36
        error ("Constant " ^ (quote o Code.string_of_const thy) const
haftmann@34026
    37
          ^ "\nhas a user-defined serialization")
haftmann@34026
    38
      | SOME const'' => (const, const'')) consts consts''
haftmann@34026
    39
    val tycos_map = map2 (fn tyco => fn NONE =>
haftmann@34026
    40
        error ("Type " ^ (quote o Sign.extern_type thy) tyco
haftmann@34026
    41
          ^ "\nhas a user-defined serialization")
haftmann@34026
    42
      | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
haftmann@34026
    43
  in (ml_code, (tycos_map, consts_map)) end;
haftmann@28054
    44
haftmann@28054
    45
haftmann@34026
    46
(** evaluation **)
haftmann@28054
    47
haftmann@30970
    48
fun eval some_target reff postproc thy t args =
haftmann@28054
    49
  let
wenzelm@36633
    50
    val ctxt = ProofContext.init_global thy;
haftmann@31063
    51
    fun evaluator naming program ((_, (_, ty)), t) deps =
haftmann@28054
    52
      let
haftmann@28054
    53
        val _ = if Code_Thingol.contains_dictvar t then
haftmann@28724
    54
          error "Term to be evaluated contains free dictionaries" else ();
haftmann@28663
    55
        val value_name = "Value.VALUE.value"
haftmann@28054
    56
        val program' = program
haftmann@28663
    57
          |> Graph.new_node (value_name,
haftmann@35228
    58
              Code_Thingol.Fun (Term.dummy_patternN, (([], ty), [(([], t), (NONE, true))])))
haftmann@28663
    59
          |> fold (curry Graph.add_edge value_name) deps;
haftmann@34026
    60
        val (value_code, [SOME value_name']) = Code_ML.evaluation_code_of thy
haftmann@34030
    61
          (the_default target some_target) "" naming program' [value_name];
haftmann@28054
    62
        val sml_code = "let\n" ^ value_code ^ "\nin " ^ value_name'
haftmann@28054
    63
          ^ space_implode " " (map (enclose "(" ")") args) ^ " end";
wenzelm@30687
    64
      in ML_Context.evaluate ctxt false reff sml_code end;
haftmann@32101
    65
  in Code_Thingol.eval thy postproc evaluator t end;
haftmann@28054
    66
haftmann@28054
    67
haftmann@34026
    68
(** instrumentalization by antiquotation **)
haftmann@28054
    69
haftmann@28054
    70
local
haftmann@28054
    71
wenzelm@33519
    72
structure CodeAntiqData = Proof_Data
haftmann@28054
    73
(
haftmann@30962
    74
  type T = (string list * string list) * (bool * (string
haftmann@30962
    75
    * (string * ((string * string) list * (string * string) list)) lazy));
haftmann@30962
    76
  fun init _ = (([], []), (true, ("", Lazy.value ("", ([], [])))));
haftmann@28054
    77
);
haftmann@28054
    78
haftmann@28054
    79
val is_first_occ = fst o snd o CodeAntiqData.get;
haftmann@28054
    80
haftmann@30962
    81
fun register_code new_tycos new_consts ctxt =
haftmann@28054
    82
  let
haftmann@30962
    83
    val ((tycos, consts), (_, (struct_name, _))) = CodeAntiqData.get ctxt;
haftmann@30962
    84
    val tycos' = fold (insert (op =)) new_tycos tycos;
haftmann@30962
    85
    val consts' = fold (insert (op =)) new_consts consts;
haftmann@28054
    86
    val (struct_name', ctxt') = if struct_name = ""
haftmann@33989
    87
      then ML_Antiquote.variant eval_struct_name ctxt
haftmann@28054
    88
      else (struct_name, ctxt);
haftmann@36466
    89
    val acc_code = Lazy.lazy
haftmann@36466
    90
      (fn () => evaluation_code (ProofContext.theory_of ctxt) eval_struct_name tycos' consts');
haftmann@30962
    91
  in CodeAntiqData.put ((tycos', consts'), (false, (struct_name', acc_code))) ctxt' end;
haftmann@28054
    92
haftmann@30962
    93
fun register_const const = register_code [] [const];
haftmann@30962
    94
haftmann@30962
    95
fun register_datatype tyco constrs = register_code [tyco] constrs;
haftmann@30962
    96
haftmann@30962
    97
fun print_const const all_struct_name tycos_map consts_map =
haftmann@30962
    98
  (Long_Name.append all_struct_name o the o AList.lookup (op =) consts_map) const;
haftmann@30962
    99
wenzelm@35019
   100
fun print_code is_first print_it ctxt =
haftmann@30962
   101
  let
haftmann@30962
   102
    val (_, (_, (struct_code_name, acc_code))) = CodeAntiqData.get ctxt;
haftmann@33989
   103
    val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
haftmann@33989
   104
    val ml_code = if is_first then ml_code
haftmann@28054
   105
      else "";
wenzelm@35019
   106
    val all_struct_name = "Isabelle." ^ struct_code_name;
haftmann@30962
   107
  in (ml_code, print_it all_struct_name tycos_map consts_map) end;
haftmann@28054
   108
haftmann@28054
   109
in
haftmann@28054
   110
wenzelm@35019
   111
fun ml_code_antiq raw_const background =
haftmann@28054
   112
  let
haftmann@31156
   113
    val const = Code.check_const (ProofContext.theory_of background) raw_const;
haftmann@28054
   114
    val is_first = is_first_occ background;
haftmann@28054
   115
    val background' = register_const const background;
wenzelm@35019
   116
  in (print_code is_first (print_const const), background') end;
haftmann@30962
   117
haftmann@28054
   118
end; (*local*)
haftmann@28054
   119
haftmann@28054
   120
haftmann@36466
   121
(** reflection support **)
haftmann@36466
   122
haftmann@36466
   123
fun check_datatype thy tyco consts =
haftmann@36466
   124
  let
haftmann@36466
   125
    val constrs = (map fst o snd o Code.get_type thy) tyco;
haftmann@36466
   126
    val missing_constrs = subtract (op =) consts constrs;
haftmann@36466
   127
    val _ = if null missing_constrs then []
haftmann@36466
   128
      else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
haftmann@36466
   129
        ^ " for datatype " ^ quote tyco);
haftmann@36466
   130
    val false_constrs = subtract (op =) constrs consts;
haftmann@36466
   131
    val _ = if null false_constrs then []
haftmann@36466
   132
      else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
haftmann@36466
   133
        ^ " for datatype " ^ quote tyco);
haftmann@36466
   134
  in () end;
haftmann@36466
   135
haftmann@36466
   136
fun add_eval_tyco (tyco, tyco') thy =
haftmann@36466
   137
  let
haftmann@36466
   138
    val k = Sign.arity_number thy tyco;
haftmann@36466
   139
    fun pr pr' fxy [] = tyco'
haftmann@36466
   140
      | pr pr' fxy [ty] =
haftmann@36466
   141
          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
haftmann@36466
   142
      | pr pr' fxy tys =
haftmann@36466
   143
          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
haftmann@36466
   144
  in
haftmann@36466
   145
    thy
haftmann@36466
   146
    |> Code_Target.add_syntax_tyco target tyco (SOME (k, pr))
haftmann@36466
   147
  end;
haftmann@36466
   148
haftmann@36507
   149
fun add_eval_constr (const, const') thy =
haftmann@36507
   150
  let
haftmann@36507
   151
    val k = Code.args_number thy const;
haftmann@36507
   152
    fun pr pr' fxy ts = Code_Printer.brackify fxy
haftmann@36507
   153
      (const' :: the_list (Code_ML.print_tuple pr' Code_Printer.BR (map fst ts)));
haftmann@36507
   154
  in
haftmann@36507
   155
    thy
haftmann@36507
   156
    |> Code_Target.add_syntax_const target const (SOME (Code_Printer.simple_const_syntax (k, pr)))
haftmann@36507
   157
  end;
haftmann@36507
   158
haftmann@36466
   159
fun add_eval_const (const, const') = Code_Target.add_syntax_const target
haftmann@36466
   160
  const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
haftmann@36466
   161
haftmann@36507
   162
fun process (code_body, (tyco_map, (constr_map, const_map))) module_name NONE thy =
haftmann@36466
   163
      let
haftmann@36466
   164
        val pr = Code_Printer.str o Long_Name.append module_name;
haftmann@36466
   165
      in
haftmann@36466
   166
        thy
haftmann@36466
   167
        |> Code_Target.add_reserved target module_name
wenzelm@37199
   168
        |> Context.theory_map
wenzelm@37199
   169
          (ML_Context.exec (fn () => ML_Context.eval_text true Position.none code_body))
haftmann@36466
   170
        |> fold (add_eval_tyco o apsnd pr) tyco_map
haftmann@36507
   171
        |> fold (add_eval_constr o apsnd pr) constr_map
haftmann@36466
   172
        |> fold (add_eval_const o apsnd pr) const_map
haftmann@36466
   173
      end
haftmann@36466
   174
  | process (code_body, _) _ (SOME file_name) thy =
haftmann@36466
   175
      let
wenzelm@37216
   176
        val preamble = "(* Generated from " ^ Path.implode (Thy_Load.thy_path (Context.theory_name thy))
haftmann@36466
   177
          ^ "; DO NOT EDIT! *)";
haftmann@36466
   178
        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code_body);
haftmann@36466
   179
      in
haftmann@36466
   180
        thy
haftmann@36466
   181
      end;
haftmann@36466
   182
haftmann@36466
   183
fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
haftmann@36466
   184
  let
haftmann@36466
   185
    val datatypes = map (fn (raw_tyco, raw_cos) =>
haftmann@36466
   186
      (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
haftmann@36507
   187
    val _ = map (uncurry (check_datatype thy)) datatypes;
haftmann@36507
   188
    val tycos = map fst datatypes;
haftmann@36507
   189
    val constrs = maps snd datatypes;
haftmann@36466
   190
    val functions = map (prep_const thy) raw_functions;
haftmann@36507
   191
    val result = evaluation_code thy module_name tycos (constrs @ functions)
haftmann@36507
   192
      |> (apsnd o apsnd) (chop (length constrs));
haftmann@36466
   193
  in
haftmann@36466
   194
    thy
haftmann@36507
   195
    |> process result module_name some_file
haftmann@36466
   196
  end;
haftmann@36466
   197
haftmann@36466
   198
val code_reflect = gen_code_reflect Code_Target.cert_tyco Code.check_const;
haftmann@36466
   199
val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
haftmann@36466
   200
haftmann@36466
   201
haftmann@28054
   202
(** Isar setup **)
haftmann@28054
   203
haftmann@28054
   204
val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
haftmann@28054
   205
haftmann@36466
   206
local
haftmann@36466
   207
haftmann@36466
   208
val datatypesK = "datatypes";
haftmann@36466
   209
val functionsK = "functions";
haftmann@36466
   210
val fileK = "file";
haftmann@36466
   211
val andK = "and"
haftmann@36466
   212
wenzelm@36970
   213
val _ = List.app Keyword.keyword [datatypesK, functionsK];
haftmann@36466
   214
wenzelm@36970
   215
val parse_datatype =
wenzelm@36970
   216
  Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
haftmann@36466
   217
haftmann@36466
   218
in
haftmann@36466
   219
haftmann@36466
   220
val _ =
wenzelm@36970
   221
  Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
wenzelm@36970
   222
    Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
wenzelm@36970
   223
      ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
wenzelm@36970
   224
    -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
wenzelm@36970
   225
    -- Scan.option (Parse.$$$ fileK |-- Parse.name)
haftmann@36534
   226
  >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
haftmann@36466
   227
    (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
haftmann@36466
   228
haftmann@36466
   229
end; (*local*)
haftmann@36466
   230
haftmann@34026
   231
val setup = Code_Target.extend_target (target, (Code_ML.target_SML, K I));
haftmann@28054
   232
haftmann@28054
   233
end; (*struct*)