Files
aji/docs/spec/06-resources-and-errors.md
dev 4f084decce cli: add whole-value linear aggregates
Implement STD-5 through source, AIR, verifier and deterministic interpreter.
Constructors consume nested owners; exhaustive unpack/take, explicit swap and
own.pack preserve ownership on success and failure. Support owning Option and
Result while keeping classification helpers Copy-only. Preserve borrow identity
across whole replacement and collection; distinguish individual owned arrays
from repeated heap arrays.

Specify feature contracts, invariants, diagnostics, compatibility and measured
source/AIR budgets in RFC 0023 and normative docs. Add canonical round trips,
AIR/source acceptance and rejection fixtures, CLI integration and CI checks.

Validate build, unit/extended tests, full conformance, forced-collection schedule
stress (32 seeds per quantum), hosted smoke, CLI suites, source coverage (88/88),
formatting and reference bundle generation. Source bundle grows 3.2%; Quick
Reference grows 4.0%. No MCC improvement is claimed.

Dynamic initialized linear buffers and explicit drain remain Q-036/STD-6;
frame/region/repeated heap storage is Copy-only. RFC remains Proposed.
2026-10-06 21:23:52 +03:00

140 lines
6.8 KiB
Markdown

# 06. Resources and Errors
## 1. Linear resources
External resources are linear unless explicitly documented otherwise.
Examples:
```text
File
Socket
Thread<T>
Task<T>
Mapping
Timer
Device
```
A linear resource must be consumed by exactly one valid terminal action such as close, join, release or ownership transfer.
The verifier rejects double consumption and use after consumption.
## 2. Typestate
Resources MAY encode state transitions in types.
Example socket states:
```text
Socket<Created>
Socket<Bound>
Socket<Listening>
Socket<Connected>
Socket<Closed>
```
A transition consumes one state and returns another.
## 3. Cleanup
Aji may provide `defer` as syntax sugar:
```aji
let file = fs.open(...)?;
defer fs.close(move file);
```
AIR must contain explicit cleanup control-flow edges. Aji has no hidden destructors.
## 4. Result
Expected failure uses `Result<T, E>`.
Propagation syntax may exist only if its lowering is explicit and does not introduce exceptions or unwinding.
## 5. Trap versus Result
Use `Result` for failures callers may reasonably handle.
Use trap for invariant violations, failed assertions and explicitly trapping primitives.
## 6. Resources in AIR (feature `resources`)
Decision record: RFC 0007.
Invariants:
1. **Linearity.** A resource value (`file`, `listener`, `stream`) is consumed exactly once on every normal path: by a closing intrinsic, by passing it to a by-value resource parameter or block parameter, or by returning it. It is never used after consumption and never silently dropped.
2. **No implicit release.** No resource is closed by scope exit, by a trap path being taken, or by any hidden action. Paths ending in `trap` end the program; the runtime then releases host resources as part of terminating the execution instance, which is not observable by the program.
3. **Explicit failure.** Every operation that can fail for external reasons delivers either its results or an `io_error` to block parameters. Failure is never a trap and never an exception.
4. **Object capabilities.** An open resource carries the authority it was opened with; operations on it need its effect but no further capability operand. Opening a resource requires a capability.
5. **Determinism.** In the `deterministic` profile every intrinsic has a fully specified result; the same module, grants, inputs and fuel produce the same run record. Profiles never invent results the program did not ask for: a run that can make no further progress ends with the environment outcome `blocked`, not with an I/O error.
Depends on `capabilities`, `effects`, `ownership`.
### 6.1 Types
| Type | Meaning | Accounted size |
|---|---|---|
| `file<read>` | file opened for reading | 8 |
| `file<write>` | file opened for writing (created or truncated) | 8 |
| `file<append>` | file opened for appending | 8 |
| `listener` | listening TCP socket | 8 |
| `stream` | connected TCP stream | 8 |
The mode of a file is part of its type, so using a file in the wrong mode is a verifier error, not a runtime failure: `fs.read` takes `mut<file<read>>`; `fs.write_all` and `fs.sync` take `mut<file<write>>` or `mut<file<append>>`.
Resource types are **linear** and **authority-bearing** (spec 05 §10.1): not copyable (`copy` is `E1001`), not zeroable, not comparable, not serializable.
Resource types as struct fields, enum payloads or fixed-array elements require `linear_aggregates` (spec 03 §25) (`E0006` reason `feature_not_declared` without it). They may appear as function parameters, return types, block parameters and as operands of borrow instructions.
### 6.2 Consumption
A resource value is **consumed** by exactly one of:
- a closing intrinsic (`fs.close`, `net.close_stream`, `net.close_listener`). A closing intrinsic consumes the resource **regardless of its result**: on both the `ok` and the `err` edge the resource is dead, and closing it again is `E2002`. After a failed close the state of the underlying host handle is unspecified, so no retry is possible;
- being a `call` argument for a parameter of resource type (ownership moves to the callee);
- being a branch argument (`br`, `cbr`, `switch`, default targets) for a block parameter of resource type;
- `ret`.
Every other operand use of a resource is a **non-consuming use**, which is only permitted through borrows: `borrow.ref %f` / `borrow.mut %f` take a resource SSA value as their root, exactly as for a `local` (RFC 0005), and produce `ref<file>` / `mut<file>`.
### 6.3 Verifier rules
The resource state of each resource value — `owned`, `consumed by close`, `consumed by transfer` — is tracked on every reachable path with the same discipline as borrows (spec 08 §11.4):
| Rule | Code |
|---|---|
| owned resource live at `ret` (other than the returned one) | `E3002` (`resource.leak`) |
| resource state differs between edges into a block | `E3002` (joins with differing states are reserved for the feature `resource_joins`) |
| resource consumed again after any consumption | `E2002` (`ownership.double_consume`) |
| non-consuming use after consumption by a closing intrinsic | `E3001` (`resource.use_after_consume`) |
| non-consuming use after consumption by transfer | `E2001` (`ownership.use_after_move`) |
| resource consumed while a borrow of it is live | `E2101` |
Resource parameters of the current function are owned by it (they were moved in). Resource block parameters own their argument.
## 7. I/O errors
`io_error` is a built-in enum (spelled without `@`, used with `enum.switch io_error %e, …`):
| Variant | Meaning |
|---|---|
| `not_found` | path or address does not exist |
| `permission_denied` | the host refused, or the path is outside the capability's scope |
| `already_exists` | exclusive creation of an existing path |
| `invalid_input` | malformed path or address (relative path, `.`/`..` component, unparsable address) |
| `no_space` | storage exhausted |
| `broken_pipe` | the peer closed while writing |
| `connection_refused` | nobody listens at the address |
| `connection_reset` | the peer reset the connection |
| `address_in_use` | listen address taken |
| `address_unavailable` | listen or connect address not available to this host |
| `timed_out` | an explicit timeout expired (reserved for timers in Phase 3; no Phase 2 operation produces it) |
| `other` | any host error not listed above |
The mapping from host errors to variants is part of each profile's specification; `other` keeps the set closed. Host error numbers are not part of AIR semantics: a runtime may attach them as diagnostic metadata outside the run record's values, never in a way the program can observe.
**Frozen variant sets.** The variants of a published built-in enum never change: adding one would make an existing exhaustive `enum.switch` without `default` non-exhaustive, turning an accepted module into a rejected one (spec 07 §8.7). This is why `timed_out` is reserved now although nothing produces it yet.