9.7 KiB
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
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.