110 likes | 278 Views
Hoare logic. TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A A A. Hoare logic. Program verification approach c ompositional: correctness of big program is expressed in terms of correctness of its parts Hoare triples: {P} S {Q} i nterpretation:
E N D
Hoare logic TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: AAA
Hoare logic • Program verification approach • compositional: correctness of big program is expressed in terms of correctness of its parts • Hoare triples: {P} S {Q} • interpretation: • if you start S in a state in which P is true, and • S terminates, then • Q will be true in the final state • if S does not terminate, nothing is asserted
Example {x ¸ 0 Æ y ¸ 0} q = 0; r = x; while r ¸ y do r = r-y; q=q-1;od {x=qy+rÆ 0 · r < y} If loop invariant is P, we have three major proof obligations 1) {x ¸0 Æy ¸0} q = 0; r = x; {P} 2) {P Ær ¸y} r = r-y; q = q+1; {P} 3) {P Ær < y} skip {x =qy+rÆ0 ·r < y}
Attempt 1 Try P = {x=qy+r} 1) {x ¸0 Æy ¸0} {x ¸ 0 Æ y ¸ 0} q = 0; r = x; skip OK {x=qy+r} {x = 0*y + x} 2) {x=qy+rÆr ¸y} {x=qy+rÆ r ¸ y} r = r-y; q = q+1; skip OK {x=qy+r} {x = (q+1)y + r-y} 3) {x=qy+rÆr < y} Fails: we cannot conclude 0 · r Skip {x =qy+rÆ0 ·r < y}
Attempt 2 Try P = {x=qy+rÆ 0 · r} 1) {x ¸0 Æy ¸0} {x ¸ 0 Æ y ¸ 0} q = 0; r = x; skip OK {x=qy+rÆ 0 · r} {x = 0*y + x Æ 0 · x} 2) {x=qy+rÆ 0 · r Ær ¸y} {x=qy+rÆ 0 · r Æ r ¸ y} r = r-y; q = q+1; skip OK {x=qy+rÆ 0 · r} {x = (q+1)y + r-y Æ 0 · r-y} 3) {x=qy+rÆ 0 · r Ær < y} OK Skip {x =qy+rÆ 0 ·r < y}
Question • In Attempt 2, proof succeeded even though • Precondition of program: y ¸ 0 • Postcondition of program: y > 0 • Program did not change y ! • What went wrong? • Nothing: • Inference rules for Hoare logic are sound provided statements terminate • If y = 0, program does not terminate. • Exercise: try to verify program with P = {x=qy+rÆ y ¸ 0} Does it go through??
Remarks • Finding the right invariant is a creative process • often you can look at the pre- and post-conditions of loop to guess • Proving termination: find some quantity that • strictly decreases in each iteration • cannot decrease indefinitely • formal approach: well-founded sets • Modern theorem-provers can sometimes find invariants and prove termination on their own in many problems • But they may also fail, and then you must step in • Analogy: indefinite integration in calculus • the system has a bunch of rules but they may fail