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:
- Executable Invariants: Checked deterministically at function entry (
requires) and exit (ensures), halting with diagnostic[W4005]on violation. - Self-Documenting Signatures: Pre- and postconditions live right inside the function header where humans and AI agents inspect them.
- Machine-Readable Tool Bounds:
wysna schemaautomatically translates contract predicates into JSON Schema (Draft 2020-12) validation bounds for AI agent tool calls.
1. Syntax: requires and ensures
Section titled “1. Syntax: requires and ensures”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}2. Deterministic Failure ([W4005])
Section titled “2. Deterministic Failure ([W4005])”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, andsizeprofiles all retain contract and bounds checks — Wysna never silently strips safety checks under-O2or-Os.- Combine contracts with
T ! Echannels cleanly: userequiresfor caller invariants (programming bugs) andT ! Efor 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:
wysna schema --output-format=json-v1 src/pricing.wysnaThis guarantees that the schema given to an autonomous agent stays mathematically synchronized with the compiled function signature — eliminating schema drift.