src/HOL/Code_Eval.thy
author huffman
Sat Jun 06 09:11:12 2009 -0700 (2009-06-06)
changeset 31488 5691ccb8d6b5
parent 31205 98370b26c2ce
child 31594 a94aa5f045fb
permissions -rw-r--r--
generalize tendsto to class topological_space
     1 (*  Title:      HOL/Code_Eval.thy
     2     Author:     Florian Haftmann, TU Muenchen
     3 *)
     4 
     5 header {* Term evaluation using the generic code generator *}
     6 
     7 theory Code_Eval
     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 inline]:
    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 setup {*
    43 let
    44   fun add_term_of tyco raw_vs thy =
    45     let
    46       val vs = map (fn (v, _) => (v, @{sort typerep})) raw_vs;
    47       val ty = Type (tyco, map TFree vs);
    48       val lhs = Const (@{const_name term_of}, ty --> @{typ term})
    49         $ Free ("x", ty);
    50       val rhs = @{term "undefined \<Colon> term"};
    51       val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
    52       fun triv_name_of t = (fst o dest_Free o fst o strip_comb o fst
    53         o HOLogic.dest_eq o HOLogic.dest_Trueprop) t ^ "_triv";
    54     in
    55       thy
    56       |> TheoryTarget.instantiation ([tyco], vs, @{sort term_of})
    57       |> `(fn lthy => Syntax.check_term lthy eq)
    58       |-> (fn eq => Specification.definition (NONE, ((Binding.name (triv_name_of eq), []), eq)))
    59       |> snd
    60       |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
    61     end;
    62   fun ensure_term_of (tyco, (raw_vs, _)) thy =
    63     let
    64       val need_inst = not (can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort term_of})
    65         andalso can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort typerep};
    66     in if need_inst then add_term_of tyco raw_vs thy else thy end;
    67 in
    68   Code.type_interpretation ensure_term_of
    69 end
    70 *}
    71 
    72 setup {*
    73 let
    74   fun mk_term_of_eq thy ty vs tyco (c, tys) =
    75     let
    76       val t = list_comb (Const (c, tys ---> ty),
    77         map Free (Name.names Name.context "a" tys));
    78       val (arg, rhs) = pairself (Thm.cterm_of thy o map_types Logic.unvarifyT o Logic.varify)
    79         (t, (map_aterms (fn t as Free (v, ty) => HOLogic.mk_term_of ty t | t => t) o HOLogic.reflect_term) t)
    80       val cty = Thm.ctyp_of thy ty;
    81     in
    82       @{thm term_of_anything}
    83       |> Drule.instantiate' [SOME cty] [SOME arg, SOME rhs]
    84       |> Thm.varifyT
    85     end;
    86   fun add_term_of_code tyco raw_vs raw_cs thy =
    87     let
    88       val vs = map (fn (v, _) => (v, @{sort typerep})) raw_vs;
    89       val ty = Type (tyco, map TFree vs);
    90       val cs = (map o apsnd o map o map_atyps)
    91         (fn TFree (v, _) => TFree (v, (the o AList.lookup (op =) vs) v)) raw_cs;
    92       val const = AxClass.param_of_inst thy (@{const_name term_of}, tyco);
    93       val eqs = map (mk_term_of_eq thy ty vs tyco) cs;
    94    in
    95       thy
    96       |> Code.del_eqns const
    97       |> fold Code.add_eqn eqs
    98     end;
    99   fun ensure_term_of_code (tyco, (raw_vs, cs)) thy =
   100     let
   101       val has_inst = can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort term_of};
   102     in if has_inst then add_term_of_code tyco raw_vs cs thy else thy end;
   103 in
   104   Code.type_interpretation ensure_term_of_code
   105 end
   106 *}
   107 
   108 
   109 subsubsection {* Code generator setup *}
   110 
   111 lemmas [code del] = term.recs term.cases term.size
   112 lemma [code, code del]: "eq_class.eq (t1\<Colon>term) t2 \<longleftrightarrow> eq_class.eq t1 t2" ..
   113 
   114 lemma [code, code del]: "(term_of \<Colon> typerep \<Rightarrow> term) = term_of" ..
   115 lemma [code, code del]: "(term_of \<Colon> term \<Rightarrow> term) = term_of" ..
   116 lemma [code, code del]: "(term_of \<Colon> String.literal \<Rightarrow> term) = term_of" ..
   117 lemma [code, code del]:
   118   "(Code_Eval.term_of \<Colon> 'a::{type, term_of} Predicate.pred \<Rightarrow> Code_Eval.term) = Code_Eval.term_of" ..
   119 lemma [code, code del]:
   120   "(Code_Eval.term_of \<Colon> 'a::{type, term_of} Predicate.seq \<Rightarrow> Code_Eval.term) = Code_Eval.term_of" ..
   121 
   122 lemma term_of_char [unfolded typerep_fun_def typerep_char_def typerep_nibble_def, code]: "Code_Eval.term_of c =
   123     (let (n, m) = nibble_pair_of_char c
   124   in Code_Eval.App (Code_Eval.App (Code_Eval.Const (STR ''Pair'') (TYPEREP(nibble \<Rightarrow> nibble \<Rightarrow> char)))
   125     (Code_Eval.term_of n)) (Code_Eval.term_of m))"
   126   by (subst term_of_anything) rule 
   127 
   128 code_type "term"
   129   (Eval "Term.term")
   130 
   131 code_const Const and App
   132   (Eval "Term.Const/ (_, _)" and "Term.$/ (_, _)")
   133 
   134 code_const "term_of \<Colon> String.literal \<Rightarrow> term"
   135   (Eval "HOLogic.mk'_message'_string")
   136 
   137 code_reserved Eval HOLogic
   138 
   139 
   140 subsubsection {* Syntax *}
   141 
   142 definition termify :: "'a \<Rightarrow> term" where
   143   [code del]: "termify x = dummy_term"
   144 
   145 abbreviation valtermify :: "'a \<Rightarrow> 'a \<times> (unit \<Rightarrow> term)" where
   146   "valtermify x \<equiv> (x, \<lambda>u. termify x)"
   147 
   148 setup {*
   149 let
   150   fun map_default f xs =
   151     let val ys = map f xs
   152     in if exists is_some ys
   153       then SOME (map2 the_default xs ys)
   154       else NONE
   155     end;
   156   fun subst_termify_app (Const (@{const_name termify}, T), [t]) =
   157         if not (Term.has_abs t)
   158         then if fold_aterms (fn Const _ => I | _ => K false) t true
   159           then SOME (HOLogic.reflect_term t)
   160           else error "Cannot termify expression containing variables"
   161         else error "Cannot termify expression containing abstraction"
   162     | subst_termify_app (t, ts) = case map_default subst_termify ts
   163        of SOME ts' => SOME (list_comb (t, ts'))
   164         | NONE => NONE
   165   and subst_termify (Abs (v, T, t)) = (case subst_termify t
   166        of SOME t' => SOME (Abs (v, T, t'))
   167         | NONE => NONE)
   168     | subst_termify t = subst_termify_app (strip_comb t) 
   169   fun check_termify ts ctxt = map_default subst_termify ts
   170     |> Option.map (rpair ctxt)
   171 in
   172   Context.theory_map (Syntax.add_term_check 0 "termify" check_termify)
   173 end;
   174 *}
   175 
   176 locale term_syntax
   177 begin
   178 
   179 notation App (infixl "<\<cdot>>" 70)
   180   and valapp (infixl "{\<cdot>}" 70)
   181 
   182 end
   183 
   184 interpretation term_syntax .
   185 
   186 no_notation App (infixl "<\<cdot>>" 70)
   187   and valapp (infixl "{\<cdot>}" 70)
   188 
   189 
   190 subsection {* Numeric types *}
   191 
   192 definition term_of_num :: "'a\<Colon>{semiring_div} \<Rightarrow> 'a\<Colon>{semiring_div} \<Rightarrow> term" where
   193   "term_of_num two = (\<lambda>_. dummy_term)"
   194 
   195 lemma (in term_syntax) term_of_num_code [code]:
   196   "term_of_num two k = (if k = 0 then termify Int.Pls
   197     else (if k mod two = 0
   198       then termify Int.Bit0 <\<cdot>> term_of_num two (k div two)
   199       else termify Int.Bit1 <\<cdot>> term_of_num two (k div two)))"
   200   by (auto simp add: term_of_anything Const_def App_def term_of_num_def Let_def)
   201 
   202 lemma (in term_syntax) term_of_nat_code [code]:
   203   "term_of (n::nat) = termify (number_of :: int \<Rightarrow> nat) <\<cdot>> term_of_num (2::nat) n"
   204   by (simp only: term_of_anything)
   205 
   206 lemma (in term_syntax) term_of_int_code [code]:
   207   "term_of (k::int) = (if k = 0 then termify (0 :: int)
   208     else if k > 0 then termify (number_of :: int \<Rightarrow> int) <\<cdot>> term_of_num (2::int) k
   209       else termify (uminus :: int \<Rightarrow> int) <\<cdot>> (termify (number_of :: int \<Rightarrow> int) <\<cdot>> term_of_num (2::int) (- k)))"
   210   by (simp only: term_of_anything)
   211 
   212 lemma (in term_syntax) term_of_code_numeral_code [code]:
   213   "term_of (k::code_numeral) = termify (number_of :: int \<Rightarrow> code_numeral) <\<cdot>> term_of_num (2::code_numeral) k"
   214   by (simp only: term_of_anything)
   215 
   216 subsection {* Obfuscate *}
   217 
   218 print_translation {*
   219 let
   220   val term = Const ("<TERM>", dummyT);
   221   fun tr1' [_, _] = term;
   222   fun tr2' [] = term;
   223 in
   224   [(@{const_syntax Const}, tr1'),
   225     (@{const_syntax App}, tr1'),
   226     (@{const_syntax dummy_term}, tr2')]
   227 end
   228 *}
   229 
   230 hide const dummy_term App valapp
   231 hide (open) const Const termify valtermify term_of term_of_num
   232 
   233 
   234 subsection {* Evaluation setup *}
   235 
   236 ML {*
   237 signature EVAL =
   238 sig
   239   val eval_ref: (unit -> term) option ref
   240   val eval_term: theory -> term -> term
   241 end;
   242 
   243 structure Eval : EVAL =
   244 struct
   245 
   246 val eval_ref = ref (NONE : (unit -> term) option);
   247 
   248 fun eval_term thy t =
   249   Code_ML.eval NONE ("Eval.eval_ref", eval_ref) I thy (HOLogic.mk_term_of (fastype_of t) t) [];
   250 
   251 end;
   252 *}
   253 
   254 setup {*
   255   Value.add_evaluator ("code", Eval.eval_term o ProofContext.theory_of)
   256 *}
   257 
   258 end