src/Tools/Code/code_eval.ML
author wenzelm
Sat Jul 24 21:22:21 2010 +0200 (2010-07-24)
changeset 37950 bc285d91041e
parent 37744 3daaf23b9ab4
child 38669 9ff76d0f0610
permissions -rw-r--r--
moved basic thy file name operations from Thy_Load to Thy_Header;
haftmann@37744
     1
(*  Title:      Tools/Code/code_eval.ML
haftmann@28054
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28054
     3
haftmann@34028
     4
Runtime services building on code generation into implementation language SML.
haftmann@28054
     5
*)
haftmann@28054
     6
haftmann@34028
     7
signature CODE_EVAL =
haftmann@28054
     8
sig
haftmann@34028
     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@36470
    12
  val evaluation_code: theory -> string -> string list -> string list
haftmann@34028
    13
    -> string * ((string * string) list * (string * string) list)
haftmann@28054
    14
  val setup: theory -> theory
haftmann@28054
    15
end;
haftmann@28054
    16
haftmann@34028
    17
structure Code_Eval : CODE_EVAL =
haftmann@28054
    18
struct
haftmann@28054
    19
haftmann@33992
    20
(** generic **)
haftmann@33992
    21
haftmann@34028
    22
val target = "Eval";
haftmann@28054
    23
haftmann@34032
    24
val eval_struct_name = "Code";
haftmann@33992
    25
haftmann@36470
    26
fun evaluation_code thy struct_name_hint tycos consts =
haftmann@33992
    27
  let
haftmann@36271
    28
    val (consts', (naming, program)) = Code_Thingol.consts_program thy false consts;
haftmann@34028
    29
    val tycos' = map (the o Code_Thingol.lookup_tyco naming) tycos;
haftmann@36470
    30
    val struct_name = if struct_name_hint = "" then eval_struct_name
haftmann@36470
    31
      else struct_name_hint;
haftmann@34028
    32
    val (ml_code, target_names) = Code_ML.evaluation_code_of thy target
haftmann@36470
    33
      struct_name naming program (consts' @ tycos');
haftmann@34028
    34
    val (consts'', tycos'') = chop (length consts') target_names;
haftmann@34028
    35
    val consts_map = map2 (fn const => fn NONE =>
haftmann@34028
    36
        error ("Constant " ^ (quote o Code.string_of_const thy) const
haftmann@34028
    37
          ^ "\nhas a user-defined serialization")
haftmann@34028
    38
      | SOME const'' => (const, const'')) consts consts''
haftmann@34028
    39
    val tycos_map = map2 (fn tyco => fn NONE =>
haftmann@34028
    40
        error ("Type " ^ (quote o Sign.extern_type thy) tyco
haftmann@34028
    41
          ^ "\nhas a user-defined serialization")
haftmann@34028
    42
      | SOME tyco'' => (tyco, tyco'')) tycos tycos'';
haftmann@34028
    43
  in (ml_code, (tycos_map, consts_map)) end;
haftmann@28054
    44
haftmann@28054
    45
haftmann@34028
    46
(** evaluation **)
haftmann@28054
    47
haftmann@30970
    48
fun eval some_target reff postproc thy t args =
haftmann@28054
    49
  let
wenzelm@36610
    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@37437
    58
              Code_Thingol.Fun (Term.dummy_patternN, ((([], ty), [(([], t), (NONE, true))]), NONE)))
haftmann@28663
    59
          |> fold (curry Graph.add_edge value_name) deps;
haftmann@34028
    60
        val (value_code, [SOME value_name']) = Code_ML.evaluation_code_of thy
haftmann@34032
    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@30672
    64
      in ML_Context.evaluate ctxt false reff sml_code end;
haftmann@32123
    65
  in Code_Thingol.eval thy postproc evaluator t end;
haftmann@28054
    66
haftmann@28054
    67
haftmann@34028
    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@33992
    87
      then ML_Antiquote.variant eval_struct_name ctxt
haftmann@28054
    88
      else (struct_name, ctxt);
haftmann@36470
    89
    val acc_code = Lazy.lazy
haftmann@36470
    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@30962
    92
haftmann@30962
    93
fun register_const const = register_code [] [const];
haftmann@28054
    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@33992
   103
    val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
haftmann@33992
   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@36470
   121
(** reflection support **)
haftmann@36470
   122
haftmann@36470
   123
fun check_datatype thy tyco consts =
haftmann@36470
   124
  let
haftmann@37448
   125
    val constrs = (map (fst o fst) o snd o Code.get_type thy) tyco;
haftmann@36470
   126
    val missing_constrs = subtract (op =) consts constrs;
haftmann@36470
   127
    val _ = if null missing_constrs then []
haftmann@36470
   128
      else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
haftmann@36470
   129
        ^ " for datatype " ^ quote tyco);
haftmann@36470
   130
    val false_constrs = subtract (op =) constrs consts;
haftmann@36470
   131
    val _ = if null false_constrs then []
haftmann@36470
   132
      else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
haftmann@36470
   133
        ^ " for datatype " ^ quote tyco);
haftmann@36470
   134
  in () end;
haftmann@36470
   135
haftmann@36470
   136
fun add_eval_tyco (tyco, tyco') thy =
haftmann@36470
   137
  let
haftmann@36470
   138
    val k = Sign.arity_number thy tyco;
haftmann@36470
   139
    fun pr pr' fxy [] = tyco'
haftmann@36470
   140
      | pr pr' fxy [ty] =
haftmann@36470
   141
          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
haftmann@36470
   142
      | pr pr' fxy tys =
haftmann@36470
   143
          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
haftmann@36470
   144
  in
haftmann@36470
   145
    thy
haftmann@36470
   146
    |> Code_Target.add_syntax_tyco target tyco (SOME (k, pr))
haftmann@36470
   147
  end;
haftmann@36470
   148
haftmann@36514
   149
fun add_eval_constr (const, const') thy =
haftmann@36514
   150
  let
haftmann@36514
   151
    val k = Code.args_number thy const;
haftmann@36514
   152
    fun pr pr' fxy ts = Code_Printer.brackify fxy
haftmann@36514
   153
      (const' :: the_list (Code_ML.print_tuple pr' Code_Printer.BR (map fst ts)));
haftmann@36514
   154
  in
haftmann@36514
   155
    thy
haftmann@36514
   156
    |> Code_Target.add_syntax_const target const (SOME (Code_Printer.simple_const_syntax (k, pr)))
haftmann@36514
   157
  end;
haftmann@36514
   158
haftmann@36470
   159
fun add_eval_const (const, const') = Code_Target.add_syntax_const target
haftmann@36470
   160
  const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
haftmann@36470
   161
haftmann@36514
   162
fun process (code_body, (tyco_map, (constr_map, const_map))) module_name NONE thy =
haftmann@36470
   163
      let
haftmann@36470
   164
        val pr = Code_Printer.str o Long_Name.append module_name;
haftmann@36470
   165
      in
haftmann@36470
   166
        thy
haftmann@36470
   167
        |> Code_Target.add_reserved target module_name
wenzelm@37198
   168
        |> Context.theory_map
wenzelm@37198
   169
          (ML_Context.exec (fn () => ML_Context.eval_text true Position.none code_body))
haftmann@36470
   170
        |> fold (add_eval_tyco o apsnd pr) tyco_map
haftmann@36514
   171
        |> fold (add_eval_constr o apsnd pr) constr_map
haftmann@36470
   172
        |> fold (add_eval_const o apsnd pr) const_map
haftmann@36470
   173
      end
haftmann@36470
   174
  | process (code_body, _) _ (SOME file_name) thy =
haftmann@36470
   175
      let
wenzelm@37950
   176
        val preamble =
wenzelm@37950
   177
          "(* Generated from " ^ Path.implode (Thy_Header.thy_path (Context.theory_name thy))
haftmann@36470
   178
          ^ "; DO NOT EDIT! *)";
haftmann@36470
   179
        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code_body);
haftmann@36470
   180
      in
haftmann@36470
   181
        thy
haftmann@36470
   182
      end;
haftmann@36470
   183
haftmann@36470
   184
fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
haftmann@36470
   185
  let
haftmann@36470
   186
    val datatypes = map (fn (raw_tyco, raw_cos) =>
haftmann@36470
   187
      (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
haftmann@36514
   188
    val _ = map (uncurry (check_datatype thy)) datatypes;
haftmann@36514
   189
    val tycos = map fst datatypes;
haftmann@36514
   190
    val constrs = maps snd datatypes;
haftmann@36470
   191
    val functions = map (prep_const thy) raw_functions;
haftmann@36514
   192
    val result = evaluation_code thy module_name tycos (constrs @ functions)
haftmann@36514
   193
      |> (apsnd o apsnd) (chop (length constrs));
haftmann@36470
   194
  in
haftmann@36470
   195
    thy
haftmann@36514
   196
    |> process result module_name some_file
haftmann@36470
   197
  end;
haftmann@36470
   198
haftmann@36470
   199
val code_reflect = gen_code_reflect Code_Target.cert_tyco Code.check_const;
haftmann@36470
   200
val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
haftmann@36470
   201
haftmann@36470
   202
haftmann@28054
   203
(** Isar setup **)
haftmann@28054
   204
haftmann@28054
   205
val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
haftmann@28054
   206
haftmann@36470
   207
local
haftmann@36470
   208
haftmann@36470
   209
val datatypesK = "datatypes";
haftmann@36470
   210
val functionsK = "functions";
haftmann@36470
   211
val fileK = "file";
haftmann@36470
   212
val andK = "and"
haftmann@36470
   213
wenzelm@36960
   214
val _ = List.app Keyword.keyword [datatypesK, functionsK];
haftmann@36470
   215
wenzelm@36960
   216
val parse_datatype =
wenzelm@36960
   217
  Parse.name --| Parse.$$$ "=" -- (Parse.term ::: (Scan.repeat (Parse.$$$ "|" |-- Parse.term)));
haftmann@36470
   218
haftmann@36470
   219
in
haftmann@36470
   220
haftmann@36470
   221
val _ =
wenzelm@36960
   222
  Outer_Syntax.command "code_reflect" "enrich runtime environment with generated code"
wenzelm@36960
   223
    Keyword.thy_decl (Parse.name -- Scan.optional (Parse.$$$ datatypesK |-- (parse_datatype
wenzelm@36960
   224
      ::: Scan.repeat (Parse.$$$ andK |-- parse_datatype))) []
wenzelm@36960
   225
    -- Scan.optional (Parse.$$$ functionsK |-- Scan.repeat1 Parse.name) []
wenzelm@36960
   226
    -- Scan.option (Parse.$$$ fileK |-- Parse.name)
haftmann@36534
   227
  >> (fn (((module_name, raw_datatypes), raw_functions), some_file) => Toplevel.theory
haftmann@36470
   228
    (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
haftmann@36470
   229
haftmann@36470
   230
end; (*local*)
haftmann@36470
   231
haftmann@34028
   232
val setup = Code_Target.extend_target (target, (Code_ML.target_SML, K I));
haftmann@28054
   233
haftmann@28054
   234
end; (*struct*)