Algorithmcore
Verification condition generation
Also called VC generation, VCGen.
Turns an annotated program into logical formulas, by weakest preconditions or symbolic paths, whose validity implies its correctness.
- Time
- O(2^n) worst
- Space
- O(2^n) extra
- Where
- V = the number of variables; n = the number of nodes of the program and its annotations
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert W. Floyd, Edsger W. Dijkstra, Cormac Flanagan, James B. Saxe, 1967
Verification condition generation, or VCGen, turns a program with a precondition, a postcondition and a loop invariant on each loop into a list of logical formulas, the verification conditions or VCs. If every VC is valid, the program is correct. The classic method walks backwards through the code with the rules of the weakest precondition, cuts each loop at its invariant, and hands the VCs to a solver. This page gives that method, proves it sound, and shows why naive wp can grow exponentially while the passive form of Flanagan and Saxe stays polynomial.
In plain words
You have a program, a claim about its input and a claim about its output. VCGen writes down a few plain statements of logic that do not mention the program at all. If those statements are true, the program keeps its promise. It works from the end of the program towards the start. Each line of code changes what must be true before it: an assignment replaces the variable by its new value, a branch splits the requirement into two cases. A loop is the hard part, so a person, or another tool, writes down a fact that holds every time the loop starts again. VCGen then asks three things: the fact holds when the loop is first reached, one turn of the loop keeps it, and the fact together with the loop exit gives what is needed after the loop. A solver checks each statement.
The problem
The input is a precondition , a statement and a postcondition . The statements are skip, , assert , assume , sequence, if then else , and while invariant do , over integer variables with , and . The output is a list of formulas such that, if all of them are valid, the Hoare triple holds for partial correctness: every run of from a state of that stops passes its asserts and ends in a state of .
Whether a program meets its specification is undecidable by Rice's theorem. VCGen does not decide it. It moves the hard part into the invariants, which someone must supply, and into the validity of the VCs. Validity is decidable only in decidable theories: Presburger arithmetic for linear integer formulas, linear real arithmetic, equality with uninterpreted functions and arrays, and their combinations. The VCs of the example below multiply two variables, and validity over the integers with multiplication is undecidable by Hilbert's tenth problem. A real tool gives each VC to an SMT solver. This page has no solver. It checks each VC in every state of a small box of integers, which is a bounded check, not a proof.
The algorithm
VCGEN(P, S, Q)- 1
side <- an empty list - 2
return [P => WP(S, Q, side)] followed by side WP(S, Q, side)- 3
case S of - 4
skip: return Q - 5
x := e: return Q[e/x] - 6
assert p: return p and Q - 7
assume p: return p => Q - 8
S1; S2: return WP(S1, WP(S2, Q, side), side) - 9
if b then S1 else S2: return (b => WP(S1, Q, side)) and (not b => WP(S2, Q, side)) - 10
while b invariant I do B: - 11
append (I and b) => WP(B, I, side) to side - 12
append (I and not b) => Q to side - 13
return I
Lines L4 to L9 are the rules of the weakest precondition, with the formula with in place of every free . A loop is cut at its invariant (lines L10 to L13). The code before the loop must establish , which is what line L13 asks for. Line L11 asks that one turn of the body keeps , and line L12 asks that and the exit give . The side conditions are checked in every state, not only in the states that the code before the loop leaves. So the invariant must state every fact about the loop that the proof needs, even facts about variables that the loop does not change.
Example
Integer division by repeated subtraction. The precondition is , and the postcondition is .
q := 0; r := x;
while y <= r invariant x = q*y + r and r >= 0 do
r := r - y; q := q + 1
WP of the loop body for the invariant is , so VCGEN returns three VCs:
- (the invariant holds at entry; 19 nodes),
- (one turn keeps it; 33 nodes),
- (the exit gives the postcondition; 32 nodes).
All three hold in every state of over , and they are valid over the integers by simple algebra. The run from , visits the loop head four times. The table shows which VC covers each step.
| head visit | guard | VC used | |||
|---|---|---|---|---|---|
| 1 | 0 | 7 | , | true | 1 to reach it, 2 to go on |
| 2 | 1 | 5 | true | 2 | |
| 3 | 2 | 3 | true | 2 | |
| 4 | 3 | 1 | false | 3: |
The size of naive wp. Let be copies of "if then else ", with the precondition and the postcondition . The table counts the nodes of the VC as a tree, as a DAG that shares equal subterms, and the nodes of the compact VC of the section on variants. The counts come from the functions size and dag_size of the implementation; there is no randomness. All the VCs hold on .
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |
|---|---|---|---|---|---|---|---|---|---|---|
| naive wp, tree | 40 | 106 | 270 | 662 | 1574 | 3654 | 8326 | 18694 | 41478 | 91142 |
| naive wp, DAG | 21 | 42 | 82 | 162 | 322 | 642 | 1282 | 2562 | 5122 | 10242 |
| compact VC, tree | 41 | 67 | 93 | 119 | 145 | 171 | 197 | 223 | 249 | 275 |
The DAG size is exactly for , so sharing does not help: each of the paths substitutes a different term, such as , into its copy of the postcondition. The compact VC grows by 26 nodes per if.
Correctness
The full proof is in the proof file. The main steps:
- Exact on loop-free code. For a loop-free , a state satisfies exactly when the run from it passes its asserts and is blocked or ends in . This is an induction on ; the assignment case is the substitution lemma. So the single VC holds in every state of a set exactly when every run from a state of is correct. With all states, this is the weakest precondition property.
- Sound with loops. If all VCs are valid, every run from that stops is correct. The proof is an induction on , and inside a loop an induction on the number of turns: the main VC gives at the first visit of the loop head, the VC of line L11 carries from one visit to the next, and the VC of line L12 gives at the exit.
- The bounded version. The same proof only uses the VCs in the start state and in the states at loop heads. So if the VCs hold on a box , every run whose start and loop-head states lie in is correct. The tests check this statement, and only this one, on random programs.
- No converse. With a loop, a correct program can have an invalid VC, because the side VCs ask that the invariant is inductive in every state, also in states that no run reaches.
The conditions are only as good as the invariants. VCGen proves partial correctness; termination needs a variant function and one more VC per loop, see termination proof.
Proof: The verification conditions are sound, exact on loop-free code, and the compact form has the same meaningfull
Setting. States map variable names to integers. Expressions and statements are those of the page: skip, , assert , assume , sequence, if, and while invariant do . A run of a statement from a state either fails at an assert, is blocked at an assume, ends in a final state, or does not stop. A run is correct for when no assert fails and the run is blocked or ends in a state of . is the formula that the function WP of the page returns, and is the list of formulas that it appends. Write when the formula is true in the state . For a formula , is true in exactly when is true in ; this is the substitution lemma of first-order logic, and it holds here because expressions have no side effects and no bound names clash.
Lemma 1: exactness for loop-free statements
Claim. Let be loop-free. For every formula and state : if and only if the run of from is correct for .
Proof. Induction on .
- skip: the run ends in , and WP returns .
- : the run ends in , and exactly when that state satisfies .
- assert : the run fails when and ends in otherwise. So it is correct exactly when .
- assume : the run is blocked when and ends in otherwise. So it is correct exactly when .
- : the run of the sequence is correct for exactly when the run of is correct for the set of states from which runs correctly for . A run of that fails or is blocked is a run of the sequence that fails or is blocked. By induction on , that set is , and by induction on , the condition is .
- if then else : if , the run is the run of , and WP reduces to in . The other case is symmetric.
Consequence. For loop-free the list of VCs is the single formula . For any set of states , this formula holds in every state of if and only if every run of from a state of is correct for . With the box of the tests, this is the exact statement that the random test checks; with all states, it says that the VC is valid exactly when the program is correct.
Lemma 2: soundness with loops, relative to a set of states
Claim. Let be a set of states, a statement and a formula. Suppose that every formula of holds in every state of . Let , and suppose the run of from stops (it fails, is blocked or ends) and every state of that run at the head of a loop is in . Then the run is correct for .
Proof. Induction on . The cases skip, assignment, assert and assume are as in Lemma 1. For : contains and . The run of from stops and its loop heads are among those of the whole run, so by induction it is correct for . If it fails or is blocked, so is the whole run. Otherwise it ends in , and the induction on applies to the rest of the run. The if case is the same, with the branch that the run takes.
For while invariant do , WP returns , and the side list contains , and the side list of . Let be the states of the run at the loop head. They are in . We show by induction on that every that the run reaches satisfies and that the run up to has failed no assert. For , by hypothesis. Let . If , the loop ends in , and in gives : the run is correct. If , then in gives . The run of from stops, because the whole run stops, and its loop heads are among those of the whole run, so by induction on it is correct for : it fails no assert, and it is blocked or ends in . Since the whole run stops, it passes the loop head only finitely often, so one of the ending cases occurs.
Theorem (soundness). If every formula of holds in every state of , then every run of from a state that stops, and whose loop-head states are in , is correct for . When is the set of all states, this is the usual soundness of VC generation for partial correctness: valid VCs imply .
Proof. The main VC in gives , and the side VCs hold in . Apply Lemma 2.
The converse fails as soon as there is a loop, because the side VCs ask for more than correctness: they ask that is inductive in every state, also in states that no run reaches. The page shows this with the invariant of the division program.
Lemma 3: the compact VC means the same
Claim. Let be loop-free. For every state , the formula is true in exactly when is.
Proof. The compact formula is , where is the list of definitions in the order in which pass 1 made them, is the passive statement, maps each variable to its last version, and is with each variable renamed by . Each uses only the original variables and versions defined before , so evaluating the lets in gives one extension of . The let that pass 2 puts at a join only gives a name to a formula, so has the same truth value as the plain weakest precondition of the passive statement, with .
For a substitution from variables to versions, write for the renamed formula. We show: if pass 1 maps the statement with the input map to the passive statement and the output map , then for every formula ,
Induction on .
- skip: and .
- : , and , where defines . In the version has the value of . So and both read every variable from and read as the value of ; they have the same truth value.
- assert and assume : is assert or assume , and the rules of wp and WP agree after renaming.
- : with , . By induction on , the inner formula is equivalent in to . A passive statement does not change the state, so wp of is monotone in the truth value of its postcondition at the single state , and we can replace the inner formula by an equivalent one. Then induction on with gives .
- if then else : pass 1 defines , passifies to and to , and for each with defines ; maps such to and the other variables to . Suppose . Then gives each the value of , so and have the same truth value. The passive statement is , and its wp in reduces to , which is equivalent to by the same monotonicity, and by induction to . On the other side, reduces to because holds. The case is symmetric.
At the top, is the identity, so the right side is . mentions only original variables, which reads from . So the compact formula is true in exactly when is.
Lemma 4: sizes
Size is the number of nodes of a formula as a tree; a let counts one node plus its two parts.
Naive wp can be exponential. Let be copies of "if then else ". Then with , so the size at least doubles at each step and is at least . The formula has a copy of for each of the choices of signs, with replaced by a term that records the choices in order, such as . These terms are different, so even a DAG that shares equal subterms has at least nodes.
The compact VC is polynomial. Let be the number of nodes of a passive statement, each assert or assume counted with the size of its formula. We show by induction. skip: . assert or assume : . Sequence: has size at most . Choice with a single name: . Choice with a larger : the let has once and two references to its name, .
Pass 1 makes a passive statement with nodes per statement plus the formulas of the asserts, assumes and conditions, renamed name for name, so . The definitions cost per assignment, per if, and per merged version. There are at most merged versions per if, where is the number of variables, so the compact VC has size , where is the number of ifs. This is in the worst case and linear when the number of variables is bounded, the same bounds that Flanagan and Saxe give.
Complexity
Each rule of WP does a constant amount of work plus a substitution, so the time is linear in the size of the output. The output can be exponential. A sequence of ifs doubles the formula times, as the table shows, and a sequence of assignments doubles the number of occurrences of each time. In both cases, the formula is at most nodes. The compact VC below has nodes for a loop-free program with ifs, which is in the worst case and when is bounded. The brute-force check costs evaluations for the box . A real tool pays instead for the SMT calls, whose cost depends on the theory: NP-complete for quantifier-free linear integer arithmetic, and undecidable with multiplication.
Properties
- Sound, not complete. Valid VCs imply correctness. An invalid VC does not mean the program is wrong; the invariant may be too weak.
- Exact without loops. For loop-free code, the VC is valid exactly when the program is correct.
- Modular. A procedure call can be replaced by assert of its precondition, havoc of what it changes, and assume of its postcondition, so each procedure is checked once against its contract, as in design by contract.
- Syntax-directed. The output depends only on the text of the program and the annotations, and one rule handles each kind of statement.
- Backward or forward. WP goes backwards with substitution. The forward version uses the strongest postcondition and needs a fresh name for each old value, which is what symbolic execution does.
Variants and improvements
- Passive form (Flanagan and Saxe). The two causes of blow-up are substitution, which copies into each occurrence of , and branches, which copy the postcondition into both cases. The passive form gives each assignment a fresh version defined by , as in static single assignment form, and merges versions at a join. A passive statement has no assignments, so its wp needs no substitution, and Flanagan and Saxe state it as with two predicates, N for normal termination and W for going wrong. The VC has size in the worst case, and linear in the passive statement once repeated subformulas get names. The implementation of this page binds each version with a let, merges with if-then-else, and names the postcondition with a let at each join; the one-point rule makes this equal to the form with assume. The table above shows the result: 26 nodes per if, not a doubling.
- Unstructured programs. Barnett and Leino generate the passive VC directly on a control flow graph, with one boolean variable per block that says "the run from this block is correct". This is the method of Boogie.
- Loops by havoc. Flanagan and Saxe desugar a loop to: assert , havoc the variables that the body changes, assume , and then either assume , run the body, assert and assume false, or assume . The VC of the cut program is the same as lines L10 to L13, but the havoc keeps the facts about variables that the loop does not change, so the invariant can omit them.
- Forward VCs and path enumeration. Floyd's original method takes each path between two assertions, computes its strongest postcondition, and asks that it implies the assertion at the end. Symbolic execution is the same with one path condition per path.
- Without invariants. Bounded model checking unrolls each loop a fixed number of times and checks the unrolled program. Loop invariant synthesis, for example the Houdini algorithm, finds invariants automatically.
When to use it
Use VCGen in a deductive verifier, where a programmer writes contracts and invariants and expects a proof, not a test. Dafny, Why3, Frama-C with its WP plug-in, and ESC/Java all generate VCs and call SMT solvers. Use the passive form as soon as programs have more than a few branches in sequence. When no one will write invariants, use an invariant generator first, or use abstract interpretation or a model checker such as IC3, which find the inductive facts themselves.
Pitfalls
- An invariant that is true but not inductive. With the invariant alone, the division program is still correct, but VC 3 fails in the state , , , : the invariant and the exit hold, and does not. No run reaches that state, but the side VCs are checked in every state.
- Forgetting facts the loop does not change. The side VCs drop all context. If the body asserted , the invariant would have to repeat , although no statement changes . The havoc form keeps such facts for the variables that the loop does not assign.
- Taking partial correctness for termination. With the precondition only, all three VCs of the example are still valid, but the program loops forever when .
- Taking a bounded check for a proof. The VC of skip for the postcondition holds in every state of and fails at . The brute-force check of this page is only evidence; an SMT solver gives a proof for decidable theories.
- Naive wp on long code. The table above shows the doubling. A VCGen that copies the postcondition at each branch can time out on code that a passive VCGen handles at once.
- Substitution with capture. must not substitute under a binder of , and must rename a bound variable that occurs free in . Quantified invariants make this a real bug.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/verification-condition-generation/. The authors are listed in prov/7VA8XP.jsonl.
"""Verification condition generation for a small while language.
Expressions are tuples:
("int", c), ("bool", b), ("var", x),
(op, a, b) for op in + - * < <= == and or =>,
("not", a), ("ite", c, a, b) and ("let", x, e, body).
Statements are tuples:
("skip",), ("assign", x, e), ("seq", s1, s2), ("if", b, s1, s2),
("while", b, inv, body), ("assert", p), ("assume", p).
vcgen(pre, stmt, post) returns the list of verification conditions of the
page: first pre => wp(stmt, post), then the side conditions of the loops.
Each is meant to hold in every state. compact_vc(pre, stmt, post) builds the
Flanagan-Saxe style VC of a loop-free statement: assignments become
single-assignment versions bound by let, joins become ite merges, and the
postcondition is named by a let at each join, so its size is polynomial.
There is no SMT solver here. valid_on_box checks a formula in every state of
a box of integers. This is a bounded check, not a proof of validity.
"""
import itertools
_ARITH = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b}
_CMP = {"<": lambda a, b: a < b, "<=": lambda a, b: a <= b, "==": lambda a, b: a == b}
_BOOL = ("and", "or", "=>")
TRUE = ("bool", True)
def evaluate(e: tuple, env: dict):
"""The value of e in the state env (a dict from names to ints). Cost:
O(size of e), where a let counts its bound expression once."""
tag = e[0]
if tag == "int" or tag == "bool":
return e[1]
if tag == "var":
return env[e[1]]
if tag in _ARITH:
return _ARITH[tag](evaluate(e[1], env), evaluate(e[2], env))
if tag in _CMP:
return _CMP[tag](evaluate(e[1], env), evaluate(e[2], env))
if tag == "and":
return evaluate(e[1], env) and evaluate(e[2], env)
if tag == "or":
return evaluate(e[1], env) or evaluate(e[2], env)
if tag == "=>":
return (not evaluate(e[1], env)) or evaluate(e[2], env)
if tag == "not":
return not evaluate(e[1], env)
if tag == "ite":
return evaluate(e[2], env) if evaluate(e[1], env) else evaluate(e[3], env)
if tag == "let":
inner = dict(env)
inner[e[1]] = evaluate(e[2], env)
return evaluate(e[3], inner)
raise ValueError("unknown expression %r" % (tag,))
def subst(e: tuple, x: str, r: tuple) -> tuple:
"""e with every free occurrence of the variable x replaced by r. The
bound names of let are fresh in this module, so no capture occurs.
Cost: O(size of the result)."""
tag = e[0]
if tag == "var":
return r if e[1] == x else e
if tag == "int" or tag == "bool":
return e
if tag == "let":
body = e[3] if e[1] == x else subst(e[3], x, r)
return ("let", e[1], subst(e[2], x, r), body)
return (tag,) + tuple(subst(a, x, r) for a in e[1:])
def size(e: tuple) -> int:
"""The number of nodes of e as a tree. Cost: O(size of e)."""
if e[0] in ("int", "bool", "var"):
return 1
return 1 + sum(size(a) for a in e[1:] if isinstance(a, tuple))
def dag_size(e: tuple) -> int:
"""The number of distinct subterms of e, the size of e as a DAG with
shared subterms. Cost: O(size of e) set operations."""
seen = set()
stack = [e]
while stack:
t = stack.pop()
if t in seen:
continue
seen.add(t)
if t[0] not in ("int", "bool", "var"):
stack.extend(a for a in t[1:] if isinstance(a, tuple))
return len(seen)
def wp(s: tuple, q: tuple, side: list) -> tuple:
"""The weakest precondition of s for q, with each loop replaced by its
invariant. The side conditions of the loops are appended to side.
Cost: O(size of the result), which can be exponential in the size of s."""
tag = s[0] # @line L3
if tag == "skip":
return q # @line L4
if tag == "assign":
return subst(q, s[1], s[2]) # @line L5
if tag == "assert":
return ("and", s[1], q) # @line L6
if tag == "assume":
return ("=>", s[1], q) # @line L7
if tag == "seq":
return wp(s[1], wp(s[2], q, side), side) # @line L8
if tag == "if":
b = s[1] # @line L9
return ("and", ("=>", b, wp(s[2], q, side)), ("=>", ("not", b), wp(s[3], q, side)))
if tag == "while":
b, inv, body = s[1], s[2], s[3] # @line L10
side.append(("=>", ("and", inv, b), wp(body, inv, side))) # @line L11
side.append(("=>", ("and", inv, ("not", b)), q)) # @line L12
return inv # @line L13
raise ValueError("unknown statement %r" % (tag,))
def vcgen(pre: tuple, s: tuple, post: tuple) -> list:
"""The verification conditions of {pre} s {post}: the main condition
pre => wp(s, post), then the side conditions of every loop. If all of
them hold in every state, every run of s from a state of pre that stops
passes its asserts and ends in post (partial correctness)."""
side = [] # @line L1
main = ("=>", pre, wp(s, post, side)) # @line L2
return [main] + side
def valid_on_box(f: tuple, names, lo: int, hi: int):
"""Check f in every state that maps names into [lo, hi]. Return None if
f holds in all of them, or the first state where it fails. This is a
bounded check, not a proof. Cost: (hi - lo + 1)^len(names) evaluations."""
names = list(names)
for vals in itertools.product(range(lo, hi + 1), repeat=len(names)):
env = dict(zip(names, vals))
if not evaluate(f, env):
return env
return None
def run(s: tuple, env: dict, fuel: int = 10000, heads=None):
"""Execute s from the state env. Return ("ok", final state),
("fail", None) when an assert is false, ("blocked", None) when an assume
is false, or ("out", None) when fuel runs out. Each loop test uses one
unit of fuel. If heads is a list, every state at a loop head is
appended to it."""
env = dict(env)
budget = [fuel]
def go(t):
tag = t[0]
if tag == "skip":
return "ok"
if tag == "assign":
env[t[1]] = evaluate(t[2], env)
return "ok"
if tag == "assert":
return "ok" if evaluate(t[1], env) else "fail"
if tag == "assume":
return "ok" if evaluate(t[1], env) else "blocked"
if tag == "seq":
r = go(t[1])
return go(t[2]) if r == "ok" else r
if tag == "if":
return go(t[2]) if evaluate(t[1], env) else go(t[3])
if tag == "while":
while True:
if budget[0] <= 0:
return "out"
budget[0] -= 1
if heads is not None:
heads.append(dict(env))
if not evaluate(t[1], env):
return "ok"
r = go(t[3])
if r != "ok":
return r
raise ValueError("unknown statement %r" % (tag,))
r = go(s)
return (r, dict(env) if r == "ok" else None)
def assigned(s: tuple) -> set:
"""The variables that s assigns."""
tag = s[0]
if tag == "assign":
return {s[1]}
if tag == "seq" or tag == "if":
return assigned(s[-2]) | assigned(s[-1])
if tag == "while":
return assigned(s[3])
return set()
def compact_vc(pre: tuple, s: tuple, post: tuple) -> tuple:
"""A VC of {pre} s {post} for a loop-free s, equal to pre => wp(s, post)
in every state. It is built in two passes, after Flanagan and Saxe.
Pass 1 makes s passive. Each assignment x := e gets a fresh version x#k
defined by e over the current versions. At a join, each variable whose
versions differ gets a version defined by ite(g, left, right), where g
names the branch condition. The definitions become nested lets.
Pass 2 computes wp of the passive statement, which needs no substitution,
and names the postcondition with a let at each join. The result has
size O(|s| + |pre| + |post| + m), where m is the number of merged
versions, at most the number of variables times the number of ifs."""
counter = itertools.count(1)
defs = []
def rename(e, sigma):
for x, v in sigma.items():
if v != x:
e = subst(e, x, ("var", v))
return e
def passify(t, sigma):
tag = t[0]
if tag == "skip":
return ("skip",), sigma
if tag == "assign":
v = "%s#%d" % (t[1], next(counter))
defs.append((v, rename(t[2], sigma)))
out = dict(sigma)
out[t[1]] = v
return ("skip",), out
if tag == "assert" or tag == "assume":
return (tag, rename(t[1], sigma)), sigma
if tag == "seq":
a, s1 = passify(t[1], sigma)
b, s2 = passify(t[2], s1)
return ("seq", a, b), s2
if tag == "if":
g = "g#%d" % next(counter)
defs.append((g, rename(t[1], sigma)))
a, sa = passify(t[2], sigma)
b, sb = passify(t[3], sigma)
out = dict(sigma)
for x in sorted(sigma):
if sa[x] != sb[x]:
v = "%s#%d" % (x, next(counter))
defs.append((v, ("ite", ("var", g), ("var", sa[x]), ("var", sb[x]))))
out[x] = v
left = ("seq", ("assume", ("var", g)), a)
right = ("seq", ("assume", ("not", ("var", g))), b)
return ("choice", left, right), out
raise ValueError("compact_vc needs a loop-free statement, got %r" % (tag,))
def pwp(t, q):
tag = t[0]
if tag == "skip":
return q
if tag == "assert":
return ("and", t[1], q)
if tag == "assume":
return ("=>", t[1], q)
if tag == "seq":
return pwp(t[1], pwp(t[2], q))
if tag == "choice":
if q[0] in ("var", "bool"):
return ("and", pwp(t[1], q), pwp(t[2], q))
n = "q#%d" % next(counter)
name = ("var", n)
return ("let", n, q, ("and", pwp(t[1], name), pwp(t[2], name)))
raise ValueError(tag)
names = _free_vars(pre) | _free_vars(post) | _stmt_vars(s)
sigma0 = {x: x for x in names}
passive, sigma = passify(s, sigma0)
f = ("=>", pre, pwp(passive, rename(post, sigma)))
for v, e in reversed(defs):
f = ("let", v, e, f)
return f
def _free_vars(e: tuple) -> set:
tag = e[0]
if tag == "var":
return {e[1]}
if tag in ("int", "bool"):
return set()
if tag == "let":
return _free_vars(e[2]) | (_free_vars(e[3]) - {e[1]})
out = set()
for a in e[1:]:
out |= _free_vars(a)
return out
def _stmt_vars(s: tuple) -> set:
tag = s[0]
if tag == "assign":
return {s[1]} | _free_vars(s[2])
if tag in ("assert", "assume"):
return _free_vars(s[1])
if tag == "seq":
return _stmt_vars(s[1]) | _stmt_vars(s[2])
if tag == "if":
return _free_vars(s[1]) | _stmt_vars(s[2]) | _stmt_vars(s[3])
if tag == "while":
return _free_vars(s[1]) | _free_vars(s[2]) | _stmt_vars(s[3])
return set()
test_verification_condition_generation.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/verification-condition-generation/. The authors are listed in prov/7VA8XP.jsonl.
import itertools
import random
import unittest
from verification_condition_generation import (
compact_vc,
dag_size,
evaluate,
run,
size,
valid_on_box,
vcgen,
)
def V(x):
return ("var", x)
def K(c):
return ("int", c)
def seqs(*ss):
out = ss[-1]
for s in reversed(ss[:-1]):
out = ("seq", s, out)
return out
# The worked example of the page: division by repeated subtraction.
PRE = ("and", ("<=", K(0), V("x")), ("<", K(0), V("y")))
INV = ("and", ("==", V("x"), ("+", ("*", V("q"), V("y")), V("r"))), ("<=", K(0), V("r")))
BODY = ("seq", ("assign", "r", ("-", V("r"), V("y"))), ("assign", "q", ("+", V("q"), K(1))))
POST = ("and", ("==", V("x"), ("+", ("*", V("q"), V("y")), V("r"))),
("and", ("<=", K(0), V("r")), ("<", V("r"), V("y"))))
def division(inv):
return seqs(("assign", "q", K(0)), ("assign", "r", V("x")), ("while", ("<=", V("y"), V("r")), inv, BODY))
DIV_NAMES = ["x", "y", "q", "r"]
def toward_zero(n):
step = ("if", ("<", K(0), V("x")), ("assign", "x", ("-", V("x"), K(1))), ("assign", "x", ("+", V("x"), K(1))))
return seqs(*([step] * n))
def outcome_ok(res, post):
kind, final = res
if kind == "ok":
return evaluate(post, final)
return kind == "blocked"
class TestPage(unittest.TestCase):
def test_division_vcs(self):
vcs = vcgen(PRE, division(INV), POST)
self.assertEqual(len(vcs), 3)
self.assertEqual([size(f) for f in vcs], [19, 33, 32])
for f in vcs:
self.assertIsNone(valid_on_box(f, DIV_NAMES, -6, 6))
def test_division_run(self):
heads = []
res = run(division(INV), {"x": 7, "y": 2, "q": 0, "r": 0}, heads=heads)
self.assertEqual(res, ("ok", {"x": 7, "y": 2, "q": 3, "r": 1}))
self.assertEqual([(h["q"], h["r"]) for h in heads], [(0, 7), (1, 5), (2, 3), (3, 1)])
for h in heads:
self.assertTrue(evaluate(INV, h))
def test_weak_invariant_gives_invalid_vc(self):
weak = ("==", V("x"), ("+", ("*", V("q"), V("y")), V("r")))
vcs = vcgen(PRE, division(weak), POST)
self.assertIsNone(valid_on_box(vcs[0], DIV_NAMES, -6, 6))
self.assertIsNone(valid_on_box(vcs[1], DIV_NAMES, -6, 6))
self.assertIsNotNone(valid_on_box(vcs[2], DIV_NAMES, -6, 6))
# The program is still correct on every start state of the box.
for x, y in itertools.product(range(0, 7), range(1, 7)):
res = run(division(weak), {"x": x, "y": y, "q": 0, "r": 0})
self.assertTrue(outcome_ok(res, POST))
def test_bounded_check_is_not_a_proof(self):
f = vcgen(("bool", True), ("skip",), ("<", V("x"), K(100)))[0]
self.assertIsNone(valid_on_box(f, ["x"], -8, 8))
self.assertFalse(evaluate(f, {"x": 100}))
def test_exponential_example(self):
tree = []
for n in range(1, 11):
pre = ("and", ("<=", K(-n), V("x")), ("<=", V("x"), K(n)))
post = ("and", ("<=", K(0), V("x")), ("<=", V("x"), K(1)))
s = toward_zero(n)
naive = vcgen(pre, s, post)[0]
compact = compact_vc(pre, s, post)
tree.append(size(naive))
if n >= 2:
self.assertEqual(dag_size(naive), 10 * 2 ** n + 2)
self.assertEqual(size(compact), 15 + 26 * n)
self.assertIsNone(valid_on_box(naive, ["x"], -12, 12))
self.assertIsNone(valid_on_box(compact, ["x"], -12, 12))
self.assertEqual(tree, [40, 106, 270, 662, 1574, 3654, 8326, 18694, 41478, 91142])
def test_compact_needs_loop_free(self):
with self.assertRaises(ValueError):
compact_vc(PRE, division(INV), POST)
NAMES = ["x", "y", "z"]
LO, HI = -2, 2
def rand_term(rng):
a = rng.choice([V(n) for n in NAMES] + [K(rng.randint(-2, 2))])
r = rng.random()
if r < 0.4:
return a
b = rng.choice([V(n) for n in NAMES] + [K(rng.randint(-2, 2))])
return (rng.choice(["+", "-", "+", "*"]), a, b)
def rand_atom(rng):
return (rng.choice(["<", "<=", "=="]), rand_term(rng), rand_term(rng))
def rand_cond(rng):
r = rng.random()
if r < 0.6:
return rand_atom(rng)
if r < 0.8:
return ("not", rand_atom(rng))
return (rng.choice(["and", "or"]), rand_atom(rng), rand_atom(rng))
def rand_loop_free(rng, depth):
r = rng.random()
if depth == 0 or r < 0.35:
k = rng.random()
if k < 0.7:
return ("assign", rng.choice(NAMES), rand_term(rng))
if k < 0.85:
return ("assert", rand_cond(rng))
return ("assume", rand_cond(rng))
if r < 0.7:
return ("seq", rand_loop_free(rng, depth - 1), rand_loop_free(rng, depth - 1))
return ("if", rand_cond(rng), rand_loop_free(rng, depth - 1), rand_loop_free(rng, depth - 1))
def box_states():
for vals in itertools.product(range(LO, HI + 1), repeat=len(NAMES)):
yield dict(zip(NAMES, vals))
class TestRandom(unittest.TestCase):
def test_loop_free_vc_is_exact(self):
# For a loop-free program the VC holds in a state exactly when the
# run from that state is correct, so validity on the box equals
# correctness of every run from the box. The compact VC agrees.
rng = random.Random(7)
valid_count = 0
for _ in range(500):
s = rand_loop_free(rng, 3)
pre = rand_cond(rng) if rng.random() < 0.5 else ("bool", True)
post = rand_cond(rng)
vcs = vcgen(pre, s, post)
self.assertEqual(len(vcs), 1)
naive = vcs[0]
compact = compact_vc(pre, s, post)
all_ok = True
for env in box_states():
truth = (not evaluate(pre, env)) or outcome_ok(run(s, env), post)
self.assertEqual(evaluate(naive, env), truth)
self.assertEqual(evaluate(compact, env), truth)
all_ok = all_ok and truth
self.assertEqual(valid_on_box(naive, NAMES, LO, HI) is None, all_ok)
valid_count += all_ok
self.assertGreater(valid_count, 50)
def test_loops_sound_on_box(self):
# If every VC holds on the box, every run from a pre state whose
# loop-head states stay in the box passes its asserts and ends in
# the postcondition.
rng = random.Random(11)
checked = 0
for _ in range(500):
body = rand_loop_free(rng, 2)
inv = rand_cond(rng) if rng.random() < 0.7 else ("bool", True)
b = rand_atom(rng)
post = rng.choice([("not", b), rand_cond(rng), ("and", inv, ("not", b))])
pre = rand_cond(rng) if rng.random() < 0.5 else inv
s = seqs(rand_loop_free(rng, 1), ("while", b, inv, body))
vcs = vcgen(pre, s, post)
if any(valid_on_box(f, NAMES, LO, HI) is not None for f in vcs):
continue
checked += 1
for env in box_states():
if not evaluate(pre, env):
continue
heads = []
res = run(s, env, fuel=60, heads=heads)
if res[0] == "out":
continue
if all(LO <= h[n] <= HI for h in heads for n in NAMES):
self.assertTrue(outcome_ok(res, post))
self.assertGreater(checked, 50)
if __name__ == "__main__":
unittest.main()
History
Floyd's 1967 paper attached assertions to the edges of a flowchart and derived a verification condition for each path between assertions, with a tagged assertion cutting each loop. Hoare's logic of 1969 gave the same method as rules for triples, and Dijkstra's weakest preconditions of 1975 turned the rules into a function that computes the condition backwards. King's verifier of 1969 and the Stanford Pascal Verifier of the 1970s generated VCs mechanically. In 2001 Flanagan and Saxe found the two causes of exponential VCs in ESC/Java, assignments and joins, and fixed both with the passive form. Barnett and Leino extended the method to unstructured programs in 2005, and it is the core of Boogie and of the verifiers built on it.
References
- Cormac Flanagan and James B. Saxe, Avoiding exponential explosion, generating compact verification conditions, Proceedings of POPL 2001, pp. 193 to 205, Figure 2 (wp), Sections 4 to 6 (the two causes of blow-up, passive form, the outcome predicates N and W), Theorems 1 to 3, Section 7.1 (loops)
- Mike Barnett and K. Rustan M. Leino, Weakest-precondition of unstructured programs, Proceedings of PASTE 2005, pp. 82 to 87, the passive form of a control flow graph and its VC
- Edsger W. Dijkstra, Guarded commands, nondeterminacy and formal derivation of programs, Communications of the ACM 18(8), 1975, pp. 453 to 457, the rules of wp for assignment, sequence and alternation
- Robert W. Floyd, Assigning meanings to programs, in Mathematical Aspects of Computer Science, Proceedings of Symposia in Applied Mathematics 19, American Mathematical Society, 1967, pp. 19 to 32, the verification conditions of a flowchart with a tagged assertion on each loop
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7VA8XP Edit this page History Report an error Markdown