ADR-0324:
Lightweight Executable Function Contracts (requires /
ensures)
- Status: Accepted
- Date: 2026-11-28
- Plan: M30.2
Context
Function signatures in Tenon specify parameter and return
types, but cannot directly express value-level preconditions
(e.g., divisor != 0, idx >= 0) or
postconditions (e.g., result >= 0). Without
first-class contracts, invariants live only in comments or ad-hoc
body checks that are invisible in tenon doc --card
API summaries and cannot be uniformly enforced across
backends.
Decision
Contextual Contract Clauses on
FnDecl:- Store
pub contracts: Option<Box<FnContracts>>onFnDecl(one pointer word when absent, keepingsize_of::<FnDecl>() <= 26 * size_of::<usize>()). - Parse zero or more
requires <expr>andensures <ident> => <expr>clauses between the function signature (params/ optional-> Ret) and its{ ... }or= <expr>body. requiresandensuresare contextual keywords only recognized after a function signature, so existing identifiers namedrequiresorensuresremain valid.- Support round-trip formatting in ordinary expansion
(
compact/expand.rs), compact encoding/decoding (flag bit0x08onFrecords), and canonical forms (canon.rs).
- Store
Typechecking (
E1270/E1271):- Resolve and typecheck each
requires <expr>in parameter scope; non-boolexpressions fail withE1270. - Resolve and typecheck each
ensures <binder> => <expr>in parameter scope extended with<binder>bound to the function's return type (unitif omitted); non-boolexpressions fail withE1271.
- Resolve and typecheck each
Executable Lowering & Dual-Backend Parity:
- At function entry, lower each
requiresclause to a runtime check that traps withTrapReason::ContractRequires("contract violation: requires ...") if false. - At every function return path (explicit
return, tail expression, fallthrough, or?early return), bind the return value to a temporary local, evaluate eachensuresclause with<binder>bound to that temporary, trap withTrapReason::ContractEnsures("contract violation: ensures ...") if false, and then return the temporary. - Both the reference interpreter
(
TrapKind::ContractViolation, exit101) and C backend (trt_trap("contract violation: ...", TN_FILE, line, col), exit101) enforce contracts identically.
- At function entry, lower each
API Card Visibility (
tenon doc --card):- Extract
requiresandensuresclauses on publicfnitems intoApiItem.contracts. - Render contracts directly under function signatures in compact
text cards and as
"contracts": [...]in JSON cards so callers and coding agents see exact preconditions and postconditions without reading function bodies.
- Extract
Consequences
- Contracts are executable, checked by the typechecker, surfaced in API cards, and identical across the interpreter and C backends.
- Functions without contracts incur zero AST size overhead (null boxed option) and zero IR/runtime overhead.