Section 3.31

Hoare triple

Definition

A Hoare triple, written {P}C{Q}\{P\}\ C\ \{Q\}, is a statement about a piece of program CC: if CC starts in a state where the condition PP holds and CC finishes, then the condition QQ holds when it finishes. PP is the precondition and QQ the postcondition, both logical formulas over the program’s variables. This reading, called partial correctness, says nothing about runs that never finish; total correctness also requires CC to finish from every state that satisfies PP. Tony Hoare introduced these statements, and rules for proving them, in 1969.

The idea

A function’s comment says: given a whole number n≥0n \ge 0, it returns 1+2+…+n1 + 2 + \dots + n. That comment is a contract, a requirement on the caller and a promise about the result. A Hoare triple writes the contract in logic, so that it can be proved rather than hoped for. The proof goes piece by piece: a small set of rules, called Hoare logic, derives the triple for a whole program from triples for its statements. Robert Floyd had given a similar method for flowcharts in 1967 [268], so the rules are also called Floyd–Hoare logic.

The partial-correctness reading separates two questions. “If it finishes, is the answer right?” is answered with invariants. “Does it finish?” is answered with a separate termination argument. The separation has a trap. A program that never finishes satisfies every partial-correctness triple, because it has no final state that could violate QQ. The triple {true}\{\mathrm{true}\} while true do skip {false}\{\mathrm{false}\}, whose loop body skip does nothing, holds although no state satisfies false\mathrm{false}. A builder’s contract is a fair picture. “If you provide a level plot, and if the house is ever finished, it will have three bedrooms” is partial correctness; adding “and it will be finished” gives total correctness. The picture stops at the wording: the conditions of a triple are exact logical formulas, which can be checked mechanically.

How it works

A state gives a value to every variable. An assertion, such as x>0x > 0, is true or false in each state. Hoare logic proves triples with one rule for each kind of statement, plus one rule for adjusting conditions. Below, ∧\wedge means and, ¬\neg means not and ⇒\Rightarrow means implies.

Total-correctness triples are often written with square brackets, [P]C[Q][P]\ C\ [Q]. Edsger Dijkstra’s weakest precondition wp(C,Q)\mathrm{wp}(C, Q) is the weakest condition on the starting state that guarantees that CC finishes in a state satisfying QQ; [P]C[Q][P]\ C\ [Q] holds exactly when P⇒wp(C,Q)P \Rightarrow \mathrm{wp}(C, Q) is true in every state. Program verifiers compute such conditions automatically for code without loops and use the invariants and ranking functions that the programmer writes for loops. They give the resulting implications, called verification conditions, to an SMT solver §3.28 (satisfiability modulo theories solver, a program that decides such formulas).

Worked example

Partial correctness with an invariant. Call the following program CC:

i := 0; s := 0;
while i < n do (i := i + 1; s := s + i)

The claim is {n≥0}C{s=n(n+1)/2}\{n \ge 0\}\ C\ \{s = n(n+1)/2\}. Take the invariant II: 0≤i≤n0 \le i \le n and s=i(i+1)/2s = i(i+1)/2.

  1. Before the loop, i=0i = 0 and s=0s = 0, and 0=0⋅1/20 = 0 \cdot 1 / 2; with n≥0n \ge 0, also 0≤0≤n0 \le 0 \le n. So II holds.

  2. Each iteration starts with II and i<ni < n. The new ii is i+1i + 1, which is at most nn because i<ni < n and both are whole numbers. The new ss is i(i+1)/2+(i+1)=(i+1)(i+2)/2i(i+1)/2 + (i + 1) = (i+1)(i+2)/2, which is the formula of II for the new ii. So II holds again.

  3. At exit, II holds and i<ni < n is false, so i≤ni \le n and i≥ni \ge n; hence i=ni = n and s=n(n+1)/2s = n(n+1)/2.

By the loop rule and the sequence rule, the partial-correctness triple holds.

The termination argument. Take V=n−iV = n - i. Inside the loop i<ni < n, so V≥1V \ge 1, which is at least 0, and each iteration adds 1 to ii, so VV falls by exactly 1. With n=3n = 3 the values of (i,s,V)(i, s, V) are (0,0,3)(0, 0, 3), (1,1,2)(1, 1, 2), (2,3,1)(2, 3, 1) and (3,6,0)(3, 6, 0); then i<ni < n is false and the loop stops with s=6=3⋅4/2s = 6 = 3 \cdot 4 / 2. The invariant and the ranking function together give the total-correctness triple [n≥0]C[s=n(n+1)/2][n \ge 0]\ C\ [s = n(n+1)/2].

Partial but not total. The program i := 0; while i != n do i := i + 2, where != means not equal, satisfies the partial-correctness triple with precondition n≥0n \ge 0 and postcondition i=ni = n. The loop exits only when i=ni = n, so the invariant true\mathrm{true} and the exit condition give i=ni = n. The program is not totally correct. For n=3n = 3, ii takes the values 0, 2, 4, 6 and so on, and never equals 3. The candidate ranking function n−in - i takes the values 3, 1, −1-1, so the requirement V≥0V \ge 0 inside the loop fails. With the stronger precondition “n≥0n \ge 0 and nn even”, the invariant “ii is even and i≤ni \le n” and V=n−iV = n - i succeed. Inside the loop i≠ni \neq n, and two even numbers with i≤ni \le n and i≠ni \neq n satisfy i≤n−2i \le n - 2. So after the step i+2≤ni + 2 \le n, and VV falls by 2 while staying at least 0.

Machine arithmetic. With 8-bit unsigned integers, which hold 0 to 255 and wrap around, the triple {x≥0}y:=x+1{y>0}\{x \ge 0\}\ y := x + 1\ \{y > 0\} is not valid: for x=255x = 255, y=(255+1)mod256=0y = (255 + 1) \bmod 256 = 0, where mod\operatorname{mod} gives the remainder after division. With the precondition x≤254x \le 254 the triple is valid. In C, adding 1 to the largest value of the type int is undefined behavior §4.12, so a proof about C code must include such a bound in its precondition.

Stated precisely

Let a state σ\sigma map each variable to a value, and write σ⊨P\sigma \models P when assertion PP is true in σ\sigma. The partial-correctness triple {P}C{Q}\{P\}\ C\ \{Q\} is valid when, for every state σ\sigma with σ⊨P\sigma \models P and every state σ′\sigma' in which some run of CC started in σ\sigma finishes normally, σ′⊨Q\sigma' \models Q. The total-correctness triple [P]C[Q][P]\ C\ [Q] is valid when, for every state σ\sigma with σ⊨P\sigma \models P, every run of CC started in σ\sigma finishes normally and its final state satisfies QQ. Write true\mathrm{true} for the assertion that holds in every state and ⇔\iff for “if and only if”. Then [P]C[Q] is valid⇔{P}C{Q} is valid and [P]C[true] is valid,[P]\ C\ [Q] \text{ is valid} \iff \{P\}\ C\ \{Q\} \text{ is valid and } [P]\ C\ [\mathrm{true}] \text{ is valid}, and [P]C[true][P]\ C\ [\mathrm{true}] says only that CC finishes normally from every state that satisfies PP.

The termination part needs, for each loop, an invariant II and a function VV from states to a well-founded set: a set with an order in which every strictly decreasing sequence is finite, such as the whole numbers 0,1,2,…0, 1, 2, \dots. Whenever II and the loop condition hold, VV must be defined, and one run of the body must make VV strictly smaller. For recursion, a measure on the arguments plays the same role: it must decrease at every recursive call. Every called procedure must itself finish under its precondition.

Logics differ on runs that stop with a fault, such as a division by zero or an array §14.5 access out of bounds. In the classical reading a fault is not normal termination, so a partial-correctness triple says nothing about a faulting run, and a total-correctness triple excludes it. Many modern program logics, separation logic among them, make every triple also promise that no run that starts in a state satisfying PP faults. Which reading applies is part of the definition of the logic, not of the notation.

The rules of Hoare logic are sound: every triple they prove is valid. Stephen Cook showed in 1978 that they are also relatively complete. Every valid triple can be proved, provided that every true assertion may be used as a fact and that the assertion language can express the intermediate conditions the proof needs. The proviso cannot be dropped: for the whole numbers with addition and multiplication, no sound proof system whose proofs an algorithm §14.1 can check proves every true assertion.

Limits and common mistakes

A triple is only as strong as its postcondition. The triple {true}sort(a){a is sorted}\{\mathrm{true}\}\ \mathrm{sort}(a)\ \{a \text{ is sorted}\} is met by a program that sets every element to 0. The postcondition must also say that aa is a rearrangement of its original contents. That needs a name for the original value, such as a variable a0a_0 that the precondition sets equal to aa and that the program never changes.

A triple says what holds at the end, not what the program left alone. A proof about yy says nothing about zz unless the logic adds a frame condition, a statement of which variables or memory the program may modify; separation logic builds this in.

The assignment rule assumes that different names denote different storage. For arrays and pointers, a[i]:=5a[i] := 5 also changes a[j]a[j] when i=ji = j, so the rule must treat the whole array as one value, or the logic must track which names can refer to the same storage.

In a concurrent program, another thread can change a shared variable between two steps and break an intermediate assertion. Concurrent programs need extensions such as the Owicki–Gries method or rely-guarantee reasoning, which state what other threads may do.

Assertions about mathematical integers do not carry over to fixed-width machine integers without conditions that rule out overflow, as the 8-bit example shows.

A triple says nothing about intermediate states, running time or memory use, or about what happens when CC is interrupted halfway.

Tests cannot supply the missing termination argument: no finite set of runs that finished shows that every run finishes.

Questions answered

What extra argument turns partial correctness into total correctness?

The extra argument is a termination proof: every run of the program that starts in a state satisfying the precondition finishes normally. Partial correctness says only that if the program finishes, the postcondition holds; total correctness is exactly partial correctness plus this termination property. For each loop, the usual argument is a ranking function, an integer (or other well-founded) quantity that is at least 0 whenever the loop invariant and the loop condition hold and that strictly decreases on every iteration, so the loop cannot run forever. For the loop while i < n do i := i + 1, the quantity n−in - i works. For recursion, a measure on the arguments must decrease at every recursive call, and every called procedure must itself be proved to finish under its precondition. If the logic counts a fault, such as a division by zero or an out-of-bounds access, as a way of not finishing normally, the argument must also show that no fault occurs.

Related entries: Loop invariant (§3.24), Ranking function (§3.25), Helper contract (§2.21), Signed integer overflow (§4.15), Termination versus time bound (§2.33). Further reading: [224, 225, 268].