Module contents
Lesson 9 of 22Advanced 115 min

Hoare logic, weakest preconditions and machine-assisted verification

From informal invariants to formal calculation: Hoare triples and inference rules, Dijkstra's weakest precondition, and automatic verification conditions discharged by a solver. We sketch logical soundness against semantics and introduce Dafny, separation logic and LLM-proposed invariants.

After this lesson you can

  • Derive Hoare triples using assignment, sequence, conditional, loop and consequence rules
  • Calculate weakest preconditions and explain wp as the postcondition's preimage
  • Generate verification conditions for programs annotated with invariants
  • Sketch soundness of Hoare logic against operational semantics
  • Discharge verification conditions with a solver and read counterexamples for incorrect invariants

Before you start

Motivation: let the machine check the proof

In the previous lesson you proved programs using loop invariants and variant functions: write a property and check by hand that it holds on entry, each pass preserves it, and it implies the result on exit. These proofs are correct, but checked by a person, and people skip cases.

The classic example is binary search. In 2006 Joshua Bloch reported that Java’s standard-library version had carried an error for about nine years in mid = (low + high) / 2: when low + high exceeds 231−12^{31} - 1, the sum overflows, mid becomes negative and the program throws an exception on arrays of more than roughly a billion elements. The algorithm had its textbook invariant proof. The proof was correct for mathematical integers; the program used 32-bit integers. Nobody checked that step, because on paper it did not even look like a step.

This lesson turns the preceding proofs into a calculus a machine can execute:

  1. A program with a formal specification (precondition and postcondition) and an invariant for each loop is translated purely syntactically into a handful of first-order formulas: verification conditions.
  2. If those formulas are valid, the program is correct. The translation is a theorem, not a heuristic.
  3. Checking arithmetic formulas is work for an automatic solver such as Z3, which also returns a concrete state when a formula is false.

This is what Dafny, Why3, Frama-C and VeriFast do, and the idea enabling verification of language-model-generated code: the model proposes, the verifier decides (the generation–verification gap). Three pieces are needed: a language with precise semantics, a logic for reasoning about it, and an algorithm reducing that logic to formulas.

A minimal language and its semantics

Rigorous reasoning needs a small language with exact meaning. Use the classic while programs language, defined inductively by three grammars:

a::=n∣x∣a1+a2∣a1−a2∣a1⋅a2b::=V∣F∣a1=a2∣a1≤a2∣¬b∣b1∧b2C::=skip∣x:=a∣C1; C2∣if b then C1 else C2∣while b do C\begin{aligned} a &::= n \mid x \mid a_1 + a_2 \mid a_1 - a_2 \mid a_1 \cdot a_2 \\ b &::= \mathrm{V} \mid \mathrm{F} \mid a_1 = a_2 \mid a_1 \le a_2 \mid \neg b \mid b_1 \wedge b_2 \\ C &::= \mathbf{skip} \mid x := a \mid C_1;\, C_2 \mid \mathbf{if}\ b\ \mathbf{then}\ C_1\ \mathbf{else}\ C_2 \mid \mathbf{while}\ b\ \mathbf{do}\ C \end{aligned}

where n∈Zn \in \Z is a constant and xx a variable. Examples also use <<, >>, ≥\ge, ≠\neq, ∨\vee and operations div⁡\operatorname{div} and  mod \bmod (integer division rounded down and its remainder), defined similarly.

A state is a function σ:Var→Z\sigma : \mathrm{Var} \to \Z assigning each variable an integer. An expression’s value in a state, ⟦a⟧σ\llbracket a \rrbracket\sigma, is defined by structural recursion: ⟦n⟧σ=n\llbracket n \rrbracket\sigma = n, ⟦x⟧σ=σ(x)\llbracket x \rrbracket\sigma = \sigma(x), ⟦a1+a2⟧σ=⟦a1⟧σ+⟦a2⟧σ\llbracket a_1 + a_2 \rrbracket\sigma = \llbracket a_1 \rrbracket\sigma + \llbracket a_2 \rrbracket\sigma, and similarly for the rest. Write σ[x↦v]\sigma[x \mapsto v] for the state equal to σ\sigma except at xx, which becomes vv.

Commands get their meaning from big-step operational semantics: relation ⟨C,σ⟩⇓σ′\langle C, \sigma \rangle \Downarrow \sigma' (“executing CC from σ\sigma terminates in σ′\sigma'”) is the smallest satisfying these rules:

⟨skip,σ⟩⇓σ⟨x:=a,σ⟩⇓σ[x↦⟦a⟧σ]⟨C1,σ⟩⇓σ′⟨C2,σ′⟩⇓σ′′⟨C1; C2,σ⟩⇓σ′′\frac{}{\langle \mathbf{skip}, \sigma \rangle \Downarrow \sigma} \qquad \frac{}{\langle x := a, \sigma \rangle \Downarrow \sigma[x \mapsto \llbracket a \rrbracket\sigma]} \qquad \frac{\langle C_1, \sigma \rangle \Downarrow \sigma' \quad \langle C_2, \sigma' \rangle \Downarrow \sigma''}{\langle C_1;\, C_2, \sigma \rangle \Downarrow \sigma''} ⟦b⟧σ=V⟨C1,σ⟩⇓σ′⟨if b then C1 else C2,σ⟩⇓σ′⟦b⟧σ=F⟨C2,σ⟩⇓σ′⟨if b then C1 else C2,σ⟩⇓σ′\frac{\llbracket b \rrbracket\sigma = \mathrm{V} \quad \langle C_1, \sigma \rangle \Downarrow \sigma'}{\langle \mathbf{if}\ b\ \mathbf{then}\ C_1\ \mathbf{else}\ C_2, \sigma \rangle \Downarrow \sigma'} \qquad \frac{\llbracket b \rrbracket\sigma = \mathrm{F} \quad \langle C_2, \sigma \rangle \Downarrow \sigma'}{\langle \mathbf{if}\ b\ \mathbf{then}\ C_1\ \mathbf{else}\ C_2, \sigma \rangle \Downarrow \sigma'} ⟦b⟧σ=F⟨while b do C,σ⟩⇓σ⟦b⟧σ=V⟨C,σ⟩⇓σ′⟨while b do C,σ′⟩⇓σ′′⟨while b do C,σ⟩⇓σ′′\frac{\llbracket b \rrbracket\sigma = \mathrm{F}}{\langle \mathbf{while}\ b\ \mathbf{do}\ C, \sigma \rangle \Downarrow \sigma} \qquad \frac{\llbracket b \rrbracket\sigma = \mathrm{V} \quad \langle C, \sigma \rangle \Downarrow \sigma' \quad \langle \mathbf{while}\ b\ \mathbf{do}\ C, \sigma' \rangle \Downarrow \sigma''}{\langle \mathbf{while}\ b\ \mathbf{do}\ C, \sigma \rangle \Downarrow \sigma''}

Each terminating execution is a finite tree built with these rules. If execution does not terminate, there is simply no σ′\sigma' with ⟨C,σ⟩⇓σ′\langle C, \sigma \rangle \Downarrow \sigma': the last rule would require an infinite tree. Induction on trees shows the semantics are deterministic (for each CC and σ\sigma there is at most one σ′\sigma'), so each command defines a partial function fC:Σ⇀Σf_C : \Sigma \rightharpoonup \Sigma on the set Σ\Sigma of states. This functional view is key to weakest preconditions.

State properties are first-order formulas over (Z,+,⋅,≤)(\Z, +, \cdot, \le), called assertions; for convenience we also use functions definable in that language, such as n!n! or aba^b. Their free variables are program variables and sometimes logical variables the program does not modify, naming initial values (such as nn in x=nx = n). A state satisfies an assertion, σ⊨P\sigma \models P, with ordinary first-order semantics: σ\sigma assigns the free variables. Identify each assertion with the set of states satisfying it, so P⇒QP \Rightarrow Q is valid exactly when P⊆QP \subseteq Q.

Hoare triples

This is the previous lesson’s distinction between partial and total correctness, now with precise underlying semantics. Some examples:

  • {x=5} x:=x+1 {x=6}\{x = 5\}\ x := x + 1\ \{x = 6\} is valid in both senses.
  • {V} while V do skip {F}\{\mathrm{V}\}\ \mathbf{while}\ \mathrm{V}\ \mathbf{do}\ \mathbf{skip}\ \{\mathrm{F}\} is valid for partial correctness: the loop never terminates, so no σ′\sigma' can violate F\mathrm{F}. Partial correctness promises nothing about hanging programs.
  • {x≥0} while x≠0 do x:=x−2 {x=0}\{x \ge 0\}\ \mathbf{while}\ x \neq 0\ \mathbf{do}\ x := x - 2\ \{x = 0\} is valid for partial correctness (if it terminates, x=0x = 0), but not total: from x=3x = 3 the loop runs through 1,−1,−3,…1, -1, -3, \dots forever.

Predicates as regions

Before writing rules, view a triple geometrically. With two integer variables, a state is a grid point (x,y)(x, y) and an assertion a region. A command moves each point to another (or loses it if nonterminating).

InteractivePredicates as regions of state space
  • region QQ
  • states in wp⁡(C,Q)\operatorname{wp}(C, Q)
  • boundary of PP
  • ring: state in PP outside the preimage
  • σ↦C(σ)\sigma \mapsto C(\sigma)
With loops
σ\sigma(−1, 2)
C(σ)C(\sigma)(0, 2)
σ∈wp⁡(C,Q)\sigma \in \operatorname{wp}(C, Q)yes
wp⁡(C,Q)=x+y≥1\operatorname{wp}(C, Q) = x + y \ge 1
the formula agrees with the preimage in 121 of 121 states
States in wp⁡(C,Q)\operatorname{wp}(C, Q)55 of 121
{P} C {Q}\{P\}\ C\ \{Q\} is valid within the window: all 25 states in PP are inside wp⁡(C,Q)\operatorname{wp}(C, Q).
Each point is a state σ=(x,y)\sigma = (x, y). The aqua region is QQ; orange points are states from which CC terminates in QQ. Drag σ\sigma and follow its arrow: it is orange exactly when the arrow lands in QQ. Compare the orange region with the displayed formula obtained by substitution, and change command: translation shifts the region, rotation rotates it, absolute value folds it and x:=2xx := 2x shrinks it. The blue boundary is PP: the triple is valid when all of PP fits in the orange region. For loops compare wp and wlp: crossed-out states do not terminate.

The figure shows three facts formalized below.

  1. The good region is a preimage. Orange states are σ\sigma with fC(σ)∈Qf_C(\sigma) \in Q, that is, fC−1(Q)f_C^{-1}(Q), the preimage of QQ under partial function CC. Thus translating xx one unit right shifts the good region one unit left.
  2. An assignment’s preimage is substitution. For x:=x+1x := x + 1 and Q≡x+y≥2Q \equiv x + y \ge 2, good states satisfy (x+1)+y≥2(x + 1) + y \ge 2: QQ with x+1x + 1 replacing xx.
  3. Validity is inclusion. {P} C {Q}\{P\}\ C\ \{Q\} is valid if and only if PP lies in the preimage (except states from which CC does not terminate, ignored by partial correctness).

Assignment axiom works backward

The second fact is a lemma proved by structural induction on formulas.

Proof

First for expressions: ⟦a[e/x]⟧σ=⟦a⟧(σ[x↦⟦e⟧σ])\llbracket a[e/x] \rrbracket\sigma = \llbracket a \rrbracket(\sigma[x \mapsto \llbracket e \rrbracket\sigma]) by induction on aa. If a=xa = x, both sides equal ⟦e⟧σ\llbracket e \rrbracket\sigma; if a=y≠xa = y \neq x, both equal σ(y)\sigma(y); if a=na = n, both equal nn; and if a=a1+a2a = a_1 + a_2 (or another operation), apply induction to a1a_1 and a2a_2. For formulas atomic cases follow from this and connectives by induction. For quantifier ∀y. Q′\forall y.\, Q' there are two cases. If y=xy = x, xx is not free, substitution does not enter and both sides agree because xx‘s value does not matter. If y≠xy \neq x, capture-avoiding substitution renames yy if it appears in ee (see capture-avoiding substitution), so yy does not appear in ee, changing yy does not alter ⟦e⟧\llbracket e \rrbracket, and induction applies to Q′Q' in each state σ[y↦v]\sigma[y \mapsto v].

∎

Since executing x:=ex := e sends σ\sigma to σ[x↦⟦e⟧σ]\sigma[x \mapsto \llbracket e \rrbracket\sigma], the lemma says exactly that if Q[e/x]Q[e/x] holds before, QQ holds afterward. This is Hoare’s assignment rule:

{Q[e/x]} x:=e {Q}.\{Q[e/x]\}\ x := e\ \{Q\}.

Read right to left: given a postcondition QQ, substitution gives the precondition. This is how assignment works. What QQ will assert about xx afterward must already be true of the value xx will receive. Writing it forward as {P} x:=e {P[e/x]}\{P\}\ x := e\ \{P[e/x]\} is tempting and false: with P≡x=5P \equiv x = 5 and x:=x+1x := x + 1 it yields {x=5} x:=x+1 {x+1=5}\{x = 5\}\ x := x + 1\ \{x + 1 = 5\}, claiming that after assignment xx is 4. Floyd’s correct forward rule needs a quantifier remembering the old value:

{P} x:=e {∃v. x=e[v/x]∧P[v/x]},\{P\}\ x := e\ \{\exists v.\ x = e[v/x] \wedge P[v/x]\},

where vv is the old value of xx. That is the strongest postcondition. Backward calculation avoids the quantifier, so nearly all tools use it.

Rules of Hoare logic

A Hoare logic is a deduction system whose judgments are triples. Write ⊢{P} C {Q}\vdash \{P\}\ C\ \{Q\} if the triple is derived by these rules, one per command form plus consequence, connecting assertion logic:

{P} skip {P} (skip){Q[e/x]} x:=e {Q} (assign){P} C1 {R}{R} C2 {Q}{P} C1; C2 {Q} (seq)\frac{}{\{P\}\ \mathbf{skip}\ \{P\}}\ (\text{skip}) \qquad \frac{}{\{Q[e/x]\}\ x := e\ \{Q\}}\ (\text{assign}) \qquad \frac{\{P\}\ C_1\ \{R\} \quad \{R\}\ C_2\ \{Q\}}{\{P\}\ C_1;\, C_2\ \{Q\}}\ (\text{seq}) {P∧b} C1 {Q}{P∧¬b} C2 {Q}{P} if b then C1 else C2 {Q} (if){I∧b} C {I}{I} while b do C {I∧¬b} (while)\frac{\{P \wedge b\}\ C_1\ \{Q\} \quad \{P \wedge \neg b\}\ C_2\ \{Q\}}{\{P\}\ \mathbf{if}\ b\ \mathbf{then}\ C_1\ \mathbf{else}\ C_2\ \{Q\}}\ (\text{if}) \qquad \frac{\{I \wedge b\}\ C\ \{I\}}{\{I\}\ \mathbf{while}\ b\ \mathbf{do}\ C\ \{I \wedge \neg b\}}\ (\text{while}) ⊨P⇒P′{P′} C {Q′}⊨Q′⇒Q{P} C {Q} (cons)\frac{\models P \Rightarrow P' \quad \{P'\}\ C\ \{Q'\} \quad \models Q' \Rightarrow Q}{\{P\}\ C\ \{Q\}}\ (\text{cons})

Three observations:

  • Sequence needs an intermediate assertion RR the rule does not tell us how to find. It will be C2C_2‘s weakest precondition.
  • The loop rule is the preceding lesson in one line. If one pass preserves II (when the guard is true), then starting in II, if the loop terminates, it ends in II with a false guard. It says nothing about termination: partial correctness.
  • Consequence bridges arithmetic. Its side premises are not triples but first-order formulas over Z\Z, accepted by Hoare logic when valid. Mathematical work in verification ends up in those implications.

For total correctness the loop rule adds integer variant VV, bounded below while the loop continues and decreasing each pass:

⊨I∧b⇒V≥0[I∧b∧V=v0] C [I∧V<v0][I] while b do C [I∧¬b] (whiletot)\frac{\models I \wedge b \Rightarrow V \ge 0 \qquad [I \wedge b \wedge V = v_0]\ C\ [I \wedge V < v_0]}{[I]\ \mathbf{while}\ b\ \mathbf{do}\ C\ [I \wedge \neg b]}\ (\text{while}_{\text{tot}})

where v0v_0 is a fresh logical variable absent from CC, II and VV: it stores the variant at pass start. A strictly decreasing sequence of nonnegative integers is finite (well-foundedness of N\N), so the loop has finitely many passes.

Loop derivation trees are taller but structured the same way: every command imposes its rule, each assignment closes with consequence and each loop needs an invariant. The creative choice is the invariant; the rest is bookkeeping.

InteractiveHoare derivation builder
Derivation treeI≡y⋅x!=n!∧x≥0I \equiv y \cdot x! = n! \wedge x \ge 0, variant xx
Sequence
{x=n∧n≥0}\{x = n \wedge n \ge 0\}
y := 1; while x > 0 do (y := y · x; x := x − 1)
{y=n!}\{y = n!\}
open goal
{x=n∧n≥0}\{x = n \wedge n \ge 0\}
y := 1
{y⋅x!=n!∧x≥0}\{y \cdot x! = n! \wedge x \ge 0\}
Total loop + consequence
{y⋅x!=n!∧x≥0}\{y \cdot x! = n! \wedge x \ge 0\}
while x > 0 do (y := y · x; x := x − 1)
{y=n!}\{y = n!\}
P ⇒ I (entry)pending
y⋅x!=n!∧x≥0⇒y⋅x!=n!∧x≥0y \cdot x! = n! \wedge x \ge 0 \Rightarrow y \cdot x! = n! \wedge x \ge 0
I ∧ ¬b ⇒ Q (exit)pending
y⋅x!=n!∧x≥0∧¬(x>0)⇒y=n!y \cdot x! = n! \wedge x \ge 0 \wedge \neg(x > 0) \Rightarrow y = n!
I ∧ b ⇒ V ≥ 0 (bound)pending
y⋅x!=n!∧x≥0∧x>0⇒x≥0y \cdot x! = n! \wedge x \ge 0 \wedge x > 0 \Rightarrow x \ge 0
open goal
{y⋅x!=n!∧x≥0∧x>0∧x=v0}\{y \cdot x! = n! \wedge x \ge 0 \wedge x > 0 \wedge x = v_{0}\}
y := y · x; x := x − 1
{y⋅x!=n!∧x≥0∧x<v0}\{y \cdot x! = n! \wedge x \ge 0 \wedge x < v_{0}\}

The root is at the top and each rule places its premises below. v0v_{0} is a ghost variable: the variant’s value at the start of an iteration. Verifier convention: n!=1n! = 1 if n≤0n \le 0.

Correctness
Open goals2
Implications discharged0 of 3
With counterexample0
Variantx
The root is the program triple and each rule places premises below. Apply rules to open goals (or all at once) and send each pending implication to the solver; some close by simplification. Try candidate invariants: one too weak does not imply the postcondition, one too strong is not established on entry or preserved, and for division one sufficient for partial correctness fails total correctness. Read the counterexample: a concrete state where hypothesis holds and conclusion does not. Also try forward assignment on an open goal.

Division deserves a look. With invariant x=qy+r∧r≥0x = qy + r \wedge r \ge 0, the partial-correctness derivation closes. Total correctness fails the condition for variant rr: the counterexample has y=0y = 0, where a pass leaves rr unchanged. To decrease the variant, y>0y > 0 must be known inside the loop, and the rule allows only what is in the invariant. Precondition y>0y > 0 held initially and nothing changes it, but without writing it in II it is lost. Dafny handles this case by adding facts about loop-unmodified variables automatically; our generator, like the Hoare rule, does not.

Weakest precondition

The sequence rule needs an intermediate assertion; the region picture suggests the exact preimage. Dijkstra turned this into a calculus in 1975.

Proof

Read the definition both ways. If the partial triple is valid and σ⊨P\sigma \models P, either σ∉dom⁡fC\sigma \notin \operatorname{dom} f_C or fC(σ)⊨Qf_C(\sigma) \models Q; in both cases σ∈wlp⁡(C,Q)\sigma \in \operatorname{wlp}(C, Q). Conversely if P⊆wlp⁡(C,Q)P \subseteq \operatorname{wlp}(C, Q), every σ⊨P\sigma \models P with ⟨C,σ⟩⇓σ′\langle C, \sigma \rangle \Downarrow \sigma' satisfies σ′=fC(σ)⊨Q\sigma' = f_C(\sigma) \models Q. The total case is identical without nonterminating states.

∎

They agree for always-terminating commands such as loop-free ones. The definition’s value is that it can be calculated syntactically, bottom up, without execution:

wp⁡(skip,Q)=Qwp⁡(x:=e,Q)=Q[e/x]wp⁡(C1; C2,Q)=wp⁡(C1,wp⁡(C2,Q))wp⁡(if b then C1 else C2,Q)=(b⇒wp⁡(C1,Q))∧(¬b⇒wp⁡(C2,Q))\begin{aligned} \operatorname{wp}(\mathbf{skip}, Q) &= Q \\ \operatorname{wp}(x := e, Q) &= Q[e/x] \\ \operatorname{wp}(C_1;\, C_2, Q) &= \operatorname{wp}(C_1, \operatorname{wp}(C_2, Q)) \\ \operatorname{wp}(\mathbf{if}\ b\ \mathbf{then}\ C_1\ \mathbf{else}\ C_2, Q) &= (b \Rightarrow \operatorname{wp}(C_1, Q)) \wedge (\neg b \Rightarrow \operatorname{wp}(C_2, Q)) \end{aligned}

Each line is a preimage fact. The second is substitution. The third is composition preimage, (fC2∘fC1)−1(Q)=fC1−1(fC2−1(Q))(f_{C_2} \circ f_{C_1})^{-1}(Q) = f_{C_1}^{-1}(f_{C_2}^{-1}(Q)): to end in QQ after C1; C2C_1;\, C_2, C1C_1 must end in a state from which C2C_2 reaches QQ. The fourth splits state space by the guard. With wp the sequence rule needs no imagination: choose R=wp⁡(C2,Q)R = \operatorname{wp}(C_2, Q).

wp⁡(r:=r−y; q:=q+1, I)\operatorname{wp}(r := r - y;\ q := q + 1,\ I)
The division loop body, with invariant I ≡ x = qy + r ∧ r ≥ 0 as postcondition.
1/5

Read the result: a pass restores the invariant if beforehand x=qy+rx = qy + r and r≥yr \ge y. Guard r≥yr \ge y provides exactly the missing part. Maintenance condition I∧r≥y⇒x=qy+r∧r≥yI \wedge r \ge y \Rightarrow x = qy + r \wedge r \ge y holds by propositional logic alone.

Loops: replace a fixed point with an invariant

For loop W≡while b do CW \equiv \mathbf{while}\ b\ \mathbf{do}\ C, substitution is insufficient. Let HkH_k be the set of states from which WW terminates in QQ after exactly kk passes:

H0=¬b∧Q,Hk+1=b∧wp⁡(C,Hk),wp⁡(W,Q)=⋁k≥0Hk.H_0 = \neg b \wedge Q, \qquad H_{k+1} = b \wedge \operatorname{wp}(C, H_k), \qquad \operatorname{wp}(W, Q) = \bigvee_{k \ge 0} H_k.

That union is the least fixed point of X↦(¬b∧Q)∨(b∧wp⁡(C,X))X \mapsto (\neg b \wedge Q) \vee (b \wedge \operatorname{wp}(C, X)), expressing a loop step as “exit or execute a pass and continue.” In the region figure, while x≠y do x:=x+1\mathbf{while}\ x \neq y\ \mathbf{do}\ x := x + 1 has wp states with x≤yx \le y that end in QQ; states with x>yx > y never terminate, so are in wlp but not wp. An infinite union is not a manipulable formula, and in general no algorithm computes it (deciding whether wp⁡(W,V)\operatorname{wp}(W, \mathrm{V}) is all Σ\Sigma decides universal loop termination). Tools therefore do not calculate loop wp: they request and check an invariant.

Verification conditions

An annotated program carries a loop invariant (and, for total correctness, variant): while b inv I var V do C\mathbf{while}\ b\ \mathbf{inv}\ I\ \mathbf{var}\ V\ \mathbf{do}\ C. Annotations complete wp calculation with a loop rule that returns II as precondition while recording the invariant obligations separately.

Proof

By structural induction on CC, for every QQ, if formulas in vc⁡(C,Q)\operatorname{vc}(C, Q) are valid, then ⊢{pre⁡(C,Q)} C {Q}\vdash \{\operatorname{pre}(C, Q)\}\ C\ \{Q\}. Assignments and skip\mathbf{skip} are axioms. For sequence induction gives ⊢{pre⁡(C2,Q)} C2 {Q}\vdash \{\operatorname{pre}(C_2, Q)\}\ C_2\ \{Q\} and ⊢{pre⁡(C1,pre⁡(C2,Q))} C1 {pre⁡(C2,Q)}\vdash \{\operatorname{pre}(C_1, \operatorname{pre}(C_2, Q))\}\ C_1\ \{\operatorname{pre}(C_2, Q)\}, joined by sequence. For a conditional, pre⁡∧b\operatorname{pre} \wedge b implies pre⁡(C1,Q)\operatorname{pre}(C_1, Q) propositionally, and consequence plus induction give the then\mathit{then} branch; the other is similar. For a loop induction gives ⊢{pre⁡(C,I)} C {I}\vdash \{\operatorname{pre}(C, I)\}\ C\ \{I\}; preservation and consequence give ⊢{I∧b} C {I}\vdash \{I \wedge b\}\ C\ \{I\}; the loop rule gives ⊢{I} while⋯{I∧¬b}\vdash \{I\}\ \mathbf{while} \cdots \{I \wedge \neg b\}, and exit plus consequence give ⊢{I} while⋯{Q}\vdash \{I\}\ \mathbf{while} \cdots \{Q\}. Finally the initial condition and consequence take pre⁡(C,Q)\operatorname{pre}(C, Q) to PP. The total case is similar with rule (whiletot)(\text{while}_{\text{tot}}): induction gives ⊢[pre⁡(C,I∧V<v0)] C [I∧V<v0]\vdash [\operatorname{pre}(C, I \wedge V < v_0)]\ C\ [I \wedge V < v_0], preservation and decrease plus consequence give [I∧b∧V=v0] C [I∧V<v0][I \wedge b \wedge V = v_0]\ C\ [I \wedge V < v_0], and the bound condition is the rule’s side premise.

∎

This theorem is the heart of deductive verifiers: program verification reduces to validity of a few program-free formulas. The converse fails: an invariant too weak or strong makes a condition fail even for a correct program. The annotation fails, not the program, and a counterexample identifies it.

For integer division, with I≡x=qy+r∧r≥0∧y>0I \equiv x = qy + r \wedge r \ge 0 \wedge y > 0 and variant rr, the four conditions are

initial:x≥0∧y>0⇒x=0⋅y+x∧x≥0∧y>0exit:I∧r<y⇒x=qy+r∧0≤r<ybound:I∧r≥y⇒r≥0preservation and decrease:I∧r≥y∧v0=r⇒x=(q+1)y+(r−y)∧r−y≥0∧y>0∧r−y<v0\begin{aligned} &\text{initial:} && x \ge 0 \wedge y > 0 \Rightarrow x = 0 \cdot y + x \wedge x \ge 0 \wedge y > 0 \\ &\text{exit:} && I \wedge r < y \Rightarrow x = qy + r \wedge 0 \le r < y \\ &\text{bound:} && I \wedge r \ge y \Rightarrow r \ge 0 \\ &\text{preservation and decrease:} && I \wedge r \ge y \wedge v_0 = r \Rightarrow x = (q + 1)y + (r - y) \wedge r - y \ge 0 \wedge y > 0 \wedge r - y < v_0 \end{aligned}

None mentions the program. These are quantifier-free integer arithmetic formulas, linear here except product qyqy, appearing equally on both sides. In the next figure calculate them yourself, program by program, with animated backward calculation.

InteractiveThe postcondition travels backward
Initial condition: P ⇒ wp
Annotated programread bottom up
Px≥0∧y>0x \ge 0 \wedge y > 0
wpx≥0x \ge 0
q := 0
q⋅y=0∧x≥0q \cdot y = 0 \wedge x \ge 0
r := x
x=q⋅y+r∧r≥0x = q \cdot y + r \wedge r \ge 0
while r ≥ y do
invx=q⋅y+r∧r≥0x = q \cdot y + r \wedge r \ge 0
x=q⋅y+r∧r≥yx = q \cdot y + r \wedge r \ge y
r := r − y
x=q⋅y+r+y∧r≥0x = q \cdot y + r + y \wedge r \ge 0
q := q + 1
x=q⋅y+r∧r≥0x = q \cdot y + r \wedge r \ge 0
end
Qx=q⋅y+r∧0≤r<yx = q \cdot y + r \wedge 0 \le r < y
This stepInitial condition: P ⇒ wp
Initial: P ⇒ wpsimplifies to true
x≥0∧y>0⇒x≥0x \ge 0 \wedge y > 0 \Rightarrow x \ge 0

The calculated wp required at program entry must follow from the contract’s promise P. If this implication is valid, the annotated program is correct.

Verification conditions3 of 3
Loop exitsimplifies to true
x=q⋅y+r∧r≥0∧¬(r≥y)⇒x=q⋅y+r∧0≤r<yx = q \cdot y + r \wedge r \ge 0 \wedge \neg(r \ge y) \Rightarrow x = q \cdot y + r \wedge 0 \le r < y
Preservationsimplifies to true
x=q⋅y+r∧r≥0∧r≥y⇒x=q⋅y+r∧r≥yx = q \cdot y + r \wedge r \ge 0 \wedge r \ge y \Rightarrow x = q \cdot y + r \wedge r \ge y
Initial: P ⇒ wpsimplifies to true
x≥0∧y>0⇒x≥0x \ge 0 \wedge y > 0 \Rightarrow x \ge 0
Step10 of 10
Verification conditions3 of 3 without counterexample
All conditions pass. Trivial ones close by simplification; the rest by exhaustive search in an integer box, which is not a proof: the Z3 lab proves them for all Z\Z.
Each step calculates a precondition, bottom up. In assignments orange highlights occurrences of the variable in QQ and the expression replacing it; in conditionals the guard (blue) separates cases; in loops the invariant replaces wp and exit and preservation conditions appear. Finally P⇒wp⁡P \Rightarrow \operatorname{wp} remains. Examine the buggy swap and counterexample, compare simultaneous swap, and edit programs: remove r≥0r \ge 0 from division's invariant or i≤ni \le n from the sum's, and observe which condition breaks.

Two details of swapping. Version x:=y; y:=xx := y;\ y := x gives wp⁡≡y=b∧y=a\operatorname{wp} \equiv y = b \wedge y = a: both final values come from old yy, and the initial condition fails in any state with a≠ba \neq b. Simultaneous assignment x,y:=y,xx, y := y, x substitutes at once, Q[y,x/x,y]Q[y, x / x, y], and is correct. Substituting one at a time, first xx then yy, computes wp of a different program.

Soundness and completeness of the logic

We gave symbol-manipulating rules, ⊢\vdash, and execution-based truth, ⊨\models. As in propositional logic, they must be shown to agree (the distinction between soundness and completeness of a deduction system).

This is soundness of Hoare logic: nothing derived by the rules is false under operational semantics.

Proof

By structural induction on the triple’s derivation tree: show each rule takes valid premises to a valid conclusion. Assignment is the substitution lemma. For sequence, if ⟨C1; C2,σ⟩⇓σ′′\langle C_1;\, C_2, \sigma \rangle \Downarrow \sigma'', the only rule that could produce it requires σ′\sigma' with ⟨C1,σ⟩⇓σ′\langle C_1, \sigma \rangle \Downarrow \sigma' and ⟨C2,σ′⟩⇓σ′′\langle C_2, \sigma' \rangle \Downarrow \sigma'', so apply the two hypotheses in order. The conditional is similar by cases on bb in σ\sigma, and consequence composes two implications with the triple. The loop alone needs another induction, on the derivation of ⟨while b do C,σ⟩⇓σ′′\langle \mathbf{while}\ b\ \mathbf{do}\ C, \sigma \rangle \Downarrow \sigma'', because the loop recurs within its own derivation. You will do it step by step in an exercise. For the total rule also prove, by strong induction on the variant’s value, that the loop terminates from every state in II.

∎

The converse is subtler. Whether every valid triple is derivable depends on two arithmetic matters outside Hoare logic: whether consequence premises, formulas over Z\Z, can be established, and whether necessary intermediate assertions can be expressed.

First-order arithmetic with addition and multiplication is expressive for this language: Gödel’s β\beta function encodes finite state sequences of an execution in a formula, expressing a loop’s wlp. The proof idea uses the loop’s own wlp as invariant. Completeness is relative to an arithmetic oracle, and the qualification cannot be dropped: valid formulas of (Z,+,⋅)(\Z, +, \cdot) are not even recursively enumerable (Gödel), and {V} C {F}\{\mathrm{V}\}\ C\ \{\mathrm{F}\} is valid exactly when CC terminates from no state, undecidable (see undecidability of logic). No effective system derives exactly the valid triples. In practice the verifier cannot always prove a claim, so solvers sometimes answer “unknown.”

Implementation from scratch

The verification-condition generator fits on a screen. Programs are dataclass trees; assertions and expressions are sympy objects whose simultaneous substitution (subs(..., simultaneous=True)) is exactly Q[e/x]Q[e/x]. Each command’s rule is one line of wp.

[ ]Verification condition generatorBrowser
import sympy as sp
from dataclasses import dataclass

@dataclass(frozen=True)
class Assign:          # x1, ..., xk := e1, ..., ek  (simultánea)
    xs: tuple
    es: tuple

@dataclass(frozen=True)
class Seq:             # C1; C2; ...; Cn  (Seq(()) es skip)
    cs: tuple

@dataclass(frozen=True)
class If:              # if b then t else e
    b: object
    t: object
    e: object

@dataclass(frozen=True)
class While:           # while b inv I var V do body
    b: object
    inv: object
    body: object
    var: object = None

SKIP = Seq(())
def asig(**kw):
    """asig(x=e), o asig(x=e1, y=e2) para una asignación simultánea."""
    return Assign(tuple(sp.Symbol(k, integer=True) for k in kw), tuple(kw.values()))
def seq(*cs):
    return Seq(tuple(cs))

def wp(c, Q, vcs, total=False):
    """Precondición calculada hacia atrás; cada bucle añade sus condiciones a vcs."""
    if isinstance(c, Assign):
        return Q.subs(dict(zip(c.xs, c.es)), simultaneous=True)      # Q[e/x]
    if isinstance(c, Seq):
        for d in reversed(c.cs):
            Q = wp(d, Q, vcs, total)
        return Q
    if isinstance(c, If):
        return sp.And(sp.Implies(c.b, wp(c.t, Q, vcs, total)),
                      sp.Implies(sp.Not(c.b), wp(c.e, Q, vcs, total)))
    if isinstance(c, While):
        I, b = c.inv, c.b
        vcs.append(("salida", sp.Implies(sp.And(I, sp.Not(b)), Q)))
        if total and c.var is not None:
            v0 = sp.Symbol(f"v{len(vcs)}", integer=True)              # la variante al empezar la vuelta
            vcs.append(("cota", sp.Implies(sp.And(I, b), c.var >= 0)))
            cuerpo = wp(c.body, sp.And(I, c.var < v0), vcs, total)
            vcs.append(("conservación y decrecimiento",
                        sp.Implies(sp.And(I, b, sp.Eq(v0, c.var)), cuerpo)))
        else:
            vcs.append(("conservación", sp.Implies(sp.And(I, b), wp(c.body, I, vcs, total))))
        return I
    raise TypeError(c)

def vcgen(P, c, Q, total=False):
    vcs = []
    w = wp(c, Q, vcs, total)
    return [("inicial", sp.Implies(P, w))] + vcs

x, y, q, r = sp.symbols("x y q r", integer=True)
division = seq(asig(q=0), asig(r=x),
               While(r >= y, sp.And(sp.Eq(x, q*y + r), r >= 0, y > 0),
                     seq(asig(r=r - y), asig(q=q + 1)), var=r))
P_div = sp.And(x >= 0, y > 0)
Q_div = sp.And(sp.Eq(x, q*y + r), 0 <= r, r < y)
for nombre, f in vcgen(P_div, division, Q_div, total=True):
    print(f"{nombre:30s} {f}")

The initial condition already comes out True: sympy evaluates x=0⋅y+xx = 0 \cdot y + x while constructing it and recognizes what remains as A⇒AA \Rightarrow A. The other three are the conditions above, in sympy notation.

Two complementary tools check them. First symbolic: bring each arithmetic atom to a canonical form over Z\Z (everything on one side, expanded, strict inequalities as p−1≥0p - 1 \ge 0, equivalent over integers to p>0p > 0), then check whether the resulting propositional skeleton is a tautology using sympy’s DPLL-based satisfiable. It is incomplete but cheap, and closes all conditions reducible to “the conclusion was already in the hypothesis.” Second, exhaustively search a box [−D,D]k[-D, D]^k for counterexamples; this proves nothing but finds small errors, most of them.

[ ]Discharging conditions: algebra and bounded searchBrowser
import time
from itertools import product
Rel = sp.core.relational.Relational

def canon(a):
    """Forma canónica de un átomo sobre Z: p >= 0, p = 0 o p != 0, con p desarrollado."""
    d = sp.expand(a.lhs - a.rhs)
    if isinstance(a, (sp.Eq, sp.Ne)):
        if d.could_extract_minus_sign():
            d = -d
        return type(a)(d, 0)
    p = {sp.GreaterThan: d, sp.StrictGreaterThan: d - 1,      # d > 0  <=>  d - 1 >= 0 en Z
         sp.LessThan: -d, sp.StrictLessThan: -d - 1}[type(a)]
    return sp.Ge(p, 0)

def valida_simbolica(F):
    """Válida si lo es su esqueleto proposicional tras normalizar los átomos aritméticos."""
    F = F.xreplace({a: canon(a) for a in F.atoms(Rel)})
    if F in (sp.true, sp.false):
        return F == sp.true
    letras = {a: sp.Symbol(f"p{i}") for i, a in enumerate(F.atoms(Rel))}
    return not sp.satisfiable(sp.Not(F.xreplace(letras)))

def contraejemplo_acotado(F, presupuesto=60000):
    """Busca un estado de [-D, D]^k que falsifique F, con D tan grande como permita el presupuesto."""
    vs = sorted(F.free_symbols, key=str)
    D = 6
    while D > 1 and (2*D + 1)**len(vs) > presupuesto:
        D -= 1
    valores = [0] + [s * k for k in range(1, D + 1) for s in (1, -1)]   # 0, 1, -1, 2, -2, ...
    G = F.replace(sp.Implies, lambda a, b: sp.Or(sp.Not(a), b))
    f = sp.lambdify(vs, G, modules="math")
    n = 0
    for vals in product(valores, repeat=len(vs)):
        n += 1
        try:
            if not f(*vals):
                return dict(zip(map(str, vs), vals)), n, D
        except (ZeroDivisionError, ValueError, OverflowError):
            pass
    return None, n, D

def verificar(nombre, P, c, Q, total=False):
    print(nombre)
    for etiqueta, F in vcgen(P, c, Q, total):
        if valida_simbolica(F):
            print(f"  {etiqueta:30s} demostrada (álgebra y lógica proposicional)")
            continue
        ce, n, D = contraejemplo_acotado(F)
        if ce is None:
            print(f"  {etiqueta:30s} sin contraejemplo en {n} estados de [-{D}, {D}]^{len(F.free_symbols)}")
        else:
            print(f"  {etiqueta:30s} FALLA, contraejemplo {ce}")

t0 = time.perf_counter()
verificar("División entera (total)", P_div, division, Q_div, total=True)

n, i, s = sp.symbols("n i s", integer=True)
suma = seq(asig(i=0), asig(s=0),
           While(i < n, sp.And(sp.Eq(2*s, i*(i + 1)), i <= n),
                 seq(asig(i=i + 1), asig(s=s + i)), var=n - i))
verificar("Suma 1 + ... + n (total)", n >= 0, suma, sp.Eq(2*s, n*(n + 1)), total=True)
print(f"tiempo: {time.perf_counter() - t0:.2f} s")

Division’s preservation condition does not close symbolically, though easy: showing r−y<v0r - y < v_0 needs hypothesis equality v0=rv_0 = r, while the propositional skeleton treats v0=rv_0 = r and r−y<v0r - y < v_0 as unrelated letters. An SMT solver does what our trick cannot: combines propositional reasoning with a theory (here linear integer arithmetic) knowing an equality permits substitution. The bounded search finds no counterexample, a good sign but not a proof.

Fast exponentiation uses  mod \bmod and div⁡\operatorname{div}, and its invariant r⋅xy=abr \cdot x^y = a^b has a variable exponent: no simple algebraic trick closes it. An incomplete invariant reveals itself through a concrete counterexample.

[ ]Fast exponentiation and an incomplete invariantBrowser
t0 = time.perf_counter()
a, b = sp.symbols("a b", integer=True)
potencia = seq(asig(x=a), asig(y=b), asig(r=1),
               While(y > 0, sp.And(y >= 0, sp.Eq(r * x**y, a**b)),
                     seq(If(sp.Eq(sp.Mod(y, 2), 1), asig(r=r*x), SKIP),
                         asig(x=x*x), asig(y=sp.floor(y / 2))), var=y))
verificar("Exponenciación rápida (total)", b >= 0, potencia, sp.Eq(r, a**b), total=True)

incompleto = seq(asig(q=0), asig(r=x),
                 While(r >= y, sp.And(sp.Eq(x, q*y + r), r >= 0),       # falta y > 0
                       seq(asig(r=r - y), asig(q=q + 1)), var=r))
verificar("División sin y > 0 en el invariante (parcial)", P_div, incompleto, Q_div)
verificar("División sin y > 0 en el invariante (total)", P_div, incompleto, Q_div, total=True)

# la regla «hacia delante» {P} x := e {P[e/x]} no es correcta
P5 = sp.Eq(x, 5)
falsa = sp.Implies(P5, wp(asig(x=x + 1), P5.subs(x, x + 1), []))   # {P} C {R} válida  <=>  P => wp(C, R)
print("\n{x = 5} x := x + 1 {x + 1 = 5}:", contraejemplo_acotado(falsa)[0])
print(f"tiempo: {time.perf_counter() - t0:.2f} s")

The incomplete division invariant’s counterexample has y=0y = 0, r=v0r = v_0 and r−y=rr - y = r: a pass that does not decrease the variant. This state is unreachable (the precondition requires y>0y > 0 and nothing changes yy), but the verification condition must hold in every state satisfying II and guard, and the invariant forgot y>0y > 0. The invariant suffices for partial correctness, whose conditions do not mention the variant; not for total correctness.

Discharging conditions with Z3

Z3 is an SMT solver (satisfiability modulo theories): it decides formulas combining propositional logic with theories such as integer arithmetic, arrays and bitvectors. Its internals, CDCL plus theory decision procedures, appear under SMT theories. Here its interface suffices: FF is valid if and only if ¬F\neg F is unsatisfiable, so submit ¬F\neg F and read the answer. If unsat, FF is proved for all integers; if sat, the returned model is a counterexample.

The generator is the same, with Z3 terms instead of sympy: z3.substitute performs simultaneous substitution. It is repeated here because this cell runs in local Python and cannot see previous cells.

[ ]Verification conditions with Z3: integers and bitvectorsLocal GPU
import z3

def wp(c, Q, vcs, total=False):
    tipo = c[0]
    if tipo == "asig":                                   # ("asig", [(x, e), ...])
        return z3.substitute(Q, *c[1])
    if tipo == "seq":                                    # ("seq", [c1, c2, ...])
        for d in reversed(c[1]):
            Q = wp(d, Q, vcs, total)
        return Q
    if tipo == "if":                                     # ("if", b, t, e)
        _, b, t, e = c
        return z3.And(z3.Implies(b, wp(t, Q, vcs, total)), z3.Implies(z3.Not(b), wp(e, Q, vcs, total)))
    if tipo == "while":                                  # ("while", b, I, V, cuerpo)
        _, b, I, V, cuerpo = c
        vcs.append(("salida", z3.Implies(z3.And(I, z3.Not(b)), Q)))
        if total:
            v0 = z3.FreshConst(V.sort(), "v0")
            vcs.append(("cota", z3.Implies(z3.And(I, b), V >= 0)))
            vcs.append(("conservación y decrecimiento",
                        z3.Implies(z3.And(I, b, v0 == V), wp(cuerpo, z3.And(I, V < v0), vcs, total))))
        else:
            vcs.append(("conservación", z3.Implies(z3.And(I, b), wp(cuerpo, I, vcs, total))))
        return I
    raise ValueError(tipo)

def valor(m, d):
    v = m[d]
    return v.as_signed_long() if z3.is_bv_value(v) else v.as_long()

def demostrar(nombre, P, c, Q, total=False):
    vcs = []
    vcs.insert(0, ("inicial", z3.Implies(P, wp(c, Q, vcs, total))))
    print(nombre)
    for etiqueta, F in vcs:
        s = z3.Solver()
        s.set("timeout", 5000)
        s.add(z3.Not(F))                                 # F válida  <=>  ¬F insatisfacible
        r = s.check()
        if r == z3.unsat:
            print(f"  {etiqueta:30s} demostrada")
        elif r == z3.sat:
            m = s.model()
            modelo = {str(d).split("!")[0]: valor(m, d) for d in m.decls()}
            print(f"  {etiqueta:30s} FALLA en {dict(sorted(modelo.items()))}")
        else:
            print(f"  {etiqueta:30s} desconocido ({s.reason_unknown()})")

x, y, q, r = z3.Ints("x y q r")
def division(I):
    return ("seq", [("asig", [(q, z3.IntVal(0))]), ("asig", [(r, x)]),
                    ("while", r >= y, I, r, ("seq", [("asig", [(r, r - y)]), ("asig", [(q, q + 1)])]))])
P_div, Q_div = z3.And(x >= 0, y > 0), z3.And(x == q*y + r, 0 <= r, r < y)
demostrar("División entera, total, en Z", P_div, division(z3.And(x == q*y + r, r >= 0, y > 0)), Q_div, total=True)
demostrar("División sin y > 0 en el invariante, total", P_div, division(z3.And(x == q*y + r, r >= 0)), Q_div, total=True)

n, i, s = z3.Ints("n i s")
suma = ("seq", [("asig", [(i, z3.IntVal(0))]), ("asig", [(s, z3.IntVal(0))]),
                ("while", i < n, z3.And(2*s == i*(i + 1), i <= n), n - i,
                 ("seq", [("asig", [(i, i + 1)]), ("asig", [(s, s + i)])]))])
demostrar("Suma 1 + ... + n, total, en Z", n >= 0, suma, 2*s == n*(n + 1), total=True)

# el punto medio de la búsqueda binaria, en Z y con enteros de 32 bits
for BV in (False, True):
    lo, hi, mid = [z3.BitVec(v, 32) for v in ("lo", "hi", "mid")] if BV else z3.Ints("lo hi mid")
    P, Q = z3.And(0 <= lo, lo <= hi), z3.And(lo <= mid, mid <= hi)
    dominio = "32 bits" if BV else "Z"
    demostrar(f"mid := (lo + hi) / 2, {dominio}", P, ("asig", [(mid, (lo + hi) / 2)]), Q)
    demostrar(f"mid := lo + (hi - lo) / 2, {dominio}", P, ("asig", [(mid, lo + (hi - lo) / 2)]), Q)

# «la suma de naturales no es negativa», con 32 bits
nb, ib, sb = (z3.BitVec(v, 32) for v in ("n", "i", "s"))
suma32 = ("seq", [("asig", [(ib, z3.BitVecVal(0, 32))]), ("asig", [(sb, z3.BitVecVal(0, 32))]),
                  ("while", ib < nb, z3.And(sb >= 0, ib >= 0, ib <= nb), nb - ib,
                   ("seq", [("asig", [(ib, ib + 1)]), ("asig", [(sb, sb + ib)])]))])
demostrar("Suma con invariante s >= 0, 32 bits", nb >= 0, suma32, sb >= 0)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Three readings of the output:

  • Over Z\Z, all correct claims are proved, including sum preservation, which contains products of variables. Nonlinear integer arithmetic is undecidable generally, but Z3 has procedures closing cases like this in milliseconds.
  • The invariant without y>0y > 0 fails with a concrete model where y≤0y \le 0 (the exact model varies; with y=0y = 0 the variant does not decrease and with y<0y < 0 increases): the bounded search gave the same diagnosis, but Z3 has explored all Z\Z and proved the other three conditions.
  • With 32 bits, the naive midpoint fails. In Python /, <= and >= on bitvectors are signed operations, like Java or C int. Z3 finds a pair with lo+hi>231−1\mathit{lo} + \mathit{hi} > 2^{31} - 1: the sum wraps negative and mid\mathit{mid} leaves the interval. Bloch’s error found in milliseconds. Version lo+(hi−lo)/2\mathit{lo} + (\mathit{hi} - \mathit{lo})/2 is proved for all 2642^{64} possible pairs. “The sum of naturals is nonnegative,” trivial in Z\Z, also fails with 32 bits: in the model s+(i+1)s + (i + 1) exceeds 231−12^{31} - 1, wrapping new ss negative.

Real tools

Dafny

Dafny is a language with a built-in verifier: methods carry contracts (requires, ensures), loops carry invariants and variants (invariant, decreases), and the compiler generates verification conditions (via the intermediate Boogie language) discharged by Z3. If one fails the program does not compile. Integer division looks like this:

method Division(x: int, y: int) returns (q: int, r: int)
  requires x >= 0 && y > 0
  ensures x == q * y + r && 0 <= r < y
{
  q, r := 0, x;
  while r >= y
    invariant x == q * y + r && r >= 0
    decreases r
  {
    r, q := r - y, q + 1;
  }
}

This is exactly the lesson: invariant is II, decreases r the variant, simultaneous assignments are ours, and Dafny checks the four conditions above. There is no need to write y > 0 in the invariant: Dafny preserves facts about variables the loop does not modify, and y is a parameter. Dafny int is a mathematical integer. Machine integers use bounded types, and each operation adds a condition that the result fits.

Arrays and aliasing

The assignment rule assumes assignment changes one variable and nothing else. Arrays break that: a[i]:=3a[i] := 3 changes a[j]a[j] if i=ji = j. Treating a[i]a[i] as an ordinary variable gives false results. For example {a[j]=5} a[i]:=3 {a[j]=5}\{a[j] = 5\}\ a[i] := 3\ \{a[j] = 5\} would be “proved” because a[j]a[j] does not syntactically contain a[i]a[i], but is false when i=ji = j. McCarthy’s standard solution views the whole array as a variable whose value is a function and assignment as a function update:

wp⁡(a[i]:=e, Q)=Q[a⟨i↦e⟩/a],a⟨i↦e⟩[j]={eif i=ja[j]if i≠j\operatorname{wp}(a[i] := e,\ Q) = Q[a\langle i \mapsto e \rangle / a], \qquad a\langle i \mapsto e \rangle[j] = \begin{cases} e & \text{if } i = j \\ a[j] & \text{if } i \neq j \end{cases}

With this rule wp⁡(a[i]:=3, a[j]=5)\operatorname{wp}(a[i] := 3,\ a[j] = 5) is (i=j⇒3=5)∧(i≠j⇒a[j]=5)(i = j \Rightarrow 3 = 5) \wedge (i \neq j \Rightarrow a[j] = 5), that is, i≠j∧a[j]=5i \neq j \wedge a[j] = 5. Z3’s array theory implements exactly that read-over-write rule.

Pointers are worse: ∗p:=3*p := 3 can change ∗q*q whenever qq points to the same location, and modeling memory as one huge array requires reasoning about every possible pointer overlap. Separation logic, due to Reynolds, O’Hearn and others, changes the assertion language: x↦vx \mapsto v says memory contains exactly cell xx with value vv, and separating conjunction P∗RP \ast R says memory splits into disjoint pieces satisfying PP and RR. Its key frame rule is:

{P} C {Q}{P∗R} C {Q∗R} (frame),if C does not modify free variables of R.\frac{\{P\}\ C\ \{Q\}}{\{P \ast R\}\ C\ \{Q \ast R\}}\ (\text{frame}), \qquad \text{if } C \text{ does not modify free variables of } R.

What CC does not touch remains unchanged without mentioning it; for example {x↦1∗y↦2} [x]:=3 {x↦3∗y↦2}\{x \mapsto 1 \ast y \mapsto 2\}\ [x] := 3\ \{x \mapsto 3 \ast y \mapsto 2\} is derived without asking whether x=yx = y: ∗\ast already guarantees distinct cells. This local reasoning scales to large programs. Meta’s static analyzer Infer and verifiers like VeriFast use separation logic; Viper uses closely related permission logic.

Frontier: language-model-proposed invariants

All calculation is mechanical except inventing invariants (and variants). This is deductive verification’s bottleneck and fits what language models do well: propose plausible candidates. The division of work is:

  1. The model reads program and specification and proposes an invariant for each loop.
  2. The verification-condition generator calculates conditions and a solver tries to discharge them.
  3. If one fails, its counterexample returns to the model as feedback (“in state y=0y = 0 your variant does not decrease”), and the model proposes another candidate.

The guarantee does not depend on the model: an incorrect invariant never passes because the verifier checks conditions, and the verification-condition theorem says that if they pass the program is correct. The model can err arbitrarily; only time is lost. Pei and coauthors (ICML 2023) showed code-trained language models predict useful invariants from source code. Lemur (Wu, Barrett and Narodytska, ICLR 2024) formalizes propose-and-check as a rule calculus whose soundness is proved independently of model proposals, and uses it to verify programs beyond automatic verifiers alone.

Common mistakes

Exercises

QuizWhy backward?
Why is wp⁡(x:=x+1, x>0)\operatorname{wp}(x := x + 1,\ x > 0) equal to x>−1x > -1, not x>1x > 1?
NumericSwap without a temporary
Calculate wp⁡(x:=x+y; y:=x−y; x:=x−y,  x=3∧y=7)\operatorname{wp}(x := x + y;\ y := x - y;\ x := x - y,\ \ x = 3 \wedge y = 7). What initial value of xx is required?
QuizAn array assignment
Someone treats a[i]a[i] as a variable and applies assignment directly. What do they conclude about {a[j]=5} a[i]:=3 {a[j]=5}\{a[j] = 5\}\ a[i] := 3\ \{a[j] = 5\}, and what really happens?
Numericwp and wlp on the grid
Let C≡while x≠y do x:=x+1C \equiv \mathbf{while}\ x \neq y\ \mathbf{do}\ x := x + 1 and Q≡y≥0Q \equiv y \ge 0. How many states (x,y)∈{−5,…,5}2(x, y) \in \{-5, \dots, 5\}^2 belong to wp⁡(C,Q)\operatorname{wp}(C, Q)?
QuizTo terminate or not
Let C≡while x≠0 do x:=x−2C \equiv \mathbf{while}\ x \neq 0\ \mathbf{do}\ x := x - 2. What are wp⁡(C,V)\operatorname{wp}(C, \mathrm{V}) and wlp⁡(C,V)\operatorname{wlp}(C, \mathrm{V})?
QuizWhich invariants work?
For {n≥0} i:=0; s:=0; while i<n do (i:=i+1; s:=s+i) {2s=n(n+1)}\{n \ge 0\}\ i := 0;\ s := 0;\ \mathbf{while}\ i < n\ \mathbf{do}\ (i := i + 1;\ s := s + i)\ \{2s = n(n + 1)\}, which invariants make all three verification conditions (initial, preservation, exit) valid?

More than one answer may be correct.

QuizFrom Z to 32 bits
The triple {0≤lo≤hi} mid:=(lo+hi)/2 {lo≤mid≤hi}\{0 \le \mathit{lo} \le \mathit{hi}\}\ \mathit{mid} := (\mathit{lo} + \mathit{hi})/2\ \{\mathit{lo} \le \mathit{mid} \le \mathit{hi}\} is valid over Z\Z. What if variables are signed 32-bit integers?
ProofDeriving factorial
Prove: ⊢[x=n∧n≥0]  y:=1; while x>0 do (y:=y⋅x; x:=x−1)  [y=n!]\vdash [x = n \wedge n \ge 0]\ \ y := 1;\ \mathbf{while}\ x > 0\ \mathbf{do}\ (y := y \cdot x;\ x := x - 1)\ \ [y = n!], with explicit invariant and variant.
0
The program multiplies yy by x,x−1,…,1x, x - 1, \dots, 1. Choose loop invariant II and variant VV and check verification conditions.

Step 1 of 5. Which invariant do you choose?

ProofSoundness of consequence and loop rules
Prove: The consequence and loop rules take valid premises to valid conclusions under operational semantics (partial correctness).
0
Recall: ⊨{P} C {Q}\models \{P\}\ C\ \{Q\} means every σ⊨P\sigma \models P and σ′\sigma' with ⟨C,σ⟩⇓σ′\langle C, \sigma \rangle \Downarrow \sigma' satisfy σ′⊨Q\sigma' \models Q.

Step 1 of 4. Consequence: assume ⊨P⇒P′\models P \Rightarrow P', ⊨{P′} C {Q′}\models \{P'\}\ C\ \{Q'\} and ⊨Q′⇒Q\models Q' \Rightarrow Q. Given σ⊨P\sigma \models P and ⟨C,σ⟩⇓σ′\langle C, \sigma \rangle \Downarrow \sigma', what follows?

Codewp for assignments, sequences and conditionals
Implement wp(c, Q) for commands Assign (assignment, possibly simultaneous: xs and es are equal-length tuples), Seq (sequence; Seq(()) is skip) and If. Assertions are sympy formulas. Tests compare meanings, not formulas: for each state in a box they check σ⊨wp⁡(C,Q)\sigma \models \operatorname{wp}(C, Q) exactly when execution of CC from σ\sigma (using interpreter run) terminates in a state of QQ. Test cases include simultaneous assignments.
import sympy as sp
from dataclasses import dataclass

@dataclass(frozen=True)
class Assign:
  xs: tuple   # símbolos de sympy
  es: tuple   # una expresión por símbolo

@dataclass(frozen=True)
class Seq:
  cs: tuple

@dataclass(frozen=True)
class If:
  b: object
  t: object
  e: object

def run(c, st):
  """Intérprete: ejecuta c desde st (dict símbolo -> int) y devuelve el estado final."""
  if isinstance(c, Assign):
      vals = [int(e.subs(st)) for e in c.es]      # todas con el estado anterior
      nuevo = dict(st)
      nuevo.update(zip(c.xs, vals))
      return nuevo
  if isinstance(c, Seq):
      for d in c.cs:
          st = run(d, st)
      return st
  if isinstance(c, If):
      return run(c.t if bool(c.b.subs(st)) else c.e, st)
  raise TypeError(c)

def wp(c, Q):
  """Precondición más débil de c respecto a Q."""
  # tu código
  raise NotImplementedError
Shift+Enter to run
CodeThe integer-division invariant
Program q := 0; r := x; while r >= y do (r := r - y; q := q + 1) with precondition x≥0∧y>0x \ge 0 \wedge y > 0 must terminate with x=qy+r∧0≤r<yx = qy + r \wedge 0 \le r < y. You have the lesson's verification-condition generator and bounded counterexample search. Define INV, the loop invariant (a sympy formula in x, y, q, r), so the four total-correctness conditions with variant r have no counterexamples. Use the cell to see which condition fails with the initial invariant and why.
import sympy as sp

x, y, q, r = sp.symbols("x y q r", integer=True)

INV = sp.Eq(x, q*y + r)      # demasiado débil: corrígelo

# --- a partir de aquí no hace falta tocar nada ---
from itertools import product

def vcs_division(I):
  """Las cuatro condiciones de verificación de la división con invariante I y variante r."""
  v0 = sp.Symbol("v0", integer=True)
  wp_cuerpo = lambda Q: Q.subs(q, q + 1).subs(r, r - y)       # wp(r := r - y; q := q + 1, Q)
  return {
      "inicial": sp.Implies(sp.And(x >= 0, y > 0), I.subs({q: 0, r: x}, simultaneous=True)),
      "salida": sp.Implies(sp.And(I, r < y), sp.And(sp.Eq(x, q*y + r), 0 <= r, r < y)),
      "cota": sp.Implies(sp.And(I, r >= y), r >= 0),
      "conservación y decrecimiento": sp.Implies(sp.And(I, r >= y, sp.Eq(v0, r)), wp_cuerpo(sp.And(I, r < v0))),
  }

def contraejemplo(F, D=4):
  vs = sorted(F.free_symbols, key=str)
  if not vs:
      return None if bool(F) else {}
  f = sp.lambdify(vs, F.replace(sp.Implies, lambda a, b: sp.Or(sp.Not(a), b)), modules="math")
  for vals in product(range(-D, D + 1), repeat=len(vs)):
      if not f(*vals):
          return dict(zip(map(str, vs), vals))
  return None

for nombre, F in vcs_division(INV).items():
  print(f"{nombre:30s}", contraejemplo(F) or "sin contraejemplo")
Shift+Enter to run

Summary

Key idea
A triple {P} C {Q}\{P\}\ C\ \{Q\} is valid if PP fits in the preimage of QQ; that preimage, the weakest precondition, is calculated backward by substitution except for loops, where an invariant replaces it in exchange for verification conditions: program-free first-order formulas ready for a solver.
  • Big-step operational semantics assigns each command a partial function fCf_C on states. A triple is partially correct if every terminating execution from PP ends in QQ; totally correct if every execution from PP also terminates.
  • Assignment axiom {Q[e/x]} x:=e {Q}\{Q[e/x]\}\ x := e\ \{Q\} is the substitution lemma and works backward. Sequence, conditional, invariant loop and consequence complete the logic; consequence bridges arithmetic.
  • wp⁡(C,Q)=fC−1(Q)\operatorname{wp}(C, Q) = f_C^{-1}(Q) and wlp⁡\operatorname{wlp} adds nonterminating states. ⊨{P} C {Q}\models \{P\}\ C\ \{Q\} exactly when P⊆wlp⁡(C,Q)P \subseteq \operatorname{wlp}(C, Q). Loop-free wp is calculated by substitution; loop wp is a least fixed point replaced by an invariant.
  • Annotated programs generate verification conditions (initial, preservation, exit and, for total correctness, variant bound and decrease). Valid conditions make the triple derivable and, by logical soundness (induction on derivations), valid. Completeness is relative to an arithmetic oracle.
  • Z3 proves conditions over all Z\Z or returns a counterexample; bitvectors find overflows like binary-search midpoint. Dafny automates the process, separation logic handles aliasing, and language models can propose invariants because the verifier checks each proposal.