src/Tools/Code/code_eval.ML
author haftmann
Wed Apr 28 15:17:09 2010 +0200 (2010-04-28)
changeset 36470 ed9be131a4ec
parent 36271 2ef9dbddfcb8
child 36514 3971cd55c869
permissions -rw-r--r--
added code_reflect command
haftmann@34028
     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@28275
    50
    val ctxt = ProofContext.init 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@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
haftmann@30962
   100
fun print_datatype tyco constrs all_struct_name tycos_map consts_map =
haftmann@28054
   101
  let
haftmann@30962
   102
    val upperize = implode o nth_map 0 Symbol.to_ascii_upper o explode;
haftmann@30962
   103
    fun check_base name name'' =
haftmann@30962
   104
      if upperize (Long_Name.base_name name) = upperize name''
haftmann@30962
   105
      then () else error ("Name as printed " ^ quote name''
haftmann@30962
   106
        ^ "\ndiffers from logical base name " ^ quote (Long_Name.base_name name) ^ "; sorry.");
haftmann@30962
   107
    val tyco'' = (the o AList.lookup (op =) tycos_map) tyco;
haftmann@30962
   108
    val constrs'' = map (the o AList.lookup (op =) consts_map) constrs;
haftmann@30962
   109
    val _ = check_base tyco tyco'';
haftmann@30962
   110
    val _ = map2 check_base constrs constrs'';
haftmann@30962
   111
  in "datatype " ^ tyco'' ^ " = datatype " ^ Long_Name.append all_struct_name tyco'' end;
haftmann@30962
   112
wenzelm@35019
   113
fun print_code is_first print_it ctxt =
haftmann@30962
   114
  let
haftmann@30962
   115
    val (_, (_, (struct_code_name, acc_code))) = CodeAntiqData.get ctxt;
haftmann@33992
   116
    val (ml_code, (tycos_map, consts_map)) = Lazy.force acc_code;
haftmann@33992
   117
    val ml_code = if is_first then ml_code
haftmann@28054
   118
      else "";
wenzelm@35019
   119
    val all_struct_name = "Isabelle." ^ struct_code_name;
haftmann@30962
   120
  in (ml_code, print_it all_struct_name tycos_map consts_map) end;
haftmann@28054
   121
haftmann@28054
   122
in
haftmann@28054
   123
wenzelm@35019
   124
fun ml_code_antiq raw_const background =
haftmann@28054
   125
  let
haftmann@31156
   126
    val const = Code.check_const (ProofContext.theory_of background) raw_const;
haftmann@28054
   127
    val is_first = is_first_occ background;
haftmann@28054
   128
    val background' = register_const const background;
wenzelm@35019
   129
  in (print_code is_first (print_const const), background') end;
haftmann@30962
   130
wenzelm@35019
   131
fun ml_code_datatype_antiq (raw_tyco, raw_constrs) background =
haftmann@30962
   132
  let
haftmann@30962
   133
    val thy = ProofContext.theory_of background;
haftmann@30962
   134
    val tyco = Sign.intern_type thy raw_tyco;
haftmann@31156
   135
    val constrs = map (Code.check_const thy) raw_constrs;
haftmann@35299
   136
    val constrs' = (map fst o snd o Code.get_type thy) tyco;
haftmann@33038
   137
    val _ = if eq_set (op =) (constrs, constrs') then ()
haftmann@30962
   138
      else error ("Type " ^ quote tyco ^ ": given constructors diverge from real constructors")
haftmann@30962
   139
    val is_first = is_first_occ background;
haftmann@30962
   140
    val background' = register_datatype tyco constrs background;
wenzelm@35019
   141
  in (print_code is_first (print_datatype tyco constrs), background') end;
haftmann@28054
   142
haftmann@28054
   143
end; (*local*)
haftmann@28054
   144
haftmann@28054
   145
haftmann@36470
   146
(** reflection support **)
haftmann@36470
   147
haftmann@36470
   148
fun check_datatype thy tyco consts =
haftmann@36470
   149
  let
haftmann@36470
   150
    val constrs = (map fst o snd o Code.get_type thy) tyco;
haftmann@36470
   151
    val missing_constrs = subtract (op =) consts constrs;
haftmann@36470
   152
    val _ = if null missing_constrs then []
haftmann@36470
   153
      else error ("Missing constructor(s) " ^ commas (map quote missing_constrs)
haftmann@36470
   154
        ^ " for datatype " ^ quote tyco);
haftmann@36470
   155
    val false_constrs = subtract (op =) constrs consts;
haftmann@36470
   156
    val _ = if null false_constrs then []
haftmann@36470
   157
      else error ("Non-constructor(s) " ^ commas (map quote false_constrs)
haftmann@36470
   158
        ^ " for datatype " ^ quote tyco);
haftmann@36470
   159
  in () end;
haftmann@36470
   160
haftmann@36470
   161
fun add_eval_tyco (tyco, tyco') thy =
haftmann@36470
   162
  let
haftmann@36470
   163
    val k = Sign.arity_number thy tyco;
haftmann@36470
   164
    fun pr pr' fxy [] = tyco'
haftmann@36470
   165
      | pr pr' fxy [ty] =
haftmann@36470
   166
          Code_Printer.concat [pr' Code_Printer.BR ty, tyco']
haftmann@36470
   167
      | pr pr' fxy tys =
haftmann@36470
   168
          Code_Printer.concat [Code_Printer.enum "," "(" ")" (map (pr' Code_Printer.BR) tys), tyco']
haftmann@36470
   169
  in
haftmann@36470
   170
    thy
haftmann@36470
   171
    |> Code_Target.add_syntax_tyco target tyco (SOME (k, pr))
haftmann@36470
   172
  end;
haftmann@36470
   173
haftmann@36470
   174
fun add_eval_const (const, const') = Code_Target.add_syntax_const target
haftmann@36470
   175
  const (SOME (Code_Printer.simple_const_syntax (0, (K o K o K) const')));
haftmann@36470
   176
haftmann@36470
   177
fun process (code_body, (tyco_map, const_map)) module_name NONE thy =
haftmann@36470
   178
      let
haftmann@36470
   179
        val pr = Code_Printer.str o Long_Name.append module_name;
haftmann@36470
   180
      in
haftmann@36470
   181
        thy
haftmann@36470
   182
        |> Code_Target.add_reserved target module_name
haftmann@36470
   183
        |> Context.theory_map (ML_Context.exec (fn () => ML_Context.eval true Position.none code_body))
haftmann@36470
   184
        |> fold (add_eval_tyco o apsnd pr) tyco_map
haftmann@36470
   185
        |> fold (add_eval_const o apsnd pr) const_map
haftmann@36470
   186
      end
haftmann@36470
   187
  | process (code_body, _) _ (SOME file_name) thy =
haftmann@36470
   188
      let
haftmann@36470
   189
        val preamble = "(* Generated from " ^ Path.implode (ThyLoad.thy_path (Context.theory_name thy))
haftmann@36470
   190
          ^ "; DO NOT EDIT! *)";
haftmann@36470
   191
        val _ = File.write (Path.explode file_name) (preamble ^ "\n\n" ^ code_body);
haftmann@36470
   192
      in
haftmann@36470
   193
        thy
haftmann@36470
   194
      end;
haftmann@36470
   195
haftmann@36470
   196
fun gen_code_reflect prep_type prep_const raw_datatypes raw_functions module_name some_file thy  =
haftmann@36470
   197
  let
haftmann@36470
   198
    val datatypes = map (fn (raw_tyco, raw_cos) =>
haftmann@36470
   199
      (prep_type thy raw_tyco, map (prep_const thy) raw_cos)) raw_datatypes;
haftmann@36470
   200
    val functions = map (prep_const thy) raw_functions;
haftmann@36470
   201
    val _ = map (uncurry (check_datatype thy)) datatypes;
haftmann@36470
   202
  in
haftmann@36470
   203
    thy
haftmann@36470
   204
    |> process (evaluation_code thy module_name (map fst datatypes) (maps snd datatypes @ functions)) module_name some_file
haftmann@36470
   205
  end;
haftmann@36470
   206
haftmann@36470
   207
val code_reflect = gen_code_reflect Code_Target.cert_tyco Code.check_const;
haftmann@36470
   208
val code_reflect_cmd = gen_code_reflect Code_Target.read_tyco Code.read_const;
haftmann@36470
   209
haftmann@36470
   210
haftmann@28054
   211
(** Isar setup **)
haftmann@28054
   212
haftmann@28054
   213
val _ = ML_Context.add_antiq "code" (fn _ => Args.term >> ml_code_antiq);
haftmann@30962
   214
val _ = ML_Context.add_antiq "code_datatype" (fn _ =>
wenzelm@35360
   215
  (Args.type_name true --| Scan.lift (Args.$$$ "=")
haftmann@30962
   216
    -- (Args.term ::: Scan.repeat (Scan.lift (Args.$$$ "|") |-- Args.term)))
haftmann@30962
   217
      >> ml_code_datatype_antiq);
haftmann@28054
   218
haftmann@36470
   219
local
haftmann@36470
   220
haftmann@36470
   221
structure P = OuterParse
haftmann@36470
   222
and K = OuterKeyword
haftmann@36470
   223
haftmann@36470
   224
val datatypesK = "datatypes";
haftmann@36470
   225
val functionsK = "functions";
haftmann@36470
   226
val module_nameK = "module_name";
haftmann@36470
   227
val fileK = "file";
haftmann@36470
   228
val andK = "and"
haftmann@36470
   229
haftmann@36470
   230
val _ = List.app K.keyword [datatypesK, functionsK];
haftmann@36470
   231
haftmann@36470
   232
val parse_datatype = (P.name --| P.$$$ "=" -- (P.term ::: (Scan.repeat (P.$$$ "|" |-- P.term))));
haftmann@36470
   233
haftmann@36470
   234
in
haftmann@36470
   235
haftmann@36470
   236
val _ =
haftmann@36470
   237
  OuterSyntax.command "code_reflect" "enrich runtime environment with generated code"
haftmann@36470
   238
    K.thy_decl (Scan.optional (P.$$$ datatypesK |-- (parse_datatype
haftmann@36470
   239
      ::: Scan.repeat (P.$$$ andK |-- parse_datatype))) []
haftmann@36470
   240
    -- Scan.optional (P.$$$ functionsK |-- Scan.repeat1 P.name) []
haftmann@36470
   241
    --| P.$$$ module_nameK -- P.name
haftmann@36470
   242
    -- Scan.option (P.$$$ fileK |-- P.name)
haftmann@36470
   243
  >> (fn (((raw_datatypes, raw_functions), module_name), some_file) => Toplevel.theory
haftmann@36470
   244
    (code_reflect_cmd raw_datatypes raw_functions module_name some_file)));
haftmann@36470
   245
haftmann@36470
   246
end; (*local*)
haftmann@36470
   247
haftmann@34028
   248
val setup = Code_Target.extend_target (target, (Code_ML.target_SML, K I));
haftmann@28054
   249
haftmann@28054
   250
end; (*struct*)