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