cli: implement explicit source borrow returns

This commit is contained in:
dev committed 2026-10-07 18:20:45 +03:00
1 parent 715a8be491
commit a9a0d63f27
78 files changed
+970 -48

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ jobs:
- run: zig build && python3 tests/hosted/smoke.py
- run: python3 tests/hosted/source_modules.py
- run: python3 tests/hosted/source_generics.py
- run: python3 tests/hosted/source_borrow_returns.py
- run: python3 tests/hosted/source_static_functions.py
- run: python3 tests/hosted/source_linear.py
- run: python3 tests/hosted/source_buffers.py
+1
View File
@@ -18,6 +18,7 @@ zig build run -- run f.air # verify and execute @main (deterministic profile)
python3 tests/hosted/smoke.py # hosted profile against the real OS
python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts
python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance
python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views, packages and profiles
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
+5
View File
@@ -131,3 +131,8 @@ RFC 0033 bounded I/O (cl100k, relative to BinaryHeap): Quick Reference 8,284 →
RFC 0034 owning buffered files (cl100k, relative to bounded I/O): Quick Reference 8,350 → 8,445 (+1.1%), other source docs 58,473 → 61,223 (+4.7%), full source excluding AIR 66,823 → 69,668 (+4.3%). library/std.md is 24,364 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe concrete operations keep fixed allocation, file transfer, prefetch and first-error/partial-write cleanup visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +105.0%, justified by these contracts without an empirical MCC claim. Full representation/API details stay on demand; front-door consolidation remains separate work.
RFC 0035 caller-buffer paths (cl100k, relative to buffered files): Quick Reference 8,445 → 8,518 (+0.9%), other source docs 61,223 → 63,296 (+3.4%), full source excluding AIR 69,668 → 71,814 (+3.1%). library/std.md is 26,437 tokens; AIR remains 179,282 bytes / 51 sections. Six pure operations return raw Copy ranges or write a measured canonical prefix, keeping lifetime, byte syntax, capacity failure and authority visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +111.3%, justified by these contracts without an empirical MCC claim. API details stay on demand; front-door consolidation remains separate work.
RFC 0036 (Proposed), explicit source borrow returns (cl100k, relative to paths): Quick Reference 8,518 → 8,642 (+1.46%), other source docs 63,296 → 64,160 (+1.37%), full source excluding AIR 71,814 → 72,802 (+1.38%). language/ownership.md is 1,834 tokens; AIR remains 179,282 bytes / 51 sections. Existing `from`, ref/mut bindings and named returns reuse verifier/runtime primitives; frontend ancestry selects transferred lexical ends. No new keyword, AIR feature, verifier state or diagnostic. Cumulative full-source growth is +114.24%, justified in the proposed RFC without an empirical MCC claim. This measurement records the implementation for review, not owner adoption.
RFC 0036 review fixes clarify reserved task borrow returns and known array bounds in unused generic signatures. These rules add 54 cl100k tokens: other source docs 64,160 → 64,214, full source 72,848 → 72,902 (+0.07%); Quick Reference stays 8,688. o200k groups are 8,723 / 64,413 / 73,136; Qwen2.5 8,954 / 65,794 / 74,748. language/ownership.md is 1,873 cl100k tokens; AIR and library/std.md stay unchanged. The additions make source rejection predictable without adding a semantic feature.
+8 -1
View File
@@ -101,11 +101,18 @@ Rules (checked by the verifier):
- **A borrow lives until the end of the block where it was bound** (`ref r = …;` / `mut r = …;`). A borrow written as an argument (`f(mut buf)`) lives for that call. To end one early, put it in an inner `{ … }` block.
- **Exclusive XOR shared.** While a `mut` borrow of a place is live, no other borrow of the same place, and no direct use of it, is allowed (`E2101`). Disjoint fields and `split_at` halves are independent.
- A borrow cannot outlive what it borrows from (`E2102`). A function returns a borrow only with `-> ref<T> from param`.
- A borrow cannot outlive what it borrows from (`E2102`). A function returns a borrow only with explicit `from param`. Bind returned views with `ref`/`mut`; the `from` argument must be a named borrow. Return the bound name without `move`; a local-frame view cannot escape (`E2108`).
- **Moves are explicit:** a named linear value is consumed only as `move x` (otherwise `E7003`). A fresh temporary needs no `move`: `consume(make())`. Copyable values are passed plainly; `move` on them is `E7006`.
- Use after move is `E2001`, use after close/free/take `E3001`, a second consumption `E2002`, and a linear value never consumed `E3002`. Every path must consume it, including early `return`s.
- Index proofs: inside `if i < s.len { … }` the access `s[i]` needs no runtime check.
Returned views (details in `/docs/language/ownership.md`):
```aji
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
```
## 5. Failure: every outcome is a `match` arm
```aji
+1
View File
@@ -48,6 +48,7 @@ docs/reference/type-properties.md
docs/spec/01-language-overview.md :: ## 6. Trap
> language/ownership.md
docs/spec/15-source-language.md :: ## 19. Source borrow returns
docs/spec/15-source-language.md :: ## 9. Frame storage, borrow scopes and features
docs/spec/03-memory-model.md :: ## 3. Safe-reference aliasing rule
docs/spec/03-memory-model.md :: ## 4. Borrow lifetime
+3
View File
@@ -28,6 +28,7 @@ Status values: `open`, `resolved`.
| Q-020 | resolved | P2 | Size bound for SSA array values |
| Q-024 | resolved | P5 | Memory-model clarifications found by the independent oracle |
| Q-025 | resolved | STD-5 | Array construction from complete element values |
| Q-034 | open | P6-11 adoption | Source borrow-return calls (implementation prepared; RFC 0036 Proposed) |
| Q-035 | resolved | STD-5 | Whole-value linear aggregates |
| Q-036 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain |
| Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors |
@@ -260,6 +261,8 @@ The source plan names monomorphized generics but does not define application syn
During STD-4 validation, existing `from` declarations still return the frontend's unimplemented outcome and borrow bindings accept places rather than borrow-returning calls. Generics preserve the syntax/metadata and this existing limitation; they do not add an implicit lifetime or a new binding spelling. A separate source/lifetime increment must specify and implement the binding/temporary-end rules vertically before public libraries return retained borrowed views.
**Implementation prepared (P6-11, RFC 0036 Proposed):** spec 15 §19 and the frontend define exact-mode ref/mut call bindings, a named borrowed `from` argument, named returns and transfer of owned ancestors. The existing AIR verifier enforces provenance/lifetime; no runtime rule or AIR construct changes. Source/AIR twins, generic/package/profile checks, task loans and per-step collection cover the increment. Owner adoption of RFC 0036 remains separate.
## Q-035 — Whole-value linear aggregates
**Resolved on the STD-5 branch (RFC 0023 Implemented):** spec 03 §25 and source spec 15 §16 specify complete construction/exhaustive consumption, fixed arrays, explicit exchange and ownership-preserving allocation failure. No partial-move/field initialization state or destructor is introduced. Among heap/frame/region storage forms, only individual own<T> may hold linear content; frame locals, repeated heap arrays and bulk regions retain Copy-only content. Dynamic linear buffers need a separately specified extension in the collection phase.
+1 -1
View File
@@ -141,7 +141,7 @@ Targets for Phase 6A, measured on dev tasks:
## Standard library track
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is next. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is implemented for review (RFC 0036 Proposed). Larger syntax/contracts work retains its separate spec gate. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
## Task conventions
+9 -2
View File
@@ -139,7 +139,14 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
| P6-8 | todo | Formatter | P6-2 | `aji fmt` | idempotent; output parses to the same AST |
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
| P6-11 | todo | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics |
| P6-11 | done (implementation; RFC 0036 Proposed) | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics |
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
The [standard-library track](standard-library.md) implements nineteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. STD-7a/RFC 0033 implements bounded std.io composition with explicit progress, resource loans and exact effects; conformance, GC/schedule, CLI and documentation checks pass. STD-7b/RFC 0034 implements safe owning buffered file adapters with explicit finish/discard and first-error/no-retry behavior; conformance, GC/schedule, CLI and documentation checks pass. STD-7c/RFC 0035 adds pure caller-buffer lexical paths and Copy component ranges; conformance, GC/schedule, CLI and documentation checks pass. The owner adopts STD-0..7 as an intermediate foundation and resumes language work (2026-10-07); remaining std system/service milestones stay in the backlog. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
The [standard-library track](standard-library.md) implements nineteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. STD-7a/RFC 0033 implements bounded std.io composition with explicit progress, resource loans and exact effects; conformance, GC/schedule, CLI and documentation checks pass. STD-7b/RFC 0034 implements safe owning buffered file adapters with explicit finish/discard and first-error/no-retry behavior; conformance, GC/schedule, CLI and documentation checks pass. STD-7c/RFC 0035 adds pure caller-buffer lexical paths and Copy component ranges; conformance, GC/schedule, CLI and documentation checks pass. The owner adopts STD-0..7 as an intermediate foundation and resumes language work (2026-10-07); remaining std system/service milestones stay in the backlog. P6-11 implements explicit borrowed returns over the existing AIR; RFC 0036 remains Proposed pending owner adoption (Q-034). These increments do not complete Phase 6.
## P6-11 implementation review (2026-10-07)
RFC 0036 remains Proposed for owner adoption; its spec integration and implementation are prepared together. Borrow functions preserve explicit origins through ordinary/generic/package calls; exact-mode ref/mut bindings retain a named parent. Named returns transfer only their owned ancestor chain, and ordinary verifier/interpreter semantics decide provenance, aliasing, task loans and traps. Static function parameter borrow contracts and borrow joins stay outside this task.
Validation: full conformance 1,135/1,135 with no failures or pending tests; 56 focused conformance cases including a frozen Phase 1 AIR twin and four canonical AIR goldens; per-step collection and 200 schedule seeds across four quanta for the concurrent fixture; 61 generic regression cases; unit tests, format and bundle/example checks; CLI integration 133 checks, generic/module integration 20/36 checks, hosted smoke. Independent read-only review by Claude found a misleading feature diagnostic when spawning a borrow-returning function and missing array bounds in unused generic signatures. Both were fixed and independently rechecked. Added cases cover those failures, valid generic bounds, normal scope/shield/lock returns, an unjoined task and lock-guard escape. Source construct coverage is 119/119. Quick Reference/source budget is recorded in RFC 0036 and docs/agent/README.md. Larger syntax/contracts work still needs its separate spec gate.
+2 -2
View File
@@ -127,7 +127,7 @@ RFC 0021 records invariants, diagnostics, compatibility, complete validation and
Explicit function/struct/enum generics specialize deterministically to ordinary AIR. Structural Copy/Send/Share/Freeze/Local constraints, header checking, nominal identity, direct-import visibility and fixed expansion limits are specified by spec 15 §15 and RFC 0022. Every concrete specialization passes ordinary ownership/effect/task verification; unused bodies make no validity promise for future types. The compiler registry adds safe Copy-only std.option/std.result with classification helpers. No allocation, implicit cleanup, AIR opcode or authority is added.
The finite-layout E1003 check now traverses arrays, repairing a prior verifier gap with source/AIR fixtures. Existing source `from`-returns remain unimplemented and are logged as Q-034 rather than given an invented lifetime/binding contract. RFC 0022 records complete validation and source/AIR budget measurements. Next is STD-5: the independent linear_aggregates vertical feature, required before containers or option/result can own resources. P6-4's generic/structural specialization task is implemented on this branch; this does not complete Phase 6.
The finite-layout E1003 check now traverses arrays, repairing a prior verifier gap with source/AIR fixtures. At STD-4, source `from`-returns remained unimplemented; P6-11 subsequently supplies the explicit lifetime/binding contract (RFC 0036 Proposed). RFC 0022 records complete validation and source/AIR budget measurements. Next is STD-5: the independent linear_aggregates vertical feature, required before containers or option/result can own resources. P6-4's generic/structural specialization task is implemented on this branch; this does not complete Phase 6.
## STD-5 verification
@@ -193,4 +193,4 @@ All 1079 conformance cases pass, including 18 path fixtures. All path runtime fi
The owner requested a sufficient intermediate std stage, integration of the work branch and resumption of language development. STD-0 through STD-7 provide nineteen compiler-pinned safe source modules: math/bytes/hash, UTF-8/hex/Base64/formatting, option/result, Vec/Deque/U64Map/general HashMap/HashSet/BinaryHeap, bounded std.io, owning buffered file adapters and lexical paths. The branch also supplies explicit modules/generics, whole-value linear aggregates/initialized buffers, pure error values and exact static callable contracts, through source/AIR/verifier/interpreter and tests where applicable. RFCs 0016–0035 are adopted and implemented; their rules are integrated into spec/reference in the same merged change.
This intermediate gate is sufficient to resume language work. It does not mark Std 0.1 complete: filesystem gaps, args/env, time/random wrappers, structured logs and CLI/storage exit examples remain STD-8; the public 5–10k LOC integration gate and network/JSON/HTTP/TLS milestones remain in the backlog. Frozen evaluation inputs and the private held-out corpus are untouched. Next source-language work is Q-034/P6-11 (explicit borrowed-return calls/bindings); P7/P8 retain their existing gate.
This intermediate gate is sufficient to resume language work. It does not mark Std 0.1 complete: filesystem gaps, args/env, time/random wrappers, structured logs and CLI/storage exit examples remain STD-8; the public 5–10k LOC integration gate and network/JSON/HTTP/TLS milestones remain in the backlog. Frozen evaluation inputs and the private held-out corpus are untouched. Q-034/P6-11 now has an implementation for review with explicit borrowed-return calls/bindings (RFC 0036 Proposed); P7/P8 retain their existing gate.
+1 -1
View File
@@ -447,4 +447,4 @@ Join normalizes absolute child alone, replacing base. Otherwise it normalizes ba
Both writers first validate all input bytes: NUL yields invalid_input, including in base when an absolute child replaces it. Invalid input precedes size_overflow, which precedes short_output. Every returned error leaves the entire destination unchanged. Success writes exactly the reported prefix, preserves the suffix and writes no NUL terminator. Only final normalized size must fit: a long component followed by `..` can normalize into one byte of output. Reverse measurement/emission needs fixed frame state and no intermediate buffer or allocation. Work is linear in supplied input/output bytes.
Input borrows can overlap each other; destination must be disjoint. Explicit split_at permits source/output in one allocation. Existing type/borrow/task-loan/Send/Share checks apply, including no-op/short-output paths. No unsafe boundary, new language/AIR semantics or hidden effects are needed. Borrow-return source support (Q-034) remains separate. The [pure example](../../examples/std/path.aji) joins into a caller buffer and borrows basename/parent/extension from the returned prefix. The independent Python forward-stack oracle covers normalization/join/query/capacity/idempotence; hosted fixtures confirm filesystem authority remains independent.
Input borrows can overlap each other; destination must be disjoint. Explicit split_at permits source/output in one allocation. Existing type/borrow/task-loan/Send/Share checks apply, including no-op/short-output paths. No unsafe boundary, new language/AIR semantics or hidden effects are needed. Ordinary source functions can return retained views under spec 15 §19; path queries retain their Copy range API. The [pure example](../../examples/std/path.aji) joins into a caller buffer and borrows basename/parent/extension from the returned prefix. The independent Python forward-stack oracle covers normalization/join/query/capacity/idempotence; hosted fixtures confirm filesystem authority remains independent.
+68
View File
@@ -0,0 +1,68 @@
# RFC 0036: Explicit source borrow returns
Status: Proposed\
Scope: P6-11 / Q-034; source 0.1 over existing format-0 ownership/arrays
The implementation, proposed spec integration and tests are prepared together. Only the owner moves this RFC to Accepted; implementation does not imply adoption.
## Motivation and precise invariant
AIR and the source declaration grammar already express `from`, but source calls could not retain the result. Functions can now expose borrowed elements and views without copying storage or giving away the owner. A result remains derived from exactly the named borrowed parameter; every owned borrow ends on each normal path or transfers with the result and its owned ancestors. Local-frame memory never escapes. Public effects and authority remain explicit.
## Normative integration
Spec 15 §19 contains the complete source rules and examples; §15/§17/§18 point to it. Existing declaration/expression grammar suffices: `from p`, `ref name = call(...);`, `mut name = call(...);`, `return name;` and a named function tail. The source bundle includes §19 in language/ownership.md; the Quick Reference has one checked example.
Borrow-return functions declare one borrowed origin with a compatible mode. Calls retain only a named borrowed origin and bind the result with the exact shared/exclusive mode. Other temporary arguments end after the call. Borrow-returning calls in ordinary value expressions/nested arguments reject; a return first binds any produced borrow and then names it. Branches can return directly but never merge borrow values. Unused generic signatures check what is known before specialization, while concrete substitutions check otherwise unknown modes. Static callable parameters still cannot carry borrow-return contracts.
## Verifier rule and implementation
Spec 08 §11.3 already checks roots, modes, live ancestor transfer and caller parent lifetime. Existing aliasing, task loans, initialization, region-generation and bounds checks remain authoritative. No verifier transfer state is added. The frontend tracks a bounded map from generated borrow identities to their immediate parents, including calls, split siblings, buffer/graph views and region outcome values. At a return it omits ends only for the result and ancestors, ends unrelated borrows in reverse order, and still emits structured scope/shield/lock exits. This map chooses cleanup mechanics; it cannot certify provenance. Frame and wrong-parameter returns reach the AIR verifier and are rejected there.
No new AIR instruction, feature or instruction meaning is added: signatures use `from %p`, calls produce the existing owned child, and `ret` transfers it. The contracts for `call`, `ret`, projections, reborrows and slice construction remain spec 07a/spec 08. Effects/capabilities, memory/concurrency access and trap behavior are unchanged. This completes source support for existing primitives rather than introducing an instruction as syntax sugar.
## Runtime and deterministic interpreter behavior
No interpreter/backend/runtime change, implicit heap allocation, refcount, destructor or unwinding. Returned identities refer to the caller's storage (or its explicitly allocated graph/region/buffer). Bounds violations retain T0008 and source mapping. Source and hand-written AIR have the same run record; deterministic/hosted profiles use the same verified contracts. Per-step collection and scheduler stress validate retained views and task lending.
## Valid and rejected examples
```aji
fn first(s: slice<u64>) -> ref<u64> from s effects [] {
ref item = s[0];
return item;
}
fn main() -> u64 effects [] {
let data = [42u64, 7u64];
ref s = data;
ref item = first(s);
return *item;
}
```
Replacing the body of first with `let n = 1u64; ref item = n; return item;` rejects E2108. Returning a child of another parameter rejects E2102. `first(ref data)` rejects E7006 with the named-parent repair. Mutating an exclusive parent while the returned child lives rejects E2101; calling through a task-loaned parent or lending its returned child twice rejects E4101. Ending the returned child in an inner block restores access to its parent.
## Diagnostics and compatibility
No new code or envelope. E7002 identifies unknown origins; E7005 identifies invalid origin/return types or modes; E7006 identifies missing from, invalid result/argument/return placement, main returns, borrow moves and spawning a borrow-returning function. The latter reports the source spawn directly instead of an unactionable feature-header error; task_borrow_returns remains reserved. Existing E2108/E2102/E2101/E2104/E3101/E4101 and T0008 retain their meaning and source/AIR locations. Validation also found that non-generic zero/oversized array annotations and repeated literals emitted invalid AIR; source type checking now reports E7005 for the existing format-0 1..2^32 bound instead of a compiler-bug diagnostic. Unused generic signatures also check these known bounds; formerly accepted invalid unused signatures now reject E7005. The exact maximum reaches the existing verifier shape budget (E5101) rather than a source type-size rejection when lowered. Existing valid source and AIR retain canonical lowering and behavior; formerly unimplemented from declarations become executable. Generic `move` on a borrow stays rejected. Existing libraries keep their Copy range APIs; this increment does not redesign them or complete Phase 6.
## Agent complexity impact
- New concepts: none in AIR; source now requires an explicit named parent for retained call results and transfers a named return's owned ancestors.
- Verifier/runtime state: none. Frontend signature metadata holds the from parameter index; mechanical ancestry is linear in generated borrow definitions, with ancestor walks bounded by the function's finite instruction graph.
- Syntax: no keyword, grammar production or AIR opcode. Two already existing binding forms now accept declared borrow-returning calls; return/function-tail names use the existing forms.
- Interactions: nominal package calls, explicit generic substitution, mutable/shared views, split siblings, owned buffers, regions, task loans and structured exits. No borrow joins, lifetime inference, callable lifetime parameters or aggregate borrows.
- Repairability: local E7xxx messages require named bindings and exact modes; provenance failures remain stable verifier codes at the return/call. Agents can end a view by placing it in an inner block.
- Existing primitives suffice: the AIR facility was implemented in Phase 1. Extending source completes its vertical path and avoids manually authoring SSA and borrow.end.
- Budget: source and Quick Reference measurements are recorded below. AIR bundle is unchanged. Detailed rules stay on demand in ownership.md. No empirical Model Capability Compression improvement is claimed and no private benchmark material was accessed.
## Alternatives considered
Promoting inline origin temporaries would invisibly extend their lifetimes and complicate repair and ordering. Ending them immediately would make every retained child invalid. Mandatory named parents reuse the established graph/buffer convention. Borrow-valued joins, implicit mode conversion and lifetime parameters would add semantic state beyond existing format 0. Returning named borrows and explicit branches covers the current primitive facility without those additions.
## Validation
The source conformance corpus covers direct/tail/branch returns, call forwarding, nested projection ancestors, split siblings, mutable slices, buffer views, region allocation outcome paths, generic contracts and task loans. Review adds normal returns through scope/shield/lock exits, rejection of an unjoined task and lock-guard escape at a borrow return, direct spawn rejection, and unused generic array bounds. An independent source twin compares with the frozen Phase 1 AIR borrow-return program. CLI integration checks canonical lowering, source/AIR records, packages with ordinary/generic qualified calls, imported diagnostic/trap provenance, profiles and audit/exploration commands. CI runs the integration script. Validation: unit tests and formatting pass; 56 focused conformance tests pass with per-step collection; the concurrent fixture also passes 200 schedule seeds across four quanta; the generic corpus passes 61/61. CLI integration passes 133 checks, existing generic/module integrations pass 20/36 checks, and hosted filesystem/stdin/TCP smoke passes. After review fixes, the full conformance run passes 1,135/1,135 with no failures or pending tests. Source construct coverage passes 119/119. Independent read-only review by Claude found the source spawn diagnostic defect and unused generic array-bound gap; both were corrected and independently rechecked, with no further findings in those fixes.
Measured cl100k growth from RFC 0035: Quick Reference 8,518 → 8,642 (+1.46%); other source documentation 63,296 → 64,160 (+1.37%); full source excluding AIR 71,814 → 72,802 (+1.38%). language/ownership.md is 1,834 tokens (previously 985). Corresponding o200k groups are 8,677 / 64,359 / 73,036; qwen2.5 groups are 8,900 / 65,733 / 74,633. AIR remains 179,282 bytes / 19 files / 51 sections; its source-bundle copy stays 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k source growth over the pre-std 33,981 baseline is +114.24%, justified by completing an existing explicit lifetime facility; Quick Reference remains beyond the plan's current 5–8k target and front-door consolidation/selective reading remains separate work. These measurements precede the review's reserved-float clarification and validation fixes; the latter add 54 cl100k tokens, with current full source at 72,902 and Quick Reference at 8,688. Current counts are recorded in docs/agent/README.md. No empirical MCC benefit is inferred.
+33 -6
View File
@@ -171,7 +171,7 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
| Source | Meaning |
|---|---|
| `ref r = place;` / `mut r = place;` | **the only way to bind a borrow**: a statement, valid to the end of the enclosing block. `let r = mut x;` is `E7006`. An active borrow cannot be shadowed by the same name in the same scope (`E7006`). Borrowing a whole array binds a slice (`slice<T>` / `slice_mut<T>`). Borrowing a borrow binding reborrows it. |
| `ref r = place;` / `mut r = place;` | **the only way to bind a borrow**: a statement, valid to the end of the enclosing block. `let r = mut x;` is `E7006`. An active borrow cannot be shadowed by the same name in the same scope (`E7006`). Borrowing a whole array binds a slice (`slice<T>` / `slice_mut<T>`). Borrowing a borrow binding reborrows it. Declared borrow-returning calls are bound with the same forms under §19. |
| `ref place` / `mut place` as an argument | a temporary borrow for that call (ended right after it); allowed only as an argument |
| `*r` | load through `ref<T>`/`mut<T>` of a scalar or struct; slices and arrays use `s[i]` (`E7006`) |
| `r.f` | field through a borrow of a struct (borrow, load, end) |
@@ -370,7 +370,7 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
## 9. Frame storage, borrow scopes and features
- **Frame storage.** Addressability is a property of lowering, not of source types. Linear values (owners, regions, resources, endpoints, tasks, mutexes) never get frame storage: they are borrowed in place. A variable whose name is borrowed, indexed, or written through a field or element anywhere in the function lowers to `local<T>` storage, allocated in the entry block (spec 08 §11.5). Every other variable is an SSA value. The decision is by name, so the same source always gives the same placement. The frame-size limit applies to the lowered AIR. There is no implicit heap allocation.
- **Borrow scopes.** A borrow bound by `ref`/`mut` ends at the end of the block that contains the binding. Because a borrow's name is not visible after its scope, a use after the borrow ended (`E2106`) cannot be written in source. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope. The frontend emits `borrow.end` in reverse order of creation. A borrow that must end earlier is placed in an inner block. Borrows lent to tasks end at the join (spec 04 §34).
- **Borrow scopes.** A borrow bound by `ref`/`mut` ends at the end of the block that contains the binding. Because a borrow's name is not visible after its scope, a use after the borrow ended (`E2106`) cannot be written in source. A temporary borrow, used directly as an operand, ends at the end of its statement. Both end at every normal exit from their scope, except the named returned borrow and its owned ancestors transferred under §19. The frontend emits `borrow.end` in reverse order of creation. A borrow that must end earlier is placed in an inner block. Borrows lent to tasks end at the join (spec 04 §34).
- **Features.** The frontend emits the `features [...]` header as the dependency closure of the constructs used, always including `effects`.
- **Effects.** They are declared by the programmer. `E3101` names the missing effect and suggests the complete effect list (`suggested_effects`).
@@ -526,7 +526,7 @@ Every generic use MUST supply exactly its ordered arguments (type arguments here
Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; type parameters are types, not values or operations; static function parameters are separately defined in §18. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT bypass the member restrictions; linear members require §16, and borrowed aggregate members remain forbidden.
Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity, effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source.
Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity and array lengths (1..2^32, `E7005`), effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source.
### 15.2 Structural constraints
@@ -538,7 +538,7 @@ A type can satisfy several constraints; each requirement MUST be checked. Constr
A specialization is keyed by template module identity, declaration kind/name and the ordered structural identity of concrete arguments. Named arguments use nominal defining-module identity, independent of source filename, short/qualified spelling or import/provider order. Each key MUST emit at most one concrete declaration; repeated same-key recursion reuses it. Type-specialization cycles still obey ordinary finite-layout rules. Expanding specialization is bounded by 4,096 generated declarations and active expansion depth 64 (`E7006`), with structural type traversal bounded at depth 64. These are fixed compiler input limits, not runtime fuel or semantic flags.
Non-generic declarations retain their AIR names and order. Generated types and functions append in lexicographic specialization-key order within their categories. Their AIR identifier starts with `__aji_g_` followed by lowercase SHA-256 of the canonical key bytes; collisions with original names or earlier keys in sorted order receive the smallest unused `_1`, `_2`, … suffix. The canonical key is `type:` or `fn:`, full defining-module/declaration path, and ordered `<...>` arguments. Named arguments use full nominal paths, applied arguments recursively spell their template/arguments, arrays spell `[T;N]` with decimal N, wrappers/cap/file spell `name<T>`; argument separators are commas without whitespace. Full keys, not hashes, determine identity and reuse. Keys are limited to 16,384 bytes (`E7006`). Every required body lowers to existing format-0 constructs, and the combined module MUST pass the ordinary verifier. There is no new AIR instruction/feature, verifier transfer state, runtime dispatch, implicit allocation/refcount/destructor, effect inference or authority. Source provenance retains template locations and the locations of supplied argument types. Generic borrow/owner/task contracts use the existing runtime/interpreter rules unchanged. Existing monomorphic source and AIR retain meaning and canonical lowering. The finite-layout verifier now visits array elements as well as direct nominal members, closing a prior E1003 implementation gap without changing the normative no-recursive-value rule. Existing unimplemented source `from`-returns remain unimplemented; specialization retains their contract rather than inventing borrow lifetimes.
Non-generic declarations retain their AIR names and order. Generated types and functions append in lexicographic specialization-key order within their categories. Their AIR identifier starts with `__aji_g_` followed by lowercase SHA-256 of the canonical key bytes; collisions with original names or earlier keys in sorted order receive the smallest unused `_1`, `_2`, … suffix. The canonical key is `type:` or `fn:`, full defining-module/declaration path, and ordered `<...>` arguments. Named arguments use full nominal paths, applied arguments recursively spell their template/arguments, arrays spell `[T;N]` with decimal N, wrappers/cap/file spell `name<T>`; argument separators are commas without whitespace. Full keys, not hashes, determine identity and reuse. Keys are limited to 16,384 bytes (`E7006`). Every required body lowers to existing format-0 constructs, and the combined module MUST pass the ordinary verifier. There is no new AIR instruction/feature, verifier transfer state, runtime dispatch, implicit allocation/refcount/destructor, effect inference or authority. Source provenance retains template locations and the locations of supplied argument types. Generic borrow/owner/task contracts use the existing runtime/interpreter rules unchanged. Existing monomorphic source and AIR retain meaning and canonical lowering. The finite-layout verifier now visits array elements as well as direct nominal members, closing a prior E1003 implementation gap without changing the normative no-recursive-value rule. Borrow-return contracts are retained by specialization and checked under §19.
## 16. Source linear aggregates
@@ -555,7 +555,7 @@ The frontend MUST declare linear_aggregates plus its dependencies whenever any e
`buffer<T>` is the linear initialized-prefix owner of spec 03 §26. Built-ins use ordinary explicit borrows, moves and outcome matches: `buffer.new<T>(capacity, heap)`, `buffer.len(b)`, `buffer.capacity(b)`, `buffer.reserve(b, capacity, heap)`, `buffer.push(b, move value)`, `buffer.pop(b)` and `buffer.free(move owner)`. Except new/free, b MUST be a named ref/mut<buffer<T>> binding, borrowed first from an owner or aggregate field. Mutating operations require mut. len/capacity accept ref or mut. new/reserve declare mem.alloc explicitly. push requires no heap capability and never grows implicitly.
Outcomes: new has ok(buffer)/err(alloc_error); reserve has ok()/err(alloc_error); push has ok()/err(original_value); pop has ok(value)/err(); free has ok()/err(original_buffer). Ordinary exhaustive outcome matching/or trap applies. A returned linear value MUST be explicitly consumed. `ref values = buffer.view(b);` binds a shared slice from ref or mut b; `mut values = buffer.view(b);` requires mut b and binds an exclusive slice. The child borrow lasts for its explicit lexical scope and never escapes through an aggregate. This is a primitive borrow binding like graph access, not a general function returning a borrow (Q-034 remains open). Existing indexing/value.swap provides Copy reading and complete linear element exchange. Views expose only the initialized prefix; mutation/growth/free while a view or task loan is live MUST reject even on a dynamically full/empty/no-op branch.
Outcomes: new has ok(buffer)/err(alloc_error); reserve has ok()/err(alloc_error); push has ok()/err(original_value); pop has ok(value)/err(); free has ok()/err(original_buffer). Ordinary exhaustive outcome matching/or trap applies. A returned linear value MUST be explicitly consumed. `ref values = buffer.view(b);` binds a shared slice from ref or mut b; `mut values = buffer.view(b);` requires mut b and binds an exclusive slice. The child borrow lasts for its explicit lexical scope and never escapes through an aggregate. This primitive binding also permits ordinary functions to return retained views under §19. Existing indexing/value.swap provides Copy reading and complete linear element exchange. Views expose only the initialized prefix; mutation/growth/free while a view or task loan is live MUST reject even on a dynamically full/empty/no-op branch.
A specialized generic body MAY use `move name` to express complete value transfer for a type parameter. If its concrete binding is Copy, lowering passes the existing Copy value and it remains available; if linear, ordinary transfer/availability applies. This rule applies to complete Copy bindings inside a specialized generic body, not borrows or internal storage/scope/guard/shield handles. A Copy value bound in frame storage remains a Copy value and is loaded normally when transferred. Outside a specialized generic body, move of a Copy value remains E7006. No AIR ownership rule changes and no implicit destructor/allocation is added. This makes one generic container body correct for both Copy and linear contents; ordinary borrow/effect/type constraints still apply to every specialization.
@@ -563,7 +563,7 @@ The frontend MUST emit linear_buffers and its full dependencies for buffer types
## 18. Static function parameters
Generic structs, enums and functions MAY declare a static function parameter alongside type parameters: `F: fn(ref<T>) -> u64 effects []`. This is a compile-time contract, not a value type. Its ordered parameter types, return type and complete flat effect set MUST be explicit. Static function parameter names MUST be uppercase, distinct, and MUST NOT shadow a visible type or function. All types are checked/substituted like ordinary function signatures; all effect atoms MUST be registered and unique. Borrow returns and `from` contracts are outside this increment (Q-034). A callable parameter MUST NOT carry structural property constraints or be used as a type. The existing maximum of eight generic parameters counts both kinds.
Generic structs, enums and functions MAY declare a static function parameter alongside type parameters: `F: fn(ref<T>) -> u64 effects []`. This is a compile-time contract, not a value type. Its ordered parameter types, return type and complete flat effect set MUST be explicit. Static function parameter names MUST be uppercase, distinct, and MUST NOT shadow a visible type or function. All types are checked/substituted like ordinary function signatures; all effect atoms MUST be registered and unique. Static function parameter borrow returns and `from` contracts remain unsupported; ordinary functions use §19. A callable parameter MUST NOT carry structural property constraints or be used as a type. The existing maximum of eight generic parameters counts both kinds.
An explicit argument is `fn path`, or `fn path::<arguments>` for a generic function. The path MUST resolve to a directly accessible declared source function. Built-in operation names, runtime values and captures are not function arguments. `fn F` forwards an already bound static parameter; it cannot be specialized again. A type argument in a function position or a function argument in a type position is `E7005`. Wrong generic arity remains `E7006`; unknown/inaccessible functions remain `E7002`. Signature/effect mismatch diagnostics include `parameter`, `function`, `expected` and `found` contracts.
@@ -584,3 +584,30 @@ fn apply<T, F: fn(T) -> T effects []>(value: T) -> T effects [] {
```
General collections MAY use these explicit contracts for hash/equality/order operations. Their algebraic laws remain library preconditions; no compiler magic infers hashing or equality. This facility alone does not complete HashMap/HashSet or resolve their storage/API invariants.
## 19. Source borrow returns
Source functions MAY return `ref<T>`, `mut<T>`, `slice<T>` or `slice_mut<T>` with an explicit `from p` naming a borrow parameter. A borrow return without `from` is `E7006`; an unknown origin is `E7002`; a non-borrow origin or non-borrow return with `from` is `E7005`. An exclusive return requires an exclusive origin (`E7005`). `main` MUST NOT return a borrow (`E7006`). A borrow-returning function MUST NOT be passed to `task.spawn` (`E7006` at the spawn); `task_borrow_returns` remains reserved (spec 04 §33.1).
A borrow-returning call MUST be bound as `ref name = f(...);` for a shared result or `mut name = f(...);` for an exclusive result. The binding mode MUST equal the result mode (`E7005`); there is no implicit mode conversion. The argument in the callee's `from` position MUST be an existing named borrow binding or borrow parameter (`E7006` for an inline borrow, byte string or nested call). Other arguments retain ordinary call rules and their temporary borrows end after the call. This rule makes the retained parent explicit: the result ends with its binding's lexical block, before its parent. A call producing a borrow in an ordinary value expression, `let` or nested argument is `E7006`. Bind the result first, then use its name.
A borrow return MUST name a borrow parameter or borrow binding: `return view;`, or `view` as the function body's tail expression. Borrow-producing calls and inline places MUST first be bound (`E7006`). Nested blocks, `if` and `match` MUST NOT yield borrow values; branches MAY return directly. `move` does not apply to borrows (`E7006`). At each normal function return the frontend MUST omit `borrow.end` for the returned borrow and its owned ancestors, and end all other lexical borrows in reverse creation order. This is a transfer to the caller, never a destructor or an inferred resource cleanup. Task scopes, shields and locks retain their existing exit obligations.
The output uses the existing AIR `from %p`, `call`, `ret` and borrow instructions; no feature, instruction, effect, capability or runtime rule is added. The ordinary verifier (spec 08 §11.3) MUST reject a returned local-frame view (`E2108`) or a view rooted in another parameter (`E2102`). Shared/exclusive aliasing, task loans, initialization and bounds remain checked, including after a returned view ends. The frontend's ancestry bookkeeping only selects ends; it MUST NOT replace verifier provenance checks. The deterministic interpreter executes the same verified AIR in both execution profiles; invalid memory cannot be exposed by returning a view. Existing source/AIR programs keep their meaning and canonical lowering; previously unimplemented `from` declarations become executable. Static function parameter contracts remain outside this increment (§18); ordinary generic and package functions MAY return borrows. Unused generic signatures MUST still check a spelled borrow return, origin name and known modes; a bare type parameter whose mode is unknown MUST be checked after concrete substitution.
Valid:
```aji
fn first(s: slice<u64>) -> ref<u64> from s effects [] {
ref item = s[0];
return item;
}
fn main() -> u64 effects [] {
let data = [42u64, 7u64];
ref s = data;
ref item = first(s);
return *item;
}
```
Rejected: replacing the body of `first` with `let n = 1u64; ref item = n; return item;` MUST produce `E2108`. Calling `first(ref data)` MUST produce `E7006`: bind `ref s = data;` and pass `s`. Mutation through an exclusive parent while the returned view is live MUST produce `E2101`; a live task loan remains `E4101`. Borrow access out of bounds traps `T0008` identically to the existing AIR instruction.
+1 -1
View File
@@ -396,4 +396,4 @@ Join MUST normalize child alone when child is absolute; otherwise normalize the
Writing operations MUST validate input and determine final normalized length before mutation. Capacity need only accommodate the final prefix, not canceled components or raw concatenation; joining/normalization MUST NOT demand hidden scratch/heap storage. The safe reference algorithm scans components backward, tracking pending parent components, measures retained bytes/separators with checked arithmetic, then emits the retained components backward into the already-validated prefix. Pending relative parents become the leading `..` components; rooted excess parents are dropped. No combined raw input length is required. Input-size/length/cursor arithmetic MUST avoid overflow; size_overflow is ordinary data, not a trap. For conforming slices, returned errors/success do not trap except ordinary fuel exhaustion.
Existing slices, Copy structs/enums, checked bounds/arithmetic, exclusive-output/shared-input loans, effects and task Send/Share rules suffice. No owner/resource is consumed and no loan escapes. Valid/rejected calls use existing E7002/E7005/E2101/E4101; malformed bytes and insufficient capacity are ordinary WriteResult variants, not verifier diagnostics. No new syntax, AIR meaning/instruction/feature, verifier/runtime state or unsafe/trusted boundary is introduced. Query work is O(path.len); writing work is O(base.len+child.len+output.len) with fixed frame state and existing interpreter costs. Current source borrow-return limitations (Q-034) remain unchanged. Filesystem/system gaps and the Std 0.1 exit examples remain subsequent work.
Existing slices, Copy structs/enums, checked bounds/arithmetic, exclusive-output/shared-input loans, effects and task Send/Share rules suffice. No owner/resource is consumed and no loan escapes. Valid/rejected calls use existing E7002/E7005/E2101/E4101; malformed bytes and insufficient capacity are ordinary WriteResult variants, not verifier diagnostics. No new syntax, AIR meaning/instruction/feature, verifier/runtime state or unsafe/trusted boundary is introduced. Query work is O(path.len); writing work is O(base.len+child.len+output.len) with fixed frame state and existing interpreter costs. Path queries retain their Copy range API independently of ordinary source borrow returns (spec 15 §19). Filesystem/system gaps and the Std 0.1 exit examples remain subsequent work.
+31 -1
View File
@@ -191,7 +191,10 @@ const Generator = struct {
if (d.generics.len == 0 or d.generics.len != x.args.len) return g.fail("E7006", t.span, "template type argument count mismatch", x.name);
for (d.generics, x.args) |p, arg| try g.headerArgument(p, arg, params, depth + 1);
},
.array => |a| try g.headerType(a.elem.*, params, depth + 1),
.array => |a| {
if (a.len == 0 or a.len > (@as(u64, 1) << 32)) return g.fail("E7005", t.span, "array length must be between 1 and 2^32", "array");
try g.headerType(a.elem.*, params, depth + 1);
},
.wrapped => |w| try g.headerType(w.inner.*, params, depth + 1),
.cap => |k| if (authority.kindIndex(k) == null) return g.fail("E7002", t.span, "unknown capability kind", k),
.file => |mode| if (!(std.mem.eql(u8, mode, "read") or std.mem.eql(u8, mode, "write") or std.mem.eql(u8, mode, "append"))) return g.fail("E7002", t.span, "unknown file mode", mode),
@@ -216,6 +219,32 @@ const Generator = struct {
for (target.generics, f.args) |p, a| try g.headerArgument(p, a, params, depth + 1);
}
/// Check the lifetime contract even on unused templates. A bare type
/// parameter's mode is checked later, after concrete substitution.
fn borrowMode(t: ast.Type, params: []const ast.TypeParam) ?u2 {
if (t.kind == .wrapped) {
const w = t.kind.wrapped.wrapper;
if (std.mem.eql(u8, w, "ref") or std.mem.eql(u8, w, "slice")) return 1;
if (std.mem.eql(u8, w, "mut") or std.mem.eql(u8, w, "slice_mut")) return 2;
}
if (t.kind == .name) for (params) |p| {
if (p.callable == null and std.mem.eql(u8, p.name, t.kind.name)) return null;
};
return 0;
}
fn borrowReturnContract(g: *Generator, f: ast.FnDecl) Error!void {
const ret = borrowMode(f.ret, f.generics);
if (f.from) |name| {
const param = for (f.params) |p| {
if (std.mem.eql(u8, name, p.name)) break p;
} else return g.fail("E7002", f.span, "unknown from parameter", name);
const origin = borrowMode(param.ty, f.generics);
if (ret == 0 or origin == 0) return g.fail("E7005", f.span, "from requires a borrow return and a borrow parameter", name);
if (ret == 2 and origin == 1) return g.fail("E7005", f.span, "exclusive return requires an exclusive from parameter", name);
} else if (ret == 1 or ret == 2) return g.fail("E7006", f.span, "a borrow return requires from parameter", f.name);
}
fn run(g: *Generator) Error!ast.Module {
var generic = false;
for (g.m.types, 0..) |t, i| {
@@ -249,6 +278,7 @@ const Generator = struct {
try g.headerType(p.ty, f.generics, 0);
}
try g.headerType(f.ret, f.generics, 0);
try g.borrowReturnContract(f);
}
generic = generic or f.generics.len != 0;
}
+117 -33
View File
@@ -264,7 +264,7 @@ const Rest = struct {
const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 };
const FnSig = struct { params: []const Ty, ret: Ty, air_name: []const u8, display_name: []const u8 };
const FnSig = struct { params: []const Ty, ret: Ty, from: ?usize = null, air_name: []const u8, display_name: []const u8 };
const Lowerer = struct {
arena: Allocator,
@@ -295,6 +295,8 @@ const Lowerer = struct {
/// The current function's parameter names, which generated names avoid.
params: []const ast.Param = &.{},
ret: Ty = .void,
/// Mechanical ancestry for transferring lexical ends; AIR verifies provenance.
borrow_parents: std.StringHashMapUnmanaged([]const u8) = .empty,
/// Statements still to be lowered in each enclosing block (innermost
/// last), for inferring the type of an untyped `let` from its uses.
rest: std.ArrayList(Rest) = .empty,
@@ -449,7 +451,19 @@ const Lowerer = struct {
if (l.sigs.contains(f.name)) return l.fail("E7006", f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
const ps = try l.arena.alloc(Ty, f.params.len);
for (f.params, ps) |p, *t| t.* = try l.typeOf(p.ty);
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret), .air_name = f.air_name orelse f.name, .display_name = f.display_name orelse f.name });
const ret = try l.typeOf(f.ret);
var origin: ?usize = null;
if (f.from) |name| {
for (f.params, 0..) |param, i| if (std.mem.eql(u8, param.name, name)) {
origin = i;
break;
};
const i = origin orelse return l.unknown(f.span, name);
if (!ret.isBorrow() or !ps[i].isBorrow()) return l.fail("E7005", f.span, "`from` requires a borrow return and a borrow parameter", &.{});
if (ret.isMutBorrow() and !ps[i].isMutBorrow()) return l.fail("E7005", f.span, "an exclusive return requires an exclusive `from` parameter", &.{});
} else if (ret.isBorrow()) return l.fail("E7006", f.span, "a borrow return requires `from parameter`", &.{});
if (std.mem.eql(u8, f.name, "main") and ret.isBorrow()) return l.fail("E7006", f.span, "main cannot return a borrow", &.{});
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = ret, .from = origin, .air_name = f.air_name orelse f.name, .display_name = f.display_name orelse f.name });
}
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
@@ -665,7 +679,10 @@ const Lowerer = struct {
if (std.mem.eql(u8, n, "listener")) return .{ .resource = .listener };
return l.fail("E7002", t.span, "unknown type", &.{.{ .name = "name", .value = n }});
},
.array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len),
.array => |a| {
if (a.len == 0 or a.len > (@as(u64, 1) << 32)) return l.fail("E7005", t.span, "array length must be between 1 and 2^32", &.{});
return l.arrayOf(try l.memberType(a.elem.*), a.len);
},
.wrapped => |w| {
const Wr = enum { ref, mut, slice, slice_mut, own, own_array, buffer, task, sender, receiver, mutex, island, frozen, arc, iref, atomic };
const which = std.meta.stringToEnum(Wr, w.wrapper) orelse return l.notYet(t.span, "this type (later layers)");
@@ -715,7 +732,7 @@ const Lowerer = struct {
try l.findAddressable(f.body);
const sig = l.sigs.get(f.name).?;
l.ret = sig.ret;
if (f.from != null) return l.notYet(f.span, "borrow returns (layer 4)");
l.borrow_parents = .empty;
// `trusted` is the boundary of runtime, std and toolchain modules; an
// ordinary program cannot declare its own code trusted (spec 15 §8).
if (f.trusted != null) return l.fail("E7006", f.span, "`trusted` is not available in .aji programs; unsafe operations need `effects [unsafe]`, which propagates to callers", &.{});
@@ -731,6 +748,7 @@ const Lowerer = struct {
try header.appendSlice(l.arena, try l.fmt("{s}%{s}: {s}", .{ if (i == 0) "" else ", ", v, l.tyText(t) }));
}
try header.appendSlice(l.arena, try l.fmt(") -> {s}", .{l.tyText(sig.ret)}));
if (f.from) |origin| try header.appendSlice(l.arena, try l.fmt(" from %{s}", .{origin}));
_ = try l.newBlock("entry");
l.cur = 0;
@@ -815,6 +833,12 @@ const Lowerer = struct {
return .{ .name = name, .ty = ty };
}
fn defBorrow(l: *Lowerer, base: []const u8, ty: Ty, text: []const u8, parent: []const u8, span: Span) Error!Value {
const v = try l.def(base, ty, text, span);
try l.borrow_parents.put(l.arena, v.name, parent);
return v;
}
fn term(l: *Lowerer, text: []const u8, span: Span) Error!void {
try l.emit(text, span);
l.blocks.items[l.cur.?].terminated = true;
@@ -967,17 +991,28 @@ const Lowerer = struct {
l.rest.items[l.rest.items.len - 1].current = null;
l.rest.items[l.rest.items.len - 1].tail = null;
l.rest.items[l.rest.items.len - 1].current_expr = t;
result = try l.expr(t.*, want);
if (result.?.ty.isBorrow()) return l.fail("E7006", t.span, "a block cannot yield a borrow", &.{});
if (l.scopes.items.len == 1 and l.ret.isBorrow() and t.kind == .name) {
result = try l.returnValue(t.*);
} else {
result = try l.expr(t.*, want);
if (result.?.ty.isBorrow()) return l.fail("E7006", t.span, "a block cannot yield a borrow", &.{});
}
}
// The borrows bound in this block end here (lexical scope, spec 15 §9).
if (l.cur != null) try l.endScopes(l.scopes.items.len - 1, b.span);
if (l.cur != null) {
const transfer: ?[]const u8 = if (result) |v| (if (v.ty.isBorrow()) v.name else null) else null;
try l.endScopesExcept(l.scopes.items.len - 1, b.span, transfer);
}
return result;
}
/// Ends the borrows of every scope from index `from` upwards, innermost
/// first, without closing the scopes (used at block ends and exits).
fn endScopes(l: *Lowerer, from: usize, span: Span) Error!void {
try l.endScopesExcept(from, span, null);
}
fn endScopesExcept(l: *Lowerer, from: usize, span: Span, transfer: ?[]const u8) Error!void {
var i = l.scopes.items.len;
while (i > from) {
i -= 1;
@@ -985,11 +1020,25 @@ const Lowerer = struct {
var k = ends.len;
while (k > 0) {
k -= 1;
if (transfer) |v| if (std.mem.eql(u8, ends[k].op, "borrow.end") and l.borrowAncestor(ends[k].name, v)) continue;
try l.emit(try l.fmt("{s} %{s}", .{ ends[k].op, ends[k].name }), if (i == l.scopes.items.len - 1 and from == i) ends[k].span else span);
}
}
}
fn borrowAncestor(l: *Lowerer, ancestor: []const u8, child: []const u8) bool {
var current = child;
while (true) {
if (std.mem.eql(u8, ancestor, current)) return true;
current = l.borrow_parents.get(current) orelse return false;
}
}
fn returnValue(l: *Lowerer, e: ast.Expr) Error!Value {
if (l.ret.isBorrow() and e.kind != .name) return l.fail("E7006", e.span, "return a named borrow; bind a returned view or place first", &.{});
return l.consuming(e, l.ret);
}
fn scopeEnds(l: *Lowerer, names: []const []const u8, span: Span) Error!void {
const top = &l.scopes.items[l.scopes.items.len - 1];
for (names) |n| try top.append(l.arena, .{ .name = n, .span = span });
@@ -1087,13 +1136,22 @@ 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 (l.borrowReturnSig(x.place.kind.call.callee.*)) |sig| if (sig.ret.isBorrow()) {
if (x.unchecked) return l.fail("E7006", s.span, "unchecked applies to element places, not calls", &.{});
if (x.mutable != sig.ret.isMutBorrow()) return l.fail("E7005", s.span, "binding mode must match the returned borrow; use ref for shared or mut for exclusive", &.{});
const call_expr = x.place.kind.call;
const v = try l.call(x.place, call_expr.callee.*, call_expr.args, true);
try l.scopeEnds(&.{v.name}, s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = v.name, .ty = v.ty, .kind = .borrow });
return;
};
if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "buffer.view")) return l.bufferView(s, x.name, x.mutable, x.place);
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.
const rb = try l.def(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), s.span);
const rb = try l.defBorrow(x.name, p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), p.v.name, s.span);
try l.scopeEnds(&.{rb.name}, s.span);
try l.bindings.append(l.arena, .{ .name = x.name, .mutable = false, .value = rb.name, .ty = rb.ty, .kind = .borrow });
} else {
@@ -1103,10 +1161,10 @@ const Lowerer = struct {
},
.@"return" => |e| {
if (e) |x| {
const v = try l.consuming(x, l.ret);
const v = try l.returnValue(x);
try l.checkTy(x.span, v.ty, l.ret);
if (l.cur != null) {
try l.endScopes(0, s.span);
try l.endScopesExcept(0, s.span, if (v.ty.isBorrow()) v.name else null);
try l.term(try l.retText(v), s.span);
}
} else {
@@ -1272,6 +1330,12 @@ const Lowerer = struct {
return l.functionSig(name orelse return null, e.span);
}
fn borrowReturnSig(l: *Lowerer, e: ast.Expr) ?FnSig {
if (pathOf(e) != null) return null;
if (e.kind == .name and (std.mem.eql(u8, e.kind.name, "assert") or std.mem.eql(u8, e.kind.name, "assume"))) return null;
return l.calleeSig(e);
}
fn moduleCall(l: *Lowerer, e: ast.Expr) Error!?[]const u8 {
if (e.kind != .field) return null;
const name = try expressionPath(l.arena, e) orelse return null;
@@ -1468,6 +1532,7 @@ const Lowerer = struct {
return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ l.tyText(at), names.items }), e.span);
},
.array_rep => |x| {
if (x.len == 0 or x.len > (@as(u64, 1) << 32)) return l.fail("E7005", e.span, "array length must be between 1 and 2^32", &.{});
const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null;
const v = try l.expr(x.e.*, want_elem);
if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "an array element cannot be a borrow", &.{});
@@ -1519,7 +1584,7 @@ const Lowerer = struct {
};
return l.def("cast", to, try l.fmt("cast.{s}.{s} %{s}", .{ mode, to.int, v.name }), e.span);
},
.call => |x| return l.call(e, x.callee.*, x.args),
.call => |x| return l.call(e, x.callee.*, x.args, false),
.if_expr => |x| return l.ifExpr(e.span, x.*, want),
.block => |b| {
const v = try l.blockBodyWant(b.*, want);
@@ -1614,7 +1679,7 @@ const Lowerer = struct {
return l.def(if (cmp) "cmp" else "t", if (cmp) .bool else ty, try l.fmt("{s} %{s}, %{s}", .{ text, lv.name, rv.name }), e.span);
}
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value {
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr, borrow_allowed: bool) Error!Value {
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "buffer.len") or std.mem.eql(u8, p, "buffer.capacity")) {
if (args.len != 1) return l.fail("E7005", e.span, "buffer metadata read takes one named borrow", &.{});
@@ -1640,7 +1705,7 @@ const Lowerer = struct {
if (try l.moduleCall(callee)) |name| {
// Reuse ordinary call typing/borrowing/lowering, including E7002.
const owned_name = try l.arena.dupe(u8, name);
return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args);
return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args, borrow_allowed);
}
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
@@ -1704,24 +1769,36 @@ const Lowerer = struct {
}
const sig = l.functionSig(name, callee.span) orelse return l.unknown(callee.span, name);
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
if (sig.ret.isBorrow() and !borrow_allowed) return l.fail("E7006", e.span, "bind a returned borrow with ref/mut name = call(...) first", &.{});
if (sig.from) |origin| {
const a = args[origin];
if (a.kind != .name) return l.fail("E7006", a.span, "the from argument must be a named borrow; bind it first", &.{});
const b = l.lookup(a.kind.name) orelse return l.unknown(a.span, a.kind.name);
if (b.kind != .borrow) return l.fail("E7006", a.span, "the from argument must be a named borrow; bind it first", &.{});
}
var parent: ?[]const u8 = null;
var arg_names: std.ArrayList(u8) = .empty;
var temps: std.ArrayList([]const u8) = .empty;
for (args, sig.params, 0..) |a, pt, i| {
const v = try l.argument(a, pt, &temps);
if (sig.from == i) parent = v.name;
try l.checkTy(a.span, v.ty, pt);
try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const text = try l.fmt("call @{s}({s})", .{ sig.air_name, arg_names.items });
defer l.endNowIfLive(temps.items, e.span) catch {};
if (sig.ret == .void or sig.ret == .never) {
try l.emit(text, e.span);
if (sig.ret == .never) {
try l.term("trap", e.span); // `never` returns do not come back
return .{ .name = "", .ty = .never };
}
try l.endNowIfLive(temps.items, e.span);
return .{ .name = "", .ty = .void };
}
return l.def(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
const result = try l.def(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
if (parent) |p| try l.borrow_parents.put(l.arena, result.name, p);
try l.endNowIfLive(temps.items, e.span);
return result;
}
/// `Name { f: e, … }`: every field exactly once; initializers are
@@ -2060,12 +2137,12 @@ const Lowerer = struct {
l.in_constant = @intCast(l.constants.items.len);
defer l.in_constant = 0;
try l.emit(try l.fmt("local.zero %{s}", .{st}), span);
const b = try l.def("w", try l.wrap(.mut, ty), try l.fmt("borrow.mut %{s}", .{st}), span);
const b = try l.defBorrow("w", try l.wrap(.mut, ty), try l.fmt("borrow.mut %{s}", .{st}), st, span);
for (bytes, 0..) |byte, i| {
if (byte == 0) continue; // already zero
const idx = try l.def("i", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{i}), span);
const c = try l.def("c", .{ .int = "u8" }, try l.fmt("const.u8 {d}", .{byte}), span);
const el = try l.def("e", try l.wrap(.mut, .{ .int = "u8" }), try l.fmt("borrow.index %{s}, %{s}", .{ b.name, idx.name }), span);
const el = try l.defBorrow("e", try l.wrap(.mut, .{ .int = "u8" }), try l.fmt("borrow.index %{s}, %{s}", .{ b.name, idx.name }), b.name, span);
try l.emit(try l.fmt("store %{s}, %{s}", .{ el.name, c.name }), span);
try l.emit(try l.fmt("borrow.end %{s}", .{el.name}), span);
}
@@ -2080,7 +2157,7 @@ const Lowerer = struct {
.borrow => |x| {
const p = try l.uncheckedPlace(x.place.*, x.mutable, x.unchecked, a.span);
if (p.ends.len == 0) {
const rb = try l.def("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), a.span);
const rb = try l.defBorrow("b", p.v.ty, try l.fmt("{s} %{s}", .{ if (x.mutable) "borrow.mut" else "borrow.ref", p.v.name }), p.v.name, a.span);
try temps.append(l.arena, rb.name);
return rb;
}
@@ -2089,8 +2166,8 @@ const Lowerer = struct {
},
.bytes => |b| {
const st = try l.materializeBytes(b, a.span);
const r = try l.def("b", try l.wrap(.ref, st.ty), try l.fmt("borrow.ref %{s}", .{st.name}), a.span);
const sl = try l.def("s", try l.wrap(.slice, .{ .int = "u8" }), try l.fmt("slice.make %{s}", .{r.name}), a.span);
const r = try l.defBorrow("b", try l.wrap(.ref, st.ty), try l.fmt("borrow.ref %{s}", .{st.name}), st.name, a.span);
const sl = try l.defBorrow("s", try l.wrap(.slice, .{ .int = "u8" }), try l.fmt("slice.make %{s}", .{r.name}), r.name, a.span);
try temps.appendSlice(l.arena, &.{ r.name, sl.name });
return sl;
},
@@ -2138,12 +2215,12 @@ const Lowerer = struct {
// `s: mut<S>`) is a shared reborrow of it (spec 07a `borrow.ref`).
if (want_slice and !mutable and (p.v.ty == .mut or p.v.ty == .slice_mut)) {
const t = if (p.v.ty == .mut) try l.wrap(.ref, p.v.ty.inner().?) else try l.wrap(.slice, p.v.ty.inner().?);
const r = try l.def("r", t, try l.fmt("borrow.ref %{s}", .{p.v.name}), span);
const r = try l.defBorrow("r", t, try l.fmt("borrow.ref %{s}", .{p.v.name}), p.v.name, span);
p = .{ .v = r, .ends = try l.concat(p.ends, r.name) };
}
if (want_slice and (p.v.ty == .ref or p.v.ty == .mut) and p.v.ty.inner().? == .array) {
const elem = p.v.ty.inner().?.array.elem;
const sl = try l.def("s", (if (mutable) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{p.v.name}), span);
const sl = try l.defBorrow("s", (if (mutable) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{p.v.name}), p.v.name, span);
var ends: std.ArrayList([]const u8) = .empty;
try ends.appendSlice(l.arena, p.ends);
try ends.append(l.arena, sl.name);
@@ -2202,7 +2279,7 @@ const Lowerer = struct {
if (std.mem.eql(u8, x.name, f.name)) break x;
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } });
const ft = try l.typeOf(fd.ty);
const v = try l.def(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), span);
const v = try l.defBorrow(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
.index => |x| {
@@ -2217,7 +2294,7 @@ const Lowerer = struct {
var sl = base.v;
var ends = base.ends;
if (bt == .ref or bt == .mut) {
sl = try l.def("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), span);
sl = try l.defBorrow("s", (if (bt == .mut) try l.wrap(.slice_mut, elem) else try l.wrap(.slice, elem)), try l.fmt("slice.make %{s}", .{base.v.name}), base.v.name, span);
ends = try l.concat(ends, sl.name);
}
const a = try l.expr(x.lo.*, .{ .int = "usize" });
@@ -2225,7 +2302,7 @@ const Lowerer = struct {
const b = try l.expr(hi.*, .{ .int = "usize" });
try l.checkTy(hi.span, b.ty, .{ .int = "usize" });
const len = try l.def("len", .{ .int = "usize" }, try l.fmt("sub.checked.usize %{s}, %{s}", .{ b.name, a.name }), span);
const sub_ = try l.def("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), span);
const sub_ = try l.defBorrow("s", sl.ty, try l.fmt("slice.sub %{s}, %{s}, %{s}", .{ sl.name, a.name, len.name }), sl.name, span);
return .{ .v = sub_, .ends = try l.concat(ends, sub_.name) };
}
// Only the outermost index of an unchecked place is unchecked.
@@ -2238,7 +2315,7 @@ const Lowerer = struct {
} else false;
if (unchecked) l.uses.insert(.unsafe);
const index_op = if (unchecked) "borrow.index.unchecked" else if (proven) "borrow.index.proven" else "borrow.index";
const v = try l.def("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), span);
const v = try l.defBorrow("e", if (bt.isMutBorrow()) try l.wrap(.mut, elem) else try l.wrap(.ref, elem), try l.fmt("{s} %{s}, %{s}", .{ index_op, base.v.name, i.name }), base.v.name, span);
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
},
else => return l.fail("E7006", place.span, "not a place: borrow a variable, a field `x.f`, an element `s[i]` or a range `s[a..b]`", &.{}),
@@ -2332,6 +2409,8 @@ const Lowerer = struct {
const left = try l.freshName(names[0]);
const right = try l.freshName(names[1]);
try l.emit(try l.fmt("%{s}, %{s} = slice.split %{s}, %{s}", .{ left, right, p.v.name, k.name }), s.span);
try l.borrow_parents.put(l.arena, left, p.v.name);
try l.borrow_parents.put(l.arena, right, p.v.name);
try l.scopeEnds(p.ends, s.span);
try l.scopeEnds(&.{ left, right }, s.span);
try l.bindings.append(l.arena, .{ .name = names[0], .mutable = false, .value = left, .ty = p.v.ty, .kind = .borrow });
@@ -2452,7 +2531,7 @@ const Lowerer = struct {
/// outcomes in AIR order.
/// `temps`: borrows made for the operation, ended at the start of every
/// outcome block.
const Fallible = struct { text: []const u8, outcomes: []const Outcome, temps: []const []const u8 = &.{} };
const Fallible = struct { text: []const u8, outcomes: []const Outcome, borrow_parent: ?[]const u8 = null, temps: []const []const u8 = &.{} };
fn fallible(l: *Lowerer, path: []const u8) ?void {
_ = l;
@@ -2595,6 +2674,7 @@ const Lowerer = struct {
const scope_name = sb.value;
const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname);
if (sig.ret.isBorrow()) return l.fail("E7006", e.span, "a spawned function cannot return a borrow (reserved: task_borrow_returns)", &.{.{ .name = "function", .value = sig.display_name }});
const fargs = args[2..];
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
var names: std.ArrayList(u8) = .empty;
@@ -2933,11 +3013,11 @@ const Lowerer = struct {
var borrow = parent;
var shared_end: ?[]const u8 = null;
if (!mutable and parent.ty == .mut) {
borrow = try l.def("buffer_ref", try l.wrap(.ref, parent.ty.inner().?), try l.fmt("borrow.ref %{s}", .{parent.name}), place.span);
borrow = try l.defBorrow("buffer_ref", try l.wrap(.ref, parent.ty.inner().?), try l.fmt("borrow.ref %{s}", .{parent.name}), parent.name, place.span);
shared_end = borrow.name;
}
const ty = if (mutable) try l.wrap(.slice_mut, parent.ty.inner().?.buffer.*) else try l.wrap(.slice, parent.ty.inner().?.buffer.*);
const view = try l.def(name_, ty, try l.fmt("buffer.view %{s}", .{borrow.name}), place.span);
const view = try l.defBorrow(name_, ty, try l.fmt("buffer.view %{s}", .{borrow.name}), borrow.name, place.span);
if (shared_end) |n| try l.scopeEnds(&.{n}, s.span);
try l.scopeEnds(&.{view.name}, s.span);
try l.bindings.append(l.arena, .{ .name = name_, .mutable = false, .value = view.name, .ty = ty, .kind = .borrow });
@@ -2955,7 +3035,7 @@ const Lowerer = struct {
if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(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);
const v = try l.defBorrow(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 }), g.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 });
}
@@ -3114,7 +3194,7 @@ const Lowerer = struct {
try want(l, e.span, args, 2, path);
const rb = try l.regionBorrow(args[0]);
const v = try l.consuming(args[1], null);
return .{ .text = try l.fmt("region.new %{s}, %{s}", .{ rb.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
return .{ .borrow_parent = rb.name, .text = try l.fmt("region.new %{s}, %{s}", .{ rb.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (std.mem.eql(u8, path, "region.array")) {
try want(l, e.span, args, 3, path);
@@ -3122,7 +3202,7 @@ const Lowerer = struct {
const n = try l.expr(args[1], usize_ty);
try l.checkTy(args[1].span, n.ty, usize_ty);
const v = try l.consuming(args[2], null);
return .{ .text = try l.fmt("region.array %{s}, %{s}, %{s}", .{ rb.name, n.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.slice_mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
return .{ .borrow_parent = rb.name, .text = try l.fmt("region.array %{s}, %{s}, %{s}", .{ rb.name, n.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.slice_mut, v.ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) };
}
if (authority.intrinsicIndex(path)) |ix| {
const x = authority.intrinsics[ix];
@@ -3230,7 +3310,11 @@ const Lowerer = struct {
try text.appendSlice(l.arena, f.text);
for (f.outcomes, blocks) |o, *b| {
b.* = try l.newBlock(o.role);
for (o.params) |pt| try l.blocks.items[b.*].params.append(l.arena, .{ .name = try l.freshName(o.role), .ty = pt });
for (o.params) |pt| {
const name = try l.freshName(o.role);
try l.blocks.items[b.*].params.append(l.arena, .{ .name = name, .ty = pt });
if (pt.isBorrow()) if (f.borrow_parent) |parent| try l.borrow_parents.put(l.arena, name, parent);
}
try text.appendSlice(l.arena, try l.fmt(", {s} -> @{s}", .{ o.role, l.blocks.items[b.*].name }));
}
try l.term(text.items, span);
@@ -0,0 +1,9 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
struct Inner { value: u64 }
struct Outer { inner: Inner }
fn get(p: ref<Outer>) -> ref<u64> from p effects [] { ref inner = p.inner; ref value = inner.value; return value; }
fn main() -> u64 effects [] { let object = Outer { inner: Inner { value: 42u64 } }; ref p = object; ref value = get(p); return *value; }
@@ -0,0 +1,6 @@
// expect: reject E5101
// phase: 6
// spec: docs/spec/07-air.md §8.8; docs/spec/15-source-language.md §3
module test.returned_views
fn identity(p: ref<[u8; 4294967296]>) -> ref<[u8; 4294967296]> from p effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,16 @@
// expect: run
// result: 5
// equivalent: phase1/run/borrow_from_call.air
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.borrow_from_call
fn main() -> u8 effects [] {
let data = [5u8; 3];
ref s = data;
ref item = first(s);
return *item;
}
fn first(s: slice<u8>) -> ref<u8> from s effects [] {
ref item = s[0];
return item;
}
@@ -0,0 +1,7 @@
// expect: run
// trap: T0008
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[2]; return item; }
fn main() -> u64 effects [] { var data: [u64; 2] = zero; ref s = data; ref item = first(s); return *item; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn choose(s: slice<u64>, flag: bool) -> ref<u64> from s effects [] { if flag { ref item = s[0]; return item; } else { ref item = s[1]; return item; } }
fn main() -> u64 effects [] { let data = [40u64, 2u64]; ref s = data; ref a = choose(s, true); ref b = choose(s, false); return *a + *b; }
@@ -0,0 +1,8 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
// grant: heap=mem.alloc:256
module test.returned_views
fn view(b: mut<buffer<u64>>) -> slice<u64> from b effects [] { ref values = buffer.view(b); return values; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] { let b = buffer.new<u64>(1usize, heap) or trap; var result: u64 = 0u64; { mut p = b; buffer.push(p, 42u64) or trap; { ref values = view(p); result = values[0]; } buffer.pop(p) or trap; } buffer.free(move b) or trap; return result; }
@@ -0,0 +1,8 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
// grant: heap=mem.alloc:256
module test.returned_views
fn view(b: ref<buffer<u64>>) -> slice<u64> from b effects [] { ref values = buffer.view(b); return values; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] { let b = buffer.new<u64>(1usize, heap) or trap; var result: u64 = 0u64; { mut p = b; buffer.push(p, 42u64) or trap; { ref shared = p; ref values = view(shared); result = values[0]; } buffer.pop(p) or trap; } buffer.free(move b) or trap; return result; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn assert(p: ref<u64>) -> ref<u64> from p effects [] { return p; }
fn main() -> u64 effects [] { ref r = assert(true); return 42u64; }
@@ -0,0 +1,7 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn bad(s: slice<u64>) -> ref<u64> from s effects [] { return first(s); }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
@@ -0,0 +1,7 @@
// expect: reject E4101
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice_mut<u64>) -> mut<u64> from s effects [] { mut item = s[0]; return item; }
fn worker(p: mut<u64>) -> void effects [] { *p = 42u64; }
fn main() -> u64 effects [task.spawn, task.wait] { var data: [u64; 2] = zero; mut s = data; mut item = first(s); scope sc { let a = task.spawn(sc, worker, item); let b = task.spawn(sc, worker, item); task.join(move a); task.join(move b); } return *item; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
@@ -0,0 +1,28 @@
module test.returned_views
air 0
lang 0.1
features [arrays, capabilities, effects, linear_aggregates, ownership, resources]
fn @first(%s: slice<u64>) -> ref<u64> from %s
effects []
entry:
%c_1 = const.usize 0
%e_2 = borrow.index %s, %c_1
ret %e_2
fn @main() -> u64
effects []
entry:
%data_4 = local.alloc array<u64, 2>
%c_1 = const.u64 42
%c_2 = const.u64 7
%arr_3 = array.make array<u64, 2>(%c_1, %c_2)
local.store %data_4, %arr_3
%data_5 = borrow.ref %data_4
%s_6 = slice.make %data_5
%first_7 = call @first(%s_6)
%v_8 = load %first_7
borrow.end %first_7
borrow.end %s_6
borrow.end %data_5
ret %v_8
@@ -0,0 +1,8 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn forward(s: slice<u64>) -> ref<u64> from s effects [] { ref parent = s; ref item = first(parent); return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = forward(s); return *item; }
@@ -0,0 +1,35 @@
module test.returned_views
air 0
lang 0.1
features [arrays, capabilities, effects, linear_aggregates, ownership, resources]
fn @first(%s: slice<u64>) -> ref<u64> from %s
effects []
entry:
%c_1 = const.usize 0
%e_2 = borrow.index %s, %c_1
ret %e_2
fn @forward(%s: slice<u64>) -> ref<u64> from %s
effects []
entry:
%parent_1 = borrow.ref %s
%first_2 = call @first(%parent_1)
ret %first_2
fn @main() -> u64
effects []
entry:
%data_4 = local.alloc array<u64, 2>
%c_1 = const.u64 42
%c_2 = const.u64 7
%arr_3 = array.make array<u64, 2>(%c_1, %c_2)
local.store %data_4, %arr_3
%data_5 = borrow.ref %data_4
%s_6 = slice.make %data_5
%forward_7 = call @forward(%s_6)
%v_8 = load %forward_7
borrow.end %forward_7
borrow.end %s_6
borrow.end %data_5
ret %v_8
@@ -0,0 +1,6 @@
// expect: reject E2108
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>) -> ref<u64> from p effects [] { let n = 1u64; ref r = n; return r; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first<T>(s: slice<T>) -> ref<T> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first::<u64>(s); return *item; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn identity(p: ref<u64>) -> ref<u64> from p effects [] { return p; }
fn main() -> u64 effects [] { let n = 42u64; ref p = n; ref result = identity(p); return *result; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref item = first(ref data); return *item; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { return ref s[0]; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
@@ -0,0 +1,7 @@
// expect: reject E4101
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice_mut<u64>) -> mut<u64> from s effects [] { mut item = s[0]; return item; }
fn worker(s: slice_mut<u64>) -> void effects [] { s[0] = 42u64; }
fn main() -> u64 effects [task.spawn, task.wait] { var data: [u64; 2] = zero; mut s = data; scope sc { let t = task.spawn(sc, worker, s); mut item = first(s); task.join(move t); return *item; } }
@@ -0,0 +1,15 @@
// Transferring a view cannot keep a lock guard alive after its structured exit.
// expect: reject E2102
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_lock_view
fn get(mr: ref<mutex<u64>>) -> ref<u64> from mr effects [task.wait] {
lock ref mr as count { ref result = count; return result; }
cancelled { trap; }
}
fn main() -> u64 effects [task.wait] {
let m = mutex.make(42u64);
ref mr = m;
ref result = get(mr);
trap;
}
@@ -0,0 +1,5 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn main(p: ref<u64>) -> ref<u64> from p effects [] { return p; }
@@ -0,0 +1,6 @@
// expect: reject E3101
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn allocate(r: ref<region>) -> ref<u64> from r effects [] { let item = region.new(r, 42u64) or trap; ref shared = item; return shared; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>) -> ref<u64> effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; mut item = first(s); return *item; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice_mut<u64>) -> mut<u64> from s effects [] { mut item = s[0]; return item; }
fn main() -> u64 effects [] { var data: [u64; 2] = [1u64, 7u64]; { mut s = data; { mut item = first(s); *item = 42u64; } s[1] = 0u64; } return data[0]; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn tail(s: slice_mut<u64>) -> slice_mut<u64> from s effects [] { mut view = s[1..s.len]; return view; }
fn main() -> u64 effects [] { var data: [u64; 2] = [7u64, 0u64]; { mut s = data; { mut view = tail(s); view[0] = 42u64; } s[0] = 0u64; } return data[1]; }
@@ -0,0 +1,7 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn read(p: ref<u64>) -> u64 effects [] { return *p; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; return read(first(s)); }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>, unused: slice<u8>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s, b"temporary"); return *item; }
@@ -0,0 +1,81 @@
module test.returned_views
air 0
lang 0.1
features [arrays, capabilities, effects, linear_aggregates, ownership, resources]
fn @first(%s: slice<u64>, %unused: slice<u8>) -> ref<u64> from %s
effects []
entry:
%c_1 = const.usize 0
%e_2 = borrow.index %s, %c_1
ret %e_2
fn @main() -> u64
effects []
entry:
%data_4 = local.alloc array<u64, 2>
%bytes_7 = local.alloc array<u8, 9>
%c_1 = const.u64 42
%c_2 = const.u64 7
%arr_3 = array.make array<u64, 2>(%c_1, %c_2)
local.store %data_4, %arr_3
%data_5 = borrow.ref %data_4
%s_6 = slice.make %data_5
local.zero %bytes_7
%w_8 = borrow.mut %bytes_7
%i_9 = const.usize 0
%c_10 = const.u8 116
%e_11 = borrow.index %w_8, %i_9
store %e_11, %c_10
borrow.end %e_11
%i_12 = const.usize 1
%c_13 = const.u8 101
%e_14 = borrow.index %w_8, %i_12
store %e_14, %c_13
borrow.end %e_14
%i_15 = const.usize 2
%c_16 = const.u8 109
%e_17 = borrow.index %w_8, %i_15
store %e_17, %c_16
borrow.end %e_17
%i_18 = const.usize 3
%c_19 = const.u8 112
%e_20 = borrow.index %w_8, %i_18
store %e_20, %c_19
borrow.end %e_20
%i_21 = const.usize 4
%c_22 = const.u8 111
%e_23 = borrow.index %w_8, %i_21
store %e_23, %c_22
borrow.end %e_23
%i_24 = const.usize 5
%c_25 = const.u8 114
%e_26 = borrow.index %w_8, %i_24
store %e_26, %c_25
borrow.end %e_26
%i_27 = const.usize 6
%c_28 = const.u8 97
%e_29 = borrow.index %w_8, %i_27
store %e_29, %c_28
borrow.end %e_29
%i_30 = const.usize 7
%c_31 = const.u8 114
%e_32 = borrow.index %w_8, %i_30
store %e_32, %c_31
borrow.end %e_32
%i_33 = const.usize 8
%c_34 = const.u8 121
%e_35 = borrow.index %w_8, %i_33
store %e_35, %c_34
borrow.end %e_35
borrow.end %w_8
%b_36 = borrow.ref %bytes_7
%s_37 = slice.make %b_36
%first_38 = call @first(%s_6, %s_37)
borrow.end %s_37
borrow.end %b_36
%v_39 = load %first_38
borrow.end %first_38
borrow.end %s_6
borrow.end %data_5
ret %v_39
@@ -0,0 +1,5 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/07-air.md §8.8; docs/spec/15-source-language.md §3
module test.returned_views
fn main() -> u64 effects [] { var data: [u64; 4294967297] = zero; ref s = data; return s.len as! u64; }
@@ -0,0 +1,5 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/07-air.md §8.8; docs/spec/15-source-language.md §3
module test.returned_views
fn main() -> u64 effects [] { let data = [1u64; 4294967297]; ref s = data; return s.len as! u64; }
@@ -0,0 +1,6 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice_mut<u64>) -> mut<u64> from s effects [] { mut item = s[0]; return item; }
fn main() -> u64 effects [] { var data: [u64; 2] = [42u64, 7u64]; mut s = data; mut item = first(s); s[0] = 2u64; return *item; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; let item = first(s); return *item; }
@@ -0,0 +1,8 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
// grant: heap=mem.alloc:256
module test.returned_views
fn allocate(r: ref<region>) -> ref<u64> from r effects [mem.alloc] { let item = region.new(r, 42u64) or trap; ref shared = item; return shared; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] { let r = region.create(heap) or trap; var result: u64 = 0u64; { ref arena = r; ref item = allocate(arena); result = *item; } region.destroy(move r); return result; }
@@ -0,0 +1,31 @@
module test.returned_views
air 0
lang 0.1
features [capabilities, effects, heap, ownership, regions, resources]
fn @allocate(%r: ref<region>) -> ref<u64> from %r
effects [mem.alloc]
entry:
%c_1 = const.u64 42
region.new %r, %c_1, ok -> @ok_2, err -> @err_4
ok_2(%ok_3: mut<u64>):
%r_6 = borrow.ref %ok_3
ret %r_6
err_4(%err_5: alloc_error):
trap
fn @main(%heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
entry:
region.create %heap, ok -> @ok_1, err -> @err_3
ok_1(%ok_2: region):
%c_5 = const.u64 0
%r_6 = borrow.ref %ok_2
%allocate_7 = call @allocate(%r_6)
%v_8 = load %allocate_7
borrow.end %allocate_7
borrow.end %r_6
region.destroy %ok_2
ret %v_8
err_3(%err_4: alloc_error):
trap
@@ -0,0 +1,6 @@
// expect: reject E2104
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn allocate(r: ref<region>) -> ref<u64> from r effects [mem.alloc] { let item = region.new(r, 42u64) or trap; ref shared = item; return shared; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] { let r = region.create(heap) or trap; ref arena = r; ref item = allocate(arena); region.reset(r); let value = *item; trap; }
@@ -0,0 +1,8 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
// grant: heap=mem.alloc:256
module test.returned_views
fn allocate(r: ref<region>) -> ref<u64> from r effects [mem.alloc] { match region.new(r, 42u64) { ok(item) => { ref shared = item; return shared; } err(e) => { trap; } } }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] { let r = region.create(heap) or trap; var result: u64 = 0u64; { ref arena = r; ref item = allocate(arena); result = *item; } region.destroy(move r); return result; }
@@ -0,0 +1,9 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
// schedules: 20
module test.returned_views
fn first(s: slice_mut<u64>) -> mut<u64> from s effects [] { mut item = s[0]; return item; }
fn worker(p: mut<u64>) -> void effects [] { *p = 42u64; }
fn main() -> u64 effects [task.spawn, task.wait] { var data: [u64; 2] = zero; { mut s = data; mut item = first(s); scope sc { let t = task.spawn(sc, worker, item); task.join(move t); } } return data[0]; }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>) -> mut<u64> from p effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,15 @@
// task_borrow_returns is reserved; source must diagnose the spawn directly.
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_task_view
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> void effects [task.spawn, task.wait] {
let data = [42u64, 2u64];
ref s = data;
scope sc {
let t = task.spawn(sc, first, s);
task.cancel(t);
trap;
}
}
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn left(s: slice<u64>) -> slice<u64> from s effects [] { let (a, b) = s.split_at(1usize); return a; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref result = left(s); return result[0]; }
@@ -0,0 +1,33 @@
// Returning an unrelated view must still end scopes/shields and unlock guards.
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_view_exits
fn scoped(p: ref<u64>) -> ref<u64> from p effects [] {
scope sc { ref result = p; return result; }
}
fn shielded(p: ref<u64>) -> ref<u64> from p effects [] {
shield { ref result = p; return result; }
}
fn locked(p: ref<u64>, mr: ref<mutex<u64>>) -> ref<u64> from p effects [task.wait] {
lock ref mr as count { *count = *count + 1u64; ref result = p; return result; }
cancelled { return p; }
}
fn main() -> u64 effects [task.wait] {
let data = 14u64;
let m = mutex.make(0u64);
var total: u64 = 0u64;
{
ref p = data;
ref mr = m;
ref a = scoped(p);
ref b = shielded(p);
ref c = locked(p, mr);
total = *a + *b + *c;
}
let count = mutex.take(move m);
assert(count == 1u64);
return total;
}
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn tail(s: slice<u64>) -> slice<u64> from s effects [] { ref view = s[1..s.len]; return view; }
fn main() -> u64 effects [] { let data = [7u64, 42u64]; ref s = data; ref view = tail(s); return view[0]; }
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; item }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
@@ -0,0 +1,12 @@
// A transferred borrow does not discharge the task scope's join obligation.
// expect: reject E4301
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_view_unjoined
fn worker() -> void effects [] {}
fn get(p: ref<u64>) -> ref<u64> from p effects [task.spawn] {
scope sc { let task = task.spawn(sc, worker); ref result = p; return result; }
}
fn main() -> u64 effects [task.spawn] {
let data = 42u64; ref p = data; ref result = get(p); return *result;
}
@@ -0,0 +1,6 @@
// expect: reject E7002
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>) -> ref<u64> from missing effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,9 @@
// Both endpoints are valid before specialization; no unused layout is emitted.
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §15
module test.generic_array_bounds
struct Unused<T: Copy> { data: [T; 1] }
fn unused<T: Copy>(p: [T; 4294967296]) -> u64 effects [] { return 1u64; }
fn main() -> u64 effects [] { return 42u64; }
@@ -0,0 +1,6 @@
// expect: reject E7002
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad<T>(p: ref<T>) -> ref<T> from missing effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad<T>(p: ref<T>) -> ref<T> effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad<T>(p: ref<T>) -> mut<T> from p effects [] { return p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,7 @@
// Known signature bounds also apply to unused generic type fields.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §15
module test.generic_array_bounds
struct Unused<T: Copy> { data: [T; 4294967297] }
fn main() -> u64 effects [] { return 42u64; }
@@ -0,0 +1,7 @@
// Known signature bounds are checked without instantiating the template.
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §15
module test.generic_array_bounds
fn unused<T: Copy>(p: [T; 0]) -> u64 effects [] { return 1u64; }
fn main() -> u64 effects [] { return 42u64; }
@@ -0,0 +1,6 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; first(s); return 42u64; }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: u64) -> ref<u64> from p effects [] { ref r = p; return r; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,6 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>) -> u64 from p effects [] { return *p; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,6 @@
// expect: reject E2102
// phase: 6
// spec: docs/spec/15-source-language.md §19
module test.returned_views
fn bad(p: ref<u64>, q: ref<u64>) -> ref<u64> from p effects [] { ref r = q; return r; }
fn main() -> u64 effects [] { return 0u64; }
@@ -0,0 +1,5 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/07-air.md §8.8; docs/spec/15-source-language.md §3
module test.returned_views
fn main() -> u64 effects [] { var data: [u64; 0] = zero; ref s = data; return s.len as! u64; }
@@ -0,0 +1,5 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/07-air.md §8.8; docs/spec/15-source-language.md §3
module test.returned_views
fn main() -> u64 effects [] { let data = [1u64; 0]; ref s = data; return s.len as! u64; }
@@ -1,4 +1,5 @@
// expect: reject E7006
// Borrowed values cannot be transferred with move; their lifetime is expressed by from.
// phase: 6
// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17
module test.buffer
@@ -0,0 +1,7 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §19
module quickref.returned_views
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Borrow-return CLI, packages, canonical AIR and profile parity; use fuel."""
import json
from pathlib import Path
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / "zig-out/bin/aji"
FIXTURES = REPO / "tests/conformance/source/borrow_returns"
checks = 0
def cli(*args, code=0):
global checks
run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr)
checks += 1
return run.stdout
with tempfile.TemporaryDirectory(prefix="aji-borrow-returns-") as directory:
root = Path(directory)
for name in ("first", "forward", "ancestors", "mutable", "mutable_slice", "generic",
"other_temporary", "split", "region", "region_match", "buffer_shared_from_mut",
"returned_task_loan", "structured_exits"):
source = FIXTURES / f"{name}.aji"
grants = ["--grant", "heap=mem.alloc:256"] if "heap: cap" in source.read_text() else []
canonical = cli("lower", source)
assert cli("lower", source) == canonical
air = root / f"{name}.air"
air.write_text(canonical)
cli("check", air)
record = json.loads(cli("run", "--fuel", "1000000", *grants, source))
assert record["value"] == 42
assert json.loads(cli("run", "--fuel", "1000000", *grants, air)) == record
output = root / "hosted.json"
cli("run", "--profile", "hosted", "--result-file", output,
"--fuel", "1000000", *grants, source)
assert json.loads(output.read_text())["value"] == 42
cli("report", FIXTURES / "forward.aji")
cli("explore", "--max-runs", "8", FIXTURES / "returned_task_loan.aji")
for name, code in (("frame_escape", "E2108"), ("wrong_origin", "E2102"),
("inline_origin", "E7006"), ("parent_access", "E2101"), ("lock_escape", "E2102"),
("zero_array_origin", "E7005"), ("oversized_repeat_origin", "E7005"),
("spawn_return", "E7006"), ("unused_generic_zero_array", "E7005"),
("unused_generic_oversized_array", "E7005")):
commands = ("check", "lower", "run", "report", "explore") if code.startswith("E7") else ("check", "run", "report", "explore")
for command in commands:
errors = [json.loads(line) for line in cli(command, FIXTURES / f"{name}.aji", code=1).splitlines()]
assert errors[0]["code"] == code and errors[0]["file"].endswith(f"{name}.aji")
if code.startswith("E21"):
assert "air_line" in errors[0] and "air_col" in errors[0]
if name == "spawn_return":
source = FIXTURES / f"{name}.aji"
spawn_line = next(i for i, line in enumerate(source.read_text().splitlines(), 1)
if "let t = task.spawn" in line)
assert errors[0]["function"] == "first" and errors[0]["line"] == spawn_line
entry = root / "main.aji"
library = root / "views.aji"
manifest = root / "aji.toml"
manifest.write_text('[package]\nname = "returned-views"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.views = "views.aji"\n')
library.write_text('module app.views\nfn first<T>(s: slice<T>) -> ref<T> from s effects [] { ref item = s[0]; return item; }\n')
entry.write_text('module app.entry\nimport app.views;\nfn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = app.views.first::<u64>(s); return *item; }\n')
canonical = cli("lower", "--manifest", manifest)
assert cli("lower", "--manifest", manifest) == canonical and " from %s" in canonical
assert json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest))["value"] == 42
output = root / "package-hosted.json"
cli("run", "--profile", "hosted", "--result-file", output, "--fuel", "1000000", "--manifest", manifest)
assert json.loads(output.read_text())["value"] == 42
# An ordinary qualified function takes the moduleCall normalization path.
library.write_text('module app.views\nfn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }\n')
entry.write_text(entry.read_text().replace('first::<u64>', 'first'))
assert json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest))["value"] == 42
library.write_text(library.read_text().replace('ref item = s[0]', 'let n = 1u64; ref item = n'))
error = json.loads(cli("check", "--manifest", manifest, code=1))
assert error["code"] == "E2108" and error["file"] == "views.aji"
library.write_text('module app.views\nfn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[2]; return item; }\n')
record = json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest, code=4))
assert record["code"] == "T0008" and record["source_location"]["file"] == "views.aji"
print(f"source borrow-return CLI integration passed ({checks} checks)")
+2
View File
@@ -20,6 +20,8 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source")
# (area, construct, regex, needs a reject test)
CHECKLIST = [
("borrow returns", "explicit return origin", r"-> (?:ref|mut|slice|slice_mut)<[^>]+> from ", True),
("borrow returns", "returned view binding", r"(?:ref|mut) \w+ = (?:first|view|allocate)(?:::<[^>]+>)?\(", True),
("hashmap", "explicit general key policy and owning insert", r"std\.hashmap\.(insert|contains|get)::<", True),
("hashmap", "explicit general growth/extraction/drain", r"std\.hashmap\.(reserve|remove|pop|free)::<", True),
("hashset", "explicit membership and duplicate owner return", r"std\.hashset\.(insert|contains)::<", True),