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 , 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:
- 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.
- If those formulas are valid, the program is correct. The translation is a theorem, not a heuristic.
- 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:
where is a constant and a variable. Examples also use , , , , and operations and (integer division rounded down and its remainder), defined similarly.
A state is a function assigning each variable an integer. An expression’s value in a state, , is defined by structural recursion: , , , and similarly for the rest. Write for the state equal to except at , which becomes .
Commands get their meaning from big-step operational semantics: relation (“executing from terminates in ”) is the smallest satisfying these rules:
Each terminating execution is a finite tree built with these rules. If execution does not terminate, there is simply no with : the last rule would require an infinite tree. Induction on trees shows the semantics are deterministic (for each and there is at most one ), so each command defines a partial function on the set of states. This functional view is key to weakest preconditions.
State properties are first-order formulas over , called assertions; for convenience we also use functions definable in that language, such as or . Their free variables are program variables and sometimes logical variables the program does not modify, naming initial values (such as in ). A state satisfies an assertion, , with ordinary first-order semantics: assigns the free variables. Identify each assertion with the set of states satisfying it, so is valid exactly when .
Hoare triples
This is the previous lesson’s distinction between partial and total correctness, now with precise underlying semantics. Some examples:
- is valid in both senses.
- is valid for partial correctness: the loop never terminates, so no can violate . Partial correctness promises nothing about hanging programs.
- is valid for partial correctness (if it terminates, ), but not total: from the loop runs through forever.
Predicates as regions
Before writing rules, view a triple geometrically. With two integer variables, a state is a grid point and an assertion a region. A command moves each point to another (or loses it if nonterminating).
The figure shows three facts formalized below.
- The good region is a preimage. Orange states are with , that is, , the preimage of under partial function . Thus translating one unit right shifts the good region one unit left.
- An assignment’s preimage is substitution. For and , good states satisfy : with replacing .
- Validity is inclusion. is valid if and only if lies in the preimage (except states from which 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: by induction on . If , both sides equal ; if , both equal ; if , both equal ; and if (or another operation), apply induction to and . For formulas atomic cases follow from this and connectives by induction. For quantifier there are two cases. If , is not free, substitution does not enter and both sides agree because ‘s value does not matter. If , capture-avoiding substitution renames if it appears in (see capture-avoiding substitution), so does not appear in , changing does not alter , and induction applies to in each state .
∎Since executing sends to , the lemma says exactly that if holds before, holds afterward. This is Hoare’s assignment rule:
Read right to left: given a postcondition , substitution gives the precondition. This is how assignment works. What will assert about afterward must already be true of the value will receive. Writing it forward as is tempting and false: with and it yields , claiming that after assignment is 4. Floyd’s correct forward rule needs a quantifier remembering the old value:
where is the old value of . 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 if the triple is derived by these rules, one per command form plus consequence, connecting assertion logic:
Three observations:
- Sequence needs an intermediate assertion the rule does not tell us how to find. It will be ‘s weakest precondition.
- The loop rule is the preceding lesson in one line. If one pass preserves (when the guard is true), then starting in , if the loop terminates, it ends in 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 , accepted by Hoare logic when valid. Mathematical work in verification ends up in those implications.
For total correctness the loop rule adds integer variant , bounded below while the loop continues and decreasing each pass:
where is a fresh logical variable absent from , and : it stores the variant at pass start. A strictly decreasing sequence of nonnegative integers is finite (well-foundedness of ), 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.
Division deserves a look. With invariant , the partial-correctness derivation closes. Total correctness fails the condition for variant : the counterexample has , where a pass leaves unchanged. To decrease the variant, must be known inside the loop, and the rule allows only what is in the invariant. Precondition held initially and nothing changes it, but without writing it in 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 , either or ; in both cases . Conversely if , every with satisfies . 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:
Each line is a preimage fact. The second is substitution. The third is composition preimage, : to end in after , must end in a state from which reaches . The fourth splits state space by the guard. With wp the sequence rule needs no imagination: choose .
Read the result: a pass restores the invariant if beforehand and . Guard provides exactly the missing part. Maintenance condition holds by propositional logic alone.
Loops: replace a fixed point with an invariant
For loop , substitution is insufficient. Let be the set of states from which terminates in after exactly passes:
That union is the least fixed point of , expressing a loop step as “exit or execute a pass and continue.” In the region figure, has wp states with that end in ; states with 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 is all 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): . Annotations complete wp calculation with a loop rule that returns as precondition while recording the invariant obligations separately.
Proof
By structural induction on , for every , if formulas in are valid, then . Assignments and are axioms. For sequence induction gives and , joined by sequence. For a conditional, implies propositionally, and consequence plus induction give the branch; the other is similar. For a loop induction gives ; preservation and consequence give ; the loop rule gives , and exit plus consequence give . Finally the initial condition and consequence take to . The total case is similar with rule : induction gives , preservation and decrease plus consequence give , 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 and variant , the four conditions are
None mentions the program. These are quantifier-free integer arithmetic formulas, linear here except product , appearing equally on both sides. In the next figure calculate them yourself, program by program, with animated backward calculation.
Two details of swapping. Version gives : both final values come from old , and the initial condition fails in any state with . Simultaneous assignment substitutes at once, , and is correct. Substituting one at a time, first then , computes wp of a different program.
Soundness and completeness of the logic
We gave symbol-manipulating rules, , and execution-based truth, . 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 , the only rule that could produce it requires with and , so apply the two hypotheses in order. The conditional is similar by cases on in , and consequence composes two implications with the triple. The loop alone needs another induction, on the derivation of , 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 .
∎The converse is subtler. Whether every valid triple is derivable depends on two arithmetic matters outside Hoare logic: whether consequence premises, formulas over , 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 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 are not even recursively enumerable (Gödel), and is valid exactly when 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 . Each command’s rule is one line of wp.
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 while constructing it and recognizes what remains as . 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 (everything on one side, expanded, strict inequalities as , equivalent over integers to ), 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 for counterexamples; this proves nothing but finds small errors, most of them.
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 needs hypothesis equality , while the propositional skeleton treats and 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 and , and its invariant has a variable exponent: no simple algebraic trick closes it. An incomplete invariant reveals itself through a concrete counterexample.
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 , and : a pass that does not decrease the variant. This state is unreachable (the precondition requires and nothing changes ), but the verification condition must hold in every state satisfying and guard, and the invariant forgot . 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: is valid if and only if is unsatisfiable, so submit and read the answer. If unsat, 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.
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)npm run lab and open the connection link.Three readings of the output:
- Over , 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 fails with a concrete model where (the exact model varies; with the variant does not decrease and with increases): the bounded search gave the same diagnosis, but Z3 has explored all and proved the other three conditions.
- With 32 bits, the naive midpoint fails. In Python
/,<=and>=on bitvectors are signed operations, like Java or Cint. Z3 finds a pair with : the sum wraps negative and leaves the interval. Bloch’s error found in milliseconds. Version is proved for all possible pairs. “The sum of naturals is nonnegative,” trivial in , also fails with 32 bits: in the model exceeds , wrapping new 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 , 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: changes if . Treating as an ordinary variable gives false results. For example would be “proved” because does not syntactically contain , but is false when . McCarthy’s standard solution views the whole array as a variable whose value is a function and assignment as a function update:
With this rule is , that is, . Z3’s array theory implements exactly that read-over-write rule.
Pointers are worse: can change whenever 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: says memory contains exactly cell with value , and separating conjunction says memory splits into disjoint pieces satisfying and . Its key frame rule is:
What does not touch remains unchanged without mentioning it; for example is derived without asking whether : 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:
- The model reads program and specification and proposes an invariant for each loop.
- The verification-condition generator calculates conditions and a solver tries to discharge them.
- If one fails, its counterexample returns to the model as feedback (“in state 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
More than one answer may be correct.
Step 1 of 5. Which invariant do you choose?
Step 1 of 4. Consequence: assume , and . Given and , what follows?
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 exactly when execution of from (using interpreter run) terminates in a state of . 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 NotImplementedErrorq := 0; r := x; while r >= y do (r := r - y; q := q + 1) with precondition must terminate with . 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")Summary
- Big-step operational semantics assigns each command a partial function on states. A triple is partially correct if every terminating execution from ends in ; totally correct if every execution from also terminates.
- Assignment axiom is the substitution lemma and works backward. Sequence, conditional, invariant loop and consequence complete the logic; consequence bridges arithmetic.
- and adds nonterminating states. exactly when . 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 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.