hoare-calculus program-proofing
Definition
Loop Invariant
A loop invariant is a logical formula (assertion) that holds true before, during, and after the execution of a loop. Specifically, for a loop
while e do Π od, the invariant must satisfy:
- It is true before the loop starts.
- If it is true before an iteration of the loop body (and the loop condition holds), it remains true after the execution of .
Verification Rule
The Hoare calculus rule for loops relies entirely on finding a suitable invariant:
Application in Proofs
To prove a specification , one must find an invariant such that:
- Precondition implies Invariant:
- Invariance: is a valid Hoare triple.
- Postcondition follows:
Finding Invariants
Finding a loop invariant is the most difficult part of program verification. It often requires creativity and understanding of the algorithm. There is no general algorithm to automatically generate loop invariants for arbitrary programs (due to the Halting Problem).
Strategies
- Generalisation: Start with the postcondition and try to generalise it (e.g., replace a constant with a variable).
- ** weakening**: If is too strong to be an invariant, find a weaker formula that is still strong enough to imply upon termination.