src/HOL/Hoare/Hoare.ML
changeset 5646 7c2ddbaf8b8c
parent 5183 89f162de39cf
child 6162 484adda70b65
--- a/src/HOL/Hoare/Hoare.ML	Wed Oct 14 11:51:11 1998 +0200
+++ b/src/HOL/Hoare/Hoare.ML	Wed Oct 14 15:26:31 1998 +0200
@@ -1,226 +1,210 @@
 (*  Title:      HOL/Hoare/Hoare.ML
     ID:         $Id$
-    Author:     Norbert Galm & Tobias Nipkow
-    Copyright   1995 TUM
+    Author:     Leonor Prensa Nieto & Tobias Nipkow
+    Copyright   1998 TUM
 
-The verification condition generation tactics.
+Derivation of the proof rules and, most importantly, the VCG tactic.
 *)
 
-open Hoare;
-
-(*** Hoare rules ***)
+(*** The proof rules ***)
 
-val SkipRule = prove_goalw thy [Spec_def,Skip_def]
-  "(!!s. p(s) ==> q(s)) ==> Spec p Skip q"
-  (fn prems => [fast_tac (claset() addIs prems) 1]);
+Goalw [Valid_def] "p <= q ==> Valid p SKIP q";
+by(Auto_tac);
+qed "SkipRule";
 
-val AssignRule = prove_goalw thy [Spec_def,Assign_def]
-  "(!!s. p s ==> q(%x. if x=v then e s else s x)) ==> Spec p (Assign v e) q"
-  (fn prems => [fast_tac (claset() addIs prems) 1]);
+Goalw [Valid_def] "p <= {s. (f s):q} ==> Valid p (Basic f) q";
+by(Auto_tac);
+qed "BasicRule";
 
-val SeqRule = prove_goalw thy [Spec_def,Seq_def]
-  "[| Spec p c (%s. q s); Spec (%s. q s) c' r |] ==> Spec p (Seq c c') r"
-  (fn prems => [cut_facts_tac prems 1, Fast_tac 1]);
+Goalw [Valid_def] "[| Valid P c1 Q; Valid Q c2 R |] ==> Valid P (c1;c2) R";
+by(Asm_simp_tac 1);
+by(Blast_tac 1);
+qed "SeqRule";
 
-val IfRule = prove_goalw thy [Spec_def,Cond_def]
-  "[| !!s. p s ==> (b s --> q s) & (~b s --> q' s); \
-\     Spec (%s. q s) c r; Spec (%s. q' s) c' r |] \
-\  ==> Spec p (Cond b c c') r"
-  (fn [prem1,prem2,prem3] =>
-     [REPEAT (rtac allI 1),
-      REPEAT (rtac impI 1),
-      dtac prem1 1,
-      cut_facts_tac [prem2,prem3] 1,
-      fast_tac (claset() addIs [prem1]) 1]);
-
-val strenthen_pre = prove_goalw thy [Spec_def]
-  "[| !!s. p s ==> p' s; Spec p' c q |] ==> Spec p c q"
-  (fn [prem1,prem2] =>[cut_facts_tac [prem2] 1,
-                       fast_tac (claset() addIs [prem1]) 1]);
+Goalw [Valid_def]
+ "[| p <= {s. (s:b --> s:w) & (s~:b --> s:w')}; \
+\    Valid w c1 q; Valid w' c2 q |] \
+\ ==> Valid p (IF b THEN c1 ELSE c2 FI) q";
+by(Asm_simp_tac 1);
+by(Blast_tac 1);
+qed "CondRule";
 
-val lemma = prove_goalw thy [Spec_def,While_def]
-  "[| Spec (%s. I s & b s) c I; !!s. [| I s; ~b s |] ==> q s |] \
-\  ==> Spec I (While b I c) q"
-  (fn [prem1,prem2] =>
-     [REPEAT(rtac allI 1), rtac impI 1, etac exE 1, rtac mp 1, atac 2,
-      etac thin_rl 1, res_inst_tac[("x","s")]spec 1,
-      res_inst_tac[("x","s'")]spec 1, induct_tac "n" 1,
-      Simp_tac 1,
-      fast_tac (claset() addIs [prem2]) 1,
-      simp_tac (simpset() addsimps [Seq_def]) 1,
-      cut_facts_tac [prem1] 1, fast_tac (claset() addIs [prem2]) 1]);
+Goal "! s s'. Sem c s s' --> s : I Int b --> s' : I ==> \
+\     ! s s'. s : I --> iter n b (Sem c) s s' --> s' : I & s' ~: b";
+by(induct_tac "n" 1);
+ by(Asm_simp_tac 1);
+by(Simp_tac 1);
+by(Blast_tac 1);
+val lemma = result() RS spec RS spec RS mp RS mp;
 
-val WhileRule = lemma RSN (2,strenthen_pre);
+Goalw [Valid_def]
+ "[| p <= i; Valid (i Int b) c i; (i Int -b) <= q |] \
+\ ==> Valid p (WHILE b INV {i} DO c OD) q";
+by(Asm_simp_tac 1);
+by(Clarify_tac 1);
+bd lemma 1;
+ba 2;
+by(Blast_tac 1);
+by(Blast_tac 1);
+qed "WhileRule";
 
-
-(*** meta_spec used in StateElimTac ***)
+(*** The tactics ***)
 
-val meta_spec = prove_goal HOL.thy
-  "(!!s x. PROP P s x) ==> (!!s. PROP P s (x s))"
-  (fn prems => [resolve_tac prems 1]);
-
-
-(**************************************************************************************************)
-(*** Funktion zum Generieren eines Theorems durch Umbennenen von Namen von Lambda-Abstraktionen ***)
-(*** in einem bestehenden Theorem. Bsp.: "!a.?P(a) ==> ?P(?x)" aus "!x.?P(x) ==> ?P(?x)"        ***)
-(**************************************************************************************************)
+(*****************************************************************************)
+(** The function Mset makes the theorem                                     **)
+(** "?Mset <= {(x1,...,xn). ?P (x1,...,xn)} ==> ?Mset <= {s. ?P s}",        **)
+(** where (x1,...,xn) are the variables of the particular program we are    **)
+(** working on at the moment of the call. For instance, (found,x,y) are     **)
+(** the variables of the Zero Search program.                               **)
+(*****************************************************************************)
 
-(* rename_abs:term (von:string,nach:string,trm:term) benennt in trm alle Lambda-Abstraktionen
-   mit Namen von in nach um *)
+local open HOLogic in
 
-fun rename_abs (von,nach,Abs (s,t,trm)) =
-    if von=s
-	then Abs (nach,t,rename_abs (von,nach,trm))
-        else Abs (s,t,rename_abs (von,nach,trm))
-  | rename_abs (von,nach,trm1 $ trm2)   =rename_abs (von,nach,trm1) $ rename_abs (von,nach,trm2)
-  | rename_abs (_,_,trm)                =trm;
+(** maps (%x1 ... xn. t) to [x1,...,xn] **)
+fun abs2list (Const ("split",_) $ (Abs(x,T,t))) = Free (x, T)::abs2list t
+  | abs2list (Abs(x,T,t)) = [Free (x, T)]
+  | abs2list _ = [];
+
+(** maps {(x1,...,xn). t} to [x1,...,xn] **)
+fun mk_vars (Const ("Collect",_) $ T) = abs2list T
+  | mk_vars _ = [];
 
-(* ren_abs_thm:thm (von:string,nach:string,theorem:thm) benennt in theorem alle Lambda-Abstraktionen
-   mit Namen von in nach um. Vorgehen:
-        - Term t zu thoerem bestimmen
-        - Term t' zu t durch Umbenennen der Namen generieren
-        - Certified Term ct' zu t' erstellen
-        - Thoerem ct'==ct' anlegen
-        - Nach der Regel "[|P==Q; P|] ==> Q" wird aus "ct'==ct'" und theorem das Theorem zu ct'
-          abgeleitet (ist moeglich, da t' mit t unifiziert werden kann, da nur Umnbenennungen) *)
-
-fun ren_abs_thm (von,nach,theorem)      =
-        equal_elim
-                (reflexive (cterm_of (#sign (rep_thm theorem))
-			    (rename_abs (von,nach,#prop (rep_thm theorem)))))
-                theorem;
-
+(** abstraction of body over a tuple formed from a list of free variables. 
+Types are also built **)
+fun mk_abstupleC []     body = absfree ("x", unitT, body)
+  | mk_abstupleC (v::w) body = let val (n,T) = dest_Free v
+                               in if w=[] then absfree (n, T, body)
+        else let val z  = mk_abstupleC w body;
+                 val T2 = case z of Abs(_,T,_) => T
+                        | Const (_, Type (_,[_, Type (_,[T,_])])) $ _ => T;
+       in Const ("split", (T --> T2 --> boolT) --> mk_prodT (T,T2) --> boolT) 
+          $ absfree (n, T, z) end end;
 
-(****************************************************************************)
-(*** Taktik zum Anwenden eines Theorems theorem auf ein Subgoal i durch   ***)
-(***  - Umbenennen von Lambda-Abstraktionen im Theorem                    ***)
-(***  - Instanziieren von freien Variablen im Theorem                     ***)
-(***  - Composing des Subgoals mit dem Theorem                            ***)
-(****************************************************************************)
+(** maps [x1,...,xn] to (x1,...,xn) and types**)
+fun mk_bodyC []      = Const ("()", unitT) 
+  | mk_bodyC (x::xs) = if xs=[] then x 
+               else let val (n, T) = dest_Free x ;
+                        val z = mk_bodyC xs;
+                        val T2 = case z of Free(_, T) => T
+                                         | Const ("Pair", Type ("fun", [_, Type
+                                            ("fun", [_, T])])) $ _ $ _ => T;
+                 in Const ("Pair", [T, T2] ---> mk_prodT (T, T2)) $ x $ z end;
 
-(* - rens:(string*string) list, d.h. es koennen verschiedene Lambda-Abstraktionen umbenannt werden
-   - insts:(cterm*cterm) list, d.h. es koennen verschiedene Variablen instanziiert werden *)
+fun dest_Goal (Const ("Goal", _) $ P) = P;
 
-fun comp_inst_ren_tac rens insts theorem i      =
-        let fun compose_inst_ren_tac [] insts theorem i                     =
-	      compose_tac (false,
-			   cterm_instantiate insts theorem,nprems_of theorem) i
-	      | compose_inst_ren_tac ((von,nach)::rl) insts theorem i       =
-                        compose_inst_ren_tac rl insts 
-			  (ren_abs_thm (von,nach,theorem)) i
-        in  compose_inst_ren_tac rens insts theorem i  end;
+(** maps a goal of the form:
+        1. [| P |] ==> |- VARS x1 ... xn. {._.} _ {._.} or to [x1,...,xn]**) 
+fun get_vars thm = let  val c = dest_Goal (concl_of (thm));
+                        val d = Logic.strip_assums_concl c;
+                        val Const _ $ pre $ _ $ _ = dest_Trueprop d;
+      in mk_vars pre end;
 
 
-(***************************************************************    *********)
-(*** Taktik zum Eliminieren des Zustandes waehrend Hoare-Beweisen                               ***)
-(***    Bsp.: "!!s. s(Suc(0))=0 --> s(Suc(0))+1=1" wird zu "!!s b. b=0 --> b+1=1"               ***)
-(****************************************************************************)
+(** Makes Collect with type **)
+fun mk_CollectC trm = let val T as Type ("fun",[t,_]) = fastype_of trm 
+                      in Collect_const t $ trm end;
+
+fun inclt ty = Const ("op <=", [ty,ty] ---> boolT);
+
+(** Makes "Mset <= t" **)
+fun Mset_incl t = let val MsetT = fastype_of t 
+                 in mk_Trueprop ((inclt MsetT) $ Free ("Mset", MsetT) $ t) end;
+
 
-(* pvars_of_term:term list (name:string,trm:term) gibt die Liste aller Programm-Variablen
-   aus trm zurueck. name gibt dabei den Namen der Zustandsvariablen an.
-        Bsp.: bei name="s" und dem Term "s(Suc(Suc(0)))=s(0)" (entspricht "c=a")
-              wird [0,Suc(Suc(0))] geliefert (Liste ist i.A. unsortiert) *)
+fun Mset thm = let val vars = get_vars(thm);
+                   val varsT = fastype_of (mk_bodyC vars);
+                   val big_Collect = mk_CollectC (mk_abstupleC vars 
+                         (Free ("P",varsT --> boolT) $ mk_bodyC vars));
+                   val small_Collect = mk_CollectC (Abs("x",varsT,
+                           Free ("P",varsT --> boolT) $ Bound 0));
+                   val impl = implies $ (Mset_incl big_Collect) $ 
+                                          (Mset_incl small_Collect);
+                   val cimpl = cterm_of (#sign (rep_thm thm)) impl
+   in  prove_goalw_cterm [] cimpl (fn prems => 
+                              [cut_facts_tac prems 1,Blast_tac 1]) end;
 
-fun pvars_of_term (name,trm)    =
-  let fun add_vars (name,Free (s,t) $ trm,vl) =
-            if name=s then if trm mem vl then vl else trm::vl
-                      else add_vars (name,trm,vl)
-	| add_vars (name,Abs (s,t,trm),vl)    =add_vars (name,trm,vl)
-	| add_vars (name,trm1 $ trm2,vl)      =add_vars (name,trm2,add_vars (name,trm1,vl))
-	| add_vars (_,_,vl)                   =vl
-  in add_vars (name,trm,[]) end;
+end;
 
 
-(* VarsElimTac: Taktik zum Eliminieren von bestimmten Programmvariablen aus dem Subgoal i
- - v::vl:(term) list  Liste der zu eliminierenden Programmvariablen
- - meta_spec:thm      Theorem, welches zur Entfernung der Variablen benutzt wird
-		      z.B.: "(!!s x. PROP P(s,x)) ==> (!!s. PROP P(s,x(s)))"
- - namexAll:string    Name von    ^                                  (hier "x")
- - varx:term          Term zu                                      ^ (hier Var(("x",0),...))
- - varP:term          Term zu                                  ^     (hier Var(("P",0),...))
- - type_pvar:typ      Typ der Programmvariablen (d.h. 'a bei 'a prog, z.B.: nat, bool, ...)
+(*****************************************************************************)
+(** Simplifying:                                                            **)
+(** Some useful lemmata, lists and simplification tactics to control which  **)
+(** theorems are used to simplify at each moment, so that the original      **)
+(** input does not suffer any unexpected transformation                     **)
+(*****************************************************************************)
+
+val Compl_Collect = prove_goal thy "-(Collect b) = {x. ~(b x)}"
+    (fn _ => [Fast_tac 1]);
+
+(**Simp_tacs**)
 
- Vorgehen:
-      - eliminiere jede pvar durch Anwendung von comp_inst_ren_tac. Dazu:
-      - Unbenennung in meta_spec: namexAll wird in den Namen der Prog.-Var. umbenannt
-	z.B.: fuer die Prog.-Var. mit Namen "a" ergibt sich
-	      meta_spec zu "(!! s a. PROP P(s,a)) ==> (!! s. PROP P(s,x(s)))"
-      - Instanziierungen in meta_spec:
-	      varx wird mit "%s:(type_pvar) state. s(pvar)" instanziiert
-	      varP wird entsprechend instanziiert. Beispiel fuer Prog.-Var. "a":
-	 - zu Subgoal "!!s. s(Suc(0)) = s(0) ==> s(0) = 1" bestimme Term ohne "!!s.":
-		trm0 = "s(Suc(0)) = s(0) ==> s(0) = 1" (s ist hier freie Variable)
-	 - substituiere alle Vorkommen von s(pvar) durch eine freie Var. xs:
-		trm1 = "s(Suc(0)) = xs ==> xs = 1"
-	 - abstrahiere ueber xs:
-		trm2 = "%xs. s(Suc(0)) = xs ==> xs = 1"
-	 - abstrahiere ueber restliche Vorkommen von s:
-		trm3 = "%s xs. s(Suc(0)) = xs ==> xs = 1"
-	 - instanziiere varP mit trm3
-*)
+val before_set2pred_simp_tac =
+  (simp_tac (HOL_basic_ss addsimps [Collect_conj_eq RS sym,Compl_Collect]));
+
+val split_simp_tac = (simp_tac (HOL_basic_ss addsimps [split]));
+
+(*****************************************************************************)
+(** set2pred transforms sets inclusion into predicates implication,         **)
+(** maintaining the original variable names.                                **)
+(** Ex. "{x. x=0} <= {x. x <= 1}" -set2pred-> "x=0 --> x <= 1"              **)
+(** Subgoals containing intersections (A Int B) or complement sets (-A)     **)
+(** are first simplified by "before_set2pred_simp_tac", that returns only   **)
+(** subgoals of the form "{x. P x} <= {x. Q x}", which are easily           **)
+(** transformed.                                                            **)
+(** This transformation may solve very easy subgoals due to a ligth         **)
+(** simplification done by (split_all_tac)                                  **)
+(*****************************************************************************)
 
-(* StateElimTac: tactic to eliminate all program variable from subgoal i
-    - applies to subgoals of the form "!!s:('a) state. P(s)",
-        i.e. the term  Const("all",_) $ Abs ("s",pvar --> 'a,_)
-    -   meta_spec has the form "(!!s x. PROP P(s,x)) ==> (!!s. PROP P(s,x(s)))"
-*)
+fun set2pred i thm = let fun mk_string [] = ""
+                           | mk_string (x::xs) = x^" "^mk_string xs;
+                         val vars=get_vars(thm);
+                         val var_string = mk_string (map (fst o dest_Free) vars);
+      in ((before_set2pred_simp_tac i) THEN_MAYBE
+          (EVERY [rtac subsetI i, 
+                  rtac CollectI i,
+                  dtac CollectD i,
+                  (TRY(split_all_tac i)) THEN_MAYBE 
+                  ((rename_tac var_string i) THEN
+                   (full_simp_tac (HOL_basic_ss addsimps [split]) i)) ])) thm
+      end;
+
+(*****************************************************************************)
+(** BasicSimpTac is called to simplify all verification conditions. It does **)
+(** a light simplification by applying "mem_Collect_eq", then it calls      **)
+(** MaxSimpTac, which solves subgoals of the form "A <= A",                 **)
+(** and transforms any other into predicates, applying then                 **)
+(** the tactic chosen by the user, which may solve the subgoal completely.  **)
+(*****************************************************************************)
+
+fun MaxSimpTac tac = FIRST'[rtac subset_refl, set2pred THEN_MAYBE' tac];
 
-val StateElimTac = SUBGOAL (fn (Bi,i) =>
-  let val Const _ $ Abs (_,Type ("fun",[_,type_pvar]),trm) = Bi
-      val _ $ (_ $ Abs (_,_,_ $ Abs (namexAll,_,_))) $
-			    (_ $ Abs (_,_,varP $ _ $ (varx $ _))) = 
-			    #prop (rep_thm meta_spec)
-      fun vtac v i st = st |>
-	  let val cterm = cterm_of (#sign (rep_thm st))
-	      val (_,_,_ $ Abs (_,_,trm),_) = dest_state (st,i);
-	      val (sname,trm0) = variant_abs ("s",dummyT,trm);
-	      val xsname = variant_name ("xs",trm0);
-	      val trm1 = subst_term (Free (sname,dummyT) $ v,
-				     Syntax.free xsname,trm0)
-	      val trm2 = Abs ("xs", type_pvar,
-			      abstract_over (Syntax.free xsname,trm1))
-	  in
-	      comp_inst_ren_tac
-		[(namexAll,pvar2pvarID v)]
-		[(cterm varx,
-		  cterm (Abs  ("s",Type ("nat",[]) --> type_pvar,
-			       Bound 0 $ v))),
-		 (cterm varP,
-		  cterm (Abs ("s", Type ("nat",[]) --> type_pvar,
-			      abstract_over (Free (sname,dummyT),trm2))))]
-		meta_spec i
-	  end
-      fun vars_tac [] i      = all_tac
-	| vars_tac (v::vl) i = vtac v i THEN vars_tac vl i
-  in
-      vars_tac (pvars_of_term (variant_abs ("s",dummyT,trm))) i
-  end);
+fun BasicSimpTac tac =
+  simp_tac (HOL_basic_ss addsimps [mem_Collect_eq,split])
+  THEN_MAYBE' MaxSimpTac tac;
+
+(** HoareRuleTac **)
+
+fun WlpTac Mlem tac i = rtac SeqRule i THEN  HoareRuleTac Mlem tac false (i+1)
+and HoareRuleTac Mlem tac pre_cond i st = st |>
+        (*abstraction over st prevents looping*)
+    ( (WlpTac Mlem tac i THEN HoareRuleTac Mlem tac pre_cond i)
+      ORELSE
+      (FIRST[rtac SkipRule i,
+             EVERY[rtac BasicRule i,
+                   rtac Mlem i,
+                   split_simp_tac i],
+             EVERY[rtac CondRule i,
+                   HoareRuleTac Mlem tac false (i+2),
+                   HoareRuleTac Mlem tac false (i+1)],
+             EVERY[rtac WhileRule i,
+                   BasicSimpTac tac (i+2),
+                   HoareRuleTac Mlem tac true (i+1)] ] 
+       THEN (if pre_cond then (BasicSimpTac tac i) else (rtac subset_refl i)) ));
 
 
-(*** tactics for verification condition generation ***)
-
-(* pre_cond:bool gibt an, ob das Subgoal von der Form Spec(?Q,c,p) ist oder nicht. Im Fall
-   von pre_cond=false besteht die Vorbedingung nur nur aus einer scheme-Variable. Die dann
-   generierte Verifikationsbedingung hat die Form "!!s.?Q --> ...". "?Q" kann deshalb zu gegebenen
-   Zeitpunkt mittels "rtac impI" und "atac" gebunden werden, die Bedingung loest sich dadurch auf. *)
-
-fun WlpTac i = (rtac SeqRule i) THEN (HoareRuleTac (i+1) false)
-and HoareRuleTac i pre_cond st = st |>  
-	(*abstraction over st prevents looping*)
-    ( (WlpTac i THEN HoareRuleTac i pre_cond)
-      ORELSE
-      (FIRST[rtac SkipRule i,
-	     rtac AssignRule i,
-	     EVERY[rtac IfRule i,
-		   HoareRuleTac (i+2) false,
-		   HoareRuleTac (i+1) false],
-	     EVERY[rtac WhileRule i,
-		   Asm_full_simp_tac (i+2),
-		   HoareRuleTac (i+1) true]]
-       THEN
-       (if pre_cond then (Asm_full_simp_tac i) else (atac i))) );
-
-val hoare_tac = 
-  SELECT_GOAL
-    (EVERY[HoareRuleTac 1 true, ALLGOALS StateElimTac, prune_params_tac]);
-
+(** tac:(int -> tactic) is the tactic the user chooses to solve or simplify **)
+(** the final verification conditions                                       **)
+ 
+fun hoare_tac tac i thm =
+  let val Mlem = Mset(thm)
+  in SELECT_GOAL(EVERY[HoareRuleTac Mlem tac true 1]) i thm end;