Contents

A loop invariant is a boolean predicate that must hold every time the loop reaches its header. Invariants are checked before the loop condition on each iteration, including before the first.

Syntax#

An invariant follows the loop header and precedes the body. Multiple invariants use repeated : invariant clauses.

for i in 0..values.len
    : invariant i >= 0
    : invariant i <= values.len
{
    process(values[i])
}

The same form applies to for-in and condition loops.

for value in values
    : invariant seen.len <= values.len
{
    seen += [value]
}

for index < limit
    : invariant index >= 0
{
    index += 1
}

The expression must be bool.

Boundaries#

A range loop checks its invariant at the header before the exit test, including the terminal index. Use an inclusive boundary for a property that holds while the body executes.

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
}

A break can leave the loop before a later header check.

A for-in loop captures the list length at entry. The length is not re-read, so appending during iteration does not change the number of visits.

Runtime and Compile-Time Checks#

A constant-false invariant is rejected during compile-time folding. Other invariants become runtime checks. A failure aborts 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. The evaluator has a depth limit of 512 and an iteration limit of 100,000; a loop beyond those limits remains a runtime check.

A for-in loop is not executed by the compile-time evaluator. Its invariants are always runtime checks.

Checking, Not Assuming#

Loop invariants are checked, not assumed when proving a postcondition or another invariant. An invariant cannot make a postcondition compile under -release. If a postcondition depends on a property that holds 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 an Invariant#

A useful invariant describes the relationship between the loop variable and the accumulator.

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 holds at the start, after each append, and at the terminal header check. The postcondition is checked independently.

fn sum_to(n i32) i32 {
    var total = 0
    for i in 0..n
        : invariant total == i * (i - 1) / 2
    {
        total += i
    }
    return total
}

Defer#

A defer inside a loop body runs at the end of each iteration. The next header check sees the effects of the previous iteration's defers. Keep invariants independent of cleanup side effects when possible.

Release Mode#

-release removes runtime loop-invariant checks. Compile-time folding remains, so a constant-false invariant is still rejected. Removing runtime checks is safe only when the invariant has been established by reasoning or testing.

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 Abort at runtime; compile error when folded false
-release Runtime checks removed; compile-time checks remain
Used to prove postconditions No