On this page

ADR-0324: Lightweight Executable Function Contracts (requires / ensures)

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

  1. Contextual Contract Clauses on FnDecl:

    • Store pub contracts: Option<Box<FnContracts>> on FnDecl (one pointer word when absent, keeping size_of::<FnDecl>() <= 26 * size_of::<usize>()).
    • Parse zero or more requires <expr> and ensures <ident> => <expr> clauses between the function signature (params / optional -> Ret) and its { ... } or = <expr> body.
    • requires and ensures are contextual keywords only recognized after a function signature, so existing identifiers named requires or ensures remain valid.
    • Support round-trip formatting in ordinary expansion (compact/expand.rs), compact encoding/decoding (flag bit 0x08 on F records), and canonical forms (canon.rs).
  2. Typechecking (E1270 / E1271):

    • Resolve and typecheck each requires <expr> in parameter scope; non-bool expressions fail with E1270.
    • Resolve and typecheck each ensures <binder> => <expr> in parameter scope extended with <binder> bound to the function's return type (unit if omitted); non-bool expressions fail with E1271.
  3. Executable Lowering & Dual-Backend Parity:

    • At function entry, lower each requires clause to a runtime check that traps with TrapReason::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 each ensures clause with <binder> bound to that temporary, trap with TrapReason::ContractEnsures ("contract violation: ensures ...") if false, and then return the temporary.
    • Both the reference interpreter (TrapKind::ContractViolation, exit 101) and C backend (trt_trap("contract violation: ...", TN_FILE, line, col), exit 101) enforce contracts identically.
  4. API Card Visibility (tenon doc --card):

    • Extract requires and ensures clauses on public fn items into ApiItem.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.

Consequences