make reification part of HOL
authorhaftmann
Sun Jun 02 07:46:40 2013 +0200 (2013-06-02)
changeset 522868170e5327c02
parent 52285 da42b500a6aa
child 52287 7e54c4d964e7
make reification part of HOL
NEWS
src/HOL/Code_Evaluation.thy
src/HOL/Decision_Procs/Approximation.thy
src/HOL/Tools/reflection.ML
src/HOL/Tools/reification.ML
     1.1 --- a/NEWS	Sat Jun 01 14:26:04 2013 +0200
     1.2 +++ b/NEWS	Sun Jun 02 07:46:40 2013 +0200
     1.3 @@ -61,6 +61,12 @@
     1.4  
     1.5  *** HOL ***
     1.6  
     1.7 +* Reification and reflection:
     1.8 +  * Reification is now directly available in HOL-Main in structure "Reification".
     1.9 +  * Reflection now handles multiple lists with variables also.
    1.10 +  * The whole reflection stack has been decomposed into conversions.
    1.11 +INCOMPATIBILITY.
    1.12 +
    1.13  * Weaker precendence of syntax for big intersection and union on sets,
    1.14  in accordance with corresponding lattice operations.  INCOMPATIBILITY.
    1.15  
     2.1 --- a/src/HOL/Code_Evaluation.thy	Sat Jun 01 14:26:04 2013 +0200
     2.2 +++ b/src/HOL/Code_Evaluation.thy	Sun Jun 02 07:46:40 2013 +0200
     2.3 @@ -165,6 +165,11 @@
     2.4    (Eval "Code'_Evaluation.tracing")
     2.5  
     2.6  
     2.7 +subsection {* Generic reification *}
     2.8 +
     2.9 +ML_file "~~/src/HOL/Tools/reification.ML"
    2.10 +
    2.11 +
    2.12  hide_const dummy_term valapp
    2.13  hide_const (open) Const App Abs Free termify valtermify term_of tracing
    2.14  
     3.1 --- a/src/HOL/Decision_Procs/Approximation.thy	Sat Jun 01 14:26:04 2013 +0200
     3.2 +++ b/src/HOL/Decision_Procs/Approximation.thy	Sun Jun 02 07:46:40 2013 +0200
     3.3 @@ -7,7 +7,6 @@
     3.4  imports
     3.5    Complex_Main
     3.6    "~~/src/HOL/Library/Float"
     3.7 -  "~~/src/HOL/Library/Reflection"
     3.8    Dense_Linear_Order
     3.9    "~~/src/HOL/Library/Code_Target_Numeral"
    3.10  begin
    3.11 @@ -3533,7 +3532,7 @@
    3.12                        rtac @{thm impI}] i)
    3.13        THEN Subgoal.FOCUS (fn {prems, ...} => reorder_bounds_tac prems i) ctxt i
    3.14        THEN DETERM (TRY (filter_prems_tac (K false) i))
    3.15 -      THEN DETERM (Reflection.reify_tac ctxt form_equations NONE i)
    3.16 +      THEN DETERM (Reification.tac ctxt form_equations NONE i)
    3.17        THEN rewrite_interpret_form_tac ctxt prec splitting taylor i
    3.18        THEN gen_eval_tac (approximation_conv ctxt) ctxt i))
    3.19   *} "real number approximation"
    3.20 @@ -3633,7 +3632,7 @@
    3.21        THEN DETERM (TRY (filter_prems_tac (K false) 1)))
    3.22  
    3.23    fun reify_form ctxt term = apply_tactic ctxt term
    3.24 -     (Reflection.reify_tac ctxt form_equations NONE 1)
    3.25 +     (Reification.tac ctxt form_equations NONE 1)
    3.26  
    3.27    fun approx_form prec ctxt t =
    3.28            realify t
    3.29 @@ -3651,7 +3650,7 @@
    3.30  
    3.31    fun approx_arith prec ctxt t = realify t
    3.32         |> Thm.cterm_of (Proof_Context.theory_of ctxt)
    3.33 -       |> Reflection.reify ctxt form_equations
    3.34 +       |> Reification.conv ctxt form_equations
    3.35         |> prop_of
    3.36         |> Logic.dest_equals |> snd
    3.37         |> dest_interpret |> fst
     4.1 --- a/src/HOL/Tools/reflection.ML	Sat Jun 01 14:26:04 2013 +0200
     4.2 +++ b/src/HOL/Tools/reflection.ML	Sun Jun 02 07:46:40 2013 +0200
     4.3 @@ -1,13 +1,11 @@
     4.4  (*  Title:      HOL/Tools/reflection.ML
     4.5      Author:     Amine Chaieb, TU Muenchen
     4.6  
     4.7 -A trial for automatical reification.
     4.8 +A trial for automatical reflection with user-space declarations.
     4.9  *)
    4.10  
    4.11  signature REFLECTION =
    4.12  sig
    4.13 -  val reify: Proof.context -> thm list -> conv
    4.14 -  val reify_tac: Proof.context -> thm list -> term option -> int -> tactic
    4.15    val reflect: Proof.context -> thm list -> thm list -> conv
    4.16    val reflection_tac: Proof.context -> thm list -> thm list -> term option -> int -> tactic
    4.17    val reflect_with_eval: Proof.context -> thm list -> thm list -> conv -> conv
    4.18 @@ -24,293 +22,15 @@
    4.19  structure Reflection : REFLECTION =
    4.20  struct
    4.21  
    4.22 -fun dest_listT (Type (@{type_name "list"}, [T])) = T;
    4.23 -
    4.24 -val FWD = curry (op OF);
    4.25 -
    4.26 -fun rewrite_with ctxt eqs = Simplifier.rewrite (put_simpset HOL_basic_ss ctxt addsimps eqs);
    4.27 -
    4.28 -val pure_subst = @{lemma "x == y ==> PROP P y ==> PROP P x" by simp}
    4.29 -
    4.30 -fun lift_conv ctxt conv some_t = Subgoal.FOCUS (fn { concl, ... } =>
    4.31 -  let
    4.32 -    val ct = case some_t
    4.33 -     of NONE => Thm.dest_arg concl
    4.34 -      | SOME t => Thm.cterm_of (Proof_Context.theory_of ctxt) t
    4.35 -    val thm = conv ct;
    4.36 -  in
    4.37 -    if Thm.is_reflexive thm then no_tac
    4.38 -    else ALLGOALS (rtac (pure_subst OF [thm]))
    4.39 -  end) ctxt;
    4.40 -
    4.41 -(* Make a congruence rule out of a defining equation for the interpretation
    4.42 -
    4.43 -   th is one defining equation of f,
    4.44 -     i.e. th is "f (Cp ?t1 ... ?tn) = P(f ?t1, .., f ?tn)" 
    4.45 -   Cp is a constructor pattern and P is a pattern 
    4.46 -
    4.47 -   The result is:
    4.48 -     [|?A1 = f ?t1 ; .. ; ?An= f ?tn |] ==> P (?A1, .., ?An) = f (Cp ?t1 .. ?tn)
    4.49 -       + the a list of names of the A1 .. An, Those are fresh in the ctxt *)
    4.50 -
    4.51 -fun mk_congeq ctxt fs th =
    4.52 -  let
    4.53 -    val Const (fN, _) = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq
    4.54 -      |> fst |> strip_comb |> fst;
    4.55 -    val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
    4.56 -    val ((_, [th']), ctxt') = Variable.import true [th] ctxt;
    4.57 -    val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop (Thm.prop_of th'));
    4.58 -    fun add_fterms (t as t1 $ t2) =
    4.59 -          if exists (fn f => Term.could_unify (t |> strip_comb |> fst, f)) fs
    4.60 -          then insert (op aconv) t
    4.61 -          else add_fterms t1 #> add_fterms t2
    4.62 -      | add_fterms (t as Abs _) =
    4.63 -          if exists_Const (fn (c, _) => c = fN) t
    4.64 -          then K [t]
    4.65 -          else K []
    4.66 -      | add_fterms _ = I;
    4.67 -    val fterms = add_fterms rhs [];
    4.68 -    val (xs, ctxt'') = Variable.variant_fixes (replicate (length fterms) "x") ctxt';
    4.69 -    val tys = map fastype_of fterms;
    4.70 -    val vs = map Free (xs ~~ tys);
    4.71 -    val env = fterms ~~ vs; (*FIXME*)
    4.72 -    fun replace_fterms (t as t1 $ t2) =
    4.73 -        (case AList.lookup (op aconv) env t of
    4.74 -            SOME v => v
    4.75 -          | NONE => replace_fterms t1 $ replace_fterms t2)
    4.76 -      | replace_fterms t =
    4.77 -        (case AList.lookup (op aconv) env t of
    4.78 -            SOME v => v
    4.79 -          | NONE => t);
    4.80 -    fun mk_def (Abs (x, xT, t), v) =
    4.81 -          HOLogic.mk_Trueprop (HOLogic.all_const xT $ Abs (x, xT, HOLogic.mk_eq (v $ Bound 0, t)))
    4.82 -      | mk_def (t, v) = HOLogic.mk_Trueprop (HOLogic.mk_eq (v, t));
    4.83 -    fun tryext x =
    4.84 -      (x RS @{lemma "(\<forall>x. f x = g x) \<Longrightarrow> f = g" by blast} handle THM _ => x);
    4.85 -    val cong =
    4.86 -      (Goal.prove ctxt'' [] (map mk_def env)
    4.87 -        (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, replace_fterms rhs)))
    4.88 -        (fn {context, prems, ...} =>
    4.89 -          Local_Defs.unfold_tac context (map tryext prems) THEN rtac th' 1)) RS sym;
    4.90 -    val (cong' :: vars') =
    4.91 -      Variable.export ctxt'' ctxt (cong :: map (Drule.mk_term o cert) vs);
    4.92 -    val vs' = map (fst o fst o Term.dest_Var o Thm.term_of o Drule.dest_term) vars';
    4.93 -
    4.94 -  in (vs', cong') end;
    4.95 -
    4.96 -(* congs is a list of pairs (P,th) where th is a theorem for
    4.97 -     [| f p1 = A1; ...; f pn = An|] ==> f (C p1 .. pn) = P *)
    4.98 -
    4.99 -fun rearrange congs =
   4.100 -  let
   4.101 -    fun P (_, th) =
   4.102 -      let val @{term "Trueprop"} $ (Const (@{const_name HOL.eq}, _) $ l $ _) = concl_of th
   4.103 -      in can dest_Var l end;
   4.104 -    val (yes, no) = List.partition P congs;
   4.105 -  in no @ yes end;
   4.106 -
   4.107 -fun dereify ctxt eqs =
   4.108 -  rewrite_with ctxt (eqs @ @{thms nth_Cons_0 nth_Cons_Suc});
   4.109 -
   4.110 -fun reify ctxt eqs ct =
   4.111 -  let
   4.112 -    fun index_of t bds =
   4.113 -      let
   4.114 -        val tt = HOLogic.listT (fastype_of t);
   4.115 -      in
   4.116 -        (case AList.lookup Type.could_unify bds tt of
   4.117 -            NONE => error "index_of: type not found in environements!"
   4.118 -          | SOME (tbs, tats) =>
   4.119 -              let
   4.120 -                val i = find_index (fn t' => t' = t) tats;
   4.121 -                val j = find_index (fn t' => t' = t) tbs;
   4.122 -              in
   4.123 -                if j = ~1 then
   4.124 -                  if i = ~1
   4.125 -                  then (length tbs + length tats, AList.update Type.could_unify (tt, (tbs, tats @ [t])) bds)
   4.126 -                  else (i, bds)
   4.127 -                else (j, bds)
   4.128 -              end)
   4.129 -      end;
   4.130 -
   4.131 -    (* Generic decomp for reification : matches the actual term with the
   4.132 -       rhs of one cong rule. The result of the matching guides the
   4.133 -       proof synthesis: The matches of the introduced Variables A1 .. An are
   4.134 -       processed recursively
   4.135 -       The rest is instantiated in the cong rule,i.e. no reification is needed *)
   4.136 -
   4.137 -    (* da is the decomposition for atoms, ie. it returns ([],g) where g
   4.138 -       returns the right instance f (AtC n) = t , where AtC is the Atoms
   4.139 -       constructor and n is the number of the atom corresponding to t *)
   4.140 -    fun decomp_reify da cgns (ct, ctxt) bds =
   4.141 -      let
   4.142 -        val thy = Proof_Context.theory_of ctxt;
   4.143 -        val cert = cterm_of thy;
   4.144 -        val certT = ctyp_of thy;
   4.145 -        fun tryabsdecomp (ct, ctxt) bds =
   4.146 -          (case Thm.term_of ct of
   4.147 -            Abs (_, xT, ta) =>
   4.148 -              let
   4.149 -                val ([raw_xn], ctxt') = Variable.variant_fixes ["x"] ctxt;
   4.150 -                val (xn, ta) = Syntax_Trans.variant_abs (raw_xn, xT, ta);  (* FIXME !? *)
   4.151 -                val x = Free (xn, xT);
   4.152 -                val cx = cert x;
   4.153 -                val cta = cert ta;
   4.154 -                val bds = (case AList.lookup Type.could_unify bds (HOLogic.listT xT) of
   4.155 -                    NONE => error "tryabsdecomp: Type not found in the Environement"
   4.156 -                  | SOME (bsT, atsT) => AList.update Type.could_unify (HOLogic.listT xT,
   4.157 -                      (x :: bsT, atsT)) bds);
   4.158 -               in (([(cta, ctxt')],
   4.159 -                    fn ([th], bds) =>
   4.160 -                      (hd (Variable.export ctxt' ctxt [(Thm.forall_intr cx th) COMP allI]),
   4.161 -                       let
   4.162 -                         val (bsT, asT) = the (AList.lookup Type.could_unify bds (HOLogic.listT xT));
   4.163 -                       in
   4.164 -                         AList.update Type.could_unify (HOLogic.listT xT, (tl bsT, asT)) bds
   4.165 -                       end)),
   4.166 -                   bds)
   4.167 -               end
   4.168 -           | _ => da (ct, ctxt) bds)
   4.169 -      in
   4.170 -        (case cgns of
   4.171 -          [] => tryabsdecomp (ct, ctxt) bds
   4.172 -        | ((vns, cong) :: congs) =>
   4.173 -            (let
   4.174 -              val (tyenv, tmenv) =
   4.175 -                Pattern.match thy
   4.176 -                  ((fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) (concl_of cong), Thm.term_of ct)
   4.177 -                  (Vartab.empty, Vartab.empty);
   4.178 -              val (fnvs, invs) = List.partition (fn ((vn, _),_) => member (op =) vns vn) (Vartab.dest tmenv);
   4.179 -              val (fts, its) =
   4.180 -                (map (snd o snd) fnvs,
   4.181 -                 map (fn ((vn, vi), (tT, t)) => (cert (Var ((vn, vi), tT)), cert t)) invs);
   4.182 -              val ctyenv = map (fn ((vn, vi), (s, ty)) => (certT (TVar((vn, vi), s)), certT ty)) (Vartab.dest tyenv);
   4.183 -            in
   4.184 -              ((map cert fts ~~ replicate (length fts) ctxt,
   4.185 -                 apfst (FWD (Drule.instantiate_normalize (ctyenv, its) cong))), bds)
   4.186 -            end handle Pattern.MATCH => decomp_reify da congs (ct, ctxt) bds))
   4.187 -      end;
   4.188 -
   4.189 - (* looks for the atoms equation and instantiates it with the right number *)
   4.190 -    fun mk_decompatom eqs (ct, ctxt) bds = (([], fn (_, bds) =>
   4.191 -      let
   4.192 -        val tT = fastype_of (Thm.term_of ct);
   4.193 -        fun isat eq =
   4.194 -          let
   4.195 -            val rhs = eq |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd;
   4.196 -          in exists_Const
   4.197 -            (fn (n, ty) => n = @{const_name "List.nth"}
   4.198 -              andalso AList.defined Type.could_unify bds (domain_type ty)) rhs
   4.199 -              andalso Type.could_unify (fastype_of rhs, tT)
   4.200 -          end;
   4.201 -
   4.202 -        fun get_nths (t as (Const (@{const_name "List.nth"}, _) $ vs $ n)) =
   4.203 -              AList.update (op aconv) (t, (vs, n))
   4.204 -          | get_nths (t1 $ t2) = get_nths t1 #> get_nths t2
   4.205 -          | get_nths (Abs (_, _, t')) = get_nths t'
   4.206 -          | get_nths _ = I;
   4.207 -
   4.208 -        fun tryeqs [] bds = error "Cannot find the atoms equation"
   4.209 -          | tryeqs (eq :: eqs) bds = ((
   4.210 -              let
   4.211 -                val rhs = eq |> prop_of |> HOLogic.dest_Trueprop  |> HOLogic.dest_eq |> snd;
   4.212 -                val nths = get_nths rhs [];
   4.213 -                val (vss, _) = fold_rev (fn (_, (vs, n)) => fn (vss, ns) =>
   4.214 -                  (insert (op aconv) vs vss, insert (op aconv) n ns)) nths ([], []);
   4.215 -                val (vsns, ctxt') = Variable.variant_fixes (replicate (length vss) "vs") ctxt;
   4.216 -                val (xns, ctxt'') = Variable.variant_fixes (replicate (length nths) "x") ctxt';
   4.217 -                val thy = Proof_Context.theory_of ctxt'';
   4.218 -                val cert = cterm_of thy;
   4.219 -                val certT = ctyp_of thy;
   4.220 -                val vsns_map = vss ~~ vsns;
   4.221 -                val xns_map = fst (split_list nths) ~~ xns;
   4.222 -                val subst = map (fn (nt, xn) => (nt, Var ((xn, 0), fastype_of nt))) xns_map;
   4.223 -                val rhs_P = subst_free subst rhs;
   4.224 -                val (tyenv, tmenv) = Pattern.match thy (rhs_P, Thm.term_of ct) (Vartab.empty, Vartab.empty);
   4.225 -                val sbst = Envir.subst_term (tyenv, tmenv);
   4.226 -                val sbsT = Envir.subst_type tyenv;
   4.227 -                val subst_ty = map (fn (n, (s, t)) =>
   4.228 -                  (certT (TVar (n, s)), certT t)) (Vartab.dest tyenv)
   4.229 -                val tml = Vartab.dest tmenv;
   4.230 -                val (subst_ns, bds) = fold_map
   4.231 -                  (fn (Const _ $ _ $ n, Var (xn0, _)) => fn bds =>
   4.232 -                    let
   4.233 -                      val name = snd (the (AList.lookup (op =) tml xn0));
   4.234 -                      val (idx, bds) = index_of name bds;
   4.235 -                    in ((cert n, idx |> (HOLogic.mk_nat #> cert)), bds) end) subst bds;
   4.236 -                val subst_vs =
   4.237 -                  let
   4.238 -                    fun h (Const _ $ (vs as Var (_, lT)) $ _, Var (_, T)) =
   4.239 -                      let
   4.240 -                        val cns = sbst (Const (@{const_name "List.Cons"}, T --> lT --> lT));
   4.241 -                        val lT' = sbsT lT;
   4.242 -                        val (bsT, _) = the (AList.lookup Type.could_unify bds lT);
   4.243 -                        val vsn = the (AList.lookup (op =) vsns_map vs);
   4.244 -                        val cvs = cert (fold_rev (fn x => fn xs => cns $ x $xs) bsT (Free (vsn, lT')));
   4.245 -                      in (cert vs, cvs) end;
   4.246 -                  in map h subst end;
   4.247 -                val cts = map (fn ((vn, vi), (tT, t)) => (cert (Var ((vn, vi), tT)), cert t))
   4.248 -                  (fold (AList.delete (fn (((a : string), _), (b, _)) => a = b))
   4.249 -                    (map (fn n => (n, 0)) xns) tml);
   4.250 -                val substt =
   4.251 -                  let
   4.252 -                    val ih = Drule.cterm_rule (Thm.instantiate (subst_ty, []));
   4.253 -                  in map (pairself ih) (subst_ns @ subst_vs @ cts) end;
   4.254 -                val th = (Drule.instantiate_normalize (subst_ty, substt) eq) RS sym;
   4.255 -              in (hd (Variable.export ctxt'' ctxt [th]), bds) end)
   4.256 -              handle Pattern.MATCH => tryeqs eqs bds)
   4.257 -          in tryeqs (filter isat eqs) bds end), bds);
   4.258 -
   4.259 -  (* Generic reification procedure: *)
   4.260 -  (* creates all needed cong rules and then just uses the theorem synthesis *)
   4.261 -
   4.262 -    fun mk_congs ctxt eqs =
   4.263 -      let
   4.264 -        val fs = fold_rev (fn eq => insert (op =) (eq |> prop_of |> HOLogic.dest_Trueprop
   4.265 -          |> HOLogic.dest_eq |> fst |> strip_comb
   4.266 -          |> fst)) eqs [];
   4.267 -        val tys = fold_rev (fn f => fold (insert (op =)) (f |> fastype_of |> binder_types |> tl)) fs [];
   4.268 -        val (vs, ctxt') = Variable.variant_fixes (replicate (length tys) "vs") ctxt;
   4.269 -        val cert = cterm_of (Proof_Context.theory_of ctxt');
   4.270 -        val subst =
   4.271 -          the o AList.lookup (op =) (map2 (fn T => fn v => (T, cert (Free (v, T)))) tys vs);
   4.272 -        fun prep_eq eq =
   4.273 -          let
   4.274 -            val (_, _ :: vs) = eq |> prop_of |> HOLogic.dest_Trueprop
   4.275 -              |> HOLogic.dest_eq |> fst |> strip_comb;
   4.276 -            val subst = map_filter (fn (v as Var (_, T)) => SOME (cert v, subst T)
   4.277 -              | _ => NONE) vs;
   4.278 -          in Thm.instantiate ([], subst) eq end;
   4.279 -        val (ps, congs) = map_split (mk_congeq ctxt' fs o prep_eq) eqs;
   4.280 -        val bds = AList.make (K ([], [])) tys;
   4.281 -      in (ps ~~ Variable.export ctxt' ctxt congs, bds) end
   4.282 -
   4.283 -    val (congs, bds) = mk_congs ctxt eqs;
   4.284 -    val congs = rearrange congs;
   4.285 -    val (th, bds') = apfst mk_eq (divide_and_conquer' (decomp_reify (mk_decompatom eqs) congs) (ct, ctxt) bds);
   4.286 -    fun is_list_var (Var (_, t)) = can dest_listT t
   4.287 -      | is_list_var _ = false;
   4.288 -    val vars = th |> prop_of |> Logic.dest_equals |> snd
   4.289 -      |> strip_comb |> snd |> filter is_list_var;
   4.290 -    val cert = cterm_of (Proof_Context.theory_of ctxt);
   4.291 -    val vs = map (fn v as Var (_, T) =>
   4.292 -      (v, the (AList.lookup Type.could_unify bds' T) |> snd |> HOLogic.mk_list (dest_listT T))) vars;
   4.293 -    val th' = Drule.instantiate_normalize ([], (map o pairself) cert vs) th;
   4.294 -    val th'' = Thm.symmetric (dereify ctxt [] (Thm.lhs_of th'));
   4.295 -  in Thm.transitive th'' th' end;
   4.296 -
   4.297 -fun reify_tac ctxt eqs =
   4.298 -  lift_conv ctxt (reify ctxt eqs);
   4.299 -
   4.300  fun subst_correctness corr_thms ct =
   4.301    Conv.rewrs_conv (map (Thm.symmetric o mk_eq) corr_thms) ct
   4.302      handle CTERM _ => error "No suitable correctness theorem found";
   4.303  
   4.304  fun reflect ctxt corr_thms eqs =
   4.305 -  (reify ctxt eqs) then_conv (subst_correctness corr_thms)
   4.306 +  (Reification.conv ctxt eqs) then_conv (subst_correctness corr_thms)
   4.307  
   4.308  fun reflection_tac ctxt corr_thms eqs =
   4.309 -  lift_conv ctxt (reflect ctxt corr_thms eqs);
   4.310 +  Reification.lift_conv ctxt (reflect ctxt corr_thms eqs);
   4.311  
   4.312  fun first_arg_conv conv =
   4.313    let
   4.314 @@ -321,10 +41,10 @@
   4.315    in conv' end;
   4.316  
   4.317  fun reflect_with_eval ctxt corr_thms eqs conv =
   4.318 -  (reflect ctxt corr_thms eqs) then_conv (first_arg_conv conv) then_conv (dereify ctxt eqs);
   4.319 +  (reflect ctxt corr_thms eqs) then_conv (first_arg_conv conv) then_conv (Reification.dereify ctxt eqs);
   4.320  
   4.321  fun reflection_with_eval_tac ctxt corr_thms eqs conv =
   4.322 -  lift_conv ctxt (reflect_with_eval ctxt corr_thms eqs conv);
   4.323 +  Reification.lift_conv ctxt (reflect_with_eval ctxt corr_thms eqs conv);
   4.324  
   4.325  structure Data = Generic_Data
   4.326  (
   4.327 @@ -356,7 +76,7 @@
   4.328      val { reification_eqs = default_eqs, correctness_thms = _ } =
   4.329        get_default ctxt;
   4.330      val eqs = fold Thm.add_thm user_eqs default_eqs;
   4.331 -  in reify_tac ctxt eqs end;
   4.332 +  in Reification.tac ctxt eqs end;
   4.333  
   4.334  fun default_reflection_tac ctxt user_thms user_eqs =
   4.335    let
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/src/HOL/Tools/reification.ML	Sun Jun 02 07:46:40 2013 +0200
     5.3 @@ -0,0 +1,296 @@
     5.4 +(*  Title:      HOL/Tools/reification.ML
     5.5 +    Author:     Amine Chaieb, TU Muenchen
     5.6 +
     5.7 +A trial for automatical reification.
     5.8 +*)
     5.9 +
    5.10 +signature REIFICATION =
    5.11 +sig
    5.12 +  val conv: Proof.context -> thm list -> conv
    5.13 +  val tac: Proof.context -> thm list -> term option -> int -> tactic
    5.14 +  val lift_conv: Proof.context -> conv -> term option -> int -> tactic
    5.15 +  val dereify: Proof.context -> thm list -> conv
    5.16 +end;
    5.17 +
    5.18 +structure Reification : REIFICATION =
    5.19 +struct
    5.20 +
    5.21 +fun dest_listT (Type (@{type_name "list"}, [T])) = T;
    5.22 +
    5.23 +val FWD = curry (op OF);
    5.24 +
    5.25 +fun rewrite_with ctxt eqs = Simplifier.rewrite (put_simpset HOL_basic_ss ctxt addsimps eqs);
    5.26 +
    5.27 +val pure_subst = @{lemma "x == y ==> PROP P y ==> PROP P x" by simp}
    5.28 +
    5.29 +fun lift_conv ctxt conv some_t = Subgoal.FOCUS (fn { concl, ... } =>
    5.30 +  let
    5.31 +    val ct = case some_t
    5.32 +     of NONE => Thm.dest_arg concl
    5.33 +      | SOME t => Thm.cterm_of (Proof_Context.theory_of ctxt) t
    5.34 +    val thm = conv ct;
    5.35 +  in
    5.36 +    if Thm.is_reflexive thm then no_tac
    5.37 +    else ALLGOALS (rtac (pure_subst OF [thm]))
    5.38 +  end) ctxt;
    5.39 +
    5.40 +(* Make a congruence rule out of a defining equation for the interpretation
    5.41 +
    5.42 +   th is one defining equation of f,
    5.43 +     i.e. th is "f (Cp ?t1 ... ?tn) = P(f ?t1, .., f ?tn)" 
    5.44 +   Cp is a constructor pattern and P is a pattern 
    5.45 +
    5.46 +   The result is:
    5.47 +     [|?A1 = f ?t1 ; .. ; ?An= f ?tn |] ==> P (?A1, .., ?An) = f (Cp ?t1 .. ?tn)
    5.48 +       + the a list of names of the A1 .. An, Those are fresh in the ctxt *)
    5.49 +
    5.50 +fun mk_congeq ctxt fs th =
    5.51 +  let
    5.52 +    val Const (fN, _) = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq
    5.53 +      |> fst |> strip_comb |> fst;
    5.54 +    val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
    5.55 +    val ((_, [th']), ctxt') = Variable.import true [th] ctxt;
    5.56 +    val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop (Thm.prop_of th'));
    5.57 +    fun add_fterms (t as t1 $ t2) =
    5.58 +          if exists (fn f => Term.could_unify (t |> strip_comb |> fst, f)) fs
    5.59 +          then insert (op aconv) t
    5.60 +          else add_fterms t1 #> add_fterms t2
    5.61 +      | add_fterms (t as Abs _) =
    5.62 +          if exists_Const (fn (c, _) => c = fN) t
    5.63 +          then K [t]
    5.64 +          else K []
    5.65 +      | add_fterms _ = I;
    5.66 +    val fterms = add_fterms rhs [];
    5.67 +    val (xs, ctxt'') = Variable.variant_fixes (replicate (length fterms) "x") ctxt';
    5.68 +    val tys = map fastype_of fterms;
    5.69 +    val vs = map Free (xs ~~ tys);
    5.70 +    val env = fterms ~~ vs; (*FIXME*)
    5.71 +    fun replace_fterms (t as t1 $ t2) =
    5.72 +        (case AList.lookup (op aconv) env t of
    5.73 +            SOME v => v
    5.74 +          | NONE => replace_fterms t1 $ replace_fterms t2)
    5.75 +      | replace_fterms t =
    5.76 +        (case AList.lookup (op aconv) env t of
    5.77 +            SOME v => v
    5.78 +          | NONE => t);
    5.79 +    fun mk_def (Abs (x, xT, t), v) =
    5.80 +          HOLogic.mk_Trueprop (HOLogic.all_const xT $ Abs (x, xT, HOLogic.mk_eq (v $ Bound 0, t)))
    5.81 +      | mk_def (t, v) = HOLogic.mk_Trueprop (HOLogic.mk_eq (v, t));
    5.82 +    fun tryext x =
    5.83 +      (x RS @{lemma "(\<forall>x. f x = g x) \<Longrightarrow> f = g" by blast} handle THM _ => x);
    5.84 +    val cong =
    5.85 +      (Goal.prove ctxt'' [] (map mk_def env)
    5.86 +        (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, replace_fterms rhs)))
    5.87 +        (fn {context, prems, ...} =>
    5.88 +          Local_Defs.unfold_tac context (map tryext prems) THEN rtac th' 1)) RS sym;
    5.89 +    val (cong' :: vars') =
    5.90 +      Variable.export ctxt'' ctxt (cong :: map (Drule.mk_term o cert) vs);
    5.91 +    val vs' = map (fst o fst o Term.dest_Var o Thm.term_of o Drule.dest_term) vars';
    5.92 +
    5.93 +  in (vs', cong') end;
    5.94 +
    5.95 +(* congs is a list of pairs (P,th) where th is a theorem for
    5.96 +     [| f p1 = A1; ...; f pn = An|] ==> f (C p1 .. pn) = P *)
    5.97 +
    5.98 +fun rearrange congs =
    5.99 +  let
   5.100 +    fun P (_, th) =
   5.101 +      let val @{term "Trueprop"} $ (Const (@{const_name HOL.eq}, _) $ l $ _) = concl_of th
   5.102 +      in can dest_Var l end;
   5.103 +    val (yes, no) = List.partition P congs;
   5.104 +  in no @ yes end;
   5.105 +
   5.106 +fun dereify ctxt eqs =
   5.107 +  rewrite_with ctxt (eqs @ @{thms nth_Cons_0 nth_Cons_Suc});
   5.108 +
   5.109 +fun conv ctxt eqs ct =
   5.110 +  let
   5.111 +    fun index_of t bds =
   5.112 +      let
   5.113 +        val tt = HOLogic.listT (fastype_of t);
   5.114 +      in
   5.115 +        (case AList.lookup Type.could_unify bds tt of
   5.116 +            NONE => error "index_of: type not found in environements!"
   5.117 +          | SOME (tbs, tats) =>
   5.118 +              let
   5.119 +                val i = find_index (fn t' => t' = t) tats;
   5.120 +                val j = find_index (fn t' => t' = t) tbs;
   5.121 +              in
   5.122 +                if j = ~1 then
   5.123 +                  if i = ~1
   5.124 +                  then (length tbs + length tats, AList.update Type.could_unify (tt, (tbs, tats @ [t])) bds)
   5.125 +                  else (i, bds)
   5.126 +                else (j, bds)
   5.127 +              end)
   5.128 +      end;
   5.129 +
   5.130 +    (* Generic decomp for reification : matches the actual term with the
   5.131 +       rhs of one cong rule. The result of the matching guides the
   5.132 +       proof synthesis: The matches of the introduced Variables A1 .. An are
   5.133 +       processed recursively
   5.134 +       The rest is instantiated in the cong rule,i.e. no reification is needed *)
   5.135 +
   5.136 +    (* da is the decomposition for atoms, ie. it returns ([],g) where g
   5.137 +       returns the right instance f (AtC n) = t , where AtC is the Atoms
   5.138 +       constructor and n is the number of the atom corresponding to t *)
   5.139 +    fun decomp_reify da cgns (ct, ctxt) bds =
   5.140 +      let
   5.141 +        val thy = Proof_Context.theory_of ctxt;
   5.142 +        val cert = cterm_of thy;
   5.143 +        val certT = ctyp_of thy;
   5.144 +        fun tryabsdecomp (ct, ctxt) bds =
   5.145 +          (case Thm.term_of ct of
   5.146 +            Abs (_, xT, ta) =>
   5.147 +              let
   5.148 +                val ([raw_xn], ctxt') = Variable.variant_fixes ["x"] ctxt;
   5.149 +                val (xn, ta) = Syntax_Trans.variant_abs (raw_xn, xT, ta);  (* FIXME !? *)
   5.150 +                val x = Free (xn, xT);
   5.151 +                val cx = cert x;
   5.152 +                val cta = cert ta;
   5.153 +                val bds = (case AList.lookup Type.could_unify bds (HOLogic.listT xT) of
   5.154 +                    NONE => error "tryabsdecomp: Type not found in the Environement"
   5.155 +                  | SOME (bsT, atsT) => AList.update Type.could_unify (HOLogic.listT xT,
   5.156 +                      (x :: bsT, atsT)) bds);
   5.157 +               in (([(cta, ctxt')],
   5.158 +                    fn ([th], bds) =>
   5.159 +                      (hd (Variable.export ctxt' ctxt [(Thm.forall_intr cx th) COMP allI]),
   5.160 +                       let
   5.161 +                         val (bsT, asT) = the (AList.lookup Type.could_unify bds (HOLogic.listT xT));
   5.162 +                       in
   5.163 +                         AList.update Type.could_unify (HOLogic.listT xT, (tl bsT, asT)) bds
   5.164 +                       end)),
   5.165 +                   bds)
   5.166 +               end
   5.167 +           | _ => da (ct, ctxt) bds)
   5.168 +      in
   5.169 +        (case cgns of
   5.170 +          [] => tryabsdecomp (ct, ctxt) bds
   5.171 +        | ((vns, cong) :: congs) =>
   5.172 +            (let
   5.173 +              val (tyenv, tmenv) =
   5.174 +                Pattern.match thy
   5.175 +                  ((fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) (concl_of cong), Thm.term_of ct)
   5.176 +                  (Vartab.empty, Vartab.empty);
   5.177 +              val (fnvs, invs) = List.partition (fn ((vn, _),_) => member (op =) vns vn) (Vartab.dest tmenv);
   5.178 +              val (fts, its) =
   5.179 +                (map (snd o snd) fnvs,
   5.180 +                 map (fn ((vn, vi), (tT, t)) => (cert (Var ((vn, vi), tT)), cert t)) invs);
   5.181 +              val ctyenv = map (fn ((vn, vi), (s, ty)) => (certT (TVar((vn, vi), s)), certT ty)) (Vartab.dest tyenv);
   5.182 +            in
   5.183 +              ((map cert fts ~~ replicate (length fts) ctxt,
   5.184 +                 apfst (FWD (Drule.instantiate_normalize (ctyenv, its) cong))), bds)
   5.185 +            end handle Pattern.MATCH => decomp_reify da congs (ct, ctxt) bds))
   5.186 +      end;
   5.187 +
   5.188 + (* looks for the atoms equation and instantiates it with the right number *)
   5.189 +    fun mk_decompatom eqs (ct, ctxt) bds = (([], fn (_, bds) =>
   5.190 +      let
   5.191 +        val tT = fastype_of (Thm.term_of ct);
   5.192 +        fun isat eq =
   5.193 +          let
   5.194 +            val rhs = eq |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd;
   5.195 +          in exists_Const
   5.196 +            (fn (n, ty) => n = @{const_name "List.nth"}
   5.197 +              andalso AList.defined Type.could_unify bds (domain_type ty)) rhs
   5.198 +              andalso Type.could_unify (fastype_of rhs, tT)
   5.199 +          end;
   5.200 +
   5.201 +        fun get_nths (t as (Const (@{const_name "List.nth"}, _) $ vs $ n)) =
   5.202 +              AList.update (op aconv) (t, (vs, n))
   5.203 +          | get_nths (t1 $ t2) = get_nths t1 #> get_nths t2
   5.204 +          | get_nths (Abs (_, _, t')) = get_nths t'
   5.205 +          | get_nths _ = I;
   5.206 +
   5.207 +        fun tryeqs [] bds = error "Cannot find the atoms equation"
   5.208 +          | tryeqs (eq :: eqs) bds = ((
   5.209 +              let
   5.210 +                val rhs = eq |> prop_of |> HOLogic.dest_Trueprop  |> HOLogic.dest_eq |> snd;
   5.211 +                val nths = get_nths rhs [];
   5.212 +                val (vss, _) = fold_rev (fn (_, (vs, n)) => fn (vss, ns) =>
   5.213 +                  (insert (op aconv) vs vss, insert (op aconv) n ns)) nths ([], []);
   5.214 +                val (vsns, ctxt') = Variable.variant_fixes (replicate (length vss) "vs") ctxt;
   5.215 +                val (xns, ctxt'') = Variable.variant_fixes (replicate (length nths) "x") ctxt';
   5.216 +                val thy = Proof_Context.theory_of ctxt'';
   5.217 +                val cert = cterm_of thy;
   5.218 +                val certT = ctyp_of thy;
   5.219 +                val vsns_map = vss ~~ vsns;
   5.220 +                val xns_map = fst (split_list nths) ~~ xns;
   5.221 +                val subst = map (fn (nt, xn) => (nt, Var ((xn, 0), fastype_of nt))) xns_map;
   5.222 +                val rhs_P = subst_free subst rhs;
   5.223 +                val (tyenv, tmenv) = Pattern.match thy (rhs_P, Thm.term_of ct) (Vartab.empty, Vartab.empty);
   5.224 +                val sbst = Envir.subst_term (tyenv, tmenv);
   5.225 +                val sbsT = Envir.subst_type tyenv;
   5.226 +                val subst_ty = map (fn (n, (s, t)) =>
   5.227 +                  (certT (TVar (n, s)), certT t)) (Vartab.dest tyenv)
   5.228 +                val tml = Vartab.dest tmenv;
   5.229 +                val (subst_ns, bds) = fold_map
   5.230 +                  (fn (Const _ $ _ $ n, Var (xn0, _)) => fn bds =>
   5.231 +                    let
   5.232 +                      val name = snd (the (AList.lookup (op =) tml xn0));
   5.233 +                      val (idx, bds) = index_of name bds;
   5.234 +                    in ((cert n, idx |> (HOLogic.mk_nat #> cert)), bds) end) subst bds;
   5.235 +                val subst_vs =
   5.236 +                  let
   5.237 +                    fun h (Const _ $ (vs as Var (_, lT)) $ _, Var (_, T)) =
   5.238 +                      let
   5.239 +                        val cns = sbst (Const (@{const_name "List.Cons"}, T --> lT --> lT));
   5.240 +                        val lT' = sbsT lT;
   5.241 +                        val (bsT, _) = the (AList.lookup Type.could_unify bds lT);
   5.242 +                        val vsn = the (AList.lookup (op =) vsns_map vs);
   5.243 +                        val cvs = cert (fold_rev (fn x => fn xs => cns $ x $xs) bsT (Free (vsn, lT')));
   5.244 +                      in (cert vs, cvs) end;
   5.245 +                  in map h subst end;
   5.246 +                val cts = map (fn ((vn, vi), (tT, t)) => (cert (Var ((vn, vi), tT)), cert t))
   5.247 +                  (fold (AList.delete (fn (((a : string), _), (b, _)) => a = b))
   5.248 +                    (map (fn n => (n, 0)) xns) tml);
   5.249 +                val substt =
   5.250 +                  let
   5.251 +                    val ih = Drule.cterm_rule (Thm.instantiate (subst_ty, []));
   5.252 +                  in map (pairself ih) (subst_ns @ subst_vs @ cts) end;
   5.253 +                val th = (Drule.instantiate_normalize (subst_ty, substt) eq) RS sym;
   5.254 +              in (hd (Variable.export ctxt'' ctxt [th]), bds) end)
   5.255 +              handle Pattern.MATCH => tryeqs eqs bds)
   5.256 +          in tryeqs (filter isat eqs) bds end), bds);
   5.257 +
   5.258 +  (* Generic reification procedure: *)
   5.259 +  (* creates all needed cong rules and then just uses the theorem synthesis *)
   5.260 +
   5.261 +    fun mk_congs ctxt eqs =
   5.262 +      let
   5.263 +        val fs = fold_rev (fn eq => insert (op =) (eq |> prop_of |> HOLogic.dest_Trueprop
   5.264 +          |> HOLogic.dest_eq |> fst |> strip_comb
   5.265 +          |> fst)) eqs [];
   5.266 +        val tys = fold_rev (fn f => fold (insert (op =)) (f |> fastype_of |> binder_types |> tl)) fs [];
   5.267 +        val (vs, ctxt') = Variable.variant_fixes (replicate (length tys) "vs") ctxt;
   5.268 +        val cert = cterm_of (Proof_Context.theory_of ctxt');
   5.269 +        val subst =
   5.270 +          the o AList.lookup (op =) (map2 (fn T => fn v => (T, cert (Free (v, T)))) tys vs);
   5.271 +        fun prep_eq eq =
   5.272 +          let
   5.273 +            val (_, _ :: vs) = eq |> prop_of |> HOLogic.dest_Trueprop
   5.274 +              |> HOLogic.dest_eq |> fst |> strip_comb;
   5.275 +            val subst = map_filter (fn (v as Var (_, T)) => SOME (cert v, subst T)
   5.276 +              | _ => NONE) vs;
   5.277 +          in Thm.instantiate ([], subst) eq end;
   5.278 +        val (ps, congs) = map_split (mk_congeq ctxt' fs o prep_eq) eqs;
   5.279 +        val bds = AList.make (K ([], [])) tys;
   5.280 +      in (ps ~~ Variable.export ctxt' ctxt congs, bds) end
   5.281 +
   5.282 +    val (congs, bds) = mk_congs ctxt eqs;
   5.283 +    val congs = rearrange congs;
   5.284 +    val (th, bds') = apfst mk_eq (divide_and_conquer' (decomp_reify (mk_decompatom eqs) congs) (ct, ctxt) bds);
   5.285 +    fun is_list_var (Var (_, t)) = can dest_listT t
   5.286 +      | is_list_var _ = false;
   5.287 +    val vars = th |> prop_of |> Logic.dest_equals |> snd
   5.288 +      |> strip_comb |> snd |> filter is_list_var;
   5.289 +    val cert = cterm_of (Proof_Context.theory_of ctxt);
   5.290 +    val vs = map (fn v as Var (_, T) =>
   5.291 +      (v, the (AList.lookup Type.could_unify bds' T) |> snd |> HOLogic.mk_list (dest_listT T))) vars;
   5.292 +    val th' = Drule.instantiate_normalize ([], (map o pairself) cert vs) th;
   5.293 +    val th'' = Thm.symmetric (dereify ctxt [] (Thm.lhs_of th'));
   5.294 +  in Thm.transitive th'' th' end;
   5.295 +
   5.296 +fun tac ctxt eqs =
   5.297 +  lift_conv ctxt (conv ctxt eqs);
   5.298 +
   5.299 +end;