Phase 4: islands, frozen graphs and arc through every layer (RFC 0014)

AIR: types island<T>, frozen<T>, arc<T>, iref<T>; 16 instructions
(island.create/alloc/root/borrow/freeze/destroy, frozen.root/borrow/
release, arc.from_frozen/new/clone/release/root/borrow, iref.eq); features
islands (depends on heap) and arc (depends on islands) published.
Verifier: IslandSafe/ArcSafe (E2111 at the owner type), container child
borrows (one mut access per island), Send/Share rows (island not Share),
linear owners, mem.alloc effect, element rules (recursion through iref).
Interpreter: graphs with never-reused identities, T0010 for a foreign
iref, O(1) freeze/conversion/transfer, arc counts in a trace hook
(Options.arc_events), budgets per the quota table, collector support.
.aji layer 9: types, operations, island.at/frozen.at/arc.at as borrow
places with explicit container borrows, iref ==/!=.
Frontend fix: joins carry only variables the construct assigns (and that
are read again), so an unchanged linear value is never a block argument
while borrowed.

Tests: 10 AIR (phase4), 6 .aji run + 12 rejects (layer9), the reference
program island-pipeline in .aji, equivalent to an independently
hand-written AIR program (36 on 30 schedule seeds); unit tests for the
arc count trace and O(1) transfer. Quick Reference §7 graphs (checked
excerpt of quickref/graphs.aji); coverage 61/61. Bundle growth: AIR
+7.0%, Quick Reference +0.6k, source docs +4.2k (recorded).
Spec: quota rows match the header-reserved count; idioms and iref
recursion in spec 03 §22; P4-11 (air-text.ebnf gaps) recorded.
This commit is contained in:
dev committed 2026-10-05 22:14:05 +03:00
1 parent ca84ab4348
commit c699529fec
58 files changed
+2189 -98

No files matched your search

+3 -2
View File
@@ -47,6 +47,7 @@ Growth never blocks a merge automatically; a complex feature can be justified, b
| RFC 0012 waits, channels, select, mutex | 19 | 38 | 133 781 | 20 748 | 35 119 (+15.8 %) | 35 219 (+15.7 %) | 36 238 (+15.7 %) |
| Phase 3 implementation | 19 | 38 | 134 576 | 20 884 | 35 324 (+0.6 %) | 35 424 (+0.6 %) | 36 453 (+0.6 %) |
| RFC 0014 islands, frozen graphs, arc (Phase 4) | 19 | 41 | 142 918 | 22 212 | 37 785 (+7.0 %) | — | — |
RFC 0011 crossed the 10 % warning line (its own estimate said "below 10 %"): four new sections in spec 04 (tasks, loans, `Send`/`Share` table, scheduler). Below the 20 % review threshold. RFC 0012 (+15.8 %, estimate 12–16 %): five sections in spec 04 (waits and cancellation, channels, select, mutex, critical-section rule). Implementation-time spec corrections (mutex linearity, `mutex.take` rules): +0.6 %. Phase 3 total since the Phase 2 baseline: +29.2 %. Next measurement: after the E-S smoke test, or with the next RFC.
@@ -56,11 +57,11 @@ The `.aji` condition does not get the AIR bundle as its documentation. It gets a
| Path | Contents | cl100k tokens |
|---|---|---:|
| `QUICK.md` | the Quick Reference, then a table of which file to open for what | ~4.4k |
| `QUICK.md` | the Quick Reference, then a table of which file to open for what | ~5.0k (Phase 4: +0.6k for §7 graphs) |
| `language/syntax.md` | grammar, spec 15 §1, §2, §4–§6 | ~5.4k |
| `language/types.md` | spec 15 §3, integer semantics, type properties, traps | ~1.0k |
| `language/ownership.md` | spec 15 §9, aliasing, borrow lifetime, stack storage, slices, initialization (spec 03) | ~1.0k |
| `language/memory.md` | `Own<T>`, regions, allocation authority (spec 03) | ~1.4k |
| `language/memory.md` | `Own<T>`, regions, islands, frozen graphs, arc, allocation authority (spec 03) | ~3.6k |
| `language/effects-capabilities.md` | spec 05 §2–§5, §9–§10, effect and capability registries | ~4.4k |
| `language/io-resources.md` | spec 15 §8, spec 06 §1–§3, §7, intrinsic registry | ~3.0k |
| `language/concurrency.md` | implementation status, spec 15 §7, `Send`/`Share`, scheduler | ~2.2k |
+3
View File
@@ -59,6 +59,9 @@ docs/spec/06-resources-and-errors.md :: ## 7. I/O errors
docs/spec/03-memory-model.md :: ## 18. Allocation authority in AIR
docs/spec/03-memory-model.md :: ## 19. Heap in AIR
docs/spec/03-memory-model.md :: ## 20. Regions in AIR
docs/spec/03-memory-model.md :: ## 22. Islands in AIR
docs/spec/03-memory-model.md :: ## 23. Frozen graphs in AIR
docs/spec/03-memory-model.md :: ## 24. Arc in AIR
# Unsafe boundaries
docs/spec/13-contracts-and-unsafe.md :: ## 6. Unsafe code in AIR
+16
View File
@@ -62,5 +62,21 @@
"o200k_base": 35424,
"qwen2.5": 36453
}
},
{
"label": "RFC 0014 islands, frozen graphs, arc (Phase 4)",
"language": "aji",
"air": 0,
"phase": 3,
"files": 19,
"sections": 41,
"bytes": 142918,
"lines": 2118,
"words": 22212,
"tokens": {
"cl100k_base": 37785,
"o200k_base": 37888,
"qwen2.5": 38988
}
}
]
+46 -3
View File
@@ -37,7 +37,8 @@ effects [io.read, io.write]
| `own<T>`, `own_array<T>`, `region` | heap and regions (§6) |
| `cap<K>` | authority; kinds below |
| `file<read>`, `file<write>`, `file<append>`, `listener`, `stream` | linear resources |
| `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>` | concurrency (§7) |
| `island<T>`, `frozen<T>`, `arc<T>`, `iref<T>` | object graphs (§7) |
| `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>` | concurrency (§8) |
| `io_error`, `alloc_error`, `cap_error` | built-in error enums |
**Linear** values (resources, `own`, `region`, `task`, endpoints, `mutex`) are consumed exactly once. Everything else that is a plain value is copyable.
@@ -152,7 +153,47 @@ region.reset(r);
- Resource operands (`f`, `s`, `l`, endpoints) are borrowed automatically for an operation; a region is not (bind `ref arena = r;`); data borrows (`mut buf`, `ref bytes`) are always written.
- Memory budgets count live bytes, so freeing returns them. In the deterministic profile `mem.alloc` needs a grant with a budget: `--grant heap=mem.alloc:4096`.
## 7. Concurrency
## 7. Graphs: island → frozen → arc
Choose by intent:
- change a graph → `island<T>`;
- read it in parallel → `frozen<T>`;
- give it several independent owners → `arc<T>`.
Objects are addressed by `iref<T>` handles: copyable, compared only with `==`/`!=`, cycles allowed. A graph holds only plain data and irefs (`E2111` otherwise).
```aji
let isl = island.create(Node { value: 1, next: Link::End }, heap) or trap; // effect mem.alloc
{
mut g = isl; // borrow the island; it outlives the accesses
let a = island.root(g);
let b = island.alloc(g, Node { value: 2, next: Link::To(a) }) or trap;
mut first = island.at(g, a); // mut<Node>; one mutable access at a time
first.next = Link::To(b); // edges may form cycles
}
let f = island.freeze(move isl); // O(1), irreversible; irefs stay valid
…
ref fr = f; // frozen graphs are Share: lend fr to tasks
let a = frozen.root(fr);
…
let shared = arc.from_frozen(move f); // O(1); the same graph
let other = arc.clone(shared); // count + 1
arc.release(move other); // the last release frees the graph
```
- `island.at`, `frozen.at` and `arc.at` appear only as `ref x = …;`/`mut x = …;`, with a **named borrow of the owner** (`mut g = isl;`, `ref fr = f;`), as for regions. `frozen.at` and `arc.at` give `ref` only.
- An `iref` from another graph traps `T0010`.
- Ownership:
- an island is `Send`, not `Share`: move it through channels or spawn, or freeze it to share;
- `frozen` and `arc` are `Send` and `Share`.
- Every owner is consumed once:
- an island by `island.destroy(move i)` or `island.freeze`;
- a frozen graph by `frozen.release` or `arc.from_frozen`;
- each arc handle by `arc.release`.
- `create`, `alloc` and `arc.new` charge the `mem.alloc` budget. The bytes come back when the graph is freed.
## 8. Concurrency
Tasks, channels, `select`, `lock`/mutex, `shield` and the cancellation operations all work.
@@ -222,7 +263,7 @@ scope s { // every task spawned in s must
Inside a `lock` block no operation may wait or spawn, and no function may be called whose effects include `task.wait` or `task.spawn` (`E4304`). One lock at a time, so lock-order deadlocks cannot happen.
## 8. Common diagnostics → repair
## 9. Common diagnostics → repair
| Code | Meaning | Usual repair |
|---|---|---|
@@ -242,4 +283,6 @@ scope s { // every task spawned in s must
| E4101 | data race with a task | lend disjoint parts (`split_at`, fields) or join first |
| E4301 | task not joined at scope end | `task.join(move t)` before the `scope` block ends |
| E4304 | wait inside `lock` | move the wait out of the `lock` block |
| E2111 | graph content not plain data | store only integers, booleans, enums, structs/arrays of them and `iref`s in a graph |
| T0010 | `iref` of another graph | use a handle with the graph it came from |
| T0001–T0009 | runtime trap | see `kind` and `source_location` |
+7 -1
View File
@@ -9,7 +9,7 @@
> QUICK.md
docs/agent/quick-reference.md
docs/agent/source-notes.md :: ## 9. Where to read more
docs/agent/source-notes.md :: ## 10. Where to read more
> language/syntax.md
docs/reference/grammar.ebnf
@@ -37,6 +37,12 @@ docs/spec/03-memory-model.md :: ## 10. Initialization policy
docs/spec/03-memory-model.md :: ## 7. Own<T>
docs/spec/03-memory-model.md :: ## 8. Regions
docs/spec/03-memory-model.md :: ## 18. Allocation authority in AIR
docs/spec/03-memory-model.md :: ## 12. Island<T>
docs/spec/03-memory-model.md :: ## 13. Frozen<T>
docs/spec/03-memory-model.md :: ## 14. Arc<T>
docs/spec/03-memory-model.md :: ## 22. Islands in AIR
docs/spec/03-memory-model.md :: ## 23. Frozen graphs in AIR
docs/spec/03-memory-model.md :: ## 24. Arc in AIR
> language/effects-capabilities.md
docs/spec/05-effects-and-capabilities.md :: ## 2. Effects
+2 -2
View File
@@ -2,7 +2,7 @@
Text that exists only for the Source Reference Bundle (`source-bundle.txt`). Non-normative: it points at the normative files and states which source layers are implemented.
## 9. Where to read more
## 10. Where to read more
The other files in `/docs` hold the full rules. Open one only when this page is not enough.
@@ -11,7 +11,7 @@ The other files in `/docs` hold the full rules. Open one only when this page is
| exact syntax, every construct, `match` and outcomes | `/docs/language/syntax.md` |
| integer semantics, conversions, Copy/Send/Share, traps | `/docs/language/types.md` |
| borrows, scopes, frame storage, slices, initialization | `/docs/language/ownership.md` |
| `own`, regions, allocation budgets | `/docs/language/memory.md` |
| `own`, regions, islands, frozen graphs, arcs, allocation budgets | `/docs/language/memory.md` |
| effects, capabilities, grants, narrowing | `/docs/language/effects-capabilities.md` |
| files, streams, stdin/stdout, intrinsic operand tables, `io_error` | `/docs/language/io-resources.md` |
| tasks, channels, select, mutex, cancellation | `/docs/language/concurrency.md` |
+10 -9
View File
@@ -26,15 +26,16 @@ Non-normative. Part of the [implementation plan](README.md).
|---|---|---|---|---|---|
| P4-0 | done | RFC 0014: decisions D1–D10, owner review | — | `docs/rfcs/0014-islands-frozen-arc.md` | Accepted (revision 2) |
| P4-1 | done | Spec integration: spec 03 §12–14, 04 §13/§35/§38.1, 07a contract tables, 15 (layer 9), error codes (`T0010`) | P4-0 | spec, reference | contract tables complete (spec 07 §4 fields) |
| P4-1a | todo | Publish `islands` (depends on `heap`) and add `arc` (depends on `islands`) | P4-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P4-2 | todo | Interpreter: island tables, identities never reused, `T0010`, freeze, O(1) transfer; arc counts in the trace; collector support | P4-1 | `src/interp/` | transfer cost independent of graph size (unit test with an instruction-count bound); `--collect-every-step` passes |
| P4-3 | todo | Verifier: types and classes, storability (`E2111`), container child borrows, arc rules (`E4002`/`E1001`), Send/Share rows | P4-1 | `src/verifier/` | accept/reject per rule |
| P4-4 | todo | Transfer through channels and spawn; sender invalidation | P4-3 | verifier + interpreter | use after send rejected (`E2001`); schedule stress |
| P4-5 | todo | Freeze and `frozen<T>`; lending to tasks | P4-3 | verifier + interpreter | concurrent reads accepted; mutable access rejected |
| P4-6 | todo | `arc<T>`: `arc.from_frozen`, `arc.new` (`ArcSafe`), `clone`, `release`, `root`, `borrow` | P4-5 | verifier + interpreter | non-`ArcSafe` rejected (`E2111`); count changes visible in the trace |
| P4-7 | todo | `.aji` layer 9: types, operations, `island.at`/`frozen.at`/`arc.at` places, explicit container borrows; Quick Reference section; source coverage rows | P4-3 | `src/frontend/`, `docs/agent/` | `.aji` run/reject tests; Quick Reference examples checked; `tools/source_coverage.py` passes |
| P4-8 | todo | Reference program `island-pipeline` in AIR and `.aji` with equivalence | P4-4, P4-5, P4-6, P4-7 | `tests/conformance/` | passes under all P3 stress modes |
| P4-9 | todo | Complexity budget: AIR bundle, Quick Reference, Source Reference Bundle measured against the RFC estimate | P4-7 | `docs/agent/README.md` | growth recorded and justified |
| P4-1a | done | Publish `islands` (depends on `heap`) and add `arc` (depends on `islands`) | P4-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P4-2 | done | Interpreter: island tables, identities never reused, `T0010`, freeze, O(1) transfer; arc counts in the trace; collector support | P4-1 | `src/interp/` | transfer cost independent of graph size (unit test with an instruction-count bound); `--collect-every-step` passes |
| P4-3 | done | Verifier: types and classes, storability (`E2111`), container child borrows, arc rules (`E4002`/`E1001`), Send/Share rows | P4-1 | `src/verifier/` | accept/reject per rule |
| P4-4 | done | Transfer through channels and spawn; sender invalidation | P4-3 | verifier + interpreter | use after send rejected (`E2001`); schedule stress |
| P4-5 | done | Freeze and `frozen<T>`; lending to tasks | P4-3 | verifier + interpreter | concurrent reads accepted; mutable access rejected |
| P4-6 | done | `arc<T>`: `arc.from_frozen`, `arc.new` (`ArcSafe`), `clone`, `release`, `root`, `borrow` | P4-5 | verifier + interpreter | non-`ArcSafe` rejected (`E2111`); count changes visible in the trace |
| P4-7 | done | `.aji` layer 9: types, operations, `island.at`/`frozen.at`/`arc.at` places, explicit container borrows; Quick Reference section; source coverage rows | P4-3 | `src/frontend/`, `docs/agent/` | `.aji` run/reject tests; Quick Reference examples checked; `tools/source_coverage.py` passes |
| P4-8 | done | Reference program `island-pipeline` in AIR and `.aji` with equivalence | P4-4, P4-5, P4-6, P4-7 | `tests/conformance/` | passes under all P3 stress modes |
| P4-9 | done | Complexity budget: AIR bundle, Quick Reference, Source Reference Bundle measured against the RFC estimate | P4-7 | `docs/agent/README.md` | growth recorded and justified |
| P4-11 | todo | `reference/air-text.ebnf` covers the syntax of Phases 2–4: `cap<K>`, endpoint, task, graph and built-in types; `own.*`, `task.*`, `channel.*` (with the type operand of `channel.make`), `island.*`/`frozen.*`/`arc.*`/`iref.eq`; the multi-edge terminator forms (found by the independent author of `program_island_pipeline.air`) | — | `docs/reference/air-text.ebnf` | every instruction of spec 07a and spec 03 §22–§24 has a production |
| P4-10 | todo | Phase exit review | all | plan status | exit criterion passes |
## Conformance tests to add
+2 -1
View File
@@ -30,6 +30,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It
| Feature | Status | Phase | Depends on | Semantic block |
|---|---|---|---|---|
| `arc` | published | 4 | `capabilities`, `effects`, `heap`, `islands`, `ownership`, `resources` | `arc<T>`, `arc.*`, `ArcSafe` (spec 03 §24) |
| `arrays` | published | 1 | `ownership` | `array<T, N>`, `slice<T>`, `slice_mut<T>`, `array.splat`, `borrow.index[.proven]`, `slice.*`, `guard`, bounds facts (spec 07a, spec 08 §12) |
| `atomics` | reserved | 5 | `ownership` | atomic types, the five orderings, fences, `atomic.*` instructions |
| `borrow_joins` | reserved | — | `ownership` | borrow-typed block parameters (spec 08 §11.6); unscheduled |
@@ -40,7 +41,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It
| `effects` | published | 2 | — | flat effect checking of `effects [...]` for `call` and `intrinsic` (E3101, spec 05 §9) |
| `guard_transfer` | reserved | — | `cancellation`, `effects`, `ownership`, `sync`, `tasks` | `guard<T>` as parameter, return type or aggregate member; unscheduled |
| `heap` | published | 2 | `capabilities`, `effects`, `ownership`, `resources` | `own<T>`, `own_array<T>`, `own.*`, built-in `alloc_error`, `mem.alloc` budgets and `budget` narrowing (spec 03 §18–§19) |
| `islands` | reserved | 4 | `capabilities`, `effects`, `heap`, `ownership`, `regions`, `resources` | `Island<T>`, `iref<T>`, transfer, freeze, `Frozen<T>` |
| `islands` | published | 4 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `island<T>`, `frozen<T>`, `iref<T>`, `island.*`, `frozen.*`, `iref.eq`, `IslandSafe`, `T0010` (spec 03 §22–§23) |
| `linear_aggregates` | reserved | — | `capabilities`, `effects`, `ownership`, `resources` | resource types as struct fields, enum payloads and array elements; unscheduled |
| `ownership` | published | 1 | — | frame storage `local<T>`, second-class borrows `ref<T>`/`mut<T>`, `from` returns, initialization (spec 07 §8.8, spec 07a, spec 08 §11, §13) |
| `receiver_dup` | reserved | — | `cancellation`, `capabilities`, `channels`, `effects`, `heap`, `ownership`, `resources`, `tasks` | several receivers of one channel (MPMC); unscheduled |
+5 -4
View File
@@ -104,13 +104,14 @@ A graph charges the `cap<mem.alloc>` it was created with: live bytes, as for `ow
| Operation | Live bytes |
|---|---|
| `island.create`, `island.alloc` | + the object |
| `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 count |
| `arc.from_frozen` | + the count only |
| `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 and the count |
| `arc.release`, the last | − the graph |
| `frozen.release` | − the graph |
| `island.destroy` | − the graph |
+23 -5
View File
@@ -386,6 +386,23 @@ Graph owners may be parameters, returns, block arguments, channel elements and m
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.
@@ -404,7 +421,7 @@ Decision record: RFC 0014. Depends on `islands`.
| 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; charges the count | — | — | O(1) |
| `%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 |
@@ -417,13 +434,14 @@ The count is not a user atomic: no memory ordering is chosen by the program. Eac
| Operation | Live bytes |
|---|---|
| `island.create`, `island.alloc` | + the object |
| `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 count |
| `arc.from_frozen` | + the count |
| `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 and the count |
| `arc.release`, the last | − the graph |
| `frozen.release` | − the graph |
| `island.destroy` | − the graph |
+6 -1
View File
@@ -106,7 +106,12 @@ Statements end with `;`. Block constructs (`if`, `while`, `for`, `loop`, `match`
`if` and `match` are expressions when every branch yields a value of the same type through a tail expression (an expression without `;` at the end of a block) or diverges (`return`, `break`, `continue`, `trap`).
**Joins carry live variables only.** A variable is passed to a join (the block after an `if` or `match`, a loop header, a loop exit) only if it may be read after that join: on a later path, or, for a loop header, anywhere in the loop. A variable that is not read again is not passed on. This is ordinary pruned SSA construction, not tracking of moves. A linear value consumed before a join (`channel.close_receiver(move r)` before `break`) does not travel to it. A linear value that is read after it was consumed is still the verifier's `E2001`. The analysis is conservative: any read on a later path counts, and only a whole-variable assignment in straight-line code ends a variable's life.
**Joins carry only variables that change and are read again.** A variable is passed to a join (the block after an `if`, `match`, `lock` or `select`, a loop header, a loop exit) only if two things hold:
- the construct assigns it, by `x = e;` or by rebinding on an outcome edge;
- it may be read after the join: on a later path, or, for a loop header, anywhere in the loop.
Any other variable keeps its dominating value. An unchanged linear value is therefore never passed as a block argument while it is borrowed (`mut g = isl;` around a loop), and a variable that is not read again is not passed on. This is ordinary pruned SSA construction, not tracking of moves. A linear value consumed before a join (`channel.close_receiver(move r)` before `break`) does not travel to it. A linear value that is read after it was consumed is still the verifier's `E2001`. The analysis is conservative: any read on a later path counts, and only a whole-variable assignment in straight-line code ends a variable's life.
**Type inference is deliberately small.** It works within one function, it is monomorphic, and it does no overload resolution or search among several admissible types. An expression's type comes from:
+3 -2
View File
@@ -22,6 +22,7 @@ pub const Feature = struct {
};
pub const registry = [_]Feature{
.{ .name = "arc", .depends = &.{ "capabilities", "effects", "heap", "islands", "ownership", "resources" }, .status = .published, .phase = 4 },
.{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
.{ .name = "atomics", .depends = &.{"ownership"}, .status = .reserved, .phase = 5 },
.{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null },
@@ -32,7 +33,7 @@ pub const registry = [_]Feature{
.{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 },
.{ .name = "guard_transfer", .depends = &.{ "cancellation", "effects", "ownership", "sync", "tasks" }, .status = .reserved, .phase = null },
.{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .published, .phase = 2 },
.{ .name = "islands", .depends = &.{ "capabilities", "effects", "heap", "ownership", "regions", "resources" }, .status = .reserved, .phase = 4 },
.{ .name = "islands", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 4 },
.{ .name = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
.{ .name = "receiver_dup", .depends = &.{ "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "resources", "tasks" }, .status = .reserved, .phase = null },
@@ -48,7 +49,7 @@ pub const registry = [_]Feature{
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const supported = [_][]const u8{ "arc", "arrays", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
pub const Reason = enum {
unknown_feature,
+51 -7
View File
@@ -94,6 +94,11 @@ pub const Type = union(enum) {
// Feature `sync` (spec 04 §40).
mutex: *const Type,
guard: *const Type,
// Features `islands` and `arc` (spec 03 §22–§24): graph owners and handles.
island: *const Type,
frozen: *const Type,
arc: *const Type,
iref: *const Type,
pub const Array = struct { elem: Type, len: u64 };
@@ -102,7 +107,7 @@ pub const Type = union(enum) {
return switch (a) {
.int => |x| b.int == x,
.named => |x| b.named == x,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(b.inner().?),
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(b.inner().?),
.region, .scope, .shield => true,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k,
@@ -115,7 +120,7 @@ pub const Type = union(enum) {
/// Element or pointee type of storage, borrow and slice types.
pub fn inner(t: Type) ?Type {
return switch (t) {
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -132,11 +137,16 @@ pub const Type = union(enum) {
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
pub fn isLinear(t: Type) bool {
return switch (t) {
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => true,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => true,
else => false,
};
}
/// Graph owners (spec 03 §22–§24).
pub fn isGraphOwner(t: Type) bool {
return t == .island or t == .frozen or t == .arc;
}
/// Function-bound types (spec 04 §33.1, §37.3): never parameters, results
/// or members. `guard<T>` is function-bound too, under its own feature.
pub fn isTaskBound(t: Type) bool {
@@ -161,7 +171,7 @@ pub const Type = union(enum) {
/// Linear resources are neither values nor borrows: they are moved.
pub fn isValue(t: Type) bool {
return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => false,
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => false,
else => true,
};
}
@@ -314,6 +324,23 @@ pub const Op = union(enum) {
mutex_lock: struct { mutex: ValueId, ok: u32, cancelled: u32 },
mutex_borrow: ValueId,
mutex_unlock: ValueId,
// Features `islands` and `arc` (spec 03 §22–§24).
island_create: struct { value: ValueId, cap: ValueId, ok: u32, err: u32 },
island_alloc: struct { island: ValueId, value: ValueId, ok: u32, err: u32 },
island_root: ValueId,
island_borrow: struct { owner: ValueId, iref: ValueId },
island_freeze: ValueId,
island_destroy: ValueId,
frozen_root: ValueId,
frozen_borrow: struct { owner: ValueId, iref: ValueId },
frozen_release: ValueId,
arc_from_frozen: ValueId,
arc_new: struct { value: ValueId, cap: ValueId, ok: u32, err: u32 },
arc_clone: ValueId,
arc_release: ValueId,
arc_root: ValueId,
arc_borrow: struct { owner: ValueId, iref: ValueId },
iref_eq: struct { a: ValueId, b: ValueId },
ret: ?ValueId,
trap,
@@ -338,7 +365,7 @@ pub const Op = union(enum) {
pub fn isTerminator(op: Op) bool {
return switch (op) {
.br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true,
.own_new, .own_array, .region_create, .region_new, .region_array => true,
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => true,
.task_check_cancel, .task_join_cancel, .channel_make, .channel_send, .channel_recv, .channel_close_receiver, .select, .mutex_lock => true,
.intrinsic => |x| x.ok != null,
else => false,
@@ -481,6 +508,23 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
.own_take, .own_free, .region_reset, .region_destroy, .task_join, .task_cancel, .task_scope_end => |v| f(ctx, v),
.task_scope_begin, .task_cancelled, .task_check_cancel, .task_shield_begin => {},
.task_shield_end, .channel_dup, .channel_close_sender, .mutex_make, .mutex_take, .mutex_borrow, .mutex_unlock => |v| f(ctx, v),
.island_root, .island_freeze, .island_destroy, .frozen_root, .frozen_release, .arc_from_frozen, .arc_clone, .arc_release, .arc_root => |v| f(ctx, v),
inline .island_create, .arc_new => |x| {
f(ctx, x.value);
f(ctx, x.cap);
},
.island_alloc => |x| {
f(ctx, x.island);
f(ctx, x.value);
},
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| {
f(ctx, x.owner);
f(ctx, x.iref);
},
.iref_eq => |x| {
f(ctx, x.a);
f(ctx, x.b);
},
.task_join_cancel => |x| f(ctx, x.task),
.channel_make => |x| {
f(ctx, x.cap);
@@ -548,7 +592,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
/// `ok`/`err` targets of a fallible allocation terminator.
pub fn allocTargets(op: Op) ?struct { ok: u32, err: u32 } {
return switch (op) {
inline .own_new, .own_array, .region_create, .region_new, .region_array => |x| .{ .ok = x.ok, .err = x.err },
inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| .{ .ok = x.ok, .err = x.err },
else => null,
};
}
@@ -576,7 +620,7 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std.
try buf.append(gpa, ok);
try buf.append(gpa, x.err.?);
},
inline .own_new, .own_array, .region_create, .region_new, .region_array => |x| {
inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| {
try buf.append(gpa, x.ok);
try buf.append(gpa, x.err);
},
+58 -1
View File
@@ -560,12 +560,14 @@ const Parser = struct {
boxed.* = inner;
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
}
const Wrapper = enum { task, sender, receiver, mutex, guard };
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref };
if (std.meta.stringToEnum(Wrapper, t.text)) |which| {
try p.requireFeature(switch (which) {
.task => "tasks",
.sender, .receiver => "channels",
.mutex, .guard => "sync",
.island, .frozen, .iref => "islands",
.arc => "arc",
}, t.span, t.text);
_ = try p.expect(.lt, "`<`");
// Element rules (spec 04 §38.1) are checked by the type stage.
@@ -579,6 +581,10 @@ const Parser = struct {
.receiver => .{ .receiver = boxed },
.mutex => .{ .mutex = boxed },
.guard => .{ .guard = boxed },
.island => .{ .island = boxed },
.frozen => .{ .frozen = boxed },
.arc => .{ .arc = boxed },
.iref => .{ .iref = boxed },
};
}
if (eql(t.text, "cap")) {
@@ -1008,6 +1014,7 @@ const Parser = struct {
break :op .{ .cap_narrow = .{ .form = parts[2], .cap = c, .args = args.items, .ok = ok, .err = err } };
}
if (try p.parseAllocOp(op_tok)) |aop| break :op aop;
if (try p.parseGraphOp(op_tok)) |gop| break :op gop;
if (try p.parseTaskOp(op_tok)) |top| break :op top;
if (try p.parseCoordinationOp(op_tok)) |cop| break :op cop;
if (eql(op_tok.text, "intrinsic")) {
@@ -1038,6 +1045,7 @@ const Parser = struct {
const produces_value = switch (op) {
.own_take, .task_scope_begin, .task_spawn, .task_cancelled => true,
.task_shield_begin, .channel_dup, .mutex_make, .mutex_take, .mutex_borrow => true,
.island_root, .island_borrow, .island_freeze, .frozen_root, .frozen_borrow, .arc_from_frozen, .arc_clone, .arc_root, .arc_borrow, .iref_eq => true,
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
.local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true,
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
@@ -1197,6 +1205,55 @@ const Parser = struct {
}
}
/// Instructions of the features `islands` and `arc` (spec 03 §22–§24).
fn parseGraphOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"island.create", @"island.alloc", @"island.root", @"island.borrow", @"island.freeze", @"island.destroy", @"frozen.root", @"frozen.borrow", @"frozen.release", @"iref.eq", @"arc.from_frozen", @"arc.new", @"arc.clone", @"arc.release", @"arc.root", @"arc.borrow" };
const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null;
try p.requireFeature(if (std.mem.startsWith(u8, op_tok.text, "arc.")) "arc" else "islands", op_tok.span, op_tok.text);
switch (name) {
.@"island.create" => {
const v, const c = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .island_create = .{ .value = v, .cap = c, .ok = ok, .err = err } };
},
.@"island.alloc" => {
const i, const v = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .island_alloc = .{ .island = i, .value = v, .ok = ok, .err = err } };
},
.@"arc.new" => {
const v, const c = try p.twoOperands();
const ok, const err = try p.okErr();
return .{ .arc_new = .{ .value = v, .cap = c, .ok = ok, .err = err } };
},
.@"island.root" => return .{ .island_root = try p.useValue() },
.@"island.freeze" => return .{ .island_freeze = try p.useValue() },
.@"island.destroy" => return .{ .island_destroy = try p.useValue() },
.@"frozen.root" => return .{ .frozen_root = try p.useValue() },
.@"frozen.release" => return .{ .frozen_release = try p.useValue() },
.@"arc.from_frozen" => return .{ .arc_from_frozen = try p.useValue() },
.@"arc.clone" => return .{ .arc_clone = try p.useValue() },
.@"arc.release" => return .{ .arc_release = try p.useValue() },
.@"arc.root" => return .{ .arc_root = try p.useValue() },
.@"island.borrow" => {
const o, const r = try p.twoOperands();
return .{ .island_borrow = .{ .owner = o, .iref = r } };
},
.@"frozen.borrow" => {
const o, const r = try p.twoOperands();
return .{ .frozen_borrow = .{ .owner = o, .iref = r } };
},
.@"arc.borrow" => {
const o, const r = try p.twoOperands();
return .{ .arc_borrow = .{ .owner = o, .iref = r } };
},
.@"iref.eq" => {
const a, const b = try p.twoOperands();
return .{ .iref_eq = .{ .a = a, .b = b } };
},
}
}
/// Instructions of the features `heap` and `regions` (spec 03 §19–§20).
fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op {
const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" };
+26 -1
View File
@@ -122,7 +122,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
},
.region => try w.writeAll("region"),
.scope => try w.writeAll("scope"),
.task, .sender, .receiver, .mutex, .guard => |inner| {
.task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |inner| {
try w.print("{s}<", .{@tagName(t)});
try printType(m, inner.*, w);
try w.writeByte('>');
@@ -397,6 +397,31 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
},
.mutex_borrow => |v| try one(f, w, "mutex.borrow", v),
.mutex_unlock => |v| try one(f, w, "mutex.unlock", v),
.island_create => |x| {
try two(f, w, "island.create", x.value, x.cap);
try okErr(f, w, x.ok, x.err);
},
.island_alloc => |x| {
try two(f, w, "island.alloc", x.island, x.value);
try okErr(f, w, x.ok, x.err);
},
.arc_new => |x| {
try two(f, w, "arc.new", x.value, x.cap);
try okErr(f, w, x.ok, x.err);
},
.island_root => |v| try one(f, w, "island.root", v),
.island_freeze => |v| try one(f, w, "island.freeze", v),
.island_destroy => |v| try one(f, w, "island.destroy", v),
.frozen_root => |v| try one(f, w, "frozen.root", v),
.frozen_release => |v| try one(f, w, "frozen.release", v),
.arc_from_frozen => |v| try one(f, w, "arc.from_frozen", v),
.arc_clone => |v| try one(f, w, "arc.clone", v),
.arc_release => |v| try one(f, w, "arc.release", v),
.arc_root => |v| try one(f, w, "arc.root", v),
.island_borrow => |x| try two(f, w, "island.borrow", x.owner, x.iref),
.frozen_borrow => |x| try two(f, w, "frozen.borrow", x.owner, x.iref),
.arc_borrow => |x| try two(f, w, "arc.borrow", x.owner, x.iref),
.iref_eq => |x| try two(f, w, "iref.eq", x.a, x.b),
.cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form});
try value(f, x.cap, w);
+229 -19
View File
@@ -21,7 +21,8 @@
//! 6. intrinsics (I/O, files, TCP, clock, random), resources, capability
//! narrowing, unsafe operations;
//! 7. task scopes, spawn and join, channels;
//! 8. `lock` and mutexes, `select`, cancellation points, shields.
//! 8. `lock` and mutexes, `select`, cancellation points, shields;
//! 9. islands, frozen graphs, arcs and `iref` handles (spec 03 §22–§24).
const std = @import("std");
const ast = @import("ast.zig");
@@ -67,13 +68,18 @@ pub const Ty = union(enum) {
guard: *const Ty,
/// A shield (`shield { … }`, never a source value).
shield,
/// Graph owners and handles (spec 03 §22–§24).
island: *const Ty,
frozen: *const Ty,
arc: *const Ty,
iref: *const Ty,
pub const Arr = struct { elem: Ty, len: u64 };
/// Linear: consumed exactly once, by `move` (spec 15 §5).
fn isLinear(t: Ty) bool {
return switch (t) {
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield => true,
.own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc => true,
else => false,
};
}
@@ -84,7 +90,7 @@ pub const Ty = union(enum) {
.int => |x| std.mem.eql(u8, x, b.int),
.named => |i| i == b.named,
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.eql(inner(b).?),
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.eql(inner(b).?),
.cap => |k| std.mem.eql(u8, k, b.cap),
.builtin => |e| e == b.builtin,
.resource => |r| r == b.resource,
@@ -94,7 +100,7 @@ pub const Ty = union(enum) {
fn inner(t: Ty) ?Ty {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| x.*,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| x.*,
.array => |a| a.elem,
else => null,
};
@@ -321,7 +327,7 @@ const Lowerer = struct {
.never => "never",
.named => |i| l.typeNames[i],
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow",
.scope => "scope",
.shield => "shield",
.region => "region",
@@ -441,6 +447,8 @@ const Lowerer = struct {
.{ "channels", &.{ "channel.", "sender<", "receiver<", "select [" } },
.{ "sync", &.{ "mutex.", "mutex<", "guard<" } },
.{ "cancellation", &.{ "task.shield", "task.check_cancel", "task.join.cancel" } },
.{ "islands", &.{ "island.", "island<", "frozen.", "frozen<", "iref.", "iref<" } },
.{ "arc", &.{ "arc.", "arc<" } },
};
for (rules) |r| {
const used = for (texts.items) |t| {
@@ -511,7 +519,7 @@ const Lowerer = struct {
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex };
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
const in = try l.typeOf(w.inner.*);
return switch (which) {
@@ -525,6 +533,10 @@ const Lowerer = struct {
.sender => l.wrap(.sender, in),
.receiver => l.wrap(.receiver, in),
.mutex => l.wrap(.mutex, in),
.island => l.wrap(.island, in),
.frozen => l.wrap(.frozen, in),
.arc => l.wrap(.arc, in),
.iref => l.wrap(.iref, in),
};
},
.cap => |k| {
@@ -682,9 +694,12 @@ const Lowerer = struct {
/// that may be read after it (pruned SSA, spec 15 §4). A variable that is
/// not read again is not passed on, so a linear value consumed before the
/// join does not travel to it.
fn carriedLive(l: *Lowerer, depth: usize, construct: Span) Error![]const usize {
fn carriedLive(l: *Lowerer, depth: usize, construct: Span, region: Region) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
for (try l.carried(depth)) |i| if (l.liveAfter(l.bindings.items[i].name, construct)) try out.append(l.arena, i);
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (region.assigns(n) and l.liveAfter(n, construct)) try out.append(l.arena, i);
}
return out.items;
}
@@ -692,9 +707,10 @@ const Lowerer = struct {
/// itself reads (they flow around the back edge).
fn carriedLoop(l: *Lowerer, depth: usize, construct: Span, lp: LoopAst) Error![]const usize {
var out: std.ArrayList(usize) = .empty;
const region: Region = .{ .loop = lp };
for (try l.carried(depth)) |i| {
const n = l.bindings.items[i].name;
if (loopReads(lp, n) or l.liveAfter(n, construct)) try out.append(l.arena, i);
if (region.assigns(n) and (loopReads(lp, n) or l.liveAfter(n, construct))) try out.append(l.arena, i);
}
return out.items;
}
@@ -915,6 +931,8 @@ const Lowerer = struct {
const scope_start = l.scopeBindingStart();
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.endsWith(u8, p, ".at"))
return l.graphAccess(s, x.name, x.mutable, x.place);
const p = try l.uncheckedPlace(x.place, x.mutable, x.unchecked, s.span);
if (p.ends.len == 0) {
// Borrowing a borrow binding: a reborrow, ended at scope end.
@@ -991,7 +1009,7 @@ const Lowerer = struct {
const depth = l.bindings.items.len;
const lp_ast: LoopAst = .{ .cond = cond, .body = body, .step = if (step) |st| st.name else null };
const vars = try l.carriedLoop(depth, span, lp_ast);
const exit_vars = try l.carriedLive(depth, span);
const exit_vars = try l.carriedLive(depth, span, .{ .loop = lp_ast });
const header = try l.newBlock(if (cond == null) "loop" else "while");
const exit = try l.newBlock("after");
const cont = if (step != null) try l.newBlock("step") else header;
@@ -1339,6 +1357,14 @@ const Lowerer = struct {
try l.checkTy(a.span, lv.ty, ty);
const rv = try l.expr(b, ty);
try l.checkTy(b.span, rv.ty, ty);
// `iref` identity (spec 03 §22): equal graph and slot; never a trap.
if (ty == .iref) {
if (op != .eq and op != .ne) return l.fail("E7005", e.span, "`iref` handles are compared with `==` and `!=` only", &.{});
const c = try l.def("cmp", .bool, try l.fmt("iref.eq %{s}, %{s}", .{ lv.name, rv.name }), e.span);
if (op == .eq) return c;
const t = try l.def("c", .bool, "const.bool true", e.span);
return l.def("cmp", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ c.name, t.name }), e.span);
}
if (ty == .bool and !(op == .eq or op == .ne or op == .bit_and or op == .bit_or or op == .bit_xor))
return l.fail("E7005", e.span, "this operation needs integer operands", &.{});
if (ty != .bool and ty != .int) return l.fail("E7005", e.span, "this operation needs integer or boolean operands", &.{});
@@ -1565,7 +1591,7 @@ const Lowerer = struct {
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
const sv = try l.expr(m.scrutinee, st);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span);
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
var ends: std.ArrayList(ArmEnd) = .empty;
@@ -1659,7 +1685,7 @@ const Lowerer = struct {
const name = @tagName(b);
const sv = try l.expr(m.scrutinee, .{ .builtin = b });
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span);
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
const blocks = try l.arena.alloc(usize, m.arms.len);
var head: std.ArrayList(u8) = .empty;
@@ -1699,6 +1725,11 @@ const Lowerer = struct {
const eq = std.mem.eql;
if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null;
if (eq(u8, p, "task.cancelled")) return .bool;
if ((eq(u8, p, "island.root") or eq(u8, p, "frozen.root") or eq(u8, p, "arc.root")) and args.len == 1)
return if (l.peekType(args[0])) |t| (if (t.inner()) |o| (if (o.inner()) |root| l.wrap(.iref, root) catch null else null) else null) else null;
if (eq(u8, p, "island.freeze") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
if (eq(u8, p, "task.spawn") and args.len >= 2 and args[1].kind == .name) {
const sig = l.sigs.get(args[1].kind.name) orelse return null;
@@ -1860,7 +1891,8 @@ const Lowerer = struct {
.own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*),
.own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*),
.region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region),
.resource, .mutex, .sender, .receiver, .task => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty),
.frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty),
else => null,
};
const t = bt orelse return l.fail("E7006", place.span, "this value is not addressable here; borrow a variable, a field or an element", &.{.{ .name = "name", .value = n }});
@@ -2117,7 +2149,7 @@ const Lowerer = struct {
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel" };
const ops = [_][]const u8{ "own.new", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" };
for (ops) |o| if (std.mem.eql(u8, o, path)) return {};
if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {};
return null;
@@ -2206,6 +2238,41 @@ const Lowerer = struct {
try l.endNow(temps.items, e.span);
return v;
}
if (eq(p, "island.root") or eq(p, "frozen.root") or eq(p, "arc.root")) {
if (args.len != 1) return l.fail("E7005", e.span, "`.root` takes the graph's borrow binding", &.{});
const g = try l.graphBorrow(args[0], p[0..std.mem.indexOfScalar(u8, p, '.').?], false);
return try l.def("root", try l.wrap(.iref, g.ty.inner().?.inner().?), try l.fmt("{s} %{s}", .{ p, g.name }), e.span);
}
if (eq(p, "island.freeze") or eq(p, "arc.from_frozen")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
const o = try l.consuming(args[0], null);
const want: std.meta.Tag(Ty) = if (eq(p, "island.freeze")) .island else .frozen;
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island<T>`" else "`arc.from_frozen` takes a `frozen<T>`", &.{.{ .name = "found", .value = l.tyText(o.ty) }});
const out = if (want == .island) try l.wrap(.frozen, o.ty.inner().?) else try l.wrap(.arc, o.ty.inner().?);
return try l.def(if (want == .island) "frozen" else "arc", out, try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
}
if (eq(p, "island.destroy") or eq(p, "frozen.release") or eq(p, "arc.release")) {
if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{});
const o = try l.consuming(args[0], null);
const want: std.meta.Tag(Ty) = if (eq(p, "island.destroy")) .island else if (eq(p, "frozen.release")) .frozen else .arc;
if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = l.tyText(o.ty) } });
try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span);
return .{ .name = "", .ty = .void };
}
if (eq(p, "arc.clone")) {
if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`arc.clone` takes an arc by name", &.{});
const b = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name);
if (b.ty == .arc) {
const r = try l.def(args[0].kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), args[0].span);
const v = try l.def("arc", b.ty, try l.fmt("arc.clone %{s}", .{r.name}), e.span);
try l.emit(try l.fmt("borrow.end %{s}", .{r.name}), e.span);
return v;
}
if (b.ty == .ref and b.ty.inner().? == .arc) return try l.def("arc", b.ty.inner().?, try l.fmt("arc.clone %{s}", .{b.value}), e.span);
return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc<T>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }});
}
if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at"))
return l.fail("E7006", e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{});
if (eq(p, "mutex.make")) {
if (args.len != 1) return l.fail("E7005", e.span, "`mutex.make` takes the initial value", &.{});
const v = try l.consuming(args[0], null);
@@ -2248,7 +2315,7 @@ const Lowerer = struct {
};
const elem = mr.ty.ref.mutex.*;
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const vars = try l.carriedLive(depth, s.span, .{ .lock = .{ body, cancelled } });
const before = try l.snapshot();
const locked = try l.newBlock("locked");
const guard = try l.freshName("guard");
@@ -2358,7 +2425,7 @@ const Lowerer = struct {
}
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, s.span);
const vars = try l.carriedLive(depth, s.span, .{ .select = sel });
const before = try l.snapshot();
var text: std.ArrayList(u8) = .empty;
try text.appendSlice(l.arena, "select ");
@@ -2436,6 +2503,37 @@ const Lowerer = struct {
};
}
/// The named borrow binding of a graph owner that `.root`, `.at` and
/// `island.alloc` take (spec 15 §8: container borrows are explicit).
fn graphBorrow(l: *Lowerer, a: ast.Expr, owner: []const u8, mutable: bool) Error!Value {
if (a.kind == .borrow) return l.fail("E7006", a.span, "the graph's borrow is bound first (`mut g = isl;`), so it outlives the borrows taken from it", &.{});
if (a.kind != .name) return l.fail("E7005", a.span, "the graph's borrow binding is expected here, by name", &.{});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?;
if (std.meta.activeTag(b.ty) == tag) return l.fail("E7005", a.span, try l.fmt("this takes a borrow of the {s}, not the owner: bind `{s} g = {s};` in an enclosing block and pass `g`", .{ owner, if (mutable) "mut" else "ref", a.kind.name }), &.{.{ .name = "name", .value = a.kind.name }});
const ok = (b.ty == .ref or (b.ty == .mut and !mutable) or (b.ty == .mut and mutable)) and std.meta.activeTag(b.ty.inner().?) == tag;
if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}<T>` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = l.tyText(b.ty) }});
return .{ .name = b.value, .ty = b.ty };
}
/// `ref x = island.at(g, r);` / `mut x = island.at(g, r);`, and
/// `frozen.at`, `arc.at` (`ref` only): a child borrow of `g`.
fn graphAccess(l: *Lowerer, s: ast.Stmt, name: []const u8, mutable: bool, place: ast.Expr) Error!void {
const ac = place.kind.call;
const p = pathOf(ac.callee.*).?;
const owner = p[0..std.mem.indexOfScalar(u8, p, '.').?];
if (mutable and !std.mem.eql(u8, owner, "island")) return l.fail("E7005", s.span, "frozen graphs and arcs give `ref` access only", &.{});
if (ac.args.len != 2) return l.fail("E7005", place.span, "`.at` takes the graph's borrow binding and an `iref`", &.{});
const g = try l.graphBorrow(ac.args[0], owner, mutable);
const r = try l.expr(ac.args[1], null);
if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.tyText(r.ty) }});
const op = if (std.mem.eql(u8, owner, "island")) "island.borrow" else if (std.mem.eql(u8, owner, "frozen")) "frozen.borrow" else "arc.borrow";
const target = r.ty.inner().?;
const v = try l.def(name, if (mutable) try l.wrap(.mut, target) else try l.wrap(.ref, target), try l.fmt("{s} %{s}, %{s}", .{ op, g.name, r.name }), s.span);
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = name, .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
}
fn resultTy(r: authority.ResultType) Ty {
return switch (r) {
.usize => .{ .int = "usize" },
@@ -2575,6 +2673,19 @@ const Lowerer = struct {
.temps = temps.items,
};
}
if (std.mem.eql(u8, path, "island.create") or std.mem.eql(u8, path, "arc.new")) {
try want(l, e.span, args, 2, path);
const v = try l.consuming(args[0], null);
const c = try l.expectCap(args[1], "mem.alloc");
const owner = if (std.mem.eql(u8, path, "arc.new")) try l.wrap(.arc, v.ty) else try l.wrap(.island, v.ty);
return .{ .text = try l.fmt("{s} %{s}, %{s}", .{ path, v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{owner} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "island.alloc")) {
try want(l, e.span, args, 2, path);
const g = try l.graphBorrow(args[0], "island", true);
const v = try l.consuming(args[1], null);
return .{ .text = try l.fmt("island.alloc %{s}, %{s}", .{ g.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.iref, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "task.check_cancel")) {
try want(l, e.span, args, 0, path);
return .{ .text = "task.check_cancel", .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "cancelled", .params = &.{} } }) };
@@ -2690,7 +2801,7 @@ const Lowerer = struct {
if (missing.items.len != 0) return l.fail("E7004", m.span, "the match does not handle every outcome of the operation", &.{.{ .name = "missing", .value = missing.items }});
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, m.span);
const vars = try l.carriedLive(depth, m.span, .{ .match = m });
const before = try l.snapshot();
const blocks = try l.outcomeBlocks(f, m.scrutinee.span);
var ends: std.ArrayList(ArmEnd) = .empty;
@@ -2763,7 +2874,7 @@ const Lowerer = struct {
};
try l.checkTy(x.cond.span, cv.ty, .bool);
const depth = l.bindings.items.len;
const vars = try l.carriedLive(depth, span);
const vars = try l.carriedLive(depth, span, .{ .@"if" = x });
const then_b = try l.newBlock("then");
const else_b = try l.newBlock("else");
try l.term(try l.fmt("cbr %{s}, @{s}(), @{s}()", .{ cv.name, l.blocks.items[then_b].name, l.blocks.items[else_b].name }), x.cond.span);
@@ -2813,7 +2924,10 @@ fn pathOf(e: ast.Expr) ?[]const u8 {
"cap.narrow.budget", "cap.narrow.prefix", "task.spawn", "task.join", "task.cancel",
"task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv",
"channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel",
"task.join_cancel",
"task.join_cancel", "island.create", "island.alloc", "island.root", "island.at",
"island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release",
"arc.from_frozen", "arc.new", "arc.clone", "arc.release", "arc.root",
"arc.at",
};
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return null;
@@ -3077,3 +3191,99 @@ const After = struct {
};
}
};
/// The code of a branching construct, for deciding which variables it
/// assigns: a join carries only variables that may change inside.
const Region = union(enum) {
loop: LoopAst,
@"if": ast.If,
match: ast.Match,
lock: struct { ast.Block, ast.Block },
select: ast.Select,
fn assigns(r: Region, name: []const u8) bool {
return switch (r) {
.loop => |lp| (if (lp.step) |st| std.mem.eql(u8, st, name) else false) or (if (lp.cond) |c| exprAssigns(c, name) else false) or blockAssigns(lp.body, name),
.@"if" => |x| ifAssigns(x, name),
.match => |m| matchAssigns(m, name),
.lock => |b| blockAssigns(b[0], name) or blockAssigns(b[1], name),
.select => |x| selectAssigns(x, name),
};
}
};
/// Whether code assigns variable `name`: `name = e;`, or a pattern of an
/// outcome or `select` edge rebinding it (spec 15 §6).
fn blockAssigns(b: ast.Block, name: []const u8) bool {
for (b.stmts) |st| if (stmtAssigns(st, name)) return true;
if (b.tail) |t| if (exprAssigns(t.*, name)) return true;
return false;
}
fn stmtAssigns(st: ast.Stmt, name: []const u8) bool {
return switch (st.kind) {
.assign => |x| (x.place.kind == .name and std.mem.eql(u8, x.place.kind.name, name)) or exprAssigns(x.e, name),
.let => |x| exprAssigns(x.e, name),
.@"var" => |x| if (x.init) |e| exprAssigns(e, name) else false,
.borrow => |x| exprAssigns(x.place, name),
.@"return" => |e| if (e) |x| exprAssigns(x, name) else false,
.expr => |e| exprAssigns(e, name),
.@"while" => |x| exprAssigns(x.cond, name) or blockAssigns(x.body, name),
.@"for" => |x| std.mem.eql(u8, x.name, name) or blockAssigns(x.body, name),
.loop, .shield => |b| blockAssigns(b, name),
.scope => |x| blockAssigns(x.body, name),
.lock => |x| blockAssigns(x.body, name) or blockAssigns(x.cancelled, name),
.select => |x| selectAssigns(x, name),
.@"break", .@"continue", .trap => false,
};
}
fn exprAssigns(e: ast.Expr, name: []const u8) bool {
return switch (e.kind) {
.if_expr => |x| ifAssigns(x.*, name),
.match_expr => |x| matchAssigns(x.*, name),
.block => |b| blockAssigns(b.*, name),
.neg, .not, .deref, .or_trap => |x| exprAssigns(x.*, name),
.binary => |x| exprAssigns(x.l.*, name) or exprAssigns(x.r.*, name),
.cast => |x| exprAssigns(x.e.*, name),
.call => |x| blk: {
for (x.args) |a| if (exprAssigns(a, name)) break :blk true;
break :blk false;
},
.struct_lit => |x| blk: {
for (x.fields) |f| if (exprAssigns(f.e, name)) break :blk true;
break :blk false;
},
.field => |x| exprAssigns(x.e.*, name),
.index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false),
.array_rep => |x| exprAssigns(x.e.*, name),
else => false,
};
}
fn ifAssigns(x: ast.If, name: []const u8) bool {
if (exprAssigns(x.cond, name) or blockAssigns(x.then, name)) return true;
if (x.@"else") |els| return switch (els) {
.block => |b| blockAssigns(b, name),
.@"if" => |inner| ifAssigns(inner.*, name),
};
return false;
}
fn matchAssigns(m: ast.Match, name: []const u8) bool {
if (exprAssigns(m.scrutinee, name)) return true;
for (m.arms) |a| {
if (a.pattern.kind == .ctor) for (a.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
if (exprAssigns(a.body, name)) return true;
}
return false;
}
fn selectAssigns(x: ast.Select, name: []const u8) bool {
for (x.arms) |a| for (a.arms) |arm| {
if (arm.pattern.kind == .ctor) for (arm.pattern.kind.ctor.binds) |b| if (std.mem.eql(u8, b, name)) return true;
if (exprAssigns(arm.body, name)) return true;
};
for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true;
return exprAssigns(x.cancelled, name);
}
+261 -2
View File
@@ -67,11 +67,28 @@ pub const Value = union(enum) {
/// `mutex<T>` and the `guard<T>` that holds it.
mutex: *MutexCell,
guard: *MutexCell,
/// `island<T>`, `frozen<T>`, `arc<T>`: the graph (spec 03 §22–§24). The
/// ownership mode is the static type; the graph is the same object.
graph: *Graph,
/// `iref<T>`: graph identity and slot; opaque to programs.
iref: struct { id: u64, slot: u32 },
/// The guarded value is a separate cell, so a place borrowed through a
/// guard points at an ordinary cell.
pub const MutexCell = struct { locked: bool, cell: *Cell };
/// A graph: object cells addressed by slot, an identity never reused in
/// the execution, the authority it charges and the bytes it holds.
pub const Graph = struct {
id: u64,
objects: std.ArrayList(*Cell) = .empty,
authority: u32,
bytes: u64,
/// `arc` handles alive (0 while unique: island or frozen).
count: u64 = 0,
frozen: bool = false,
};
pub const Aggregate = struct {
decl: u32,
/// Active variant for enums; 0 for structs.
@@ -148,9 +165,16 @@ pub const MemoryStats = struct {
peak_live: usize = 0,
/// Largest execution heap before a collection, in heap bytes.
peak_heap: usize = 0,
/// Instructions executed.
steps: u64 = 0,
};
/// One `arc` count change (spec 03 §24: every change appears in the trace).
pub const ArcEvent = struct { op: enum { new, from_frozen, clone, release }, graph: u64, count: u64 };
pub const Options = struct {
/// Trace mode for `arc` counts: every change is appended (spec 11 §2).
arc_events: ?*std.ArrayList(ArcEvent) = null,
/// Filled with execution-heap statistics when set.
memory: ?*MemoryStats = null,
/// Collect before every instruction (tests: a missed root then fails).
@@ -237,6 +261,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
}
m.exec_heap.every_step = options.collect_every_step;
m.arc_events = options.arc_events;
if (options.collect_threshold) |t| {
m.exec_heap.floor = t;
m.exec_heap.threshold = t;
@@ -251,6 +276,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
result = .{ .returned = try c.value(outcome.returned) };
}
m.exec_heap.stats.peak_heap = @max(m.exec_heap.stats.peak_heap, m.exec_heap.space.queryCapacity());
m.exec_heap.stats.steps = m.steps;
if (options.memory) |st| st.* = m.exec_heap.stats;
m.exec_heap.space.deinit();
return result;
@@ -264,6 +290,7 @@ const Copier = struct {
cells: std.AutoHashMapUnmanaged(*Value.Cell, *Value.Cell) = .empty,
mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty,
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty,
fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value {
return switch (v) {
@@ -275,7 +302,8 @@ const Copier = struct {
.slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } },
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
.guard => |mc| .{ .guard = try c.mutex(mc) },
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver => v,
.graph => |g| .{ .graph = try c.graph(g) },
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref => v,
};
}
@@ -308,6 +336,17 @@ const Copier = struct {
return n;
}
fn graph(c: *Copier, old: *Value.Graph) std.mem.Allocator.Error!*Value.Graph {
if (c.graphs.get(old)) |n| return n;
const n = try c.to.create(Value.Graph);
try c.graphs.put(c.tmp, old, n);
n.* = old.*;
n.objects = .empty;
try n.objects.ensureTotalCapacity(c.to, old.objects.items.len);
for (old.objects.items) |cl| n.objects.appendAssumeCapacity(try c.cell(cl));
return n;
}
fn place(c: *Copier, p: Value.Place) std.mem.Allocator.Error!Value.Place {
return .{ .cell = try c.cell(p.cell), .path = if (p.path.len == 0) &.{} else try c.to.dupe(u32, p.path) };
}
@@ -323,6 +362,7 @@ const TrapKind = enum {
call_depth,
out_of_bounds,
unsafe_precondition,
foreign_iref,
fn code(k: TrapKind) *const diag.Code {
return switch (k) {
@@ -335,6 +375,7 @@ const TrapKind = enum {
.call_depth => diag.lookup("T0007").?,
.out_of_bounds => diag.lookup("T0008").?,
.unsafe_precondition => diag.lookup("T0009").?,
.foreign_iref => diag.lookup("T0010").?,
};
}
};
@@ -422,6 +463,9 @@ pub const Heap = struct {
const Machine = struct {
arena: std.mem.Allocator,
exec_heap: Heap = .{},
/// Next graph identity; identities are never reused (spec 03 §22).
next_graph: u64 = 1,
arc_events: ?*std.ArrayList(ArcEvent) = null,
module: air.Module,
fuel: ?u64,
tasks: std.ArrayList(Task) = .empty,
@@ -750,6 +794,7 @@ const Machine = struct {
.channel_make, .channel_dup, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => return m.execChannel(f, vals, inst),
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
.island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
@@ -1259,10 +1304,124 @@ const Machine = struct {
.array => |items| std.math.mul(u64, items.len, m.valueBytes(items[0]) orelse return null) catch null,
.builtin => |b| budget.accountedSize(m.module, .{ .builtin = b.which }, 0),
.cap => 8,
.iref => 16,
else => unreachable, // only value types are allocated (spec 03 §19.2)
};
}
// ------------------------------------------------------------ graphs (spec 03 §22–§24)
/// A graph's header, charged once at creation; it includes room for an
/// `arc` count, so converting to an `arc` charges nothing (spec 03 §24).
const graph_header = 16;
/// The graph behind an owner or a borrow of one.
fn graphOf(v: Value) *Value.Graph {
return switch (v) {
.graph => |g| g,
.place => |p| placePtr(p).graph,
else => unreachable,
};
}
fn arcEvent(m: *Machine, op: @FieldType(ArcEvent, "op"), g: *Value.Graph) !void {
if (m.arc_events) |list| try list.append(m.arena, .{ .op = op, .graph = g.id, .count = g.count });
}
fn newGraph(m: *Machine, a: u32, bytes: u64, root: Value) !*Value.Graph {
const g = try m.heap().create(Value.Graph);
g.* = .{ .id = m.next_graph, .authority = a, .bytes = bytes };
m.next_graph += 1;
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(root), .ty = .void };
try g.objects.append(m.heap(), cell);
return g;
}
/// Frees a graph's objects and returns its bytes to its authority.
fn releaseGraph(m: *Machine, g: *Value.Graph) void {
m.uncharge(g.authority, g.bytes);
g.bytes = 0;
g.objects = .empty;
}
/// The object an `iref` names in graph `g`, or `T0010`.
fn objectOf(g: *Value.Graph, r: Value) ?*Value.Cell {
if (r.iref.id != g.id or r.iref.slot >= g.objects.items.len) return null;
return g.objects.items[r.iref.slot];
}
fn execGraph(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
switch (inst.op) {
inline .island_create, .arc_new => |x| {
const v = vals[x.value];
const a = vals[x.cap].cap;
const bytes = if (m.valueBytes(v)) |b| (std.math.add(u64, b, graph_header) catch null) else null;
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
const g = try m.newGraph(a, bytes.?, v);
if (inst.op == .arc_new) {
g.frozen = true;
g.count = 1;
try m.arcEvent(.new, g);
}
vals[f.blocks[x.ok].params[0].value] = .{ .graph = g };
return .{ .jump = x.ok };
},
.island_alloc => |x| {
const g = graphOf(vals[x.island]);
const v = vals[x.value];
const bytes = m.valueBytes(v);
if (!m.charge(g.authority, bytes)) return allocFailed(f, vals, x.err);
g.bytes += bytes.?;
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
try g.objects.append(m.heap(), cell);
vals[f.blocks[x.ok].params[0].value] = .{ .iref = .{ .id = g.id, .slot = @intCast(g.objects.items.len - 1) } };
return .{ .jump = x.ok };
},
.island_root, .frozen_root, .arc_root => |v| return bind(vals, inst.result, .{ .iref = .{ .id = graphOf(vals[v]).id, .slot = 0 } }),
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| {
const g = graphOf(vals[x.owner]);
const cell = objectOf(g, vals[x.iref]) orelse return .{ .trap = .foreign_iref };
return bind(vals, inst.result, .{ .place = .{ .cell = cell, .path = &.{} } });
},
.island_freeze => |v| {
const g = vals[v].graph;
g.frozen = true;
return bind(vals, inst.result, .{ .graph = g });
},
.island_destroy, .frozen_release => |v| {
m.releaseGraph(vals[v].graph);
return .next;
},
.arc_from_frozen => |v| {
const g = vals[v].graph;
g.count = 1;
try m.arcEvent(.from_frozen, g);
return bind(vals, inst.result, .{ .graph = g });
},
.arc_clone => |v| {
const g = graphOf(vals[v]);
g.count += 1;
try m.arcEvent(.clone, g);
return bind(vals, inst.result, .{ .graph = g });
},
.arc_release => |v| {
const g = vals[v].graph;
g.count -= 1;
try m.arcEvent(.release, g);
if (g.count == 0) m.releaseGraph(g);
return .next;
},
.iref_eq => |x| {
const a = vals[x.a].iref;
const b = vals[x.b].iref;
return bind(vals, inst.result, .{ .boolean = a.id == b.id and a.slot == b.slot });
},
else => unreachable,
}
}
fn allocFailed(f: air.Function, vals: []Value, err: u32) Step {
vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } };
return .{ .jump = err };
@@ -1698,7 +1857,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
},
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null),
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => try s.write(null),
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
@@ -2159,3 +2318,103 @@ test "execution memory is bounded by live state, not by the iteration count" {
try std.testing.expect(large.peak_heap <= 3 * floor + 64 * 1024);
}
}
test "arc count changes appear in the trace, and the last release frees the graph" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src =
\\module t
\\fn main(heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc]
\\{
\\ let isl = island.create(7u64, heap) or trap;
\\ let a = arc.from_frozen(island.freeze(move isl));
\\ let b = arc.clone(a);
\\ arc.release(move a);
\\ var v: u64 = 0;
\\ {
\\ ref br = b;
\\ let r = arc.root(br);
\\ ref x = arc.at(br, r);
\\ v = *x;
\\ }
\\ arc.release(move b);
\\ // The budget (16 + 8 bytes) is free again: the same graph fits once more.
\\ let again = arc.new(5u64, heap) or trap;
\\ arc.release(move again);
\\ v
\\}
;
const report = try check.checkFile(arena, "t.aji", src);
if (report.status != .accepted) {
for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message });
return error.NotAccepted;
}
var events: std.ArrayList(ArcEvent) = .empty;
const outcome = try run(arena, report.module.?, "main", .{
.grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "24" }},
.arc_events = &events,
});
try std.testing.expect(outcome == .returned);
try std.testing.expectEqual(@as(u128, 7), outcome.returned.int.bits);
const Op = @FieldType(ArcEvent, "op");
const want = [_]struct { Op, u64 }{ .{ .from_frozen, 1 }, .{ .clone, 2 }, .{ .release, 1 }, .{ .release, 0 }, .{ .new, 1 }, .{ .release, 0 } };
try std.testing.expectEqual(want.len, events.items.len);
for (want, events.items) |w, e| {
try std.testing.expectEqual(w[0], e.op);
try std.testing.expectEqual(w[1], e.count);
}
// One graph identity through island → frozen → arc; the second graph is new.
try std.testing.expectEqual(events.items[0].graph, events.items[3].graph);
try std.testing.expect(events.items[4].graph != events.items[0].graph);
}
// Transfer is O(1) in the graph size (spec 03 §22): moving an island through
// a channel K times costs the same number of instructions for a graph of 10
// nodes as for one of 1000.
fn transferSteps(nodes: u64, sends: u64) !u64 {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src = try std.fmt.allocPrint(arena,
\\module t
\\fn main(heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc, task.wait]
\\{{
\\ var isl: island<u64> = island.create(0u64, heap) or trap;
\\ {{
\\ mut g = isl;
\\ for i in 0..{d}u64 {{ let r = island.alloc(g, i) or trap; }}
\\ }}
\\ match channel.make<island<u64>>(1, heap) {{
\\ ok(tx, rx) => {{
\\ for k in 0..{d}u64 {{
\\ channel.send(tx, move isl) or trap;
\\ isl = channel.recv(rx) or trap;
\\ }}
\\ channel.close_sender(move tx);
\\ channel.close_receiver(move rx) or trap;
\\ }}
\\ err(e) => {{ trap; }}
\\ }}
\\ island.destroy(move isl);
\\ 0
\\}}
, .{ nodes, sends });
const report = try check.checkFile(arena, "t.aji", src);
if (report.status != .accepted) {
for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message });
return error.NotAccepted;
}
var stats: MemoryStats = .{};
const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "1000000" }}, .memory = &stats });
try std.testing.expect(outcome == .returned);
return stats.steps;
}
test "moving an island costs the same for any graph size" {
const small = try transferSteps(10, 10) - try transferSteps(10, 0);
const large = try transferSteps(1000, 10) - try transferSteps(1000, 0);
try std.testing.expectEqual(small, large);
}
+1 -1
View File
@@ -61,7 +61,7 @@ fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo {
_ = try addOnce(arena, &info.intrinsics, reg.name);
if (reg.effect) |e| _ = try addOnce(arena, &info.direct, e);
},
.own_new, .own_array, .region_new, .region_array, .region_create, .channel_make => {
.own_new, .own_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => {
info.allocations += 1;
_ = try addOnce(arena, &info.direct, "mem.alloc");
},
+15 -1
View File
@@ -264,7 +264,7 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void
try out.append(arena, .{ .target = ok, .args = &.{} });
try out.append(arena, .{ .target = x.err.?, .args = &.{} });
},
.own_new, .own_array, .region_create, .region_new, .region_array => {
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => {
const t = air.allocTargets(op).?;
try out.append(arena, .{ .target = t.ok, .args = &.{} });
try out.append(arena, .{ .target = t.err, .args = &.{} });
@@ -585,6 +585,20 @@ fn step(w: *Walker, inst: air.Inst) !void {
w.live[g] = false;
w.dead[g] = .closed;
},
// Graphs (spec 03 §22–§24). An access is a child borrow of the
// container borrow; a `mut` child is exclusive for the whole island.
.island_alloc => |x| try w.useThrough(x.island, .exclusive),
.island_root, .frozen_root, .arc_root => |v| _ = try w.usable(v),
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| try w.derive(inst.result.?, x.owner, .elem),
.island_freeze, .arc_from_frozen => |v| {
try w.consume(v, .moved);
w.live[inst.result.?] = true;
},
.island_destroy, .frozen_release, .arc_release => |v| try w.consume(v, .closed),
.arc_clone => |v| {
try lendArgs(w, &.{v});
w.live[inst.result.?] = true;
},
// Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage.
else => {},
+2 -1
View File
@@ -28,7 +28,8 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
return switch (t) {
.int => |it| it.bits() / 8,
.bool => 1,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard => 8,
.ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard, .island, .frozen, .arc => 8,
.iref => 16,
.mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null,
.own_array => 16,
.slice, .slice_mut => 16,
+1 -1
View File
@@ -79,7 +79,7 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter");
try paramCount(c, f, inst.span, x.err, 1, "cap.narrow `err` target takes exactly one parameter");
},
.own_new, .own_array, .region_create, .region_new, .region_array => {
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => {
const t = air.allocTargets(inst.op).?;
try paramCount(c, f, inst.span, t.ok, 1, "allocation `ok` target takes exactly one parameter");
try paramCount(c, f, inst.span, t.err, 1, "allocation `err` target takes exactly one parameter");
+1 -1
View File
@@ -50,7 +50,7 @@ pub fn check(c: *Context) !void {
.task_join => if (m.declares("cancellation")) try need(c, f, inst, "task.wait"),
.task_join_cancel, .channel_send, .channel_recv, .select, .mutex_lock => try need(c, f, inst, "task.wait"),
.channel_make => try need(c, f, inst, "mem.alloc"),
.own_new, .own_array, .region_create, .region_new, .region_array => if (!contains(f.effects, "mem.alloc")) {
.own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) {
try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "effect", .value = .{ .str = "mem.alloc" } },
+107 -3
View File
@@ -85,7 +85,7 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.void, .never => pos == .ret,
.local => false,
.ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => pos != .member,
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc => pos != .member,
else => true,
};
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
@@ -93,6 +93,15 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
.{ .name = "found", .value = .{ .str = try c.typeName(t) } },
});
// A graph holds IslandSafe values only (spec 03 §22–§24): reported once,
// as E2111, at the type.
if (t.isGraphOwner()) {
if (!isIslandSafe(c.module, t.inner().?)) try c.report("E2111", span, "a graph holds only plain data and iref handles", &.{
.{ .name = "in", .value = .{ .str = owner } },
.{ .name = "found", .value = .{ .str = try c.typeName(t.inner().?) } },
});
return;
}
// The pointee of ref/mut may be a linear value (`mut<file<read>>`), and
// a task may return one; every other compound holds value types only.
// Channel elements and mutex contents may be linear (spec 04 §38.1);
@@ -226,6 +235,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
.task_scope_begin => .scope,
.task_cancelled => .bool,
.task_shield_begin => .shield,
.iref_eq => .bool,
.intrinsic => |x| blk: {
const reg = air.authority.intrinsics[x.index];
if (reg.fallible or reg.results.len == 0) break :blk .void;
@@ -327,6 +337,8 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")
pub fn isSend(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true,
// Graph contents are IslandSafe plain data (spec 03 §22–§24).
.island, .frozen, .arc, .iref => true,
.own, .own_array, .mutex => |inner| isSend(m, inner.*),
.ref, .slice => |inner| isShare(m, inner.*),
.mut, .slice_mut => |inner| isSend(m, inner.*),
@@ -340,6 +352,9 @@ pub fn isSend(m: air.Module, t: Type) bool {
pub fn isShare(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap => true,
.frozen, .arc, .iref => true,
// Its owner may mutate it: freeze to share (spec 04 §35).
.island => false,
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
.own, .own_array, .ref, .slice => |inner| isShare(m, inner.*),
// The lock synchronizes access (spec 04 §35, §40).
@@ -349,6 +364,17 @@ pub fn isShare(m: air.Module, t: Type) bool {
};
}
/// `IslandSafe` (spec 02 §6): plain data and `iref` handles, at any depth.
/// `ArcSafe` is the same set in format 0.
pub fn isIslandSafe(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .iref => true,
.array => |a| isIslandSafe(m, a.elem),
.named => |i| aggregateAll(m, i, isIslandSafe),
else => false,
};
}
fn aggregateAll(m: air.Module, i: u32, comptime pred: fn (air.Module, Type) bool) bool {
return switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
@@ -425,6 +451,8 @@ fn contains(m: air.Module, t: Type, comptime what: enum { endpoint, forbidden })
.forbidden => t.isBorrow() or t.isTaskBound() or t == .guard,
};
if (here) return true;
// An `iref<T>` holds no `T`: types may recurse through it (spec 03 §22).
if (t == .iref) return false;
if (t.inner()) |inner| if (t != .ref and t != .mut and t != .slice and t != .slice_mut) return contains(m, inner, what);
return switch (t) {
.named => |i| switch (m.types[i].kind) {
@@ -497,6 +525,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.channel_dup, .mutex_take, .mutex_borrow => |v| fc.ty[v] orelse return null,
.mutex_make => |v| return .{ .mutex = try boxed(a, fc.ty[v] orelse return null) },
.slice_split => |x| fc.ty[x.slice] orelse return null,
.island_root, .frozen_root, .arc_root, .island_freeze, .arc_from_frozen, .arc_clone => |v| fc.ty[v] orelse return null,
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| fc.ty[x.owner] orelse return null,
else => return null,
};
const invalid: Type = .void;
@@ -504,7 +534,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.resource, .region, .task, .scope, .sender, .receiver, .mutex => .{ .ref = try boxed(a, t) },
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc => .{ .ref = try boxed(a, t) },
.own => |inner| .{ .ref = inner },
.own_array => |inner| .{ .slice = inner },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
@@ -512,7 +542,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.resource, .region, .task, .scope, .sender, .receiver => .{ .mut = try boxed(a, t) },
.resource, .region, .task, .scope, .sender, .receiver, .island => .{ .mut = try boxed(a, t) },
.own => |inner| .{ .mut = inner },
.own_array => |inner| .{ .slice_mut = inner },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
@@ -548,10 +578,44 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
.channel_dup => if (t == .ref and t.ref.* == .sender) t.ref.* else invalid,
.mutex_take => if (t == .mutex) t.mutex.* else invalid,
.mutex_borrow => if (t == .guard) Type{ .mut = t.guard } else invalid,
// Graph roots and handles (spec 03 §22–§24).
.island_root => graphRoot(t, .island),
.frozen_root => graphRoot(t, .frozen),
.arc_root => graphRoot(t, .arc),
.island_freeze => if (t == .island) Type{ .frozen = t.island } else invalid,
.arc_from_frozen => if (t == .frozen) Type{ .arc = t.frozen } else invalid,
.arc_clone => if (t == .ref and t.ref.* == .arc) t.ref.* else invalid,
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| blk: {
const owner: std.meta.Tag(Type) = switch (op) {
.island_borrow => .island,
.frozen_borrow => .frozen,
else => .arc,
};
const r = fc.ty[x.iref] orelse return null;
if (r != .iref) break :blk invalid;
const target = try boxed(a, r.iref.*);
if (t == .ref and std.meta.activeTag(t.ref.*) == owner) break :blk Type{ .ref = target };
if (owner == .island and t == .mut and t.mut.* == .island) break :blk Type{ .mut = target };
break :blk invalid;
},
else => unreachable,
};
}
/// `iref<T>` of the root of a graph reached through `ref`/`mut` of its owner.
fn graphRoot(t: Type, owner: std.meta.Tag(Type)) Type {
const inner = switch (t) {
.ref, .mut => |x| x.*,
else => return .void,
};
if (std.meta.activeTag(inner) != owner) return .void;
if (t == .mut and owner != .island) return .void;
return .{ .iref = switch (inner) {
.island, .frozen, .arc => |x| x,
else => unreachable,
} };
}
fn checkFunction(c: *Context, f: air.Function) ![]const Type {
const m = c.module;
var fc: FnCtx = .{ .c = c, .f = f, .ty = try c.arena.alloc(?Type, f.values.len) };
@@ -817,6 +881,37 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
try fc.expectParams(span, x.ok, &.{.{ .guard = t.ref.mutex }});
},
.mutex_borrow, .mutex_unlock => |v| if (fc.typeOf(v) != .guard) try fc.kindError(span, v, "guard<T>"),
inline .island_create, .arc_new => |x| {
try fc.expectAllocCap(span, x.cap);
const t = fc.typeOf(x.value);
// A non-IslandSafe content is reported at the owner type (E2111).
if (!isIslandSafe(m, t)) return;
const b = try boxed(fc.c.arena, t);
try fc.expectOkErr(span, x.ok, x.err, if (inst.op == .arc_new) Type{ .arc = b } else Type{ .island = b });
},
.island_alloc => |x| {
const g = fc.typeOf(x.island);
if (g != .mut or g.mut.* != .island) return fc.kindError(span, x.island, "mut<island<T>>");
const t = fc.typeOf(x.value);
if (!isIslandSafe(m, t)) return graphContent(fc, span, t, "IslandSafe");
try fc.expectOkErr(span, x.ok, x.err, .{ .iref = try boxed(fc.c.arena, t) });
},
.island_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<island<T>> or mut<island<T>>"),
.frozen_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<frozen<T>>"),
.arc_root => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<arc<T>>"),
.island_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref<island<T>> or mut<island<T>>, and an iref<U>"),
.frozen_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref<frozen<T>> and an iref<U>"),
.arc_borrow => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.owner, "ref<arc<T>> and an iref<U>"),
.island_freeze => |v| if (fc.typeOf(v) != .island) try fc.kindError(span, v, "island<T>"),
.island_destroy => |v| if (fc.typeOf(v) != .island) try fc.kindError(span, v, "island<T>"),
.frozen_release, .arc_from_frozen => |v| if (fc.typeOf(v) != .frozen) try fc.kindError(span, v, "frozen<T>"),
.arc_clone => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<arc<T>>"),
.arc_release => |v| if (fc.typeOf(v) != .arc) try fc.kindError(span, v, "arc<T>"),
.iref_eq => |x| {
const a = fc.typeOf(x.a);
if (a != .iref) return fc.kindError(span, x.a, "iref<T>");
try fc.expectValue(span, x.b, a);
},
.cap_narrow => |x| {
const t = fc.typeOf(x.cap);
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
@@ -852,6 +947,15 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
}
}
/// A graph's content that is not `IslandSafe`/`ArcSafe` (spec 03 §22, §24).
fn graphContent(fc: *FnCtx, span: air.Span, t: Type, property: []const u8) !void {
try fc.c.report("E2111", span, "a graph holds only plain data and iref handles", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "property", .value = .{ .str = property } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(t) } },
});
}
fn resultOf(fc: *FnCtx, inst: air.Inst) Type {
return fc.typeOf(inst.result.?);
}
@@ -0,0 +1,20 @@
; Each arc handle is released once: releasing the same handle twice is E2002.
; expect: reject E2002
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.arc_release_twice
air 0
lang 0.1
features [arc, capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 1
arc.new %v, %heap, ok -> @made, err -> @oom
made(%a: arc<u64>):
arc.release %a
arc.release %a
ret %v
oom(%e: alloc_error):
trap
@@ -0,0 +1,19 @@
; A frozen graph is linear: never released, it leaks (E3002).
; expect: reject E3002
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.frozen_leak
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 1
island.create %v, %heap, ok -> @made, err -> @oom
made(%i: island<u64>):
%f = island.freeze %i
ret %v
oom(%e: alloc_error):
trap
@@ -0,0 +1,14 @@
; iref.eq compares handles of the same type.
; expect: reject E1001
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.iref_eq_types
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @same(%a: iref<u64>, %b: iref<u8>) -> bool
effects []
entry:
%c = iref.eq %a, %b
ret %c
@@ -0,0 +1,25 @@
; island.alloc needs a mutable borrow of the island.
; expect: reject E1001
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.island_alloc_via_ref
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 1
island.create %v, %heap, ok -> @made, err -> @oom
made(%i: island<u64>):
%g = borrow.ref %i
island.alloc %g, %v, ok -> @got, err -> @full
got(%r: iref<u64>):
borrow.end %g
island.destroy %i
ret %v
full(%e2: alloc_error):
trap
oom(%e: alloc_error):
trap
@@ -0,0 +1,19 @@
; A graph holds only IslandSafe values: an island of an owner is E2111.
; expect: reject E2111
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.island_content_owner
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>, %o: own<u64>) -> u64
effects [mem.alloc]
entry:
island.create %o, %heap, ok -> @made, err -> @oom
made(%i: island<own<u64>>):
island.destroy %i
%z = const.u64 0
ret %z
oom(%e: alloc_error):
trap
@@ -0,0 +1,30 @@
; One mutable access per island at a time, even through different irefs.
; expect: reject E2101
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.island_two_mut
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 1
island.create %v, %heap, ok -> @made, err -> @oom
made(%i: island<u64>):
%g = borrow.mut %i
%a = island.root %g
island.alloc %g, %v, ok -> @got, err -> @full
got(%b: iref<u64>):
%x = island.borrow %g, %a
%y = island.borrow %g, %b
borrow.end %y
borrow.end %x
borrow.end %g
island.destroy %i
ret %v
full(%e2: alloc_error):
trap
oom(%e: alloc_error):
trap
@@ -0,0 +1,22 @@
; island.freeze consumes the island: a later use is E2001.
; expect: reject E2001
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.island_use_after_freeze
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 1
island.create %v, %heap, ok -> @made, err -> @oom
made(%i: island<u64>):
%f = island.freeze %i
%g = borrow.ref %i
borrow.end %g
frozen.release %f
ret %v
oom(%e: alloc_error):
trap
@@ -0,0 +1,13 @@
; iref<T> belongs to the feature `islands`, which this module does not declare.
; expect: reject E0006
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.islands_not_declared
air 0
lang 0.1
features [ownership]
fn @keep(%r: iref<u64>) -> void
effects []
entry:
ret
@@ -0,0 +1,41 @@
; island → frozen → arc keeps one graph: an iref taken from the island reads the same
; object through the arc; a clone and two releases; the last release frees the graph,
; so the same budget fits a new graph.
; expect: run
; grant: heap=mem.alloc:24
; result: 7
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.arc_lifecycle
air 0
lang 0.1
features [arc, capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 7
island.create %v, %heap, ok -> @made, err -> @oom
made(%i: island<u64>):
%g = borrow.ref %i
%r = island.root %g
borrow.end %g
%f = island.freeze %i
%a = arc.from_frozen %f
%ar = borrow.ref %a
%b = arc.clone %ar
%x = arc.borrow %ar, %r
%w = load %x
borrow.end %x
borrow.end %ar
arc.release %a
arc.release %b
%one = const.u64 1
arc.new %one, %heap, ok -> @again, err -> @oom2
again(%c: arc<u64>):
arc.release %c
ret %w
oom(%e: alloc_error):
trap
oom2(%e2: alloc_error):
trap
@@ -0,0 +1,42 @@
; The root iref of island A used with island B traps T0010; iref.eq of the two is false.
; expect: run
; grant: heap=mem.alloc:64
; trap: T0010
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.island_foreign_iref
air 0
lang 0.1
features [capabilities, effects, heap, islands, ownership, resources]
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%v = const.u64 1
island.create %v, %heap, ok -> @a_made, err -> @oom
a_made(%a: island<u64>):
island.create %v, %heap, ok -> @b_made, err -> @oom2
b_made(%b: island<u64>):
%ga = borrow.ref %a
%gb = borrow.ref %b
%ra = island.root %ga
%rb = island.root %gb
%same = iref.eq %ra, %rb
cbr %same, @wrong(), @cross()
cross:
%x = island.borrow %gb, %ra
%w = load %x
borrow.end %x
br @done()
wrong:
br @done()
done:
borrow.end %gb
borrow.end %ga
island.destroy %a
island.destroy %b
ret %v
oom(%e: alloc_error):
trap
oom2(%e2: alloc_error):
trap
@@ -0,0 +1,204 @@
; Phase 4 exit program (hand-written AIR): island pipeline. A producer task builds a
; cyclic graph in an island and moves it through a channel; the consumer freezes it,
; lends it to two readers, turns it into an arc and sends a clone to a late reader.
; expect: run
; grant: heap=mem.alloc:1024
; schedules: 30
; quantum: 3
; result: 36
; phase: 4
; spec: docs/spec/03-memory-model.md
module test.island_pipeline
air 0
lang 0.1
features [arc, cancellation, capabilities, channels, effects, heap, islands, ownership, resources, tasks]
type @Node = struct { value: u64, next: @Link }
type @Link = enum { End, To(iref<@Node>) }
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
entry:
%cap = const.usize 1
channel.make island<@Node>, %cap, %heap, ok -> @made, err -> @oom
made(%tx: sender<island<@Node>>, %rx: receiver<island<@Node>>):
%sc1 = task.scope.begin
%prod = task.spawn %sc1, @producer(%tx, %heap)
%rxb = borrow.mut %rx
channel.recv %rxb, ok -> @got, closed -> @none, cancelled -> @none
got(%i: island<@Node>):
borrow.end %rxb
; the graph is complete and owned here: freeze it and share it with two readers
%f = island.freeze %i
%fb = borrow.ref %f
%sc2 = task.scope.begin
%six = const.u64 6
%w1 = task.spawn %sc2, @walk(%fb, %six)
%w2 = task.spawn %sc2, @walk(%fb, %six)
%s1 = task.join %w1
%s2 = task.join %w2
task.scope.end %sc2
borrow.end %fb
%t1 = add.checked.u64 %s1, %s2
; shared ownership from here on: one handle stays, a clone goes to the late reader
%a = arc.from_frozen %f
%cap2 = const.usize 1
channel.make arc<@Node>, %cap2, %heap, ok -> @made2, err -> @oom2
made2(%atx: sender<arc<@Node>>, %arx: receiver<arc<@Node>>):
%sc3 = task.scope.begin
%late = task.spawn %sc3, @late(%arx)
%ab = borrow.ref %a
%a2 = arc.clone %ab
borrow.end %ab
%atxb = borrow.mut %atx
channel.send %atxb, %a2, ok -> @sent, closed -> @refused, cancelled -> @refused
sent:
br @after_send()
refused(%back: arc<@Node>):
arc.release %back
br @after_send()
after_send:
borrow.end %atxb
channel.close_sender %atx
%s3 = task.join %late
task.scope.end %sc3
%t2 = add.checked.u64 %t1, %s3
; the last release frees the graph
arc.release %a
br @finish(%t2)
none:
borrow.end %rxb
%z = const.u64 0
br @finish(%z)
finish(%total: u64):
channel.close_receiver %rx, ok -> @rx_closed, pending -> @rx_pending
rx_pending(%rx2: receiver<island<@Node>>):
; the producer sends one island and it was received: nothing can be buffered
trap
rx_closed:
%pr = task.join %prod
task.scope.end %sc1
ret %total
oom(%e: alloc_error):
trap
oom2(%e2: alloc_error):
trap
fn @producer(%tx: sender<island<@Node>>, %heap: cap<mem.alloc>) -> u8
effects [mem.alloc, task.wait]
entry:
%one = const.u64 1
%end = enum.make @Link.End()
%root = struct.make @Node(%one, %end)
island.create %root, %heap, ok -> @created, err -> @oom_create
created(%i: island<@Node>):
%ib = borrow.mut %i
%r = island.root %ib
%three = const.u64 3
%to_r = enum.make @Link.To(%r)
%nc = struct.make @Node(%three, %to_r)
island.alloc %ib, %nc, ok -> @have_c, err -> @oom_alloc_c
have_c(%c: iref<@Node>):
%two = const.u64 2
%to_c = enum.make @Link.To(%c)
%nb = struct.make @Node(%two, %to_c)
island.alloc %ib, %nb, ok -> @have_b, err -> @oom_alloc_b
have_b(%b: iref<@Node>):
; close the ring: root.next = b, so 1 -> 2 -> 3 -> 1
%rp = island.borrow %ib, %r
%nf = borrow.field @Node.next, %rp
%to_b = enum.make @Link.To(%b)
store %nf, %to_b
borrow.end %nf
borrow.end %rp
borrow.end %ib
%txb = borrow.mut %tx
channel.send %txb, %i, ok -> @sent, closed -> @refused, cancelled -> @refused
sent:
; %i is gone: the receiver owns the graph now
borrow.end %txb
br @finish()
refused(%back: island<@Node>):
borrow.end %txb
island.destroy %back
br @finish()
finish:
channel.close_sender %tx
%z = const.u8 0
ret %z
oom_create(%e: alloc_error):
trap
oom_alloc_c(%e2: alloc_error):
trap
oom_alloc_b(%e3: alloc_error):
trap
fn @walk(%f: ref<frozen<@Node>>, %steps: u64) -> u64
effects []
entry:
%r = frozen.root %f
%z = const.u64 0
br @loop(%r, %z, %z)
loop(%cur: iref<@Node>, %acc: u64, %k: u64):
%done = eq.u64 %k, %steps
cbr %done, @fin(), @step()
step:
%p = frozen.borrow %f, %cur
%n = load %p
borrow.end %p
%v = struct.get @Node.value, %n
%acc2 = add.checked.u64 %acc, %v
%one = const.u64 1
%k2 = add.checked.u64 %k, %one
%nx = struct.get @Node.next, %n
enum.switch @Link %nx, End -> @stay, To -> @move
stay:
br @loop(%cur, %acc2, %k2)
move(%to: iref<@Node>):
br @loop(%to, %acc2, %k2)
fin:
ret %acc
fn @late(%rx: receiver<arc<@Node>>) -> u64
effects [task.wait]
entry:
%rxb = borrow.mut %rx
channel.recv %rxb, ok -> @got, closed -> @none, cancelled -> @none
got(%a: arc<@Node>):
borrow.end %rxb
%ab = borrow.ref %a
%r = arc.root %ab
%z = const.u64 0
br @loop(%r, %z, %z)
loop(%cur: iref<@Node>, %acc: u64, %k: u64):
%six = const.u64 6
%done = eq.u64 %k, %six
cbr %done, @walked(), @step()
step:
%p = arc.borrow %ab, %cur
%n = load %p
borrow.end %p
%v = struct.get @Node.value, %n
%acc2 = add.checked.u64 %acc, %v
%one = const.u64 1
%k2 = add.checked.u64 %k, %one
%nx = struct.get @Node.next, %n
enum.switch @Link %nx, End -> @stay, To -> @move
stay:
br @loop(%cur, %acc2, %k2)
move(%to: iref<@Node>):
br @loop(%to, %acc2, %k2)
walked:
borrow.end %ab
arc.release %a
br @close(%acc)
none:
borrow.end %rxb
%zero = const.u64 0
br @close(%zero)
close(%sum: u64):
channel.close_receiver %rx, ok -> @closed, pending -> @pending
pending(%rx2: receiver<arc<@Node>>):
trap
closed:
ret %sum
@@ -13,24 +13,24 @@ while_2(%i_4: u64):
cbr %cmp_5, @body_6(), @after_3()
after_3:
channel.close_sender %tx
%c_17 = const.u8 0
ret %c_17
%c_16 = const.u8 0
ret %c_16
body_6:
%tx_7 = borrow.mut %tx
channel.send %tx_7, %i_4, ok -> @ok_8, closed -> @closed_9, cancelled -> @cancelled_11
ok_8:
borrow.end %tx_7
br @endmatch_13(%i_4)
br @endmatch_13()
closed_9(%closed_10: u64):
borrow.end %tx_7
br @after_3()
cancelled_11(%cancelled_12: u64):
borrow.end %tx_7
br @after_3()
endmatch_13(%i_14: u64):
%c_15 = const.u64 1
%t_16 = add.checked.u64 %i_14, %c_15
br @while_2(%t_16)
endmatch_13:
%c_14 = const.u64 1
%t_15 = add.checked.u64 %i_4, %c_14
br @while_2(%t_15)
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
@@ -49,32 +49,32 @@ loop_11(%acc_13: u64, %r_14: receiver<u64>):
%r_16 = borrow.mut %r_14
channel.recv %r_16, ok -> @ok_17, closed -> @closed_19, cancelled -> @cancelled_20
after_12(%acc_15: u64):
%r_37 = task.join %t_10
%r_35 = task.join %t_10
task.scope.end %sc_8
br @endmatch_38(%acc_15)
br @endmatch_36(%acc_15)
ok_17(%ok_18: u64):
borrow.end %r_16
%t_21 = add.checked.u64 %acc_13, %ok_18
br @endmatch_34(%t_21, %r_14)
br @endmatch_32(%t_21, %r_14)
closed_19:
borrow.end %r_16
channel.close_receiver %r_14, ok -> @ok_22, pending -> @pending_23
cancelled_20:
borrow.end %r_16
channel.close_receiver %r_14, ok -> @ok_28, pending -> @pending_29
channel.close_receiver %r_14, ok -> @ok_27, pending -> @pending_28
ok_22:
br @after_12(%acc_13)
pending_23(%pending_24: receiver<u64>):
br @endmatch_25(%acc_13, %pending_24)
endmatch_25(%acc_26: u64, %r_27: receiver<u64>):
br @endmatch_34(%acc_26, %r_27)
ok_28:
br @endmatch_25(%pending_24)
endmatch_25(%r_26: receiver<u64>):
br @endmatch_32(%acc_13, %r_26)
ok_27:
br @after_12(%acc_13)
pending_29(%pending_30: receiver<u64>):
br @endmatch_31(%acc_13, %pending_30)
endmatch_31(%acc_32: u64, %r_33: receiver<u64>):
br @endmatch_34(%acc_32, %r_33)
endmatch_34(%acc_35: u64, %r_36: receiver<u64>):
br @loop_11(%acc_35, %r_36)
endmatch_38(%match_39: u64):
ret %match_39
pending_28(%pending_29: receiver<u64>):
br @endmatch_30(%pending_29)
endmatch_30(%r_31: receiver<u64>):
br @endmatch_32(%acc_13, %r_31)
endmatch_32(%acc_33: u64, %r_34: receiver<u64>):
br @loop_11(%acc_33, %r_34)
endmatch_36(%match_37: u64):
ret %match_37
@@ -13,8 +13,8 @@ while_2(%i_4: u64):
%cmp_6 = ne.u64 %i_4, %c_5
cbr %cmp_6, @body_7(), @after_3()
after_3:
%c_20 = const.u8 0
ret %c_20
%c_19 = const.u8 0
ret %c_19
body_7:
mutex.lock %mr, ok -> @locked_8, cancelled -> @lock_cancelled_10
locked_8(%guard_9: guard<u64>):
@@ -25,14 +25,14 @@ locked_8(%guard_9: guard<u64>):
store %count_11, %t_14
borrow.end %count_11
mutex.unlock %guard_9
br @endlock_16(%i_4)
br @endlock_16()
lock_cancelled_10:
%c_15 = const.u8 0
ret %c_15
endlock_16(%i_17: u64):
%c_18 = const.u64 1
%t_19 = add.checked.u64 %i_17, %c_18
br @while_2(%t_19)
endlock_16:
%c_17 = const.u64 1
%t_18 = add.checked.u64 %i_4, %c_17
br @while_2(%t_18)
fn @main() -> u64
effects [task.spawn, task.wait]
@@ -0,0 +1,57 @@
// Arc handles: the frozen graph becomes shared; each worker gets its own handle through
// a channel and releases it; the last release frees the graph.
// expect: run
// grant: heap=mem.alloc:512
// schedules: 20
// result: 20
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.arcshared
fn reader(rx: receiver<arc<u64>>) -> u64
effects [task.wait]
{
var sum: u64 = 0;
loop {
match channel.recv(rx) {
ok(a) => {
{
ref ar = a;
let r = arc.root(ar);
ref v = arc.at(ar, r);
sum = sum + *v;
}
arc.release(move a);
}
closed => { break; }
cancelled => { break; }
}
}
channel.close_receiver(move rx) or trap;
sum
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
let isl = island.create(10u64, heap) or trap;
let a = arc.from_frozen(island.freeze(move isl));
match channel.make<arc<u64>>(2, heap) {
ok(tx, rx) => {
var r: u64 = 0;
scope sc {
let t = task.spawn(sc, reader, move rx);
let b = arc.clone(a);
channel.send(tx, move b) or trap;
channel.send(tx, move a) or trap;
channel.close_sender(move tx);
r = task.join(move t);
}
r
}
err(e) => {
arc.release(move a);
trap;
}
}
}
@@ -0,0 +1,31 @@
// A graph charges the authority it was created with; island.alloc fails with alloc_error
// when the budget is spent, and destroy returns the bytes.
// expect: run
// grant: heap=mem.alloc:64
// result: 2
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.islandbudget
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create([0u64; 4], heap) or trap;
var outcome: u64 = 0;
{
mut g = isl;
match island.alloc(g, [0u64; 4]) {
ok(r) => { outcome = 1; }
err(e) => {
outcome = match e {
alloc_error::budget_exceeded => 2,
alloc_error::out_of_memory => 3,
};
}
}
}
island.destroy(move isl);
let again = island.create([0u64; 4], heap) or trap;
island.destroy(move again);
outcome
}
@@ -0,0 +1,28 @@
// An iref of one island used with another traps T0010; equality across islands is false.
// expect: run
// grant: heap=mem.alloc:256
// trap: T0010
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.foreigniref
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let a = island.create(1u64, heap) or trap;
let b = island.create(2u64, heap) or trap;
var out: u64 = 0;
{
ref ga = a;
ref gb = b;
let ra = island.root(ga);
let rb = island.root(gb);
if ra != rb {
ref wrong = island.at(gb, ra);
out = *wrong;
}
}
island.destroy(move a);
island.destroy(move b);
out
}
@@ -0,0 +1,34 @@
// A frozen graph is Share: two tasks read it through the same ref at once.
// expect: run
// grant: heap=mem.alloc:256
// schedules: 20
// result: 84
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.frozenreaders
fn read(f: ref<frozen<u64>>) -> u64
effects []
{
let r = frozen.root(f);
ref v = frozen.at(f, r);
*v
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn]
{
let isl = island.create(42u64, heap) or trap;
let f = island.freeze(move isl);
var sum: u64 = 0;
{
ref fr = f;
scope sc {
let a = task.spawn(sc, read, fr);
let b = task.spawn(sc, read, fr);
sum = task.join(move a) + task.join(move b);
}
}
frozen.release(move f);
sum
}
@@ -0,0 +1,13 @@
// An arc holds only ArcSafe values: a mutex is Share but not ArcSafe.
// expect: reject E2111
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.arc_mutex
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let a = arc.new(mutex.make(0u64), heap) or trap;
arc.release(move a);
0
}
@@ -0,0 +1,19 @@
// A graph access is a borrow: it is bound with ref/mut, not used as a value.
// expect: reject E7006
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.at_as_value
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
var v: u64 = 0;
{
ref g = isl;
let r = island.root(g);
let x = island.at(g, r);
}
island.destroy(move isl);
v
}
@@ -0,0 +1,14 @@
// An island holds only IslandSafe values: an owner inside is E2111.
// expect: reject E2111
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.content_owner
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let o = own.new(1u64, heap) or trap;
let isl = island.create(move o, heap) or trap;
island.destroy(move isl);
0
}
@@ -0,0 +1,14 @@
// Destroying an island while a borrow of it is live.
// expect: reject E2101
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.destroy_while_borrowed
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
ref g = isl;
island.destroy(move isl);
0
}
@@ -0,0 +1,19 @@
// A frozen graph gives ref access only.
// expect: reject E7005
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.frozen_mut
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let f = island.freeze(island.create(1u64, heap) or trap);
{
ref g = f;
let r = frozen.root(g);
mut x = frozen.at(g, r);
*x = 2;
}
frozen.release(move f);
0
}
@@ -0,0 +1,20 @@
// The container borrow is bound first; written inline it would end before the access.
// expect: reject E7006
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.inline_container_borrow
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
var v: u64 = 0;
{
ref g = isl;
let r = island.root(g);
mut x = island.at(mut isl, r);
v = *x;
}
island.destroy(move isl);
v
}
@@ -0,0 +1,19 @@
// iref handles are compared with == and != only; they have no order.
// expect: reject E7005
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.iref_order
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
var v: u64 = 0;
{
ref g = isl;
let a = island.root(g);
if a < a { v = 1; }
}
island.destroy(move isl);
v
}
@@ -0,0 +1,12 @@
// A graph owner is consumed exactly once: an island never destroyed, frozen or moved leaks.
// expect: reject E3002
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.leak
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
0
}
@@ -0,0 +1,29 @@
// An island is not Share: its owner may mutate it. Freeze it to share it with tasks.
// expect: reject E4002
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.lend_island
fn read(g: ref<island<u64>>) -> u64
effects []
{
let r = island.root(g);
ref v = island.at(g, r);
*v
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn]
{
let isl = island.create(1u64, heap) or trap;
var v: u64 = 0;
{
ref g = isl;
scope sc {
let t = task.spawn(sc, read, g);
v = task.join(move t);
}
}
island.destroy(move isl);
v
}
@@ -0,0 +1,14 @@
// island.alloc takes the island's borrow binding, not the owner.
// expect: reject E7005
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.owner_not_borrow
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
let r = island.alloc(isl, 2u64) or trap;
island.destroy(move isl);
0
}
@@ -0,0 +1,20 @@
// One mutable access per island at a time, even through different irefs.
// expect: reject E2101
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.two_mut_access
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = island.create(1u64, heap) or trap;
{
mut g = isl;
let a = island.root(g);
let b = island.alloc(g, 2u64) or trap;
mut x = island.at(g, a);
mut y = island.at(g, b);
}
island.destroy(move isl);
0
}
@@ -0,0 +1,26 @@
// After an island is sent, the sender holds nothing that reaches it.
// expect: reject E2001
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.use_after_send
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
match channel.make<island<u64>>(1, heap) {
ok(tx, rx) => {
let isl = island.create(1u64, heap) or trap;
channel.send(tx, move isl) or trap;
{
ref g = isl;
let r = island.root(g);
}
channel.close_sender(move tx);
let back = channel.recv(rx) or trap;
island.destroy(move back);
channel.close_receiver(move rx) or trap;
0
}
err(e) => { trap; }
}
}
+73
View File
@@ -0,0 +1,73 @@
// A cyclic ring of three nodes built in an island with iref edges, frozen in O(1),
// walked through a ref of the frozen graph, turned into an arc, cloned and released.
// expect: run
// grant: heap=mem.alloc:256
// result: 13
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.ring
struct Node {
value: u64,
next: Link,
}
enum Link {
End,
To(iref<Node>),
}
fn ring(heap: cap<mem.alloc>) -> island<Node>
effects [mem.alloc]
{
let isl = island.create(Node { value: 1, next: Link::End }, heap) or trap;
{
mut g = isl;
let a = island.root(g);
let b = island.alloc(g, Node { value: 2, next: Link::To(a) }) or trap;
let c = island.alloc(g, Node { value: 3, next: Link::To(b) }) or trap;
mut first = island.at(g, a);
first.next = Link::To(c);
}
move isl
}
fn walk(f: ref<frozen<Node>>, steps: u64) -> u64
effects []
{
var sum: u64 = 0;
var at: iref<Node> = frozen.root(f);
for i in 0..steps {
ref node = frozen.at(f, at);
sum = sum + node.value;
at = match node.next {
Link::End => at,
Link::To(n) => n,
};
}
sum
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let isl = ring(heap);
let f = island.freeze(move isl);
var total: u64 = 0;
{
ref fr = f;
total = walk(fr, 7);
}
let a = arc.from_frozen(move f);
let b = arc.clone(a);
{
ref ar = b;
let root = arc.root(ar);
if root == arc.root(ar) {
total = total + 0;
}
}
arc.release(move a);
arc.release(move b);
total
}
@@ -0,0 +1,107 @@
module demo.ring
air 0
lang 0.1
features [arc, capabilities, effects, heap, islands, ownership, resources]
type @Node = struct { value: u64, next: @Link }
type @Link = enum { End, To(iref<@Node>) }
fn @ring(%heap: cap<mem.alloc>) -> island<@Node>
effects [mem.alloc]
entry:
%c_1 = const.u64 1
%e_2 = enum.make @Link.End()
%s_3 = struct.make @Node(%c_1, %e_2)
island.create %s_3, %heap, ok -> @ok_4, err -> @err_6
ok_4(%ok_5: island<@Node>):
%isl_8 = borrow.mut %ok_5
%root_9 = island.root %isl_8
%c_10 = const.u64 2
%e_11 = enum.make @Link.To(%root_9)
%s_12 = struct.make @Node(%c_10, %e_11)
island.alloc %isl_8, %s_12, ok -> @ok_13, err -> @err_15
err_6(%err_7: alloc_error):
trap
ok_13(%ok_14: iref<@Node>):
%c_17 = const.u64 3
%e_18 = enum.make @Link.To(%ok_14)
%s_19 = struct.make @Node(%c_17, %e_18)
island.alloc %isl_8, %s_19, ok -> @ok_20, err -> @err_22
err_15(%err_16: alloc_error):
trap
ok_20(%ok_21: iref<@Node>):
%first_24 = island.borrow %isl_8, %root_9
%e_25 = enum.make @Link.To(%ok_21)
%next_26 = borrow.field @Node.next, %first_24
store %next_26, %e_25
borrow.end %next_26
borrow.end %first_24
borrow.end %isl_8
ret %ok_5
err_22(%err_23: alloc_error):
trap
fn @walk(%f: ref<frozen<@Node>>, %steps: u64) -> u64
effects []
entry:
%c_1 = const.u64 0
%root_2 = frozen.root %f
%c_3 = const.u64 0
br @while_4(%c_1, %root_2, %c_3)
while_4(%sum_7: u64, %at_8: iref<@Node>, %i_9: u64):
%cmp_14 = lt.u64 %i_9, %steps
cbr %cmp_14, @body_15(), @after_5(%sum_7)
after_5(%sum_10: u64):
ret %sum_10
step_6(%sum_11: u64, %at_12: iref<@Node>, %i_13: u64):
%one_27 = const.u64 1
%i_28 = add.checked.u64 %i_13, %one_27
br @while_4(%sum_11, %at_12, %i_28)
body_15:
%node_16 = frozen.borrow %f, %at_8
%value_17 = borrow.field @Node.value, %node_16
%value_18 = load %value_17
borrow.end %value_17
%t_19 = add.checked.u64 %sum_7, %value_18
%next_20 = borrow.field @Node.next, %node_16
%next_21 = load %next_20
borrow.end %next_20
enum.switch @Link %next_21, End -> @case_End_22, To -> @case_To_23
case_End_22:
br @endmatch_25(%at_8)
case_To_23(%n_24: iref<@Node>):
br @endmatch_25(%n_24)
endmatch_25(%match_26: iref<@Node>):
borrow.end %node_16
br @step_6(%t_19, %match_26, %i_9)
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
%ring_1 = call @ring(%heap)
%frozen_2 = island.freeze %ring_1
%c_3 = const.u64 0
%f_4 = borrow.ref %frozen_2
%c_5 = const.u64 7
%walk_6 = call @walk(%f_4, %c_5)
borrow.end %f_4
%arc_7 = arc.from_frozen %frozen_2
%a_8 = borrow.ref %arc_7
%arc_9 = arc.clone %a_8
borrow.end %a_8
%b_10 = borrow.ref %arc_9
%root_11 = arc.root %b_10
%root_12 = arc.root %b_10
%cmp_13 = iref.eq %root_11, %root_12
cbr %cmp_13, @then_14(), @else_15()
then_14:
%c_16 = const.u64 0
%t_17 = add.checked.u64 %walk_6, %c_16
br @endif_18(%t_17)
else_15:
br @endif_18(%walk_6)
endif_18(%total_19: u64):
borrow.end %b_10
arc.release %arc_7
arc.release %arc_9
ret %total_19
@@ -0,0 +1,78 @@
// An island moves to a worker task through a channel in O(1); the worker sums the graph
// and destroys it. The sender holds nothing that reaches it after the send.
// expect: run
// grant: heap=mem.alloc:512
// schedules: 20
// quantum: 3
// result: 6
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.islandtransfer
struct Node {
value: u64,
next: Link,
}
enum Link {
End,
To(iref<Node>),
}
fn worker(rx: receiver<island<Node>>) -> u64
effects [task.wait]
{
var sum: u64 = 0;
match channel.recv(rx) {
ok(isl) => {
{
ref g = isl;
var at: iref<Node> = island.root(g);
loop {
ref node = island.at(g, at);
sum = sum + node.value;
match node.next {
Link::End => { break; }
Link::To(n) => { at = n; }
}
}
}
island.destroy(move isl);
}
closed => {}
cancelled => {}
}
channel.close_receiver(move rx) or trap;
sum
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
match channel.make<island<Node>>(1, heap) {
ok(tx, rx) => {
var r: u64 = 0;
scope sc {
let t = task.spawn(sc, worker, move rx);
let isl = island.create(Node { value: 1, next: Link::End }, heap) or trap;
{
mut g = isl;
let a = island.root(g);
let b = island.alloc(g, Node { value: 2, next: Link::End }) or trap;
let c = island.alloc(g, Node { value: 3, next: Link::To(b) }) or trap;
mut first = island.at(g, a);
first.next = Link::To(c);
}
match channel.send(tx, move isl) {
ok => {}
closed(back) => { island.destroy(move back); }
cancelled(back) => { island.destroy(move back); }
}
channel.close_sender(move tx);
r = task.join(move t);
}
r
}
err(e) => { trap; }
}
}
@@ -0,0 +1,141 @@
// Reference program (Phase 4 exit): island pipeline. A producer task builds a cyclic
// graph in an island and moves it through a channel (O(1), no copy). The consumer
// freezes it, lends the frozen graph to two readers at once, turns it into an arc,
// sends a clone to a late reader, and releases every handle; the last release frees
// the graph. Each reader walks the ring 6 steps: 2 × (1+2+3+1+2+3) + 12 = 36.
// expect: run
// grant: heap=mem.alloc:1024
// schedules: 30
// quantum: 3
// result: 36
// equivalent: phase4/run/program_island_pipeline.air
// phase: 6
// spec: docs/spec/03-memory-model.md
module demo.islandpipeline
struct Node {
value: u64,
next: Link,
}
enum Link {
End,
To(iref<Node>),
}
// Builds the ring 1 → 2 → 3 → 1 and moves it into the channel.
fn produce(tx: sender<island<Node>>, heap: cap<mem.alloc>) -> u8
effects [mem.alloc, task.wait]
{
let isl = island.create(Node { value: 1, next: Link::End }, heap) or trap;
{
mut g = isl;
let a = island.root(g);
let c = island.alloc(g, Node { value: 3, next: Link::To(a) }) or trap;
let b = island.alloc(g, Node { value: 2, next: Link::To(c) }) or trap;
mut first = island.at(g, a);
first.next = Link::To(b);
}
match channel.send(tx, move isl) {
ok => {}
closed(back) => { island.destroy(move back); }
cancelled(back) => { island.destroy(move back); }
}
channel.close_sender(move tx);
0
}
// Sums `steps` nodes along the ring, through a shared borrow of the frozen graph.
fn walk(f: ref<frozen<Node>>, steps: u64) -> u64
effects []
{
var sum: u64 = 0;
var at: iref<Node> = frozen.root(f);
for i in 0..steps {
ref node = frozen.at(f, at);
sum = sum + node.value;
at = match node.next {
Link::End => at,
Link::To(n) => n,
};
}
sum
}
// A late reader that owns its own arc handle and releases it.
fn late(rx: receiver<arc<Node>>) -> u64
effects [task.wait]
{
var sum: u64 = 0;
match channel.recv(rx) {
ok(a) => {
{
ref ar = a;
var at: iref<Node> = arc.root(ar);
for i in 0..6u64 {
ref node = arc.at(ar, at);
sum = sum + node.value * 2;
at = match node.next {
Link::End => at,
Link::To(n) => n,
};
}
}
arc.release(move a);
}
closed => {}
cancelled => {}
}
channel.close_receiver(move rx) or trap;
sum / 2
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn, task.wait]
{
var total: u64 = 0;
match channel.make<island<Node>>(1, heap) {
ok(tx, rx) => {
scope sc {
let p = task.spawn(sc, produce, move tx, heap);
match channel.recv(rx) {
ok(isl) => {
let f = island.freeze(move isl);
{
ref fr = f;
scope readers {
let r1 = task.spawn(readers, walk, fr, 6);
let r2 = task.spawn(readers, walk, fr, 6);
total = task.join(move r1) + task.join(move r2);
}
}
let a = arc.from_frozen(move f);
match channel.make<arc<Node>>(1, heap) {
ok(atx, arx) => {
scope lates {
let l = task.spawn(lates, late, move arx);
let b = arc.clone(a);
match channel.send(atx, move b) {
ok => {}
closed(back) => { arc.release(move back); }
cancelled(back) => { arc.release(move back); }
}
channel.close_sender(move atx);
total = total + task.join(move l);
}
}
err(e) => {}
}
arc.release(move a);
}
closed => {}
cancelled => {}
}
channel.close_receiver(move rx) or trap;
task.join(move p);
}
}
err(e) => { trap; }
}
total
}
@@ -0,0 +1,59 @@
// Quick Reference: graphs (island → frozen → arc).
// expect: run
// grant: heap=mem.alloc:256
// schedules: 10
// result: 8
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.qrgraphs
struct Node {
value: u64,
next: Link,
}
enum Link {
End,
To(iref<Node>),
}
fn read(fr: ref<frozen<Node>>, a: iref<Node>) -> u64
effects []
{
ref node = frozen.at(fr, a); // ref access only
node.value
}
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.spawn]
{
let isl = island.create(Node { value: 1, next: Link::End }, heap) or trap; // effect mem.alloc
{
mut g = isl; // borrow the island; it outlives the accesses
let a = island.root(g);
let b = island.alloc(g, Node { value: 2, next: Link::To(a) }) or trap;
mut first = island.at(g, a); // mut<Node>; one mutable access at a time
first.next = Link::To(b); // edges may form cycles
}
let f = island.freeze(move isl); // O(1), irreversible; irefs stay valid
var sum: u64 = 0;
{
ref fr = f; // frozen graphs are Share: lend fr to tasks
let a = frozen.root(fr);
scope s {
let t = task.spawn(s, read, fr, a);
sum = task.join(move t);
}
}
let shared = arc.from_frozen(move f); // O(1); the same graph
let other = arc.clone(shared); // count + 1
arc.release(move other); // the last release frees the graph
{
ref ar = shared;
let a = arc.root(ar);
ref node = arc.at(ar, a);
sum = sum + node.value * 7;
}
arc.release(move shared);
sum
}
+5
View File
@@ -74,6 +74,11 @@ CHECKLIST = [
("cancellation", "`shield`", r"\bshield \{", False),
("cancellation", "`task.check_cancel`", r"task\.check_cancel\(", False),
("cancellation", "`task.join_cancel`", r"task\.join_cancel\(", True),
("graphs", "`island.create` / `island.alloc` / `island.at`", r"island\.(create|alloc|at)\(", True),
("graphs", "`island.freeze` / `frozen.at` / `frozen.release`", r"island\.freeze\(|frozen\.(at|release)\(", True),
("graphs", "`arc.from_frozen` / `arc.clone` / `arc.release` / `arc.at`", r"arc\.(from_frozen|clone|release|at)\(", True),
("graphs", "`iref` equality", r"(?s)(?:island|frozen|arc)\.root\(.*\b\w+ (?:==|!=) (?:\w+|arc\.root\(\w+\)) \{", False),
("graphs", "graphs through channels and tasks", r"channel\.make<(island|arc)<", True),
("unsafe", "`ref unchecked` / `assume`", r"\bunchecked\b|\bassume\(", True),
("unsafe", "`trusted` rejected", r"\btrusted\b", True),
]