src/HOL/Code_Evaluation.thy
author haftmann
Wed Sep 15 15:31:32 2010 +0200 (2010-09-15)
changeset 39401 887f4218a39a
parent 39387 6608c4838ff9
child 39403 aad9f3cfa1d9
permissions -rw-r--r--
code_eval renamed to code_runtime
haftmann@32657
     1
(*  Title:      HOL/Code_Evaluation.thy
haftmann@28228
     2
    Author:     Florian Haftmann, TU Muenchen
haftmann@28228
     3
*)
haftmann@28228
     4
haftmann@28228
     5
header {* Term evaluation using the generic code generator *}
haftmann@28228
     6
haftmann@32657
     7
theory Code_Evaluation
haftmann@31205
     8
imports Plain Typerep Code_Numeral
haftmann@28228
     9
begin
haftmann@28228
    10
haftmann@28228
    11
subsection {* Term representation *}
haftmann@28228
    12
haftmann@28228
    13
subsubsection {* Terms and class @{text term_of} *}
haftmann@28228
    14
haftmann@28228
    15
datatype "term" = dummy_term
haftmann@28228
    16
haftmann@31205
    17
definition Const :: "String.literal \<Rightarrow> typerep \<Rightarrow> term" where
haftmann@28228
    18
  "Const _ _ = dummy_term"
haftmann@28228
    19
haftmann@28661
    20
definition App :: "term \<Rightarrow> term \<Rightarrow> term" where
haftmann@28228
    21
  "App _ _ = dummy_term"
haftmann@28228
    22
haftmann@28228
    23
code_datatype Const App
haftmann@28228
    24
haftmann@28335
    25
class term_of = typerep +
haftmann@31031
    26
  fixes term_of :: "'a \<Rightarrow> term"
haftmann@28228
    27
haftmann@28228
    28
lemma term_of_anything: "term_of x \<equiv> t"
haftmann@28228
    29
  by (rule eq_reflection) (cases "term_of x", cases t, simp)
haftmann@28228
    30
haftmann@31191
    31
definition valapp :: "('a \<Rightarrow> 'b) \<times> (unit \<Rightarrow> term)
haftmann@31178
    32
  \<Rightarrow> 'a \<times> (unit \<Rightarrow> term) \<Rightarrow> 'b \<times> (unit \<Rightarrow> term)" where
haftmann@31191
    33
  "valapp f x = (fst f (fst x), \<lambda>u. App (snd f ()) (snd x ()))"
haftmann@31178
    34
haftmann@32069
    35
lemma valapp_code [code, code_unfold]:
haftmann@31191
    36
  "valapp (f, tf) (x, tx) = (f x, \<lambda>u. App (tf ()) (tx ()))"
haftmann@31191
    37
  by (simp only: valapp_def fst_conv snd_conv)
haftmann@31178
    38
haftmann@28228
    39
haftmann@28228
    40
subsubsection {* @{text term_of} instances *}
haftmann@28228
    41
haftmann@32344
    42
instantiation "fun" :: (typerep, typerep) term_of
haftmann@32344
    43
begin
haftmann@32344
    44
haftmann@32344
    45
definition
haftmann@32344
    46
  "term_of (f \<Colon> 'a \<Rightarrow> 'b) = Const (STR ''dummy_pattern'') (Typerep.Typerep (STR ''fun'')
haftmann@32344
    47
     [Typerep.typerep TYPE('a), Typerep.typerep TYPE('b)])"
haftmann@32344
    48
haftmann@32344
    49
instance ..
haftmann@32344
    50
haftmann@32344
    51
end
haftmann@32344
    52
haftmann@28228
    53
setup {*
haftmann@28228
    54
let
haftmann@31139
    55
  fun add_term_of tyco raw_vs thy =
haftmann@28228
    56
    let
haftmann@31139
    57
      val vs = map (fn (v, _) => (v, @{sort typerep})) raw_vs;
haftmann@31139
    58
      val ty = Type (tyco, map TFree vs);
haftmann@28228
    59
      val lhs = Const (@{const_name term_of}, ty --> @{typ term})
haftmann@28228
    60
        $ Free ("x", ty);
haftmann@28228
    61
      val rhs = @{term "undefined \<Colon> term"};
haftmann@28228
    62
      val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
haftmann@28243
    63
      fun triv_name_of t = (fst o dest_Free o fst o strip_comb o fst
haftmann@28243
    64
        o HOLogic.dest_eq o HOLogic.dest_Trueprop) t ^ "_triv";
haftmann@28228
    65
    in
haftmann@28228
    66
      thy
haftmann@38348
    67
      |> Class.instantiation ([tyco], vs, @{sort term_of})
haftmann@28228
    68
      |> `(fn lthy => Syntax.check_term lthy eq)
haftmann@28965
    69
      |-> (fn eq => Specification.definition (NONE, ((Binding.name (triv_name_of eq), []), eq)))
haftmann@28228
    70
      |> snd
haftmann@31139
    71
      |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
haftmann@28228
    72
    end;
haftmann@31139
    73
  fun ensure_term_of (tyco, (raw_vs, _)) thy =
haftmann@31139
    74
    let
haftmann@31139
    75
      val need_inst = not (can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort term_of})
haftmann@31139
    76
        andalso can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort typerep};
haftmann@31205
    77
    in if need_inst then add_term_of tyco raw_vs thy else thy end;
haftmann@28228
    78
in
haftmann@35299
    79
  Code.datatype_interpretation ensure_term_of
haftmann@35299
    80
  #> Code.abstype_interpretation ensure_term_of
haftmann@28228
    81
end
haftmann@28228
    82
*}
haftmann@28228
    83
haftmann@28228
    84
setup {*
haftmann@28228
    85
let
haftmann@31139
    86
  fun mk_term_of_eq thy ty vs tyco (c, tys) =
haftmann@28228
    87
    let
haftmann@28228
    88
      val t = list_comb (Const (c, tys ---> ty),
haftmann@28228
    89
        map Free (Name.names Name.context "a" tys));
wenzelm@35845
    90
      val (arg, rhs) =
wenzelm@35845
    91
        pairself (Thm.cterm_of thy o map_types Logic.unvarifyT_global o Logic.varify_global)
wenzelm@35845
    92
          (t, (map_aterms (fn t as Free (v, ty) => HOLogic.mk_term_of ty t | t => t) o HOLogic.reflect_term) t)
haftmann@31139
    93
      val cty = Thm.ctyp_of thy ty;
haftmann@31139
    94
    in
haftmann@31139
    95
      @{thm term_of_anything}
haftmann@31139
    96
      |> Drule.instantiate' [SOME cty] [SOME arg, SOME rhs]
wenzelm@35845
    97
      |> Thm.varifyT_global
haftmann@28228
    98
    end;
haftmann@31139
    99
  fun add_term_of_code tyco raw_vs raw_cs thy =
haftmann@28228
   100
    let
haftmann@31746
   101
      val algebra = Sign.classes_of thy;
haftmann@31746
   102
      val vs = map (fn (v, sort) =>
haftmann@31746
   103
        (v, curry (Sorts.inter_sort algebra) @{sort typerep} sort)) raw_vs;
haftmann@31139
   104
      val ty = Type (tyco, map TFree vs);
haftmann@31139
   105
      val cs = (map o apsnd o map o map_atyps)
haftmann@31139
   106
        (fn TFree (v, _) => TFree (v, (the o AList.lookup (op =) vs) v)) raw_cs;
haftmann@31139
   107
      val const = AxClass.param_of_inst thy (@{const_name term_of}, tyco);
haftmann@31139
   108
      val eqs = map (mk_term_of_eq thy ty vs tyco) cs;
haftmann@31139
   109
   in
haftmann@31139
   110
      thy
haftmann@31139
   111
      |> Code.del_eqns const
haftmann@31139
   112
      |> fold Code.add_eqn eqs
haftmann@31139
   113
    end;
haftmann@31139
   114
  fun ensure_term_of_code (tyco, (raw_vs, cs)) thy =
haftmann@31139
   115
    let
haftmann@31139
   116
      val has_inst = can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort term_of};
haftmann@31205
   117
    in if has_inst then add_term_of_code tyco raw_vs cs thy else thy end;
haftmann@28228
   118
in
haftmann@35299
   119
  Code.datatype_interpretation ensure_term_of_code
haftmann@28228
   120
end
haftmann@28228
   121
*}
haftmann@28228
   122
haftmann@35366
   123
setup {*
haftmann@35366
   124
let
haftmann@35366
   125
  fun mk_term_of_eq thy ty vs tyco abs ty_rep proj =
haftmann@35366
   126
    let
haftmann@35366
   127
      val arg = Var (("x", 0), ty);
haftmann@35366
   128
      val rhs = Abs ("y", @{typ term}, HOLogic.reflect_term (Const (abs, ty_rep --> ty) $ Bound 0)) $
haftmann@35366
   129
        (HOLogic.mk_term_of ty_rep (Const (proj, ty --> ty_rep) $ arg))
haftmann@35366
   130
        |> Thm.cterm_of thy;
haftmann@35366
   131
      val cty = Thm.ctyp_of thy ty;
haftmann@35366
   132
    in
haftmann@35366
   133
      @{thm term_of_anything}
haftmann@35366
   134
      |> Drule.instantiate' [SOME cty] [SOME (Thm.cterm_of thy arg), SOME rhs]
wenzelm@35845
   135
      |> Thm.varifyT_global
haftmann@35366
   136
    end;
haftmann@35366
   137
  fun add_term_of_code tyco raw_vs abs raw_ty_rep proj thy =
haftmann@35366
   138
    let
haftmann@35366
   139
      val algebra = Sign.classes_of thy;
haftmann@35366
   140
      val vs = map (fn (v, sort) =>
haftmann@35366
   141
        (v, curry (Sorts.inter_sort algebra) @{sort typerep} sort)) raw_vs;
haftmann@35366
   142
      val ty = Type (tyco, map TFree vs);
haftmann@35366
   143
      val ty_rep = map_atyps
haftmann@35366
   144
        (fn TFree (v, _) => TFree (v, (the o AList.lookup (op =) vs) v)) raw_ty_rep;
haftmann@35366
   145
      val const = AxClass.param_of_inst thy (@{const_name term_of}, tyco);
haftmann@35366
   146
      val eq = mk_term_of_eq thy ty vs tyco abs ty_rep proj;
haftmann@35366
   147
   in
haftmann@35366
   148
      thy
haftmann@35366
   149
      |> Code.del_eqns const
haftmann@35366
   150
      |> Code.add_eqn eq
haftmann@35366
   151
    end;
haftmann@35366
   152
  fun ensure_term_of_code (tyco, (raw_vs, ((abs, ty), (proj, _)))) thy =
haftmann@35366
   153
    let
haftmann@35366
   154
      val has_inst = can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort term_of};
haftmann@35366
   155
    in if has_inst then add_term_of_code tyco raw_vs abs ty proj thy else thy end;
haftmann@35366
   156
in
haftmann@35366
   157
  Code.abstype_interpretation ensure_term_of_code
haftmann@35366
   158
end
haftmann@35366
   159
*}
haftmann@35366
   160
haftmann@28228
   161
bulwahn@39274
   162
instantiation String.literal :: term_of
bulwahn@39274
   163
begin
bulwahn@39274
   164
bulwahn@39274
   165
definition
bulwahn@39274
   166
  "term_of s = App (Const (STR ''STR'')
bulwahn@39274
   167
    (Typerep.Typerep (STR ''fun'') [Typerep.Typerep (STR ''list'') [Typerep.Typerep (STR ''char'') []],
bulwahn@39274
   168
      Typerep.Typerep (STR ''String.literal'') []])) (term_of (String.explode s))"
bulwahn@39274
   169
bulwahn@39274
   170
instance ..
bulwahn@39274
   171
bulwahn@39274
   172
end
bulwahn@39274
   173
haftmann@28228
   174
subsubsection {* Code generator setup *}
haftmann@28228
   175
haftmann@28562
   176
lemmas [code del] = term.recs term.cases term.size
haftmann@38857
   177
lemma [code, code del]: "HOL.equal (t1\<Colon>term) t2 \<longleftrightarrow> HOL.equal t1 t2" ..
haftmann@28228
   178
haftmann@28562
   179
lemma [code, code del]: "(term_of \<Colon> typerep \<Rightarrow> term) = term_of" ..
haftmann@28562
   180
lemma [code, code del]: "(term_of \<Colon> term \<Rightarrow> term) = term_of" ..
haftmann@31205
   181
lemma [code, code del]: "(term_of \<Colon> String.literal \<Rightarrow> term) = term_of" ..
haftmann@30427
   182
lemma [code, code del]:
haftmann@32657
   183
  "(Code_Evaluation.term_of \<Colon> 'a::{type, term_of} Predicate.pred \<Rightarrow> Code_Evaluation.term) = Code_Evaluation.term_of" ..
haftmann@30427
   184
lemma [code, code del]:
haftmann@32657
   185
  "(Code_Evaluation.term_of \<Colon> 'a::{type, term_of} Predicate.seq \<Rightarrow> Code_Evaluation.term) = Code_Evaluation.term_of" ..
haftmann@28228
   186
haftmann@32657
   187
lemma term_of_char [unfolded typerep_fun_def typerep_char_def typerep_nibble_def, code]: "Code_Evaluation.term_of c =
haftmann@28243
   188
    (let (n, m) = nibble_pair_of_char c
haftmann@32657
   189
  in Code_Evaluation.App (Code_Evaluation.App (Code_Evaluation.Const (STR ''String.char.Char'') (TYPEREP(nibble \<Rightarrow> nibble \<Rightarrow> char)))
haftmann@32657
   190
    (Code_Evaluation.term_of n)) (Code_Evaluation.term_of m))"
haftmann@28243
   191
  by (subst term_of_anything) rule 
haftmann@28243
   192
haftmann@28228
   193
code_type "term"
haftmann@31031
   194
  (Eval "Term.term")
haftmann@28228
   195
haftmann@28228
   196
code_const Const and App
haftmann@31594
   197
  (Eval "Term.Const/ ((_), (_))" and "Term.$/ ((_), (_))")
haftmann@28228
   198
haftmann@31205
   199
code_const "term_of \<Colon> String.literal \<Rightarrow> term"
haftmann@33632
   200
  (Eval "HOLogic.mk'_literal")
haftmann@31048
   201
haftmann@31048
   202
code_reserved Eval HOLogic
haftmann@28228
   203
haftmann@28228
   204
haftmann@31178
   205
subsubsection {* Syntax *}
haftmann@31178
   206
haftmann@31191
   207
definition termify :: "'a \<Rightarrow> term" where
haftmann@31191
   208
  [code del]: "termify x = dummy_term"
haftmann@31191
   209
haftmann@31191
   210
abbreviation valtermify :: "'a \<Rightarrow> 'a \<times> (unit \<Rightarrow> term)" where
haftmann@31191
   211
  "valtermify x \<equiv> (x, \<lambda>u. termify x)"
haftmann@31178
   212
haftmann@31178
   213
setup {*
haftmann@31178
   214
let
haftmann@31178
   215
  fun map_default f xs =
haftmann@31178
   216
    let val ys = map f xs
haftmann@31178
   217
    in if exists is_some ys
haftmann@31178
   218
      then SOME (map2 the_default xs ys)
haftmann@31178
   219
      else NONE
haftmann@31178
   220
    end;
haftmann@31178
   221
  fun subst_termify_app (Const (@{const_name termify}, T), [t]) =
haftmann@31178
   222
        if not (Term.has_abs t)
haftmann@31178
   223
        then if fold_aterms (fn Const _ => I | _ => K false) t true
haftmann@31191
   224
          then SOME (HOLogic.reflect_term t)
haftmann@31178
   225
          else error "Cannot termify expression containing variables"
haftmann@31178
   226
        else error "Cannot termify expression containing abstraction"
haftmann@31178
   227
    | subst_termify_app (t, ts) = case map_default subst_termify ts
haftmann@31178
   228
       of SOME ts' => SOME (list_comb (t, ts'))
haftmann@31178
   229
        | NONE => NONE
haftmann@31178
   230
  and subst_termify (Abs (v, T, t)) = (case subst_termify t
haftmann@31178
   231
       of SOME t' => SOME (Abs (v, T, t'))
haftmann@31178
   232
        | NONE => NONE)
haftmann@31178
   233
    | subst_termify t = subst_termify_app (strip_comb t) 
haftmann@31178
   234
  fun check_termify ts ctxt = map_default subst_termify ts
haftmann@31178
   235
    |> Option.map (rpair ctxt)
haftmann@31178
   236
in
haftmann@31178
   237
  Context.theory_map (Syntax.add_term_check 0 "termify" check_termify)
haftmann@31178
   238
end;
haftmann@31178
   239
*}
haftmann@31178
   240
haftmann@31178
   241
locale term_syntax
haftmann@31178
   242
begin
haftmann@31178
   243
haftmann@31191
   244
notation App (infixl "<\<cdot>>" 70)
haftmann@31191
   245
  and valapp (infixl "{\<cdot>}" 70)
haftmann@31178
   246
haftmann@31178
   247
end
haftmann@31178
   248
haftmann@31178
   249
interpretation term_syntax .
haftmann@31178
   250
haftmann@31191
   251
no_notation App (infixl "<\<cdot>>" 70)
haftmann@31191
   252
  and valapp (infixl "{\<cdot>}" 70)
haftmann@31191
   253
haftmann@31191
   254
haftmann@31191
   255
subsection {* Numeric types *}
haftmann@31191
   256
haftmann@31191
   257
definition term_of_num :: "'a\<Colon>{semiring_div} \<Rightarrow> 'a\<Colon>{semiring_div} \<Rightarrow> term" where
haftmann@31191
   258
  "term_of_num two = (\<lambda>_. dummy_term)"
haftmann@31191
   259
haftmann@31191
   260
lemma (in term_syntax) term_of_num_code [code]:
haftmann@31191
   261
  "term_of_num two k = (if k = 0 then termify Int.Pls
haftmann@31191
   262
    else (if k mod two = 0
haftmann@31191
   263
      then termify Int.Bit0 <\<cdot>> term_of_num two (k div two)
haftmann@31191
   264
      else termify Int.Bit1 <\<cdot>> term_of_num two (k div two)))"
haftmann@31191
   265
  by (auto simp add: term_of_anything Const_def App_def term_of_num_def Let_def)
haftmann@31191
   266
haftmann@31191
   267
lemma (in term_syntax) term_of_nat_code [code]:
haftmann@31191
   268
  "term_of (n::nat) = termify (number_of :: int \<Rightarrow> nat) <\<cdot>> term_of_num (2::nat) n"
haftmann@31191
   269
  by (simp only: term_of_anything)
haftmann@31191
   270
haftmann@31191
   271
lemma (in term_syntax) term_of_int_code [code]:
haftmann@31191
   272
  "term_of (k::int) = (if k = 0 then termify (0 :: int)
haftmann@31191
   273
    else if k > 0 then termify (number_of :: int \<Rightarrow> int) <\<cdot>> term_of_num (2::int) k
haftmann@31191
   274
      else termify (uminus :: int \<Rightarrow> int) <\<cdot>> (termify (number_of :: int \<Rightarrow> int) <\<cdot>> term_of_num (2::int) (- k)))"
haftmann@31191
   275
  by (simp only: term_of_anything)
haftmann@31191
   276
haftmann@31205
   277
lemma (in term_syntax) term_of_code_numeral_code [code]:
haftmann@31205
   278
  "term_of (k::code_numeral) = termify (number_of :: int \<Rightarrow> code_numeral) <\<cdot>> term_of_num (2::code_numeral) k"
haftmann@31203
   279
  by (simp only: term_of_anything)
haftmann@31191
   280
haftmann@39387
   281
haftmann@31191
   282
subsection {* Obfuscate *}
haftmann@31178
   283
haftmann@31178
   284
print_translation {*
haftmann@31178
   285
let
haftmann@31178
   286
  val term = Const ("<TERM>", dummyT);
haftmann@31178
   287
  fun tr1' [_, _] = term;
haftmann@31178
   288
  fun tr2' [] = term;
haftmann@31178
   289
in
haftmann@31178
   290
  [(@{const_syntax Const}, tr1'),
haftmann@31178
   291
    (@{const_syntax App}, tr1'),
haftmann@31178
   292
    (@{const_syntax dummy_term}, tr2')]
haftmann@31178
   293
end
haftmann@31178
   294
*}
haftmann@31178
   295
haftmann@31178
   296
haftmann@39387
   297
subsection {* Evaluation setup *}
bulwahn@33473
   298
bulwahn@33473
   299
ML {*
haftmann@39387
   300
signature CODE_EVALUATION =
haftmann@39387
   301
sig
haftmann@39387
   302
  val eval_term: theory -> term -> term
haftmann@39387
   303
  val put_term: (unit -> term) -> Proof.context -> Proof.context
haftmann@39387
   304
  val tracing: string -> 'a -> 'a
haftmann@39387
   305
end;
haftmann@39387
   306
haftmann@39387
   307
structure Code_Evaluation : CODE_EVALUATION =
bulwahn@33473
   308
struct
bulwahn@33473
   309
haftmann@39387
   310
structure Evaluation = Proof_Data (
haftmann@39387
   311
  type T = unit -> term
haftmann@39387
   312
  fun init _ () = error "Evaluation"
haftmann@39387
   313
);
haftmann@39387
   314
val put_term = Evaluation.put;
haftmann@39387
   315
haftmann@39387
   316
fun tracing s x = (Output.tracing s; x);
haftmann@39387
   317
haftmann@39401
   318
fun eval_term thy t = Code_Runtime.eval NONE (Evaluation.get, put_term, "Code_Evaluation.put_term")
haftmann@39387
   319
  I thy (HOLogic.mk_term_of (fastype_of t) t) [];
bulwahn@33473
   320
bulwahn@33473
   321
end
bulwahn@33473
   322
*}
bulwahn@33473
   323
haftmann@39387
   324
setup {*
haftmann@39387
   325
  Value.add_evaluator ("code", Code_Evaluation.eval_term o ProofContext.theory_of)
haftmann@39387
   326
*}
haftmann@39387
   327
haftmann@39387
   328
definition tracing :: "String.literal \<Rightarrow> 'a \<Rightarrow> 'a" where
haftmann@39387
   329
  [code del]: "tracing s x = x"
haftmann@39387
   330
bulwahn@33473
   331
code_const "tracing :: String.literal => 'a => 'a"
bulwahn@33473
   332
  (Eval "Code'_Evaluation.tracing")
bulwahn@33473
   333
bulwahn@33473
   334
code_reserved Eval Code_Evaluation
haftmann@31178
   335
haftmann@39387
   336
hide_const dummy_term App valapp
haftmann@39387
   337
hide_const (open) Const termify valtermify term_of term_of_num tracing
haftmann@28228
   338
haftmann@28228
   339
end