Writing Preconditions and Postconditions
Clause syntax, result names, blocks, purity, scope, and common mistakes.
Contents
A function contract is a sequence of clauses placed between the return type and the body. Each clause is introduced by a colon and is either an inline pre, an inline post, or a named contract application. The rules are small, but a few details determine whether a contract means what its author intended.
Preconditions#
A precondition is written : pre expression. The expression must be bool, and it is evaluated in the function's parameter scope plus the module scope.
fn divide(numerator i32, denominator i32) i32
: pre denominator != 0
=> numerator / denominator
Multiple preconditions are written as repeated clauses. They are conjunctive: every clause must hold.
fn narrow(n i32) i32
: pre n >= 0
: pre n <= 10
: pre n != 5
=> n
A precondition may call a pure helper. The helper is evaluated at compile time when its arguments are known, which keeps the contract readable without losing precision.
pure fn even(n i32) bool => n % 2 == 0
fn half(n i32) i32
: pre even(n)
: post r => r * 2 == n
=> n / 2
An impure helper is allowed in a precondition, but it makes the clause a runtime check. The compiler cannot execute the helper during folding because its effects are not known.
fn check(n i32) bool {
print(n)
return n > 0
}
fn need_positive(n i32) i32
: pre check(n)
=> n
The call above prints when the precondition is evaluated at runtime. Use an impure helper in a contract only when the check genuinely depends on runtime state; otherwise a pure predicate is cheaper, safer, and more likely to be discharged at compile time.
Postconditions#
A postcondition is written : post expression or : post name => expression. The optional name binds the returned value inside the clause.
fn absolute(n i32) i32
: post r => r >= 0
: post r => r == n || r == -n
{
if n < 0 {
return -n
}
return n
}
A postcondition without a result name is an ordinary predicate over the parameters, globals, and functions. It is useful when the guarantee does not mention the result.
fn require_positive(n i32) i32
: pre n > 0
: post n > 0
=> n
Every distinct result name is bound to the same returned value and is in scope in every postcondition of that function. This allows a contract to use more than one name for readability, or to refer to a name introduced by an earlier clause.
pure fn increment(n i32) i32
: post r => r == n + 1
: post next => next == r
=> n + 1
A result name may not duplicate a parameter name or another result name. Result names are not visible in the function body or in preconditions. They exist only inside postconditions.
Postconditions and Mutable Parameters#
Haze has no old expression. A postcondition sees the parameter values as they are when the function returns. If the body mutates a parameter, a postcondition that refers to that parameter sees the mutated value, not the value from the call site.
fn clear(n i32) i32
: post n == 0
{
n = 0
return n
}
The contract above describes the final state, not the initial state. To describe a transition, use a new local value and avoid mutating the parameter.
fn cleared(_n i32) i32
: post r => r == 0
=> 0
The idiomatic rule follows directly: do not mutate parameters in a function whose contract describes what changed. Construct a new value, return it, and let the caller decide whether to rebind.
Function-Level Blocks#
A function contract clause may be written as a block of expressions. Each expression is a separate conjunctive clause, exactly as in a contract declaration. The block is a convenient way to list several related conditions without repeating the : pre prefix.
fn allow(n i32) i32
: pre {
n > 0
n < 100
n != 42
}
=> n
The example requires all three conditions. It is equivalent to the following explicit conjunction.
fn allow(n i32) i32
: pre n > 0 && n < 100 && n != 42
=> n
The same rule applies to a postcondition block. Every expression in the block is checked, and every expression is part of the conjunction. Named contract declarations use the same block rule. The Named Contracts chapter covers the declaration form and its composition.
Contract Expressions Must Be Boolean#
Every preconditions and postcondition must have type bool. A comparison, a logical combination, or a call to a boolean function is valid. An arithmetic expression is not.
fn invalid(n i32) i32
: pre n + 1 // error: contract expression must be bool
=> n
The error is reported at the clause, before the body is checked. Use a comparison such as n + 1 > 0 or a named predicate.
Definition-Time Checks#
The compiler evaluates contracts even when a function is never called, as long as the contract does not depend on parameters. A contract that is always false is a compile error.
fn impossible() i32
: pre 1 == 2
=> 1
A postcondition that is false without consulting the result is also rejected at definition time.
pure fn also_impossible() i32
: post r => 1 == 2
=> 1
A contract that depends on parameters is kept and checked at each call or at runtime. The compiler does not reject a function merely because the compiler cannot prove its postcondition for all inputs.
Call-Site Checks#
When a call has constant arguments, the compiler evaluates the callee's preconditions at the call site. A false precondition is a compile error that points at both the call and the clause.
fn checked(n i32) i32
: pre n > 0
=> n
fn main() {
print(checked(0)) // compile-time error
}
When the arguments are not constant, the precondition remains in the callee and is checked at runtime. The caller does not need to reproduce the check, but the caller does need to ensure the value is in the domain if it wants to avoid a runtime failure.
Purity and Folding#
A contract expression may call any visible function. A pure function is evaluated during compile-time folding when its arguments are known. An impure function is only checked for its own preconditions at compile time; its body and postconditions are not evaluated. This is why contracts should prefer pure helpers even though impure helpers are accepted.
The evaluator supports literals, variables, unary and binary operators, casts, short-circuit logic, if, block expressions, and calls to non-generic functions with known arguments. It does not evaluate field access, indexing, record literals, list literals, match, is, interpolation, or lambdas. A contract that uses one of those forms remains a runtime check.
type Account {
id i32
balance i64
}
pure fn solvent(account Account) bool => account.balance >= 0
fn deposit(account Account, amount i64) Account
: pre amount > 0
: post r => r.balance == account.balance + amount
=> Account { id = account.id, balance = account.balance + amount }
The postcondition above refers to fields and a record literal, so it is not folded even when every argument is constant. It is still a useful contract; it is simply a runtime check. The Compile Time and Runtime chapter explains the boundary in detail.
Contracts on Generic Functions#
A generic function may carry inline preconditions and postconditions. The clauses are checked per instantiation after substitution. A contract that is independent of the type parameters can be discharged once; a contract that depends on a type parameter's operations is checked for each concrete instantiation.
fn require_non_empty[T](values List[T]) List[T]
: pre values.len > 0
: post r => r.len >= 1
=> values
A contract declaration cannot declare type parameters. If a reusable contract must mention a generic type, write the clauses inline or specialize the contract to a concrete type.
Contracts on Trait Methods#
Trait method declarations may carry preconditions and postconditions. Default method bodies carry their contracts when they are instantiated. When an implementation supplies its own method, the trait's clauses are copied onto it automatically with the parameter names mapped to the implementation's names. An implementation may add more clauses, and all of them are checked together.
trait Number[T] {
pub fn add(x, y T) T
}
type Pos {
value i64
}
impl Pos of Number {
pub fn add(x, y Self) Self
: pre x.value >= 0
: post r => r.value >= x.value
=> Self { value = x.value + y.value }
}
Common Mistakes#
| Mistake | Consequence | Remedy |
|---|---|---|
| Writing a block when a single predicate is intended | Each expression becomes a separate conjunct | Use && inside one expression when that is clearer |
Referring to old |
No such expression exists | Describe the result or use a separate function |
| Mutating a parameter | Postconditions see the mutated value | Return a new value instead |
| Calling an impure helper | Clause becomes a runtime check | Use a pure predicate where possible |
| Duplicating a type invariant in every precondition | Noise and drift | Let the type carry the property |
| Writing a precondition the body never uses | The contract documents a domain, but the implementation may be too permissive | Check that the body actually relies on the assumption |
| Writing a postcondition that restates the return type | Little value | State a relationship between input and output |
Using -release to hide a violated contract |
Undefined behaviour in optimized builds | Fix the contract or the implementation |
The next chapter, Named Contracts, shows how to package a set of clauses and apply it to several functions without duplicating the text.