ES
Language GuideSafety & Contracts

Design-by-Contract (requires / ensures)

First-class preconditions (requires), postconditions (ensures with result binding), deterministic W4005 enforcement, and JSON Schema extraction in Wysna.

Wysna treats Design-by-Contract as a first-class language construct rather than an external macro or comment convention. Contracts serve three roles simultaneously:

  1. Executable Invariants: Checked deterministically at function entry (requires) and exit (ensures), halting with diagnostic [W4005] on violation.
  2. Self-Documenting Signatures: Pre- and postconditions live right inside the function header where humans and AI agents inspect them.
  3. Machine-Readable Tool Bounds: wysna schema automatically translates contract predicates into JSON Schema (Draft 2020-12) validation bounds for AI agent tool calls.

Place requires and ensures clauses between the return type and the function body. Multiple predicates can be comma-separated or placed on separate lines. Inside ensures, the contextual identifier result binds to the function’s return value:

pub fn withdraw(mut balance: int, amount: int) -> int ! str
requires amount > 0, balance >= amount
ensures result >= 0
{
balance -= amount
return balance
}
pub fn quote_total(quantity: int, unit_price_cents: int) -> int
requires quantity > 0
requires unit_price_cents >= 0
ensures result == quantity * unit_price_cents
{
return quantity * unit_price_cents
}

When a caller breaks a precondition or a buggy implementation breaks a postcondition, execution aborts immediately with canonical code [W4005] across the interpreter, ANSI C99 native binaries, Selfhost Stage-2, and LLVM:

  • dev, release, and size profiles all retain contract and bounds checks — Wysna never silently strips safety checks under -O2 or -Os.
  • Combine contracts with T ! E channels cleanly: use requires for caller invariants (programming bugs) and T ! E for expected recoverable domain failures (network timeouts, invalid external JSON, business thresholds).

3. Extracting Contracts for AI Agents (wysna schema)

Section titled “3. Extracting Contracts for AI Agents (wysna schema)”

Run wysna schema on any contracted module to generate Draft 2020-12 JSON Schema definitions and LLM tool schemas enriched with verified MIR effects, capabilities, pure, and idempotent metadata:

Terminal window
wysna schema --output-format=json-v1 src/pricing.wysna

This guarantees that the schema given to an autonomous agent stays mathematically synchronized with the compiled function signature — eliminating schema drift.