cli: implement explicit source borrow returns
This commit is contained in:
1 parent
715a8be491
commit
a9a0d63f27
78 files changed
+970
-48
No files matched your search
@@ -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.
|
||||
@@ -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.
|
||||
Reference in new issue
Block a user