Loop Invariants
Loop header invariants, boundaries, compile-time folding, and proof obligations.
Contents
A loop invariant is a boolean predicate that must hold every time the loop reaches its header. Haze supports invariants on all loop forms, and checks them before the loop condition on each iteration, including the initial check before the first iteration.
Syntax#
An invariant follows the loop header and precedes the body. Multiple invariants may be written as repeated : invariant clauses.
for i in 0..values.len
: invariant i >= 0
: invariant i <= values.len
{
process(values[i])
}
The same form is available for a for-in loop and a condition loop.
for value in values
: invariant seen.len <= values.len
{
seen += [value]
}
for index < limit
: invariant index >= 0
{
index += 1
}
The invariant expression must be bool. In a range or for-in loop the loop variable is in scope; in a condition loop only the names visible at the loop header are in scope.
Boundary Semantics#
A range loop checks its invariant at the header before the exit test. That means the invariant is also checked at the terminal index, where the loop is about to stop. An invariant that is intended to hold only while the body is executing must therefore use an inclusive boundary.
for i in 0..n
: invariant i <= n // holds at i == n
{
// body
}
for i in 0..n
: invariant i < n // fails at i == n
{
// body
}
The first loop is correct for the usual "index is within the half-open range" property. The second is a common mistake: it holds during the body but not at the final header check. A break can leave the loop before a later header check, so an invariant that would fail on a later iteration may never be evaluated if the body breaks early.
A for-in loop captures the list length at entry. Its invariant is checked at the header on each iteration, including the final check after the last element. The length is not re-read from the list, so appending to the list during iteration does not change the number of visits.
Runtime and Compile-Time Checks#
An invariant that is constant and false is rejected during compile-time folding. An invariant that the compiler cannot decide becomes a runtime check. A runtime failure calls the panic path with loop invariant failed.
const floor = 1
for i in 0..4
: invariant floor > 3 // compile-time error
{
print(i)
}
In a pure function with known bounds, the evaluator can execute the loop and check the invariant on each iteration. A failure is reported at compile time. The evaluator has a depth limit of 512 and an iteration limit of 100,000; a loop beyond those limits is not folded and its invariant remains a runtime check.
A for-in loop is not executed by the compile-time evaluator, even in a pure function. Its invariants are always runtime checks.
Checking, Not Assuming#
Haze checks loop invariants; it does not assume them when proving a postcondition or another invariant. This is deliberate. The compiler is not a full program verifier, and an invariant is a runtime assertion about the loop, not an induction hypothesis supplied to a proof engine.
The practical consequence is that an invariant cannot make a postcondition compile under -release. If a postcondition depends on a property that is only true because of the loop invariant, state the property in the postcondition as well or factor the loop into a function with its own contract.
Writing a Useful Invariant#
A useful invariant describes the relationship between the loop variable and the accumulator. It should be strong enough to be interesting, but simple enough that the compiler can evaluate it and a reader can verify it.
fn range(lo i32, hi i32) List[i32]
: pre lo >= 0
: pre lo <= hi
: post r => r.len == hi - lo
{
var out List[i32] = []
for i in lo..hi
: invariant out.len == i - lo
{
out += [i]
}
return out
}
The invariant says that after i - lo iterations, the output has exactly that many elements. It holds at the start (0 == lo - lo), after each append, and at the terminal header check (hi - lo == hi - lo). The postcondition follows from the same property, but the compiler does not use the invariant to prove it; the postcondition is checked independently.
A second useful pattern relates a running total to the range already processed.
fn sum_to(n i32) i32 {
var total = 0
for i in 0..n
: invariant total == i * (i - 1) / 2
{
total += i
}
return total
}
The invariant is the closed form for the sum of the integers below i. It is more informative than a simple bound and catches an off-by-one error in the loop body immediately.
Invariants and Defer#
A defer registered inside a loop body runs at the end of each iteration. The next header check sees the effects of the previous iteration's defers. If an invariant depends on a value changed by a defer, the invariant is checked against the post-defer state, not the state at the end of the body statement.
Keep invariants independent of cleanup side effects when possible. A cleanup that changes an accumulator used by the invariant is legal but makes the proof harder to follow.
Release Mode#
The -release flag removes runtime loop-invariant checks. Compile-time folding is not disabled, so a constant-false invariant is still rejected. Removing the runtime checks is only safe when the invariant has been established by reasoning or testing outside the compiler; otherwise a release build can silently violate the property that the invariant was meant to protect.
Summary#
| Loop form | Invariant scope | Compile-time evaluation |
|---|---|---|
for i in lo..hi |
i, outer names |
Pure loops with known bounds may be folded |
for x in list |
x, outer names |
Not executed by the evaluator |
for condition |
Outer names | Pure loops with known bounds may be folded |
Bare for |
Outer names | Not normally foldable |
| Property | Rule |
|---|---|
| Checked when | At the loop header, before the condition |
| Initial check | Yes, before the first body execution |
| Terminal check | Yes for range and for-in loops |
| Multiple clauses | All conjunctive |
| Failure | Panic at runtime; compile error when folded false |
-release |
Runtime checks removed; compile-time checks remain |
| Used to prove postconditions | No; invariants are checked, not assumed |