Introduce linear_buffers through the specification, AIR parser/serializer, verifier, deterministic interpreter and source lowering. A buffer owns an initialized prefix with explicit reserve, bounded push, moving pop/views and recoverable empty-only free. Growth charges old+new capacity; failed growth, full push and nonempty free preserve or return complete ownership. Implement compiler-pinned safe std.vec with nine operations for Copy values, owners, files and channel endpoints. Permit complete Copy moves inside specialized generic bodies without weakening monomorphic or borrow rules. Update RFC 0024, Q-036, STD-6a/b, reference grammar, Quick Reference, bundles, source coverage and CI. Remaining collections stay STD-6c. Validation: unit tests and AIR round-trip; 757 conformance cases; 56 dedicated buffer cases with per-instruction collection and 32-seed schedule stress; extended memory test; hosted smoke; 36 module, 20 generic, 49 linear and 118 buffer CLI checks; 91/91 source constructs; Zig fmt and reference bundles. Full source bundle: 49,589 -> 52,384 cl100k tokens (+5.6%); AIR 175,736 bytes. The reference interpreter's push copies its initialized prefix; no native performance or empirical MCC benefit is claimed.
473 lines
29 KiB
Markdown
473 lines
29 KiB
Markdown
# 03. Memory and Ownership Model
|
||
|
||
This file is normative. Rationale is in RFC 0001.
|
||
|
||
## 1. Goals
|
||
|
||
Aji memory management must provide:
|
||
|
||
- memory safety without tracing GC;
|
||
- no implicit allocation;
|
||
- stable, inspectable ownership transitions;
|
||
- efficient bulk allocation;
|
||
- efficient transfer of complex mutable graphs between tasks;
|
||
- verifier-friendly alias rules;
|
||
- explicit boundaries for unsafe pointer work.
|
||
|
||
## 2. Core forms
|
||
|
||
```text
|
||
Own<T> individually owned dynamic allocation
|
||
Region bulk allocation/lifetime domain
|
||
Island<T> uniquely owned closed mutable graph
|
||
Frozen<T> deeply immutable graph
|
||
Arc<T> explicit shared ownership of Share data
|
||
ref<T> immutable borrow
|
||
mut<T> exclusive mutable borrow
|
||
Uninit<T> allocated but not yet initialized
|
||
addr<T> unsafe raw address
|
||
```
|
||
|
||
## 3. Safe-reference aliasing rule
|
||
|
||
For overlapping storage, safe code permits either:
|
||
|
||
```text
|
||
N immutable borrows: ref<T>
|
||
```
|
||
|
||
or:
|
||
|
||
```text
|
||
1 exclusive mutable borrow: mut<T>
|
||
```
|
||
|
||
but never both at the same time.
|
||
|
||
The verifier enforces the rule across control flow and task scopes.
|
||
|
||
## 4. Borrow lifetime
|
||
|
||
A borrow cannot outlive the storage from which it was derived.
|
||
|
||
Source syntax may infer local borrow lifetimes. Public APIs whose output lifetime depends on input lifetime must express the relationship.
|
||
|
||
Conceptually:
|
||
|
||
```aji
|
||
fn first<'a, T>(values: slice<'a, T>) -> Option<ref<'a, T>>
|
||
```
|
||
|
||
In AIR, borrows are second-class (spec 07 §8.8): they live only in SSA values and call arguments, never in aggregates, and a function returns a borrow only with an explicit `from %param` naming the borrow parameter it derives from (spec 08 §11.3). Every borrow created in a function is ended explicitly on every normal path (`borrow.end`). Source-level lifetimes lower to this form; source programs that need more are rejected by the frontend.
|
||
|
||
## 5. Provenance
|
||
|
||
Every safe reference has logical provenance including:
|
||
|
||
- originating allocation or region allocation;
|
||
- region generation if applicable;
|
||
- byte bounds;
|
||
- alignment guarantee;
|
||
- access mode.
|
||
|
||
Safe code cannot create a reference from an integer.
|
||
|
||
Safe pointer arithmetic cannot create a reference outside the originating allocation.
|
||
|
||
## 6. Stack storage
|
||
|
||
Normal locals live in the current activation frame.
|
||
|
||
Their references cannot escape the frame unless the language proves that the target execution context completes before the frame ends, as with structured child tasks.
|
||
|
||
In AIR, frame storage is `local.alloc`, permitted only in a function's entry block so the frame size is known before execution and bounded (spec 08 §11.5). A borrow derived from frame storage never leaves its call (`E2108`, spec 08 §11.3).
|
||
|
||
## 7. Own<T>
|
||
|
||
`Own<T>` is a move-only handle to an individually allocated object.
|
||
|
||
```aji
|
||
let node: Own<Node> = heap.alloc<Node>(alloc_cap)?;
|
||
```
|
||
|
||
Allocation MUST be explicit and fallible unless an explicitly trapping allocation primitive is used.
|
||
|
||
Access occurs through borrows:
|
||
|
||
```aji
|
||
borrow node as ref n { inspect(n); }
|
||
borrow node as mut n { n.value = 42; }
|
||
```
|
||
|
||
Deallocation consumes the owner:
|
||
|
||
```aji
|
||
heap.free(move node);
|
||
```
|
||
|
||
## 8. Regions
|
||
|
||
A `Region` owns many allocations and releases them collectively.
|
||
|
||
```aji
|
||
let r = region.create(allocator, limit = 16 MiB)?;
|
||
let n = region.alloc<Node>(mut r)?;
|
||
```
|
||
|
||
Individual region allocations are not freed separately.
|
||
|
||
A region may be reset or destroyed.
|
||
|
||
```aji
|
||
region.reset(mut r);
|
||
region.destroy(move r);
|
||
```
|
||
|
||
### 8.1 Region generations
|
||
|
||
A reset logically increments the region generation.
|
||
|
||
Any borrow or reference associated with a prior generation becomes invalid. Generations are checked statically only: a region cannot be reset or destroyed while a borrow derived from it is live, and use of a borrow from a prior generation is rejected (`E2104`). Safe code performs no runtime generation checks. Cyclic or arena-style graphs use `Island<T>` or indices (§14). (Decision Q-010; specified with the `regions` feature in Phase 2.)
|
||
|
||
### 8.2 Reset precondition
|
||
|
||
Reset MUST be rejected when an externally usable safe reference to the current generation remains live.
|
||
|
||
## 9. Slices
|
||
|
||
A safe slice logically contains:
|
||
|
||
```text
|
||
provenance + base + length
|
||
```
|
||
|
||
Immutable slice:
|
||
|
||
```text
|
||
slice<T>
|
||
```
|
||
|
||
Exclusive mutable slice:
|
||
|
||
```text
|
||
slice_mut<T>
|
||
```
|
||
|
||
Indexing is bounds checked unless eliminated by proof.
|
||
|
||
Non-trapping access returns `Option`.
|
||
|
||
### 9.1 Disjoint partitioning
|
||
|
||
Verifier-recognized operations such as:
|
||
|
||
```aji
|
||
let (left, right) = slice.split_mut(data, mid);
|
||
```
|
||
|
||
establish that the output regions do not overlap. This fact may justify concurrent mutable access.
|
||
|
||
## 10. Initialization policy
|
||
|
||
Allocation does not imply initialization unless the operation says so.
|
||
|
||
Examples:
|
||
|
||
```text
|
||
region.alloc_uninit<T> uninitialized
|
||
region.alloc_zeroed<T> byte-zero initialized where valid for T
|
||
region.alloc_value(value) initialized from explicit value
|
||
```
|
||
|
||
Zeroing is never silently inserted as a consequence of allocation.
|
||
|
||
## 11. Uninitialized memory
|
||
|
||
Uninitialized storage has type `Uninit<T>`.
|
||
|
||
It cannot be read.
|
||
|
||
A write that fully initializes storage changes its verifier state to initialized storage.
|
||
|
||
For arrays/buffers the verifier may track initialized prefixes or ranges.
|
||
|
||
## 12. Island<T>
|
||
|
||
An `island<T>` is a uniquely owned, closed, mutable graph whose root has type `T`. Its objects are addressed by opaque `iref<U>` handles, which may form cycles. It holds only `IslandSafe` values (spec 02 §6), so it never points into mutable memory outside itself and carries no authority. It moves between tasks in O(1), and after the move the sender holds nothing that reaches it. In AIR: §22.
|
||
|
||
## 13. Frozen<T>
|
||
|
||
`island.freeze` turns an island into a `frozen<T>`. It is irreversible and O(1), and keeps the graph's identity. A `frozen<T>` is deeply immutable, has one owner, and is `Send` and `Share`, so it is lent to tasks by `ref`. No safe operation yields a mutable borrow of it. In AIR: §23.
|
||
|
||
## 14. Arc<T>
|
||
|
||
`arc<T>` is explicitly counted shared ownership of an immutable graph. It is made from a frozen graph (`arc.from_frozen`) or from one `ArcSafe` value (`arc.new`). The count changes only at `arc.clone` and `arc.release`, and the last release frees memory and nothing else. No operation silently changes a count. Cycles belong inside a graph (`iref` edges), not between arcs. In AIR: §24.
|
||
|
||
The three modes of one graph, chosen by intent:
|
||
|
||
```text
|
||
island<T> mutable, unique change it
|
||
│ island.freeze O(1)
|
||
frozen<T> immutable, unique owner, Share read it in parallel
|
||
│ arc.from_frozen O(1)
|
||
arc<T> immutable, shared ownership several independent owners
|
||
```
|
||
|
||
## 15. Stable addresses and pinning
|
||
|
||
Region and island allocations are address-stable until reset/destruction.
|
||
|
||
For individually owned objects that require address stability, Aji may provide `Pin<T>`.
|
||
|
||
Pinning is required for selected FFI, DMA and self-referential runtime structures.
|
||
|
||
## 16. Raw addresses
|
||
|
||
`addr<T>` is unsafe-only.
|
||
|
||
Raw addresses may be null, outlive safe lifetimes, perform arithmetic and cross FFI boundaries.
|
||
|
||
Dereference requires unsafe code and documented proof obligations.
|
||
|
||
## 17. Unsafe memory obligations
|
||
|
||
Unsafe code is responsible for establishing:
|
||
|
||
- allocation validity;
|
||
- alignment;
|
||
- initialization;
|
||
- lifetime;
|
||
- provenance assumptions required by the backend;
|
||
- aliasing discipline;
|
||
- synchronization where memory is shared concurrently.
|
||
|
||
## 18. Allocation authority in AIR (feature `heap`)
|
||
|
||
Decision record: RFC 0008.
|
||
|
||
Invariants:
|
||
|
||
1. **No implicit allocation, no implicit free.** Memory is obtained only by an allocating instruction with a `cap<mem.alloc>` operand (directly or through a region created from one), and returned only by `own.free`, `region.reset` or `region.destroy`.
|
||
2. **Linearity.** `own<T>`, `own_array<T>` and `region` are linear values with the rules of spec 06 §6 (consumed exactly once on every normal path; `E3002`, `E2001`, `E2002`).
|
||
3. **No dangling access.** Heap and region memory is reached only through second-class borrows, which cannot outlive the owner (heap) or the region generation (regions). There are no runtime generation checks.
|
||
4. **Bounded memory.** Every allocation is charged against a budget held by the authority object of the capability. The budget limits the bytes that are **live at the same time**.
|
||
5. **Shared quota.** Copies of a capability refer to one authority object and share one budget; narrowing creates a child budget whose charges also count against every ancestor.
|
||
6. **No hidden destruction of linear values.** `own.free`, `own.take`, `region.reset` and `region.destroy` can never make a linear value disappear: Copy-only allocations retain this restriction. Feature `linear_aggregates` permits individual `own<T>` content with ownership-preserving `own.pack`/`own.take` (§25); own.free and bulk arrays/regions cannot destroy linear content.
|
||
|
||
### 18.1 Budget semantics
|
||
|
||
A `cap<mem.alloc>` refers to an authority object with a `limit` (bytes, or unlimited) and a counter `used`. An allocation of `b` accounted bytes succeeds only if `used + b ≤ limit` holds for the object and every ancestor; it then adds `b` to `used` of each. Freeing returns the bytes to the same objects:
|
||
|
||
```text
|
||
alloc 10 MiB → used = 10 MiB
|
||
free 10 MiB → used = 0
|
||
```
|
||
|
||
The budget is a limit on simultaneously live memory, not a cumulative execution quota.
|
||
|
||
*Live allocation* and *live reference* are different things. A region allocation stays charged until `region.reset` or `region.destroy`, even after every borrow of it has ended: `borrow.end` never returns quota, because the region still holds the memory. Implementations MAY additionally report `total_allocated_bytes`, `peak_live_bytes` and `allocation_count` in audit reports; these never affect semantics.
|
||
|
||
Accounted bytes are those of spec 08 §7.1: `own<T>` charges `accounted_size(T)`, `own_array<T>` charges `n × accounted_size(T)` with checked arithmetic (overflow fails the allocation with `budget_exceeded`). Allocator overhead is not charged.
|
||
|
||
### 18.2 Instantiation
|
||
|
||
The scope of a `mem.alloc` grant is the byte limit (`--grant heap=mem.alloc:67108864`). In the `deterministic` profile the limit is **mandatory** (a grant without it is `not_instantiated` with reason `invalid_scope`), so every deterministic run has bounded memory. In the `hosted` profile an absent limit means unlimited by the program; the host may still fail an allocation (`out_of_memory`).
|
||
|
||
### 18.3 Narrowing form `budget`
|
||
|
||
`cap.narrow.budget %c, %n, ok -> @ok, err -> @err` (`%n: usize`) creates a child authority object with `limit = n` and parent `%c`. The `err` edge receives `not_subset` if `n` exceeds the parent's limit. Two copies of either capability share their object's budget.
|
||
|
||
Narrowing reserves nothing. Children of one parent may have limits that add up to more than the parent's (a 64 MiB parent with two 48 MiB children); they then compete for the parent's real 64 MiB, because every charge to a child is also a charge to the parent:
|
||
|
||
```text
|
||
allocate 10 MiB through child → child.used += 10, parent.used += 10
|
||
free it → child.used -= 10, parent.used -= 10
|
||
```
|
||
|
||
### 18.4 Errors
|
||
|
||
`alloc_error` is a built-in enum with the variants `budget_exceeded` (the budget of the capability or an ancestor would be exceeded) and `out_of_memory` (the host could not provide memory; never produced by the `deterministic` profile). Its variant set is frozen on publication.
|
||
|
||
## 19. Heap in AIR (feature `heap`)
|
||
|
||
Depends on `capabilities`, `effects`, `ownership`, `resources`.
|
||
|
||
### 19.1 Types
|
||
|
||
| Type | Meaning | Accounted size of the handle |
|
||
|---|---|---|
|
||
| `own<T>` | one heap object of value type `T` | 8 |
|
||
| `own_array<T>` | `n` heap elements of value type `T`, `n` chosen at runtime | 16 |
|
||
|
||
Both are linear and not copyable; as members of aggregates they need `linear_aggregates` (`E0006`).
|
||
|
||
### 19.2 Instructions
|
||
|
||
| Instruction | Operands → result | Effect | Notes |
|
||
|---|---|---|---|
|
||
| `own.new %v, %c, ok -> @ok, err -> @err` | `T`, `cap<mem.alloc>` → `@ok(%o: own<T>)`, `@err(%e: alloc_error)` | `mem.alloc` | object initialized with `%v` |
|
||
| `own.array %n, %v, %c, ok -> @ok, err -> @err` | `usize`, `T`, `cap<mem.alloc>` → `@ok(%a: own_array<T>)` | `mem.alloc` | every element initialized with `%v` |
|
||
| `own.take %o` | `own<T>` (consumed) → `T` | — | moves the value out, frees the allocation, returns the bytes |
|
||
| `own.free %o` | `own<T>` or `own_array<T>` (consumed) | — | returns the bytes to the budget |
|
||
| `borrow.ref` / `borrow.mut` | `own<T>` → `ref<T>` / `mut<T>`; `own_array<T>` → `slice<T>` / `slice_mut<T>` | — | the owner is the borrow root |
|
||
|
||
Heap memory is always initialized, so no initialization tracking is needed. `own.free` or `own.take` while a borrow of the owner is live is `E2101`. `own.take` is the inverse of `own.new` (`T → own<T> → T`); an `own_array<T>` has no `take`, since a runtime-sized array is not an SSA value.
|
||
|
||
`T` in baseline `own<T>` and in `own_array<T>` must be Copy. Linear `T` in individual `own<T>` needs `linear_aggregates` (`E0006` reason `feature_not_declared`), whose whole-value extraction/allocation rules are §25; bulk linear heap arrays remain unsupported. An owner is passed to a function by value (moving it) or by borrow (lending it), exactly like a resource.
|
||
|
||
## 20. Regions in AIR (feature `regions`)
|
||
|
||
Depends on `capabilities`, `effects`, `heap`, `ownership`, `resources`.
|
||
|
||
### 20.1 Type and lifetime
|
||
|
||
`region` is a linear value owning many allocations that share one lifetime. It is created from a capability, allocated from through a **shared** borrow, and reset or destroyed directly:
|
||
|
||
| Instruction | Operands → result | Effect | Notes |
|
||
|---|---|---|---|
|
||
| `region.create %c, ok -> @ok, err -> @err` | `cap<mem.alloc>` → `@ok(%r: region)`, `@err(%e: alloc_error)` | `mem.alloc` | allocations of the region are charged to `%c` |
|
||
| `region.new %rb, %v, ok -> @ok, err -> @err` | `ref<region>`, `T` → `@ok(%p: mut<T>)` | `mem.alloc` | fresh object initialized with `%v` |
|
||
| `region.array %rb, %n, %v, ok -> @ok, err -> @err` | `ref<region>`, `usize`, `T` → `@ok(%s: slice_mut<T>)` | `mem.alloc` | fresh array |
|
||
| `region.reset %r` | `region` (not consumed) | — | frees every allocation of the generation, returns all their bytes, starts a new generation |
|
||
| `region.destroy %r` | `region` (consumed) | — | frees every allocation and the region, returns all their bytes |
|
||
|
||
Values stored by `region.new`/`region.array` must be value types (no linear values), for the same reason as for `own<T>`.
|
||
|
||
Budget accounting of a region, normatively:
|
||
|
||
```text
|
||
region.new / region.array → used += allocation charge
|
||
borrow.end of an allocation → used unchanged
|
||
region.reset → used -= every allocation of the generation
|
||
region.destroy → used -= every allocation of the region
|
||
```
|
||
|
||
### 20.2 Verifier rules (static generations, Q-010)
|
||
|
||
- A region allocation `%p` is an owned borrow whose parent is the shared region borrow `%rb` and whose path is a fresh element unique to that allocation. Allocations are therefore disjoint from each other, and the exclusive borrow `mut<T>` of a fresh object does not conflict with the shared parent (this is the one place where an exclusive child of a shared borrow is permitted, because the storage is new).
|
||
- `region.reset %r` and `region.destroy %r` are exclusive accesses to the region value. If a **live reference** into the region exists — any live borrow derived from `%r`, in particular a live borrow of an allocation — the instruction is `E2104` (`memory.region_generation`): reset or destroy would invalidate a live reference. Allocations whose borrows have all ended are not an obstacle; destroying them is what `reset` and `destroy` are for.
|
||
- Ending `%rb` while one of its allocations is live is `E2102`, so no allocation outlives the borrow it came from.
|
||
- A function may return a region allocation with `from %rb` when `%rb` is a `ref<region>` parameter (spec 08 §11.3 applies unchanged: the root is the parameter). Frame-derived borrows still never escape (`E2108`).
|
||
|
||
No reference to a region allocation exists after `reset` or `destroy`, so safe code performs no generation checks at runtime.
|
||
|
||
### 20.3 Not in this RFC
|
||
|
||
Allocations cannot contain borrows (borrows are second-class), so linked structures inside a region use indices; cyclic owned graphs are islands (Phase 4).
|
||
|
||
## 21. Runtime
|
||
|
||
- Authority objects for `mem.alloc` carry `limit`, `used` and `parent`. Narrowing appends a child. Charges walk the parent chain.
|
||
- `own<T>` is a cell holding a value; `own_array<T>` a cell holding an array of `n` values. A region keeps a generation counter and the bytes charged by its current generation.
|
||
- In the `deterministic` profile memory is bounded by the mandatory budgets, so the interpreter's own memory use is bounded by a function of the module and its grants.
|
||
|
||
## 22. Islands in AIR (feature `islands`)
|
||
|
||
Decision record: RFC 0014. Depends on `heap` and its closure.
|
||
|
||
**Types.**
|
||
|
||
- `island<T>`: a graph owner; linear; `Send`, not `Share`.
|
||
- `iref<T>`: an opaque `{graph identity, slot}`; copyable, `IslandSafe`, `Send`, `Share`.
|
||
|
||
Graph owners may be parameters, returns, block arguments, channel elements and mutex contents. Their membership in aggregates requires `linear_aggregates` (§25); it does not weaken IslandSafe graph-content rules.
|
||
|
||
**Identity.** A graph's identity comes from a per-execution counter and is never reused. A handle cannot be built from, cast to or inspected as an integer.
|
||
|
||
| Instruction | Operands → result | Ownership and memory | Effect | Verifier | Runtime / trap |
|
||
|---|---|---|---|---|---|
|
||
| `island.create %v, %mem, ok -> @ok, err -> @err` (terminator) | `T` (consumed), `cap<mem.alloc>`; `@ok(island<T>)`, `@err(alloc_error)` | `%v` is the root object; charges its size and the graph header | `mem.alloc` | `T: IslandSafe` (`E2111`, field `found`) | a new identity; over budget → `@err` |
|
||
| `island.alloc %ib, %v, ok -> @ok, err -> @err` (terminator) | `mut<island<T>>`, `U` (consumed); `@ok(iref<U>)`, `@err(alloc_error)` | a new object; charges the graph's authority | `mem.alloc` | `U: IslandSafe` (`E2111`) | — |
|
||
| `%r = island.root %ib` | `ref`/`mut<island<T>>` → `iref<T>` | — | — | — | the root object |
|
||
| `%p = island.borrow %ib, %r` | `ref<island<T>>` → `ref<U>`; `mut<island<T>>` → `mut<U>`; `%r: iref<U>` | child borrow of `%ib` | — | ends before `%ib` (`E2102`); a `mut` child is exclusive: any other access through `%ib` while it lives is `E2101` | `T0010` if `%r` belongs to another graph |
|
||
| `%f = island.freeze %i` | `island<T>` (consumed) → `frozen<T>` | same storage, identity and quota | — | — | O(1) |
|
||
| `island.destroy %i` | `island<T>` (consumed) | frees the graph; returns its bytes | — | — | — |
|
||
| `%c = iref.eq %a, %b` | `iref<U>`, `iref<U>` → `bool` | — | — | — | equal identity and slot; handles of different graphs are unequal, never a trap |
|
||
|
||
Objects are never freed one by one. Two irefs naming different objects are not treated as disjoint: a mutable access is exclusive for the whole island.
|
||
|
||
**Types may recurse through `iref`.** `@Node = struct { value: u64, next: @Link }` with `@Link = enum { End, To(iref<@Node>) }` is well formed, whatever the declaration order: an `iref<T>` holds no `T`.
|
||
|
||
**Idioms.** Accesses are ordinary borrows, ended before the container borrow:
|
||
|
||
```text
|
||
; write a field of an object ; read an object of a frozen graph
|
||
%g = borrow.mut %isl %fb = borrow.ref %f
|
||
%n = island.borrow %g, %r ; mut<@Node> %p = frozen.borrow %fb, %r ; ref<@Node>
|
||
%nf = borrow.field @Node.next, %n %v = load %p
|
||
store %nf, %link borrow.end %p
|
||
borrow.end %nf borrow.end %fb
|
||
borrow.end %n
|
||
borrow.end %g
|
||
```
|
||
|
||
The container borrow may stay live across the edges of `island.alloc`, like any borrow (SSA dominance). A trap may leave graph owners unconsumed: the execution ends (spec 04 §33.2). `arc.clone` only reads its `ref<arc<T>>`, which may end right after the clone while the new handle lives on.
|
||
|
||
## 23. Frozen graphs in AIR (feature `islands`)
|
||
|
||
`frozen<T>`: a graph owner; linear; `Send`, `Share`. There is no thaw.
|
||
|
||
| Instruction | Operands → result | Ownership and memory | Verifier | Runtime / trap |
|
||
|---|---|---|---|---|
|
||
| `%r = frozen.root %fb` | `ref<frozen<T>>` → `iref<T>` | — | — | — |
|
||
| `%p = frozen.borrow %fb, %r` | `ref<frozen<T>>`, `iref<U>` → `ref<U>` | child borrow | `E2102` | `T0010` |
|
||
| `frozen.release %f` | `frozen<T>` (consumed) | frees the graph; returns its bytes | — | — |
|
||
|
||
## 24. Arc in AIR (feature `arc`)
|
||
|
||
Decision record: RFC 0014. Depends on `islands`.
|
||
|
||
`arc<T>`: a handle to a shared, immutable graph with root type `T`. Each handle is linear; the type is `Send` and `Share`.
|
||
|
||
| Instruction | Operands → result | Ownership and memory | Effect | Verifier | Runtime |
|
||
|---|---|---|---|---|---|
|
||
| `%a = arc.from_frozen %f` | `frozen<T>` (consumed) → `arc<T>` | same storage and identity; count 1; no charge (the graph header has room for the count) | — | — | O(1); never fails |
|
||
| `arc.new %v, %mem, ok -> @ok, err -> @err` (terminator) | `T` (consumed), `cap<mem.alloc>`; `@ok(arc<T>)`, `@err(alloc_error)` | a one-object graph; count 1 | `mem.alloc` | `T: ArcSafe` (`E2111`) | — |
|
||
| `%a2 = arc.clone %ar` | `ref<arc<T>>` → `arc<T>` | count + 1 | — | — | synchronized by the runtime |
|
||
| `arc.release %a` | `arc<T>` (consumed) | count − 1; the last release frees the graph and the count | — | — | synchronized; never fails |
|
||
| `%r = arc.root %ar` | `ref<arc<T>>` → `iref<T>` | — | — | — | — |
|
||
| `%p = arc.borrow %ar, %r` | `ref<arc<T>>`, `iref<U>` → `ref<U>` | child borrow | — | `E2102` | `T0010` |
|
||
|
||
The count is not a user atomic: no memory ordering is chosen by the program. Each count change appears in the execution trace (spec 11 §2).
|
||
|
||
**Quota (all three modes).** A graph charges the authority it was created with. The ownership mode does not change the budget.
|
||
|
||
| Operation | Live bytes |
|
||
|---|---|
|
||
| `island.create` | + the root object and the graph header (16 bytes, with room for an `arc` count) |
|
||
| `island.alloc` | + the object |
|
||
| `island.freeze` | unchanged |
|
||
| `arc.new` | + the value and the graph header |
|
||
| `arc.from_frozen` | unchanged (the header has room for the count) |
|
||
| `arc.clone` | unchanged |
|
||
| `arc.release`, not the last | unchanged |
|
||
| `arc.release`, the last | − the graph |
|
||
| `frozen.release` | − the graph |
|
||
| `island.destroy` | − the graph |
|
||
|
||
|
||
## 25. Linear aggregates in AIR
|
||
|
||
Feature `linear_aggregates` permits resources, owners, regions, graph owners, atomic cells, channel endpoints and mutexes as struct fields, enum payloads and fixed-array elements. Borrows/storage, task/scope/shield and guards MUST NOT become aggregate members; their existing gates remain. A declared aggregate or fixed array is linear exactly when any transitive member is linear. All variants contribute to an enum's class, including a payload-free variant. Copy remains structural. Ownership type graphs through aggregate members and owning wrappers MUST be acyclic (E1003); `iref` graph edges remain opaque. This initial feature does not add partial moves, holes, automatic cleanup or dynamic linear buffers.
|
||
|
||
Construction (`struct.make`, `enum.make`, `array.make`) MUST consume every linear input exactly once and produce one complete owned value. Every normal path MUST transfer or fully unpack that value; no nested resource may disappear. Copy projections of a live linear struct are allowed, but projecting a linear field with `struct.get`, or duplicating a linear value with `copy`, `load`, `local.load`, `array.splat` or `slice.copy`, MUST reject E1001. Ordinary `store` MUST NOT overwrite linear content. Borrowed fields/elements use existing exclusive/shared alias and task-loan rules; `value.swap` exchanges a complete initialized value with an explicitly supplied replacement and returns the previous value. No field is ever uninitialized.
|
||
|
||
`struct.unpack` and `array.unpack` consume their whole operand and deliver every field/element in declaration/index order to one continuation. `enum.take` consumes its whole enum and delivers the selected payload to an exhaustive variant continuation. It MUST have every variant exactly once and no default. Payload-free variants still consume the enum. Copy operands may also be unpacked; they remain available. Existing `enum.switch` remains observational and MUST NOT read a linear enum. Existing linear diagnostics E2001/E2002/E3001/E3002 apply to moved, repeated or missing consumption, with E2101/E4101 for live borrows/task loans.
|
||
|
||
Among heap/frame/region storage forms, only individual `own<T>` may hold linear aggregate content in this phase; channels and mutexes retain their existing complete-value transfer rules. `own.pack` explicitly moves a value into an individually owned allocation: on failure, the error continuation receives both alloc_error and the original complete value. `own.take` consumes the owner, frees the allocation and returns its complete content, including all nested owners/resources. `own.free` MUST reject E1001 when content is linear. Repeated heap arrays, region allocations and frame locals MUST remain Copy-only; bulk freeing cannot destroy resources. Dynamic linear buffers require a separate feature/API with an explicit drain contract. Existing heap/region operations on Copy values retain their semantics.
|
||
|
||
Verifier state is whole-value availability, existing borrow provenance and initialization, with no per-field moved state. Structural Send/Share still apply, so transfer to workers/channels/mutexes requires their ordinary rules. The deterministic interpreter moves existing handles, performs swaps as one instruction and uses existing allocation budgets/fuel; it performs no user cleanup on normal paths or traps. AIR format 0 remains compatible: previously unsupported feature/type/opcode cases gain meanings; previously accepted Copy modules keep identical behavior.
|
||
|
||
|
||
## 26. Dynamic initialized buffers
|
||
|
||
Feature `linear_buffers` adds the linear complete value `buffer<T>`, accounted handle size 24 bytes. T MUST be a complete value with ordinary linear_aggregates member rules: no borrow/storage/function-bound content. Ownership type graphs through buffer wrappers MUST be acyclic (E1003). `buffer<T>` is Send exactly when T is Send and Share exactly when T is Share, like own_array. Local propagates through T; no guard/task/channel-transfer gate is weakened.
|
||
|
||
A buffer uniquely owns capacity C and a contiguous initialized prefix of length L, 0 ≤ L ≤ C. Only [0,L) is observable. Every live linear element is owned exactly once inside that prefix. There are no observable holes, default values, implicit destructors or partially moved fields. Constructors start with L=0. Push/pop change the prefix by one complete value; pop is LIFO. Views borrow precisely the prefix. Metadata changes, growth and consumption obey ordinary exclusive alias and task-loan rules; a live view excludes those operations, even when a dynamic branch would perform no change.
|
||
|
||
Allocation charges C × accounted_size(T), using checked arithmetic and the named mem.alloc authority. Overflows/authority exhaustion return alloc_error::budget_exceeded. Zero capacity is valid and charged zero. Capacity is a target usize, not a format-0 fixed-array type length. Growth to C' > C allocates explicitly from the supplied authority: it MUST charge the complete new capacity before releasing the old charge to its original authority. Thus peak live charges include both allocations. Success transfers all initialized values and changes capacity/authority; failure preserves length, capacity, contents and old authority exactly. A request ≤ C succeeds without mutation/allocation, but public effects/capability requirements remain explicit. Unused capacity contains no user value and cannot be borrowed.
|
||
|
||
Push requires no allocation effect or capability: if L<C, it transfers one value and increments L; otherwise it returns that original value without mutation. Pop returns the last complete value and decrements L, or reports empty with no change. `buffer.free` consumes the whole handle: it frees storage only when L=0, otherwise returns that same complete buffer. This applies uniformly to Copy and linear T. Every normal path MUST explicitly transfer/drain nested resources; a caller MAY trap under the existing abnormal-path contract but no cleanup is inserted. Existing own.array, own.free and region/frame rules retain their meanings.
|
||
|
||
The verifier tracks whole buffer ownership and existing borrow provenance, not a symbolic length or per-slot initialization state. Prefix validity is enforced by the trusted primitive semantics. Views use existing slice borrow/end, load/store bounds and explicit value.swap rules. Copy loads/copies require Copy T; ordinary overwrite of linear T remains forbidden. The deterministic interpreter preserves buffer identity and initialized prefix across tracing collection, tasks and swaps; metadata accesses participate in race checks, and allocation uses existing deterministic budgets and fuel. No synchronization, ambient authority, implicit allocation or new trap is added. The feature is additive in AIR format 0.
|