Contracts
The design-by-contract model, the kinds of clauses, and what the compiler guarantees.
Contents
Design by contract is the organising idea of Haze. A contract is a boolean expression that states an obligation or a guarantee, written next to the code it describes, using the same expression language as ordinary Haze. Contracts are evaluated at compile time where the compiler has enough information, at runtime where it does not, and they disappear entirely only when the program is built with -release.
The Kinds of Contract#
Haze has five contract forms. They share the same expression language but serve different purposes.
| Form | Where it appears | What it states |
|---|---|---|
| Precondition | : pre expr on a function or trait method |
What the caller must establish before the call |
| Postcondition | : post r => expr on a function or trait method |
What the callee guarantees about the result and final state |
| Named contract | contract Name(...) { ... }, applied with : Name(args) |
A reusable bundle of preconditions and postconditions |
| Type invariant | : invariant expr on a refinement or record |
Which values of the type are valid |
| Loop invariant | : invariant expr on a for loop |
What remains true at the loop header |
assert is not a contract form. It is a test-only statement, covered in Testing Contracts.
The Division of Responsibility#
A precondition belongs to the caller. It says that the function is not required to handle inputs outside the stated domain. A postcondition belongs to the callee. It says that every accepted call produces a result satisfying the stated property. A type invariant belongs to the value. It says that a constructed value is valid and that a value that violates it cannot exist.
This division is why contracts are not just assertions scattered through a body. A precondition at the top of a function documents a caller obligation and lets the body assume it. A postcondition at the bottom documents a caller guarantee and lets callers rely on it. An invariant on a type makes the guarantee travel with every value of that type.
type Account {
id i32
balance i64
}
contract Funded(account Account, amount i64) {
pre amount > 0
pre amount <= account.balance
}
fn withdraw(account Account, amount i64) Account
: Funded(account, amount)
: post r => r.id == account.id
: post r => r.balance == account.balance - amount
=> Account { id = account.id, balance = account.balance - amount }
The named contract Funded collects the caller's obligations. The two postconditions state the callee's guarantee. A caller that cannot establish Funded has to handle that fact before calling, and a caller that receives the result may rely on the id and balance claims.
Compile-Time and Runtime#
The compiler contains a constant evaluator that runs after type checking. It folds module constants, evaluates pure functions with constant arguments, and checks every contract it can decide. A contract that evaluates to false at compile time is an error. A contract that evaluates to true is discharged. A contract that cannot be decided is kept and becomes a runtime check.
fn half(n i32) i32
: pre n % 2 == 0
: post r => r * 2 == n
=> n / 2
fn main() {
print(half(10)) // checked at compile time
print(half(7)) // compile-time error: precondition fails
}
The second call is rejected before the program runs. When the argument is a runtime value, the same precondition becomes a runtime check.
fn show(n i32) {
print(half(n)) // runtime check; the compiler cannot know n
}
Compile-time evaluation is deliberately concrete. It does not perform range analysis, relational reasoning, or symbolic algebra. It evaluates constants, pure function calls, arithmetic, comparisons, short-circuit logic, and a few control-flow expressions. If a property requires reasoning that the evaluator does not perform, the contract stays as a runtime check rather than being guessed. The Compile Time and Runtime chapter gives the full decision table.
Failure Semantics#
A failed runtime precondition, postcondition, or loop invariant calls the runtime panic path and aborts the program. This is intentional. A contract violation is a programming error: the caller broke a stated obligation, or the callee broke a stated guarantee. Such an error is not an expected outcome and is not modelled as a value.
Expected failure is modelled separately with Result. A function that can fail returns Result[T, E], and the caller handles the error with match, is, or ?. Checked construction T { ... }? also returns an error value rather than panicking when an invariant does not hold. The distinction is the central rule of idiomatic Haze:
| Situation | Mechanism | Failure behaviour |
|---|---|---|
| Input outside the function's domain | Precondition | Panic (a caller bug) |
| Callee breaks its guarantee | Postcondition | Panic (an implementation bug) |
| Loop does not maintain its invariant | Loop invariant | Panic (an implementation bug) |
| Expected operation failure | Result[T, E] |
Returned as Error |
| Expected absence | Option[T] |
Returned as None |
| Runtime value may violate a type invariant | T { ... }? |
Returned as Error |
Contract Scope#
A precondition or postcondition may refer to the function's parameters, module constants, types, constructors, and functions. A postcondition may also refer to the result names introduced after post. Result names are bound to the returned value and are visible in every postcondition of the same function.
pure fn next(n i32) i32
: post r => r == n + 1
: post s => s == r
=> n + 1
Both r and s are bound to the same result. The second clause may refer to r because all result names are in scope in every postcondition. A result name may not duplicate a parameter name.
A type invariant uses self for a refinement and the field names for a record. A loop invariant uses the loop variable and any names visible at the loop header. There is no implicit result variable and no old expression. A postcondition sees the final values of parameters, not their pre-state. This is why idiomatic Haze avoids mutating parameters in functions with postconditions.
Named Contracts Are Applied, Not Proved#
The syntax : FactorialCond(n) in a function signature applies a named contract. The compiler expands the contract's clauses with the supplied arguments and checks them exactly as if they had been written inline. The expansion is capture-safe and recursive composition is rejected.
This is sometimes described as the function conforming to the contract. Technically, there is no separate conformance proof. The function simply receives the clauses, and the ordinary compile-time and runtime checks decide whether they hold. The practical effect is the same for a well-written contract: the function's callers can rely on the clauses, and a violation is reported at the call site or at runtime.
Contracts and Types#
Contracts and types are complementary. A type invariant makes an invalid value unrepresentable, so no contract is needed to restate the property. A precondition states an obligation that depends on the call context, which a type alone cannot express. A postcondition states a relationship between input and output, which is also beyond most type systems.
The idiomatic preference is to move as much as possible into types and keep contracts for the relationships that types cannot capture. A positive integer belongs in a refinement type. A sorted list belongs in a postcondition, because the property depends on the operation that produced it. A valid transfer belongs in a combination of record invariants, preconditions, and postconditions.
Where to Read Next#
Writing Preconditions and Postconditions explains the syntax and the common mistakes. Named Contracts covers reuse and composition. Loop Invariants covers the loop form. Checked Construction covers the boundary between invariants and Result. Compile Time and Runtime explains what the evaluator can decide, and Testing Contracts explains how tests complement contracts without duplicating them.