src/HOL/ex/reflection.ML
author urbanc
Tue Jun 05 09:56:19 2007 +0200 (2007-06-05)
changeset 23243 a37d3e6e8323
parent 22568 ed7aa5a350ef
child 23548 e25991f126ce
permissions -rw-r--r--
included Class.thy in the compiling process for Nominal/Examples
     1 (*
     2     ID:         $Id$
     3     Author:     Amine Chaieb, TU Muenchen
     4 
     5 A trial for automatical reification.
     6 *)
     7 
     8 signature REFLECTION = sig
     9   val genreify_tac: Proof.context -> thm list -> term option -> int -> tactic
    10   val reflection_tac: Proof.context -> thm list -> term option -> int -> tactic
    11   val gen_reflection_tac: Proof.context -> (cterm -> thm)
    12     -> thm list -> term option -> int -> tactic
    13 end;
    14 
    15 structure Reflection : REFLECTION
    16 = struct
    17 
    18 val ext2 = thm "ext2";
    19 val nth_Cons_0 = thm "nth_Cons_0";
    20 val nth_Cons_Suc = thm "nth_Cons_Suc";
    21 
    22   (* Make a congruence rule out of a defining equation for the interpretation *)
    23   (* th is one defining equation of f, i.e.
    24      th is "f (Cp ?t1 ... ?tn) = P(f ?t1, .., f ?tn)" *)
    25   (* Cp is a constructor pattern and P is a pattern *)
    26 
    27   (* The result is:
    28       [|?A1 = f ?t1 ; .. ; ?An= f ?tn |] ==> P (?A1, .., ?An) = f (Cp ?t1 .. ?tn) *)
    29   (*  + the a list of names of the A1 .. An, Those are fresh in the ctxt*)
    30 
    31 
    32 fun mk_congeq ctxt fs th = 
    33   let 
    34    val (f as Const(fN,fT)) = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq 
    35 				|> fst |> strip_comb |> fst
    36    val thy = ProofContext.theory_of ctxt
    37    val cert = Thm.cterm_of thy
    38    val (((_,_),[th']), ctxt') = Variable.import_thms true [th] ctxt
    39    val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop (Thm.prop_of th'))
    40    fun add_fterms (t as t1 $ t2) = 
    41        if exists (fn f => could_unify (t |> strip_comb |> fst, f)) fs then insert (op aconv) t
    42        else add_fterms t1 #> add_fterms t2
    43      | add_fterms (t as Abs(xn,xT,t')) = 
    44        if (fN mem (term_consts t)) then (fn _ => [t]) else (fn _ => [])
    45      | add_fterms _ = I
    46    val fterms = add_fterms rhs []
    47    val (xs, ctxt'') = Variable.variant_fixes (replicate (length fterms) "x") ctxt'
    48    val tys = map fastype_of fterms
    49    val vs = map Free (xs ~~ tys)
    50    val env = fterms ~~ vs
    51 		    (* FIXME!!!!*)	
    52    fun replace_fterms (t as t1 $ t2) =
    53        (case AList.lookup (op aconv) env t of
    54 	    SOME v => v
    55 	  | NONE => replace_fterms t1 $ replace_fterms t2)
    56      | replace_fterms t = (case AList.lookup (op aconv) env t of
    57 			       SOME v => v
    58 			     | NONE => t)
    59       
    60    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)))
    61      | mk_def (t, v) = HOLogic.mk_Trueprop (HOLogic.mk_eq (v, t))
    62    fun tryext x = (x RS ext2 handle _ =>  x)
    63    val cong = (Goal.prove ctxt'' [] (map mk_def env)
    64 			  (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, replace_fterms rhs)))
    65 			  (fn x => LocalDefs.unfold_tac (#context x) (map tryext (#prems x)) 
    66 							THEN rtac th' 1)) RS sym
    67 	      
    68    val (cong' :: vars') = 
    69        Variable.export ctxt'' ctxt (cong :: map (Drule.mk_term o cert) vs)
    70    val vs' = map (fst o fst o Term.dest_Var o Thm.term_of o Drule.dest_term) vars'
    71 					      
    72   in  (vs', cong') end; 
    73  (* congs is a list of pairs (P,th) where th is a theorem for *)
    74         (* [| f p1 = A1; ...; f pn = An|] ==> f (C p1 .. pn) = P *)
    75 val FWD = curry (op OF);
    76 
    77  (* da is the decomposition for atoms, ie. it returns ([],g) where g
    78  returns the right instance f (AtC n) = t , where AtC is the Atoms
    79  constructor and n is the number of the atom corresponding to t *)
    80 
    81 (* Generic decomp for reification : matches the actual term with the
    82 rhs of one cong rule. The result of the matching guides the
    83 proof synthesis: The matches of the introduced Variables A1 .. An are
    84 processed recursively
    85  The rest is instantiated in the cong rule,i.e. no reification is needed *)
    86 
    87 exception REIF of string;
    88 
    89 val bds = ref ([]: (typ * ((term list) * (term list))) list);
    90 
    91 fun index_of t = 
    92  let 
    93   val tt = HOLogic.listT (fastype_of t)
    94  in 
    95   (case AList.lookup Type.could_unify (!bds) tt of
    96     NONE => error "index_of : type not found in environements!"
    97   | SOME (tbs,tats) =>
    98     let
    99      val i = find_index_eq t tats
   100      val j = find_index_eq t tbs 
   101     in (if j= ~1 then 
   102 	    if i= ~1 
   103 	    then (bds := AList.update (op =) (tt,(tbs,tats@[t])) (!bds) ; 
   104 		  length tbs + length tats) 
   105 	    else i else j)
   106     end)
   107  end;
   108 
   109 fun dest_listT (Type ("List.list", [T])) = T;
   110 
   111 fun decomp_genreif da cgns (t,ctxt) =
   112  let 
   113   val thy = ProofContext.theory_of ctxt 
   114   val cert = cterm_of thy
   115   fun tryabsdecomp (s,ctxt) = 
   116    (case s of 
   117      Abs(xn,xT,ta) => 
   118      (let
   119        val ([xn],ctxt') = Variable.variant_fixes ["x"] ctxt
   120        val (xn,ta) = variant_abs (xn,xT,ta)
   121        val x = Free(xn,xT)
   122        val _ = (case AList.lookup (op =) (!bds) (HOLogic.listT xT)
   123 		 of NONE => error "tryabsdecomp: Type not found in the Environement"
   124 		  | SOME (bsT,atsT) => 
   125 		    (bds := AList.update (op =) (HOLogic.listT xT, ((x::bsT), atsT)) (!bds)))
   126       in ([(ta, ctxt')] , 
   127 	  fn [th] => ((let val (bsT,asT) = the(AList.lookup (op =) (!bds) (HOLogic.listT xT))
   128 		       in (bds := AList.update (op =) (HOLogic.listT xT,(tl bsT,asT)) (!bds))
   129 		       end) ; 
   130 		      hd (Variable.export ctxt' ctxt [(forall_intr (cert x) th) COMP allI])))
   131 	end)
   132     | _ => da (s,ctxt))
   133   in 
   134   (case cgns of 
   135     [] => tryabsdecomp (t,ctxt)
   136   | ((vns,cong)::congs) => ((let
   137         val cert = cterm_of thy
   138 	val certy = ctyp_of thy
   139         val (tyenv, tmenv) =
   140         Pattern.match thy
   141         ((fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) (concl_of cong), t)
   142         (Envir.type_env (Envir.empty 0),Term.Vartab.empty)
   143         val (fnvs,invs) = List.partition (fn ((vn,_),_) => vn mem vns) (Vartab.dest tmenv)
   144         val (fts,its) = 
   145 	    (map (snd o snd) fnvs,
   146              map (fn ((vn,vi),(tT,t)) => (cert(Var ((vn,vi),tT)), cert t)) invs)
   147 	val ctyenv = map (fn ((vn,vi),(s,ty)) => (certy (TVar((vn,vi),s)), certy ty)) (Vartab.dest tyenv)
   148     in (fts ~~ (replicate (length fts) ctxt), FWD (instantiate (ctyenv, its) cong))
   149     end)
   150       handle MATCH => decomp_genreif da congs (t,ctxt)))
   151   end;
   152           (* looks for the atoms equation and instantiates it with the right number *)
   153 
   154 fun mk_decompatom eqs (t,ctxt) =
   155  let 
   156   val tT = fastype_of t
   157   fun isat eq = 
   158    let 
   159     val rhs = eq |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd
   160    in exists_Const 
   161 	  (fn (n,ty) => n="List.nth" 
   162 			andalso 
   163 			AList.defined Type.could_unify (!bds) (domain_type ty)) rhs 
   164 	  andalso Type.could_unify (fastype_of rhs, tT)
   165    end
   166   fun get_nth t = 
   167    case t of
   168      Const("List.nth",_)$vs$n => (t,vs,n)
   169    | t1$t2 => (get_nth t1 handle REIF "get_nth" => get_nth t2)
   170    | Abs(_,_,t') => get_nth t'
   171    | _ => raise REIF "get_nth"
   172   val ([xn,vsn],ctxt') = Variable.variant_fixes ["x","vs"] ctxt
   173   val thy = ProofContext.theory_of ctxt'
   174   val cert = cterm_of thy
   175   fun tryeqs [] = raise REIF "Can not find the atoms equation"
   176     | tryeqs (eq::eqs) = ((
   177       let 
   178        val rhs = eq |> prop_of |> HOLogic.dest_Trueprop 
   179 			  |> HOLogic.dest_eq |> snd
   180        val (nt,vs,n) = get_nth rhs
   181        val ntT = fastype_of nt
   182        val ntlT = HOLogic.listT ntT
   183        val (bsT,asT) = the (AList.lookup (op =) (!bds) ntlT) 
   184        val x = Var ((xn,0),ntT)
   185        val rhs_P = subst_free [(nt,x)] rhs
   186        val (_, tmenv) = Pattern.match 
   187 			    thy (rhs_P, t)
   188 			    (Envir.type_env (Envir.empty 0),Term.Vartab.empty)
   189        val tml = Vartab.dest tmenv
   190        val SOME (_,t') = AList.lookup (op =) tml (xn,0)
   191        val cvs = 
   192 	   cert (fold_rev (fn x => fn xs => Const("List.list.Cons", ntT --> ntlT --> ntlT)$x$xs)
   193 		       bsT (Free (vsn, ntlT)))
   194        val cts = map (fn ((vn,vi),(tT,t)) => (cert(Var ((vn,vi),tT)), cert t)) 
   195 		     (AList.delete (op =) (xn,0) tml)
   196        val th = (instantiate 
   197 		     ([],
   198 		      [(cert vs, cvs),(cert n, t' |> index_of |> IntInf.fromInt |> HOLogic.mk_nat |> cert)]
   199 		      @cts) eq) RS sym
   200       in hd (Variable.export ctxt' ctxt [th])
   201       end)
   202 	  handle MATCH => tryeqs eqs)
   203  in ([], fn _ => tryeqs (filter isat eqs))
   204  end;
   205 
   206 (* 
   207 fun mk_decompatom eqs (t,ctxt) =
   208  let 
   209   val tT = fastype_of t
   210   val tlT = HOLogic.listT tT
   211   val (bsT,asT) = (the (AList.lookup (op =) (!bds) tlT) 
   212 		   handle Option => error "mk_decompatom: Type not found in the env.")
   213   fun isateq (_$_$(Const("List.nth",_)$vs$_)) = (fastype_of vs = tlT)
   214     | isateq _ = false
   215  in case List.find (isateq o HOLogic.dest_Trueprop o prop_of) eqs of
   216      NONE => raise REIF "Can not find the atoms equation"
   217    | SOME th =>
   218      ([],
   219       fn ths =>
   220         let 
   221          val ([x], ctxt') = Variable.variant_fixes ["vs"] ctxt
   222 	 val cert = cterm_of (ProofContext.theory_of ctxt')
   223          val (Const("List.nth",_)$(vs as Var((vsn,vsi),_))$n) = 
   224              (snd o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) th
   225          val cvs = 
   226 	     cert (foldr (fn (x,xs) => Const("List.list.Cons", tT --> tlT --> tlT)$x$xs) 
   227 			 (Free(x,tlT)) bsT)
   228 	 val th' = (instantiate ([],
   229 				 [(cert vs, cvs), 
   230 				  (cert n, cert  (HOLogic.mk_nat(index_of t)))]) th)
   231 		       RS sym
   232         in hd (Variable.export ctxt' ctxt [th']) end)
   233  end;
   234 *)
   235   (* Generic reification procedure: *)
   236   (* creates all needed cong rules and then just uses the theorem synthesis *)
   237 
   238 fun mk_congs ctxt raw_eqs = 
   239  let 
   240   val fs = fold_rev (fn eq =>
   241 		     insert (op =) (eq |> prop_of |> HOLogic.dest_Trueprop 
   242 			 |> HOLogic.dest_eq |> fst |> strip_comb 
   243 			 |> fst)) raw_eqs []
   244   val tys = fold_rev (fn f => fn ts => (f |> fastype_of |> binder_types |> split_last |> fst) 
   245 				    union ts) fs []
   246   val _ = bds := AList.make (fn _ => ([],[])) tys
   247   val (vs, ctxt') = Variable.variant_fixes (replicate (length tys) "vs") ctxt
   248   val thy = ProofContext.theory_of ctxt'
   249   val cert = cterm_of thy
   250   val vstys = map (fn (t,v) => (t,SOME (cert (Free(v,t))))) 
   251 		  (tys ~~ vs)
   252   fun insteq eq ts = 
   253    let val itms = map (fn t => t|> (AList.lookup (op =) vstys) |> the) ts
   254    in instantiate' [] itms eq
   255    end
   256   val eqs = map (fn eq => eq |> prop_of |> HOLogic.dest_Trueprop 
   257 			     |> HOLogic.dest_eq |> fst |> strip_comb |> fst |> fastype_of 
   258 			     |> binder_types |> split_last |> fst 
   259 			     |> (insteq eq)) raw_eqs
   260   val (ps,congs) = split_list (map (mk_congeq ctxt' fs) eqs)
   261  in  ps ~~ (Variable.export ctxt' ctxt congs)
   262  end;
   263 
   264 fun genreif ctxt raw_eqs t =
   265  let 
   266   val _ = bds := []
   267   val congs = mk_congs ctxt raw_eqs
   268   val th = divide_and_conquer (decomp_genreif (mk_decompatom raw_eqs) congs) (t,ctxt)
   269   val tys = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd
   270 	       |> strip_comb |> fst |> fastype_of |> strip_type |> fst
   271 	       |> split_last |> fst
   272   val cert = cterm_of (ProofContext.theory_of ctxt)
   273   val cvs = map (fn t => t |> (AList.lookup (op =) (!bds)) |> the |> snd 
   274 			   |> HOLogic.mk_list (dest_listT t) |> cert |> SOME)
   275 		tys
   276   val th' = (instantiate' [] cvs (th RS sym)) RS sym
   277   val t' = (fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of) th'
   278   val th'' = Goal.prove ctxt [] [] (HOLogic.mk_Trueprop (HOLogic.mk_eq (t, t')))
   279 			(fn _ => Simp_tac 1)
   280   val _ = bds := []
   281  in FWD trans [th'',th']
   282  end;
   283 
   284 fun genreflect ctxt conv corr_thm raw_eqs t =
   285     let val th = FWD trans [genreif ctxt raw_eqs t, corr_thm RS sym]
   286         val ft = (snd o Thm.dest_comb o snd o Thm.dest_comb o snd o Thm.dest_comb o cprop_of) th
   287         val rth = conv ft
   288     in simplify (HOL_basic_ss addsimps raw_eqs addsimps [nth_Cons_0, nth_Cons_Suc])
   289                 (simplify (HOL_basic_ss addsimps [rth]) th)
   290     end
   291 
   292 fun genreify_tac ctxt eqs to i = (fn st =>
   293   let
   294     val P = HOLogic.dest_Trueprop (List.nth (prems_of st, i - 1))
   295     val t = (case to of NONE => P | SOME x => x)
   296     val th = (genreif ctxt eqs t) RS ssubst
   297   in rtac th i st
   298   end);
   299 
   300     (* Reflection calls reification and uses the correctness *)
   301         (* theorem assumed to be the dead of the list *)
   302 fun gen_reflection_tac ctxt conv (corr_thm :: raw_eqs) to i = (fn st =>
   303   let
   304     val P = HOLogic.dest_Trueprop (nth (prems_of st) (i - 1));
   305     val t = the_default P to;
   306     val th = genreflect ctxt conv corr_thm raw_eqs t
   307       RS ssubst;
   308   in rtac th i st end);
   309 
   310 fun reflection_tac ctxt = gen_reflection_tac ctxt NBE.normalization_conv;
   311 
   312 end