Hoare logic Hoare logic Program verification approach compositional








- Slides: 8

Hoare logic

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

Verification Rules

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} q = 0; r = x; {x=qy+r} 2) {x=qy+r Æ r ¸ y} r = r-y; q = q+1; {x=qy+r} 3) {x=qy+r Æ r < y} Skip {x =qy+r Æ 0 · r < y} {x ¸ 0 Æ y ¸ 0} skip {x = 0*y + x} {x=qy+r Æ r ¸ y} skip {x = (q+1)y + r-y} OK OK Fails: we cannot conclude 0 · r

Attempt 2 Try P = {x=qy+r Æ 0 · r} 1) {x ¸ 0 Æ y ¸ 0} q = 0; r = x; {x=qy+r Æ 0 · r} 2) {x=qy+r Æ 0 · r Æ r ¸ y} r = r-y; q = q+1; {x=qy+r Æ 0 · r} 3) {x=qy+r Æ 0 · r Æ r < y} Skip {x =qy+r Æ 0 · r < y} {x ¸ 0 Æ y ¸ 0} skip {x = 0*y + x Æ 0 · x} OK {x=qy+r Æ 0 · r Æ r ¸ y} skip {x = (q+1)y + r-y Æ 0 · r-y} OK OK

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