src/HOL/Library/reflection.ML
changeset 29650 cc3958d31b1d
parent 29273 285c00993bc2
child 29805 a5da150bd0ab
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/HOL/Library/reflection.ML	Wed Jan 28 11:04:10 2009 +0100
     1.3 @@ -0,0 +1,327 @@
     1.4 +(*  Title:      HOL/Library/reflection.ML
     1.5 +    Author:     Amine Chaieb, TU Muenchen
     1.6 +
     1.7 +A trial for automatical reification.
     1.8 +*)
     1.9 +
    1.10 +signature REFLECTION =
    1.11 +sig
    1.12 +  val genreify_tac: Proof.context -> thm list -> term option -> int -> tactic
    1.13 +  val reflection_tac: Proof.context -> thm list -> thm list -> term option -> int -> tactic
    1.14 +  val gen_reflection_tac: Proof.context -> (cterm -> thm)
    1.15 +    -> thm list -> thm list -> term option -> int -> tactic
    1.16 +end;
    1.17 +
    1.18 +structure Reflection : REFLECTION =
    1.19 +struct
    1.20 +
    1.21 +val ext2 = @{thm ext2};
    1.22 +val nth_Cons_0 = @{thm nth_Cons_0};
    1.23 +val nth_Cons_Suc = @{thm nth_Cons_Suc};
    1.24 +
    1.25 +  (* Make a congruence rule out of a defining equation for the interpretation *)
    1.26 +  (* th is one defining equation of f, i.e.
    1.27 +     th is "f (Cp ?t1 ... ?tn) = P(f ?t1, .., f ?tn)" *)
    1.28 +  (* Cp is a constructor pattern and P is a pattern *)
    1.29 +
    1.30 +  (* The result is:
    1.31 +      [|?A1 = f ?t1 ; .. ; ?An= f ?tn |] ==> P (?A1, .., ?An) = f (Cp ?t1 .. ?tn) *)
    1.32 +  (*  + the a list of names of the A1 .. An, Those are fresh in the ctxt*)
    1.33 +
    1.34 +
    1.35 +fun mk_congeq ctxt fs th = 
    1.36 +  let 
    1.37 +   val (f as Const(fN,fT)) = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq 
    1.38 +     |> fst |> strip_comb |> fst
    1.39 +   val thy = ProofContext.theory_of ctxt
    1.40 +   val cert = Thm.cterm_of thy
    1.41 +   val (((_,_),[th']), ctxt') = Variable.import_thms true [th] ctxt
    1.42 +   val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop (Thm.prop_of th'))
    1.43 +   fun add_fterms (t as t1 $ t2) = 
    1.44 +       if exists (fn f => Term.could_unify (t |> strip_comb |> fst, f)) fs then insert (op aconv) t
    1.45 +       else add_fterms t1 #> add_fterms t2
    1.46 +     | add_fterms (t as Abs(xn,xT,t')) = 
    1.47 +       if exists_Const (fn (c, _) => c = fN) t then (fn _ => [t]) else (fn _ => [])
    1.48 +     | add_fterms _ = I
    1.49 +   val fterms = add_fterms rhs []
    1.50 +   val (xs, ctxt'') = Variable.variant_fixes (replicate (length fterms) "x") ctxt'
    1.51 +   val tys = map fastype_of fterms
    1.52 +   val vs = map Free (xs ~~ tys)
    1.53 +   val env = fterms ~~ vs
    1.54 +		    (* FIXME!!!!*)	
    1.55 +   fun replace_fterms (t as t1 $ t2) =
    1.56 +       (case AList.lookup (op aconv) env t of
    1.57 +	    SOME v => v
    1.58 +	  | NONE => replace_fterms t1 $ replace_fterms t2)
    1.59 +     | replace_fterms t = (case AList.lookup (op aconv) env t of
    1.60 +			       SOME v => v
    1.61 +			     | NONE => t)
    1.62 +      
    1.63 +   fun mk_def (Abs(x,xT,t),v) = HOLogic.mk_Trueprop ((HOLogic.all_const xT)$ Abs(x,xT,HOLogic.mk_eq(v$(Bound 0), t)))
    1.64 +     | mk_def (t, v) = HOLogic.mk_Trueprop (HOLogic.mk_eq (v, t))
    1.65 +   fun tryext x = (x RS ext2 handle THM _ =>  x)
    1.66 +   val cong = (Goal.prove ctxt'' [] (map mk_def env)
    1.67 +			  (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, replace_fterms rhs)))
    1.68 +			  (fn x => LocalDefs.unfold_tac (#context x) (map tryext (#prems x)) 
    1.69 +							THEN rtac th' 1)) RS sym
    1.70 +	      
    1.71 +   val (cong' :: vars') = 
    1.72 +       Variable.export ctxt'' ctxt (cong :: map (Drule.mk_term o cert) vs)
    1.73 +   val vs' = map (fst o fst o Term.dest_Var o Thm.term_of o Drule.dest_term) vars'
    1.74 +					      
    1.75 +  in  (vs', cong') end; 
    1.76 + (* congs is a list of pairs (P,th) where th is a theorem for *)
    1.77 +        (* [| f p1 = A1; ...; f pn = An|] ==> f (C p1 .. pn) = P *)
    1.78 +val FWD = curry (op OF);
    1.79 +
    1.80 + (* da is the decomposition for atoms, ie. it returns ([],g) where g
    1.81 + returns the right instance f (AtC n) = t , where AtC is the Atoms
    1.82 + constructor and n is the number of the atom corresponding to t *)
    1.83 +
    1.84 +(* Generic decomp for reification : matches the actual term with the
    1.85 +rhs of one cong rule. The result of the matching guides the
    1.86 +proof synthesis: The matches of the introduced Variables A1 .. An are
    1.87 +processed recursively
    1.88 + The rest is instantiated in the cong rule,i.e. no reification is needed *)
    1.89 +
    1.90 +exception REIF of string;
    1.91 +
    1.92 +val bds = ref ([]: (typ * ((term list) * (term list))) list);
    1.93 +
    1.94 +fun index_of t = 
    1.95 + let 
    1.96 +  val tt = HOLogic.listT (fastype_of t)
    1.97 + in 
    1.98 +  (case AList.lookup Type.could_unify (!bds) tt of
    1.99 +    NONE => error "index_of : type not found in environements!"
   1.100 +  | SOME (tbs,tats) =>
   1.101 +    let
   1.102 +     val i = find_index_eq t tats
   1.103 +     val j = find_index_eq t tbs 
   1.104 +    in (if j= ~1 then 
   1.105 +	    if i= ~1 
   1.106 +	    then (bds := AList.update Type.could_unify (tt,(tbs,tats@[t])) (!bds) ; 
   1.107 +		  length tbs + length tats) 
   1.108 +	    else i else j)
   1.109 +    end)
   1.110 + end;
   1.111 +
   1.112 +fun dest_listT (Type ("List.list", [T])) = T;
   1.113 +
   1.114 +fun decomp_genreif da cgns (t,ctxt) =
   1.115 + let 
   1.116 +  val thy = ProofContext.theory_of ctxt 
   1.117 +  val cert = cterm_of thy
   1.118 +  fun tryabsdecomp (s,ctxt) = 
   1.119 +   (case s of 
   1.120 +     Abs(xn,xT,ta) => 
   1.121 +     (let
   1.122 +       val ([xn],ctxt') = Variable.variant_fixes ["x"] ctxt
   1.123 +       val (xn,ta) = variant_abs (xn,xT,ta)
   1.124 +       val x = Free(xn,xT)
   1.125 +       val _ = (case AList.lookup Type.could_unify (!bds) (HOLogic.listT xT)
   1.126 +		 of NONE => error "tryabsdecomp: Type not found in the Environement"
   1.127 +		  | SOME (bsT,atsT) => 
   1.128 +		    (bds := AList.update Type.could_unify (HOLogic.listT xT, ((x::bsT), atsT)) (!bds)))
   1.129 +      in ([(ta, ctxt')] , 
   1.130 +	  fn [th] => ((let val (bsT,asT) = the(AList.lookup Type.could_unify (!bds) (HOLogic.listT xT))
   1.131 +		       in (bds := AList.update Type.could_unify (HOLogic.listT xT,(tl bsT,asT)) (!bds))
   1.132 +		       end) ; 
   1.133 +		      hd (Variable.export ctxt' ctxt [(forall_intr (cert x) th) COMP allI])))
   1.134 +	end)
   1.135 +    | _ => da (s,ctxt))
   1.136 +  in 
   1.137 +  (case cgns of 
   1.138 +    [] => tryabsdecomp (t,ctxt)
   1.139 +  | ((vns,cong)::congs) => ((let
   1.140 +        val cert = cterm_of thy
   1.141 +	val certy = ctyp_of thy
   1.142 +        val (tyenv, tmenv) =
   1.143 +        Pattern.match thy
   1.144 +        ((fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) (concl_of cong), t)
   1.145 +        (Envir.type_env (Envir.empty 0), Vartab.empty)
   1.146 +        val (fnvs,invs) = List.partition (fn ((vn,_),_) => vn mem vns) (Vartab.dest tmenv)
   1.147 +        val (fts,its) = 
   1.148 +	    (map (snd o snd) fnvs,
   1.149 +             map (fn ((vn,vi),(tT,t)) => (cert(Var ((vn,vi),tT)), cert t)) invs)
   1.150 +	val ctyenv = map (fn ((vn,vi),(s,ty)) => (certy (TVar((vn,vi),s)), certy ty)) (Vartab.dest tyenv)
   1.151 +    in (fts ~~ (replicate (length fts) ctxt), FWD (instantiate (ctyenv, its) cong))
   1.152 +    end)
   1.153 +      handle MATCH => decomp_genreif da congs (t,ctxt)))
   1.154 +  end;
   1.155 +
   1.156 + (* looks for the atoms equation and instantiates it with the right number *)
   1.157 +
   1.158 +
   1.159 +fun mk_decompatom eqs (t,ctxt) =
   1.160 +let 
   1.161 + val tT = fastype_of t
   1.162 + fun isat eq = 
   1.163 +  let 
   1.164 +   val rhs = eq |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd
   1.165 +   in exists_Const 
   1.166 +	  (fn (n,ty) => n="List.nth" 
   1.167 +			andalso 
   1.168 +			AList.defined Type.could_unify (!bds) (domain_type ty)) rhs 
   1.169 +	  andalso Type.could_unify (fastype_of rhs, tT)
   1.170 +   end
   1.171 + fun get_nths t acc = 
   1.172 +  case t of
   1.173 +    Const("List.nth",_)$vs$n => insert (fn ((a,_),(b,_)) => a aconv b) (t,(vs,n)) acc
   1.174 +  | t1$t2 => get_nths t1 (get_nths t2 acc)
   1.175 +  | Abs(_,_,t') => get_nths t'  acc
   1.176 +  | _ => acc
   1.177 +
   1.178 + fun 
   1.179 +   tryeqs [] = error "Can not find the atoms equation"
   1.180 + | tryeqs (eq::eqs) = ((
   1.181 +  let 
   1.182 +   val rhs = eq |> prop_of |> HOLogic.dest_Trueprop  |> HOLogic.dest_eq |> snd
   1.183 +   val nths = get_nths rhs []
   1.184 +   val (vss,ns) = fold_rev (fn (_,(vs,n)) => fn (vss,ns) => 
   1.185 +                             (insert (op aconv) vs vss, insert (op aconv) n ns)) nths ([],[]) 
   1.186 +   val (vsns, ctxt') = Variable.variant_fixes (replicate (length vss) "vs") ctxt
   1.187 +   val (xns, ctxt'') = Variable.variant_fixes (replicate (length nths) "x") ctxt' 
   1.188 +   val thy = ProofContext.theory_of ctxt''
   1.189 +   val cert = cterm_of thy
   1.190 +   val certT = ctyp_of thy
   1.191 +   val vsns_map = vss ~~ vsns
   1.192 +   val xns_map = (fst (split_list nths)) ~~ xns
   1.193 +   val subst = map (fn (nt, xn) => (nt, Var ((xn,0), fastype_of nt))) xns_map
   1.194 +   val rhs_P = subst_free subst rhs
   1.195 +   val (tyenv, tmenv) = Pattern.match 
   1.196 +	                    thy (rhs_P, t)
   1.197 +	                    (Envir.type_env (Envir.empty 0), Vartab.empty)
   1.198 +   val sbst = Envir.subst_vars (tyenv, tmenv)
   1.199 +   val sbsT = Envir.typ_subst_TVars tyenv
   1.200 +   val subst_ty = map (fn (n,(s,t)) => (certT (TVar (n, s)), certT t)) 
   1.201 +                      (Vartab.dest tyenv)
   1.202 +   val tml = Vartab.dest tmenv
   1.203 +   val t's = map (fn xn => snd (valOf (AList.lookup (op =) tml (xn,0)))) xns (* FIXME : Express with sbst*)
   1.204 +   val subst_ns = map (fn (Const _ $ vs $ n, Var (xn0,T)) => 
   1.205 +                          (cert n, snd (valOf (AList.lookup (op =) tml xn0)) 
   1.206 +                             |> (index_of #> HOLogic.mk_nat #> cert))) 
   1.207 +                      subst
   1.208 +   val subst_vs = 
   1.209 +    let 
   1.210 +     fun ty (Const _ $ (vs as Var (vsn,lT)) $ n, Var (xn0,T)) = (certT T, certT (sbsT T))
   1.211 +     fun h (Const _ $ (vs as Var (vsn,lT)) $ n, Var (xn0,T)) = 
   1.212 +      let 
   1.213 +       val cns = sbst (Const("List.list.Cons", T --> lT --> lT))
   1.214 +       val lT' = sbsT lT
   1.215 +       val (bsT,asT) = the (AList.lookup Type.could_unify (!bds) lT)
   1.216 +       val vsn = valOf (AList.lookup (op =) vsns_map vs)
   1.217 +       val cvs = cert (fold_rev (fn x => fn xs => cns$x$xs) bsT (Free (vsn, lT')))
   1.218 +      in (cert vs, cvs) end
   1.219 +    in map h subst end
   1.220 +   val cts = map (fn ((vn,vi),(tT,t)) => (cert(Var ((vn,vi),tT)), cert t)) 
   1.221 +                 (fold (AList.delete (fn (((a: string),_),(b,_)) => a = b)) 
   1.222 +                       (map (fn n => (n,0)) xns) tml)
   1.223 +   val substt = 
   1.224 +    let val ih = Drule.cterm_rule (Thm.instantiate (subst_ty,[]))
   1.225 +    in map (fn (v,t) => (ih v, ih t)) (subst_ns@subst_vs@cts)  end
   1.226 +   val th = (instantiate (subst_ty, substt)  eq) RS sym
   1.227 +  in  hd (Variable.export ctxt'' ctxt [th]) end)
   1.228 + handle MATCH => tryeqs eqs)
   1.229 +in ([], fn _ => tryeqs (filter isat eqs))
   1.230 +end;
   1.231 +
   1.232 +  (* Generic reification procedure: *)
   1.233 +  (* creates all needed cong rules and then just uses the theorem synthesis *)
   1.234 +
   1.235 +  fun mk_congs ctxt raw_eqs = 
   1.236 + let
   1.237 +  val fs = fold_rev (fn eq =>
   1.238 +		     insert (op =) (eq |> prop_of |> HOLogic.dest_Trueprop 
   1.239 +			 |> HOLogic.dest_eq |> fst |> strip_comb 
   1.240 +			 |> fst)) raw_eqs []
   1.241 +  val tys = fold_rev (fn f => fn ts => (f |> fastype_of |> binder_types |> tl) 
   1.242 +				    union ts) fs []
   1.243 +  val _ = bds := AList.make (fn _ => ([],[])) tys
   1.244 +  val (vs, ctxt') = Variable.variant_fixes (replicate (length tys) "vs") ctxt
   1.245 +  val thy = ProofContext.theory_of ctxt'
   1.246 +  val cert = cterm_of thy
   1.247 +  val vstys = map (fn (t,v) => (t,SOME (cert (Free(v,t))))) 
   1.248 +		  (tys ~~ vs)
   1.249 +  val is_Var = can dest_Var
   1.250 +  fun insteq eq vs = 
   1.251 +   let
   1.252 +     val subst = map (fn (v as Var(n,t)) => (cert v, (valOf o valOf) (AList.lookup (op =) vstys t)))  
   1.253 +  (filter is_Var vs)
   1.254 +   in Thm.instantiate ([],subst) eq
   1.255 +   end
   1.256 +  val eqs = map (fn eq => eq |> prop_of |> HOLogic.dest_Trueprop 
   1.257 +			     |> HOLogic.dest_eq |> fst |> strip_comb |> snd |> tl
   1.258 +			     |> (insteq eq)) raw_eqs
   1.259 +  val (ps,congs) = split_list (map (mk_congeq ctxt' fs) eqs)
   1.260 +in ps ~~ (Variable.export ctxt' ctxt congs)
   1.261 +end
   1.262 +
   1.263 +fun partition P [] = ([],[])
   1.264 +  | partition P (x::xs) = 
   1.265 +     let val (yes,no) = partition P xs
   1.266 +     in if P x then (x::yes,no) else (yes, x::no) end
   1.267 +
   1.268 +fun rearrange congs = 
   1.269 +let 
   1.270 + fun P (_, th) = 
   1.271 +  let val @{term "Trueprop"}$(Const ("op =",_) $l$_) = concl_of th
   1.272 +  in can dest_Var l end
   1.273 + val (yes,no) = partition P congs 
   1.274 + in no @ yes end
   1.275 +
   1.276 +
   1.277 +
   1.278 +fun genreif ctxt raw_eqs t =
   1.279 + let 
   1.280 +  val congs = rearrange (mk_congs ctxt raw_eqs)
   1.281 +  val th = divide_and_conquer (decomp_genreif (mk_decompatom raw_eqs) congs) (t,ctxt)
   1.282 +  fun is_listVar (Var (_,t)) = can dest_listT t
   1.283 +       | is_listVar _ = false
   1.284 +  val vars = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd
   1.285 +	       |> strip_comb |> snd |> filter is_listVar
   1.286 +  val cert = cterm_of (ProofContext.theory_of ctxt)
   1.287 +  val cvs = map (fn (v as Var(n,t)) => (cert v, the (AList.lookup Type.could_unify (!bds) t) |> snd |> HOLogic.mk_list (dest_listT t) |> cert)) vars
   1.288 +  val th' = instantiate ([], cvs) th
   1.289 +  val t' = (fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) th'
   1.290 +  val th'' = Goal.prove ctxt [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq (t, t')))
   1.291 +			(fn _ => simp_tac (local_simpset_of ctxt) 1)
   1.292 +  val _ = bds := []
   1.293 +in FWD trans [th'',th']
   1.294 +end
   1.295 +
   1.296 +
   1.297 +fun genreflect ctxt conv corr_thms raw_eqs t =
   1.298 +let 
   1.299 +  val reifth = genreif ctxt raw_eqs t
   1.300 +  fun trytrans [] = error "No suitable correctness theorem found"
   1.301 +    | trytrans (th::ths) = 
   1.302 +         (FWD trans [reifth, th RS sym] handle THM _ => trytrans ths)
   1.303 +  val th = trytrans corr_thms
   1.304 +  val ft = (Thm.dest_arg1 o Thm.dest_arg o Thm.dest_arg o cprop_of) th
   1.305 +  val rth = conv ft
   1.306 +in simplify (HOL_basic_ss addsimps raw_eqs addsimps [nth_Cons_0, nth_Cons_Suc])
   1.307 +           (simplify (HOL_basic_ss addsimps [rth]) th)
   1.308 +end
   1.309 +
   1.310 +fun genreify_tac ctxt eqs to i = (fn st =>
   1.311 +  let
   1.312 +    val P = HOLogic.dest_Trueprop (List.nth (prems_of st, i - 1))
   1.313 +    val t = (case to of NONE => P | SOME x => x)
   1.314 +    val th = (genreif ctxt eqs t) RS ssubst
   1.315 +  in rtac th i st
   1.316 +  end);
   1.317 +
   1.318 +    (* Reflection calls reification and uses the correctness *)
   1.319 +        (* theorem assumed to be the dead of the list *)
   1.320 +fun gen_reflection_tac ctxt conv corr_thms raw_eqs to i = (fn st =>
   1.321 +  let
   1.322 +    val P = HOLogic.dest_Trueprop (nth (prems_of st) (i - 1));
   1.323 +    val t = the_default P to;
   1.324 +    val th = genreflect ctxt conv corr_thms raw_eqs t
   1.325 +      RS ssubst;
   1.326 +  in (rtac th i THEN TRY(rtac TrueI i)) st end);
   1.327 +
   1.328 +fun reflection_tac ctxt = gen_reflection_tac ctxt Codegen.evaluation_conv;
   1.329 +
   1.330 +end