# 07a. AIR Instruction Contracts Normative. Each instruction lists the fields required by spec 07 §4. Syntax is in [`../reference/air-text.ebnf`](../reference/air-text.ebnf). This file covers the format-0 baseline (Phase 0) and the features `ownership` and `arrays` (Phase 1). Later phases add instructions here, grouped by feature, before implementing them. An instruction of a feature is only valid in a module that declares the feature (spec 07 §8.1). ## Common contract for format version 0 The baseline instructions operate on Copy values; feature-specific contracts below specify linear ownership. Unless an entry says otherwise: | Field | Value | |---|---| | Ownership transition | none; operands remain available | | Borrow transition | none | | Memory reads/writes | none | | Synchronization | none | | Effects required | none | | Capabilities required | none | | Traps | none | Notation: `T` is the type suffix of the opcode; `I` ranges over integer types; `type(%x)` is the type of value `%x`. "Rejects with E1001" means the verifier reports `type.mismatch` at the instruction. ## Values ### `error.const B.variant` (feature `error_values`) - Static operands: built-in error family `B` and its registered payload-free variant; no SSA operands. - Result: one Copy value of type `B`. - Ownership/borrow/memory/concurrency transitions: none; effects and capabilities required: none; traps: none. - Verifier transfer: define one available Copy value. Unknown family/variant: `E0004`; undeclared feature: `E0006`; incompatible result use: `E1001`. Payload syntax: `E0001`. - Interpreter: bind the built-in family/tag deterministically, using normal fuel; no program allocation or authority acquisition. - Complete contract and source syntax: spec 05 §14. `enum.make` is unchanged. ### `const.T lit` - Operands: an integer literal (`T` ∈ `I`) or `true`/`false` (`T` = `bool`). - Result: `T`. - Verifier: the literal MUST be representable in `T`, otherwise `E0002`. - Interpreter: produces the literal value. ### `copy %a` - Operands: any value. - Result: `type(%a)`. - Interpreter: produces a value equal to `%a`. ## Integer arithmetic ### `add|sub|mul.checked.I %a, %b` - Operands: `type(%a) = type(%b) = I`, otherwise `E1001`. - Result: `I`. - Traps: `T0003` if the mathematical result is not representable in `I`. - Interpreter: mathematical result. ### `add|sub|mul.wrap.I %a, %b` - Operands and result as above. No traps. - Interpreter: mathematical result modulo 2^N, reinterpreted in `I`. ### `div|rem.checked.I %a, %b` - Operands and result as above. - Traps: `T0004` if `%b = 0`; `T0003` for signed `MIN` divided by `-1`. - Interpreter: truncating division; remainder has the sign of the dividend (spec 02 §2.1). ## Bitwise ### `and|or|xor.T %a, %b` - Operands: `T` ∈ `I ∪ {bool}`; both operands of type `T`, otherwise `E1001`. - Result: `T`. - Interpreter: bitwise operation (logical for `bool`). ### `shl|shr.I %a, %b` - Operands: both of type `I`, otherwise `E1001`. - Result: `I`. - Traps: `T0005` if `%b < 0` or `%b ≥ N`. - Interpreter: spec 02 §2.1. ## Comparisons ### `eq|ne.T %a, %b` - Operands: `T` ∈ `I ∪ {bool}`; both of type `T`, otherwise `E1001`. - Result: `bool`. ### `lt|le|gt|ge.I %a, %b` - Operands: both of type `I`, otherwise `E1001`. - Result: `bool`. Signed comparison for signed `I`, unsigned otherwise. ## Casts ### `cast.widen.I %a` - Operands: `type(%a)` ∈ `I`; the conversion MUST be lossless for every value (spec 02 §2.1), otherwise `E1002`. - Result: `I`. ### `cast.checked.I %a` - Operands: `type(%a)` ∈ `I`, otherwise `E1002`. - Result: `I`. - Traps: `T0006` if the value of `%a` is not representable in `I`. ### `cast.wrap.I %a` - Operands: `type(%a)` ∈ `I`, otherwise `E1002`. - Result: `I`, the low N bits of the two's-complement representation of `%a`. ## Assertions ### `assert %c` - Operands: `type(%c) = bool`, otherwise `E1001`. - Result: none. - Traps: `T0002` if `%c` is false. ## Aggregates ### `struct.make @S(%f1, …, %fn)` - Operands: `@S` is a struct type with exactly n fields (`E1001` otherwise); `type(%fi)` equals the type of field i. - Result: `@S`. ### `struct.get @S.f, %s` - Operands: `@S` is a struct type with a field `f` (`E0004` otherwise); `type(%s) = @S` (`E1001` otherwise). - Result: the type of field `f`. ### `enum.make @E.V(%p1, …, %pn)` - Operands: `@E` is an enum type with a variant `V` (`E0004` otherwise) whose payload has exactly n types; `type(%pi)` equals payload type i (`E1001` otherwise). - Result: `@E`. ## Calls ### `call @f(%a1, …, %an)` - Operands: `@f` is a function of the module (`E0004` otherwise) with n parameters; `type(%ai)` equals parameter type i (`E1001` otherwise). - Result: the return type of `@f`. A result MUST be bound unless the return type is `void` or `never`, and MUST NOT be bound when it is `void` (`E1001`). - Effects: the callee's effect set (checked from Phase 2). - Traps: whatever the callee traps; `T0007` if the call would exceed the call-depth limit of 1 024 active frames. - Interpreter: evaluates the callee with fresh parameter bindings; returns its result. ## Terminators A terminator ends a block (spec 07 §8.2). Terminators bind no result. ### `br @b(%a1, …, %an)` - Operands: `@b` has n parameters (`E5002`); `type(%ai)` equals parameter type i (`E1001`). - Interpreter: binds the arguments simultaneously and continues at `@b`. ### `cbr %c, @t(…), @f(…)` - Operands: `type(%c) = bool` (`E1001`); both targets as for `br`. - Interpreter: continues at `@t` if `%c` is true, otherwise at `@f`. ### `switch.I %v, k1 -> @b1(…), …, default -> @d(…)` - Operands: `type(%v) = I` (`E1001`); each `ki` representable in `I` (`E0002`); case values pairwise distinct (`E5002`); targets as for `br`. - Interpreter: continues at the case whose value equals `%v`, otherwise at `default`. ### `enum.switch @E %v, V1 -> @b1, …[, default -> @d(…)]` - Operands: `type(%v) = @E` (`E1001`); each `Vi` is a variant of `@E` (`E0004`) and appears at most once (`E5002`); every variant appears unless `default` is present (`E5002`); the parameters of `@bi` MUST equal the payload types of `Vi` in number (`E5002`) and type (`E1001`). - Interpreter: continues at the arm for the active variant, binding its payload to the target block's parameters; otherwise at `default`. ### `ret [%v]` - Operands: `type(%v)` equals the function's return type (`E1001`). Without operand only in `void` functions (`E1001`). Not allowed in `never` functions (`E1001`). - Interpreter: returns from the function. ### `trap` - Traps: `T0001`, always. ## Feature `ownership` and feature `arrays` Types, borrow rules and bounds facts used below: spec 07 §8.8 (types), spec 08 §11 (borrows), spec 08 §12 (facts), spec 08 §13 (initialization). Decision record: RFC 0005. Common contract unless stated: no effects, no capabilities, no synchronization. "Owned borrow" means a borrow created in the current function (§5.1). ### `ownership` | Instruction | Operands → result | Verifier | Runtime | |---|---|---|---| | `%s = local.alloc T` | → `local` | only in the entry block (`E5002`); storage is uninitialized; counts toward the frame limit (spec 08 §11.5) | allocates frame storage once per call, freed at return | | `local.store %s, %v` | `local`, `T` | no live borrow of `%s` (`E2101`); initializes `%s` | writes `%v` | | `local.zero %s` | `local` | `T` zeroable: integers, `bool`, arrays and structs of zeroable types (`E1001`); no live borrow (`E2101`); initializes | writes all-zero value | | `%v = local.load %s` | `local` → `T` | initialized (`E1010`); no live `mut` borrow of `%s` (`E2101`) | reads | | `%r = borrow.ref %x` | `local`, `ref`, `mut` → `ref`; `slice`, `slice_mut` → `slice` | spec 08 §11.2; locals must be initialized (`E1010`); child of `%x` unless `%x` is a local | shared view of the same place | | `%m = borrow.mut %x` | `local`, `mut` → `mut`; `slice_mut` → `slice_mut` | spec 08 §11.2; locals must be initialized (`E1010`); child of `%x` unless `%x` is a local | exclusive view of the same place | | `%f = borrow.field @S.f, %b` | `ref<@S>`/`mut<@S>` → `ref`/`mut` | child of `%b`; distinct fields are disjoint | reference to the field | | `borrow.end %b` | owned borrow | no live children (`E2102`); not a parameter (`E2107`); not already ended (`E2106`) | none | | `%v = load %b` | `ref`/`mut` → `T` | `%b` usable for reading (spec 08 §11.2) | reads | | `store %b, %v` | `mut`, `T` | `%b` usable for writing (spec 08 §11.2) | writes | ### `arrays` | Instruction | Operands → result | Verifier | Runtime | |---|---|---|---| | `%a = array.splat array %v` | `T` → `array` | — | every element is `%v` | | `%e = borrow.index %b, %i` | `ref`/`mut` of `array`, or `slice`/`slice_mut` of `T`; `usize` → `ref`/`mut` | child of `%b` | traps `T0008` if `%i ≥ length` | | `%e = borrow.index.proven %b, %i` | as above | `%i < length` proven (spec 08 §12), otherwise `E2103` | no check | | `%s = slice.make %b` | `ref>`/`mut>` → `slice`/`slice_mut` | child of `%b` | whole array | | `%n = slice.len %s` | `slice`/`slice_mut` → `usize` | — | length | | `%t = slice.sub %s, %start, %len` | slice, `usize`, `usize` → same slice type | child of `%s` | traps `T0008` unless `start ≤ slice.len(s)` and `len ≤ slice.len(s) − start` (evaluated without overflow); result covers `[start, start + len)` | | `%l, %r = slice.split %s, %at` | slice, `usize` → two slices of the same type | two children of `%s`, disjoint | traps `T0008` unless `at ≤ slice.len(s)`; `l` covers `[0, at)`, `r` covers `[at, len)` | | `slice.copy %dst, %src` | `slice_mut`, `slice`/`slice_mut` | both usable (spec 08 §11.2); overlapping operands are rejected by the aliasing rules (spec 08 §11.2), so this is never a `memmove` | traps `T0008` unless `len(dst) ≥ len(src)`; copies exactly `len(src)` elements into the start of `dst` | | `guard %c` | `bool` | adds a fact (spec 08 §12) | traps `T0002` if false | New trap code: `T0008 trap.out_of_bounds`. `slice.make` creates a slice only from an existing borrow of an array, covering exactly that array and inheriting its provenance. No instruction creates a slice from an address and a length. An overlap-safe copy, if ever needed, will be a separate instruction (`slice.move`). ### Runtime - Frame storage is allocated by `local.alloc` and released at return; no code runs at release. - The interpreter represents a borrow as (storage, path) and a slice as (storage, path, offset, length). It performs no alias or liveness checks at runtime: the verifier guarantees them. Bounds checks run exactly where §4 says. - Behavior is deterministic; storage addresses are never observable. ## Feature `effects` and feature `capabilities` Rules: spec 05 §9–§12. Decision record: RFC 0006. | Instruction | Operands → result | Verifier | Runtime | |---|---|---|---| | `cap.narrow.
%c, %arg…, ok -> @ok, err -> @err` (terminator) | `cap`, form arguments | form registered for `K` (`E3202`); `@ok` has one parameter `cap`, `@err` one parameter `cap_error` (`E5002` count, `E1001` type) | continues at `@ok` with a narrower capability sharing nothing wider than `%c`, or at `@err` with the reason; never traps | | `[%r =] intrinsic (%a…)` | per registry entry | operand types (`E1001`), capability kind (`E3201`), effect (`E3101`), borrows as for `call`; unknown name `E0004` | forwards to the host through the capability | Intrinsics have an infallible form (`[%r =] intrinsic …`) and a fallible terminator form (`intrinsic …, ok -> @ok, err -> @err`) (spec 05 §11.1). The catalogue is `reference/intrinsics.md`. Effect checking applies to `call` and `intrinsic` in modules that declare `effects` (spec 05 §9.3). ## Feature `resources` Resource types and their consumption rules: spec 06 §6. Resources are used through `borrow.ref`/`borrow.mut` (which accept a resource value as root) and consumed by closing intrinsics, by-value resource parameters, resource block parameters and `ret`. ## Feature `heap` and feature `regions` Instructions, budget accounting and verifier rules: spec 03 §18–§20. Summary: | Instruction | Form | Effect | |---|---|---| | `own.new %v, %c, ok -> @ok, err -> @err` | terminator, `@ok(own)`, `@err(alloc_error)` | `mem.alloc` | | `own.array %n, %v, %c, ok -> @ok, err -> @err` | terminator, `@ok(own_array)`, `@err(alloc_error)` | `mem.alloc` | | `%v = own.take %o` | consumes `own`, yields `T` | — | | `own.free %o` | consumes `own` or `own_array` | — | | `region.create %c, ok -> @ok, err -> @err` | terminator, `@ok(region)`, `@err(alloc_error)` | `mem.alloc` | | `region.new %rb, %v, ok -> @ok, err -> @err` | terminator, `@ok(mut)`, `@err(alloc_error)` | `mem.alloc` | | `region.array %rb, %n, %v, ok -> @ok, err -> @err` | terminator, `@ok(slice_mut)`, `@err(alloc_error)` | `mem.alloc` | | `region.reset %r` | region not consumed | — | | `region.destroy %r` | consumes region | — | `borrow.ref`/`borrow.mut` accept owners and regions as roots: `own` gives `ref`/`mut`, `own_array` gives `slice`/`slice_mut`, `region` gives `ref`/`mut`. ## Feature `unsafe` | Instruction | Operands → result | Precondition | Reference interpreter | |---|---|---|---| | `assume %c` | `bool` | `%c` is true; establishes a fact like `guard` (spec 08 §12) | traps `T0009` if false | | `%e = borrow.index.unchecked %b, %i` | as `borrow.index` | `%i <` length of `%b` | traps `T0009` if violated | Allowed only in functions that declare the effect `unsafe` or are `trusted` (`E6001`, spec 13 §6.4). ## Feature `tasks` Types `scope` and `task` (linear, function-bound), instructions `task.scope.begin`, `task.spawn %s, @f(…)`, `task.join`, `task.cancel`, `task.cancelled`, `task.scope.end`; loans, `Send`/`Share` and the scheduler: spec 04 §33–§36. In a module that declares `cancellation`, `task.join` waits and requires the effect `task.wait` (spec 04 §37.4); `task.spawn` always requires `task.spawn`. ## Features `cancellation`, `channels`, `sync` `cancellation`: type `shield`, effect `task.wait`, instructions `task.check_cancel`, `task.join.cancel`, `task.shield.begin`, `task.shield.end`; the waiting-operation rule: spec 04 §37. `channels`: types `sender`, `receiver`, instructions `channel.make`, `channel.sender.dup`, `channel.send`, `channel.recv`, `channel.close_sender`, `channel.close_receiver`, `select`: spec 04 §38–§39. `sync`: types `mutex`, `guard`, instructions `mutex.make`, `mutex.take`, `mutex.lock`, `mutex.borrow`, `mutex.unlock`; the critical-section rule: spec 04 §40–§41. Every terminator of these features follows spec 07 §8.2: each named target receives exactly the parameters its contract lists. ## Features `islands`, `arc` `islands`: types `island`, `frozen`, `iref`, instructions `island.create`, `island.alloc`, `island.root`, `island.borrow`, `island.freeze`, `island.destroy`, `frozen.root`, `frozen.borrow`, `frozen.release`, `iref.eq`; `IslandSafe`, identity and `T0010`: spec 03 §22–§23. `arc`: type `arc`, instructions `arc.from_frozen`, `arc.new`, `arc.clone`, `arc.release`, `arc.root`, `arc.borrow`; `ArcSafe` and the quota lifecycle: spec 03 §24. ## Feature `atomics` Status `reserved` until it is published with its implementation (P5-2a). Its contracts are fixed by RFC 0015: - type: linear `atomic` for AtomicScalar `T`; - instructions: `atomic.new`, `atomic.take`, `atomic.load.`, `atomic.store.`, `atomic..` (`xchg`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`), `atomic.cmpxchg..` (two results), `atomic.fence.`; - the contract table: spec 04 §42. `atomic.cmpxchg` has two results, in this order: the value read and a `bool` that is `true` when it exchanged; - `atomic` is `Share`, so one `ref>` may be lent to any number of tasks (spec 04 §35); - the orderings: spec 04 §24; - the memory model: spec 04 §20–§30; - effects: spec 05 §13. ## Run result `aji run` executes the function `@main`, whose parameters MUST all be capabilities, bound by name at instantiation (spec 05 §10.2); without the `capabilities` feature it takes no parameters. On return it reports `{"status":"returned","value":V}` where `V` renders the returned value as JSON: | Type | Rendering | |---|---| | integer | decimal number | | `bool` | `true` / `false` | | `void` | `null` | | struct | object of fields in declaration order | | enum | `{"variant":"Name","payload":[…]}` | On a trap it reports `{"status":"trapped", "code":…, "kind":…, "function":…, "block":…, "inst":…}` (spec 01 §6). Programs that declare `capabilities` also get `"stdout"` and `"stderr"` (captured output) and `"files"` (files written in the virtual file system, keyed by path in byte order) in the record of the `deterministic` profile (spec 11 §8). **Canonical record.** The run record is canonical JSON: UTF-8, no whitespace, fields in the order this section lists them, integers in decimal, no locale dependence. Strings escape `"` as `\"`, `\` as `\\`, the control characters U+0008, U+0009, U+000A, U+000C, U+000D as `\b`, `\t`, `\n`, `\f`, `\r`, and other characters below U+0020 as `\u00xx` (lowercase hex); everything else, including non-ASCII, is written as its UTF-8 bytes. Byte data is encoded unambiguously: - `stdout`, `stderr`: a JSON string if the bytes are valid UTF-8, otherwise `{"encoding":"base64","data":"…"}`; - every entry of `files`: always `{"encoding":"base64","data":"…"}`, since file contents are arbitrary bytes. Base64 is RFC 4648 with padding. Two records are equal exactly when their bytes are equal. When the deterministic runtime detects quiescence it reports `{"status":"blocked","kind":"no_future_event",…}` (spec 11 §8). When instantiation fails (spec 05 §10.2) the program does not start and the runner reports `{"status":"not_instantiated","reason":…,…}`. When the runner stops execution because an execution limit is exhausted (spec 11 §7), it reports `{"status":"limit_exceeded","kind":"fuel","limit":N,"steps":N}`. This is an outcome of the execution environment, not of the program, and is not a trap. ## Linear aggregates (`linear_aggregates`) These contracts specialize ownership of newly enabled linear member types; baseline Copy instructions keep their prior semantics. All instructions require `linear_aggregates`; an array type also requires `arrays`, and `own.pack` also requires `heap`. Existing feature dependency closures apply. ### `array.make array(%v0, …, %vN-1)` Operands MUST be exactly N complete values of T (E1001). Result is array. Linear inputs are consumed, each exactly once; Copy inputs remain available. Memory, synchronization, effects, capabilities and traps: none. Interpreter assembles elements in order. Verifier marks a linear result available. Normal SSA/size/argument limits apply. ### `struct.unpack @S %value, next -> @block` and `array.unpack array %value, next -> @block` Operand MUST have the named struct/array type. No SSA result; the sole continuation MUST have all field/element parameters of exactly those types in order (E5002 counts, E1001 types). The whole linear operand is consumed and linear parameters become available; Copy operands remain available. Memory, synchronization, effects, capabilities and traps: none. Interpreter transfers every component and jumps. Block-parameter/size limits apply; there are no ignored components. ### `enum.take @E %value, Variant -> @block, …` Operand MUST be the named enum type; every variant MUST appear exactly once with no default (E5002). No SSA result; target payload types/counts follow ordinary enum.switch rules. It consumes a linear operand and transfers its selected complete payload; Copy operands remain available. Memory, synchronization, effects, capabilities and traps: none. Interpreter selects the tag deterministically. Existing enum.switch MUST reject E1001 for a linear enum. ### `%old = value.swap %borrow, %replacement` Operands MUST be mut and T; T MUST be an initialized value, never a borrow/storage/function-bound value (E1001). Result T. A linear replacement is consumed; a linear result becomes available. The borrowed place remains initialized with the complete replacement. Reads/writes: the whole place; exclusive alias and task-loan rules apply (E2101/E4101). Synchronization, effects, capabilities and traps: none; swapping an atomic cell through an ordinary borrow remains forbidden (E4202). Interpreter exchanges whole values in one instruction, retaining existing race instrumentation. ### `own.pack T %value, %cap, ok -> @success, err -> @failure` Operands MUST be complete T and cap (E1001/E3201); T may be Copy or linear. No SSA result; success receives own, failure receives (alloc_error,T) (E5002/E1001). Linear input is consumed on both edges; success owns it inside the allocation, failure owns the same original value. Memory: new allocation initialized with the complete value on success; none on failure. Effects: mem.alloc. Capability: explicit bounded mem.alloc. Synchronization/traps: none; ordinary alloc_error failure reasons/budget rules apply. Interpreter transfers handles without duplicating ownership and charges/frees the same accounted bytes as own.new/own.take. ## Dynamic buffers (`linear_buffers`) These instructions add no concurrency effects. Metadata access uses existing shared/exclusive race and task-loan checks; views carry child provenance. Valid buffer states MUST NOT trap; allocation failure is an outcome, while execution limits retain spec 11 behavior. All operations require linear_buffers and its full dependency closure (arrays, capabilities, effects, heap, linear_aggregates, ownership, resources). buffer content and lifetime rules are spec 03 §26. T MUST be a complete value. Counts/indices are usize. All continuations receive exactly the listed parameters (E5002 count, E1001 types), with no SSA result for terminators. New operations add no traps, except existing borrowed-index bounds checks applied to a view. No synchronization is performed. | Instruction | Operands/result or continuations | Ownership/memory/transfer | Effects/capabilities | |---|---|---|---| | `buffer.new T %capacity, %cap, ok -> @ok, err -> @err` | usize, cap; ok(buffer), err(alloc_error) | new initialized empty prefix; no consumed input; successful result owned | mem.alloc, explicit mem.alloc cap | | `%n = buffer.len %borrow` / `%n = buffer.capacity %borrow` | ref> or mut> → usize | shared metadata read through live borrow, no consumption | — | | `buffer.reserve %borrow, %capacity, %cap, ok -> @ok, err -> @err` | mut>, usize, cap; ok(), err(alloc_error) | exclusive metadata/storage access; charge new backing before releasing old; failure preserves buffer; borrow remains live on both edges | mem.alloc, explicit mem.alloc cap | | `buffer.push %borrow, %value, ok -> @ok, err -> @err` | mut>, T; ok(), err(T) | exclusive access; linear input consumed on both edges; success appends, failure returns original value; borrow remains live | — | | `buffer.pop %borrow, ok -> @ok, err -> @err` | mut>; ok(T), err() | exclusive access; success removes/owns last value; empty preserves prefix; borrow remains live | — | | `%view = buffer.view %borrow` | ref> → slice; mut> → slice_mut | child borrow of initialized prefix, same shared/exclusive mode and provenance; MUST explicitly end; no ownership transferred | — | | `buffer.free %buffer, ok -> @ok, err -> @err` | buffer; ok(), err(buffer) | linear handle consumed on both edges; empty frees/releases charge, nonempty returns same complete buffer; live descendant borrows/task loans reject | — | Verifier transfer uses existing whole-value availability for new/free and returned linear block parameters, and useThrough/child provenance for borrowed operations. Length/capacity/view are shared/exclusive access as declared above; all modifying operations require exclusive access even for an empty/full/no-op dynamic case (E2101/E4101). Runtime observes L/C, updates the initialized prefix atomically per instruction and selects the corresponding continuation deterministically. Allocation overflow/exhaustion selects err(alloc_error); no user value is destroyed by a failing operation. Local/borrow/task-bound element types, mismatches and copy/overwrite of linear contents reject E1001; cyclic ownership rejects E1003. Existing resource-leak/repeated-consumption errors apply. No new diagnostic/effect/capability/trap is introduced.