Language reference · section 12
12. Contracts
Feature: Contracts
Scenario: requires is checked before the body runs
Given a function with "requires amount > 0"
When the caller passes 0
Then the program throws Error("contract failed: requires amount > 0") before the body runs
Scenario: ensures is checked after the body returns
Given a function with "ensures result >= 0"
When the function returns -1
Then the program throws Error("contract failed: ensures result >= 0")
Scenario: Contract lines come first in a body
Given a requires line after another statement
Then the compiler reports an error "`requires` and `ensures` must come at the top of a function body, before other statements"
Scenario: A function with ensures cannot have a parameter named result
Given a function with ensures and a parameter named result
Then the compiler reports an error "a parameter cannot be named `result` when the function has `ensures`; `result` is the return value there"
Scenario: Contracts are not allowed on @memo, @worker, or streaming functions
Given a @memo, @worker, or streaming function with a contract
Then the compiler reports an error "`requires` and `ensures` are not supported on @memo, @worker, or streaming functions yet"
Scenario: Contracts are not allowed in a @wasm function
Given a @wasm function with a contract
Then the compiler reports an error "requires and ensures are not supported in @wasm functions yet"
fn withdraw(amount: int, balance: int): int:
requires amount > 0
requires amount <= balance
ensures result >= 0
return balance - amount