cli: add initialized buffers and safe owning vectors
Introduce linear_buffers through the specification, AIR parser/serializer, verifier, deterministic interpreter and source lowering. A buffer owns an initialized prefix with explicit reserve, bounded push, moving pop/views and recoverable empty-only free. Growth charges old+new capacity; failed growth, full push and nonempty free preserve or return complete ownership. Implement compiler-pinned safe std.vec with nine operations for Copy values, owners, files and channel endpoints. Permit complete Copy moves inside specialized generic bodies without weakening monomorphic or borrow rules. Update RFC 0024, Q-036, STD-6a/b, reference grammar, Quick Reference, bundles, source coverage and CI. Remaining collections stay STD-6c. Validation: unit tests and AIR round-trip; 757 conformance cases; 56 dedicated buffer cases with per-instruction collection and 32-seed schedule stress; extended memory test; hosted smoke; 36 module, 20 generic, 49 linear and 118 buffer CLI checks; 91/91 source constructs; Zig fmt and reference bundles. Full source bundle: 49,589 -> 52,384 cl100k tokens (+5.6%); AIR 175,736 bytes. The reference interpreter's push copies its initialized prefix; no native performance or empirical MCC benefit is claimed.
This commit is contained in:
101 files changed
+2377
-71
No files matched your search
@@ -107,3 +107,5 @@ RFC 0022 explicit generics (cl100k, relative to modules): Quick Reference 6,501
|
||||
|
||||
|
||||
RFC 0023 whole-value linear aggregates (cl100k, relative to generics): Quick Reference 6,948 → 7,225 (+4.0%); other source docs 41,086 → 42,364 (+3.1%); full source docs excluding AIR 48,034 → 49,589 (+3.2%). New on-demand `language/linear-aggregates.md` is 1,133 tokens; `library/std.md` is 8,398. AIR grows to 168,336 bytes (+4.7%). Whole unpack/exhaustive match/explicit swap/allocation failure expose ownership without per-field holes, cleanup or new transfer state. Cumulative source growth is approximately +45.9%; Quick Reference remains beyond its 4–6k target. RFC 0023 justifies the added contracts; consolidation remains separate work and no MCC improvement is claimed.
|
||||
|
||||
RFC 0024 initialized buffers and safe Vec (cl100k, relative to linear aggregates): Quick Reference 7,225 → 7,667 (+6.1%); other source docs 42,364 → 44,717 (+5.6%); full source excluding AIR 49,589 → 52,384 (+5.6%). New on-demand language/buffers.md is 1,175 tokens; library/std.md is 9,432. AIR grows to 175,736 bytes (+4.4%). Initialized prefixes, explicit reserve, returned failure ownership and empty-only free permit safe resource containers without per-slot verifier state. Cumulative full source growth is +54.2%, with the RFC's owner-review justification; Quick Reference consolidation remains separate work and no empirical MCC improvement is claimed.
|
||||
@@ -89,3 +89,6 @@ docs/reference/intrinsics.md
|
||||
|
||||
# Whole-value linear aggregates (STD-5)
|
||||
docs/spec/03-memory-model.md :: ## 25. Linear aggregates in AIR
|
||||
|
||||
# Dynamic initialized storage (STD-6a)
|
||||
docs/spec/03-memory-model.md :: ## 26. Dynamic initialized buffers
|
||||
@@ -426,3 +426,26 @@ fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
```
|
||||
|
||||
`[move a, move b]` constructs ordered array elements; `let (a,b) = array.unpack(move data);` extracts every element. `value.swap(mut place, move replacement)` returns the old complete value. `own.pack(move value, heap)` has ok(owner) and err(error, original_value); own.take extracts linear content, while own.free cannot destroy it. Dynamic heap arrays/regions/frame storage remain Copy-only. Owning std.option/std.result use ordinary linear enums; is_some/is_ok retain Copy constraints. Full contracts: language/linear-aggregates.md.
|
||||
|
||||
## 14. Buffers and Vec
|
||||
|
||||
`buffer<T>` uniquely owns capacity and an initialized prefix, including owners/resources. Allocate with `buffer.new<T>(capacity, heap)` (mem.alloc); borrow the handle first for len/capacity/reserve/push/pop/view. `reserve(b, capacity, heap)` grows explicitly, charging old+new capacity at the peak. Push never grows: full returns the original item. Pop moves the last element out. Free succeeds only when empty; otherwise it returns the buffer. No destructor drains it.
|
||||
|
||||
```aji
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let data = buffer.new<own<u64>>(1, heap) or trap;
|
||||
let item = own.new(42u64, heap) or trap;
|
||||
var answer: u64 = 0;
|
||||
{ mut b = data;
|
||||
buffer.push(b, move item) or trap;
|
||||
let last = buffer.pop(b) or trap;
|
||||
answer = own.take(move last);
|
||||
}
|
||||
buffer.free(move data) or trap;
|
||||
return answer;
|
||||
}
|
||||
```
|
||||
|
||||
`ref values = buffer.view(b);` / `mut values = buffer.view(b);` borrow only the prefix. A live child view/task loan blocks shape changes, even a no-op reserve. Read Copy elements; use value.swap to replace linear elements, consuming the returned old value. Full contracts: language/buffers.md.
|
||||
|
||||
Import `std.vec` for `Vec<T>` and new/len/capacity/reserve/push/pop/free/get/replace, each explicitly specialized `::<T>`. new/reserve require mem.alloc; push is bounded, get requires Copy, pop returns std.option.Option<T>. Failure variants retain ownership: full(item), out_of_bounds(item), not_empty(vector). Match move on linear results; import std.option to name its variants. Signatures: library/std.md. Inside a specialized generic body, `move name` also accepts complete Copy bindings and retains their availability; monomorphic Copy moves and moves of borrows still reject.
|
||||
@@ -25,6 +25,10 @@ docs/spec/15-source-language.md :: ## 13. Built-in standard modules
|
||||
docs/spec/15-source-language.md :: ## 16. Source linear aggregates
|
||||
docs/spec/03-memory-model.md :: ## 25. Linear aggregates in AIR
|
||||
|
||||
> language/buffers.md
|
||||
docs/spec/15-source-language.md :: ## 17. Source dynamic buffers
|
||||
docs/spec/03-memory-model.md :: ## 26. Dynamic initialized buffers
|
||||
|
||||
> language/generics.md
|
||||
docs/spec/15-source-language.md :: ## 15. Explicit source generics
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ The other files in `/docs` hold the full rules. Open one only when this page is
|
||||
|
||||
| Need | Read |
|
||||
|---|---|
|
||||
| built-in bytes/math/UTF-8/hex/Base64/decimal integers, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| built-in bytes/math/text/formatting, option/result and owning Vec, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| initialized buffer storage, explicit growth/drain and child views | `/docs/language/buffers.md` |
|
||||
| whole-value linear aggregates, unpack, exchange and allocation failure | `/docs/language/linear-aggregates.md` |
|
||||
| generic declarations/applications, property constraints and specialization limits | `/docs/language/generics.md` |
|
||||
| explicit package imports, qualified types, manifest file inputs | `/docs/language/modules.md` |
|
||||
|
||||
@@ -29,7 +29,7 @@ Status values: `open`, `resolved`.
|
||||
| Q-024 | resolved | P5 | Memory-model clarifications found by the independent oracle |
|
||||
| Q-025 | resolved | STD-5 | Array construction from complete element values |
|
||||
| Q-035 | resolved | STD-5 | Whole-value linear aggregates |
|
||||
| Q-036 | open | STD-6 | Dynamic initialized linear buffer storage and drain |
|
||||
| Q-036 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain |
|
||||
|
||||
## Q-001 — Text AIR grammar
|
||||
|
||||
@@ -266,3 +266,5 @@ During STD-4 validation, existing `from` declarations still return the frontend'
|
||||
## Q-036 — Dynamic initialized linear buffer storage and drain
|
||||
|
||||
STD-5 intentionally enables only complete fixed-size values and individually owned allocation. A growable Vec of resources needs bounded dynamic storage with explicit initialized length, moving extraction, failure-preserving growth and complete drain before freeing. Repeated own.array and bulk region/frame freeing remain Copy-only. STD-6 must specify this storage contract through all layers before publishing Vec<File>, Vec<sender<Job>> or a HashMap owning values. Partial holes, implicit destructors or host-only container magic are not an answer.
|
||||
|
||||
**Resolved on STD-6a (RFC 0024 Proposed):** spec 03 §26 uses an initialized contiguous prefix, explicit peak-charged reserve, failure returning pushed values and empty-only free returning the buffer on failure. Views reuse slice provenance and bounds. Safe Vec wrappers are spec 16 §2.10; other collections remain separate work.
|
||||
@@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
|
||||
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
|
||||
|
||||
The [standard-library track](standard-library.md) implements eight compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch 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 on the branch. 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). Dynamic linear storage remains Q-036/STD-6. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
|
||||
The [standard-library track](standard-library.md) implements nine compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch 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 on the branch. 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). Remaining collections are STD-6c. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
|
||||
@@ -23,7 +23,7 @@ Without external source dependencies, Aji should support ordinary CLI tools, sto
|
||||
| Built-in standard imports and enum types | STD-0/1a/2a/2b branch implementation | compiler-pinned, closed registry; six modules; qualified enum types/constructors/patterns; no package lookup |
|
||||
| General modules/imported struct literals | STD-3 branch implementation (P6-3; RFC Proposed) | explicit manifest mapping, direct qualified names, ordinary verifier |
|
||||
| User generics/structural constraints | STD-4 branch implementation (P6-4; RFC Proposed) | needed for reusable `Vec<T>`, `HashMap<K,V>`, option/result |
|
||||
| `linear_aggregates` | STD-5 branch implementation (RFC Proposed) | whole-value owning structs/enums/fixed arrays; dynamic buffer storage remains STD-6 prerequisite |
|
||||
| `linear_aggregates` | STD-5 branch implementation (RFC Proposed) | whole-value owning structs/enums/fixed arrays; initialized buffer<T>/std.vec implemented by STD-6a/b |
|
||||
| Extended filesystem, IPv6/DNS, args/env, TLS/crypto | not promised by current runtime | audit each primitive, authority, error and profile model before implementation |
|
||||
|
||||
A `Vec<u64>` prototype is not completion of `Vec<T>`. The collection gate requires valid and rejected examples for `Vec<File>`, `HashMap<Key, Own<Value>>` and `Vec<sender<Job>>`, plus cleanup and failure paths. No linked list is planned.
|
||||
@@ -54,7 +54,9 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob
|
||||
| STD-3 | done (branch implementation; RFC Proposed) | general modules and imported type names (P6-3) | STD-0 | deterministic resolution, collisions/cycles and diagnostics specified and covered |
|
||||
| STD-4 | done (branch implementation; RFC Proposed) | source generics (P6-4), constraints and option/result | STD-3 | deterministic specialization and rejected constraint examples; source/AIR budgets measured |
|
||||
| STD-5 | done (branch implementation; RFC Proposed) | independent whole-value `linear_aggregates` RFC and vertical implementation phase | STD-3/4 for its source surface | spec → AIR → verifier → interpreter → source/lowering → Quick Reference → AIR/source tests; linear elements consumed on every path |
|
||||
| STD-6 | todo | dynamic initialized linear storage/drain contract (Q-036), then buffer, Vec, Deque, HashMap, HashSet, BinaryHeap | STD-4/5 | allocate/grow/remove/free contracts, allocation failure leaves documented state, linear elements survive moves and are consumed; no hidden destruction |
|
||||
| STD-6a | done (branch implementation; RFC 0024 Proposed) | dynamic initialized buffer<T> storage/drain contract (Q-036) | STD-4/5 | vertical allocate/grow/push/pop/view/free; allocation failures preserve state, returned owners consumed; no hidden destruction |
|
||||
| STD-6b | done (branch implementation; RFC 0024 Proposed) | safe std.vec for Copy/owners/files/channel endpoints | STD-6a | explicit reserve, bounded push, moving pop/replace, empty-only free; deterministic and failure/cleanup tests |
|
||||
| STD-6c | todo | Deque, HashMap, HashSet, BinaryHeap | STD-6a/b | safe collection contracts, including HashMap<Key, Own<Value>>, recoverable failures and explicit draining |
|
||||
| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority |
|
||||
| STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry |
|
||||
| STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material |
|
||||
|
||||
@@ -43,6 +43,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It
|
||||
| `heap` | published | 2 | `capabilities`, `effects`, `ownership`, `resources` | `own<T>`, `own_array<T>`, `own.*`, built-in `alloc_error`, `mem.alloc` budgets and `budget` narrowing (spec 03 §18–§19) |
|
||||
| `islands` | published | 4 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `island<T>`, `frozen<T>`, `iref<T>`, `island.*`, `frozen.*`, `iref.eq`, `IslandSafe`, `T0010` (spec 03 §22–§23) |
|
||||
| `linear_aggregates` | published | 6 | `capabilities`, `effects`, `ownership`, `resources` | whole-value linear structs/enums/fixed arrays, unpack/take/swap and ownership-preserving own.pack; spec 03 §25 |
|
||||
| `linear_buffers` | published | 6 | `arrays`, `capabilities`, `effects`, `heap`, `linear_aggregates`, `ownership`, `resources` | initialized prefix buffer<T>, explicit growth/push/pop/view/empty-only free; spec 03 §26 |
|
||||
| `ownership` | published | 1 | — | frame storage `local<T>`, second-class borrows `ref<T>`/`mut<T>`, `from` returns, initialization (spec 07 §8.8, spec 07a, spec 08 §11, §13) |
|
||||
| `receiver_dup` | reserved | — | `cancellation`, `capabilities`, `channels`, `effects`, `heap`, `ownership`, `resources`, `tasks` | several receivers of one channel (MPMC); unscheduled |
|
||||
| `regions` | published | 2 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `region`, `region.*`, static generations (spec 03 §20) |
|
||||
|
||||
@@ -118,6 +118,11 @@ capability_op = "cap.narrow." ident local { "," local } ok_err (* te
|
||||
|
||||
(* Feature heap (spec 03 §18–§19). *)
|
||||
heap_op = "own.new" local "," local ok_err (* terminator: value, cap<mem.alloc> *)
|
||||
| "buffer.new" type local "," local ok_err
|
||||
| ( "buffer.len" | "buffer.capacity" | "buffer.view" ) local
|
||||
| "buffer.reserve" local "," local "," local ok_err
|
||||
| "buffer.push" local "," local ok_err
|
||||
| ( "buffer.pop" | "buffer.free" ) local ok_err
|
||||
| "own.array" local "," local "," local ok_err (* terminator: count, element, cap<mem.alloc> *)
|
||||
| "own.take" local
|
||||
| "own.free" local ;
|
||||
@@ -211,6 +216,7 @@ type = int_type | "bool" | "void" | "never" | global
|
||||
| "cap" "<" path ">" (* feature capabilities; a capability kind, e.g. cap<fs.read> *)
|
||||
| "file" "<" ( "read" | "write" | "append" ) ">" (* feature resources *)
|
||||
| "listener" | "stream" (* feature resources *)
|
||||
| "buffer" "<" type ">" (* feature linear_buffers *)
|
||||
| ( "own" | "own_array" ) "<" type ">" (* feature heap *)
|
||||
| "region" (* feature regions *)
|
||||
| "scope" | "task" "<" type ">" (* feature tasks *)
|
||||
|
||||
@@ -41,7 +41,7 @@ type = int_type | "bool" | "void" | "never" | path
|
||||
| "file" "<" ( "read" | "write" | "append" ) ">" ;
|
||||
(* `>>` closes two type arguments: mut<file<write>> *)
|
||||
wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array"
|
||||
| "task" | "sender" | "receiver" | "mutex" ;
|
||||
| "task" | "sender" | "receiver" | "mutex" | "buffer" ;
|
||||
int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
|
||||
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ;
|
||||
(* `region`, `listener`, `stream`, `io_error`, `alloc_error`,
|
||||
@@ -52,7 +52,7 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
|
||||
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
|
||||
statement = "let" binding [ ":" type ] "=" expr ";"
|
||||
| "var" ident ":" type "=" ( expr | "zero" ) ";"
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] ident "=" place ";" (* borrow binding *)
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] ident "=" ( place | borrow_call ) ";" (* borrow binding; buffer.view(b) / graph access also bind child borrows, spec 15 §17 *)
|
||||
| place "=" expr ";"
|
||||
| "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";"
|
||||
| expr ";"
|
||||
@@ -102,6 +102,8 @@ primary = int_lit | "true" | "false" | string
|
||||
| "(" expr ")"
|
||||
| if_expr | match_expr | block ;
|
||||
field_init = ident ":" expr ;
|
||||
borrow_call = "buffer" "." "view" "(" ident ")"
|
||||
| ( "island" | "frozen" | "arc" ) "." "at" "(" expr "," expr ")" ;
|
||||
place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ;
|
||||
|
||||
int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ;
|
||||
|
||||
+19
-2
@@ -1,8 +1,8 @@
|
||||
# Standard library API
|
||||
|
||||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external dependencies or grants.
|
||||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec new/reserve.
|
||||
|
||||
All functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||||
Except std.vec new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||||
|
||||
| Module | Function signature | Result/failure |
|
||||
|---|---|---|
|
||||
@@ -227,3 +227,20 @@ Requires direct `import std.option;` / `import std.result;`; explicit generic sp
|
||||
| `std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool` | true for ok; false for err; effects [] |
|
||||
|
||||
All are ordinary safe source/static specialization, with no allocation or authority. Generic helper calls use `is_some::<u64>(value)` / `is_ok::<u64, u8>(value)`. Constructors and patterns use `std.option.Option::<u64>::some(value)` or `std.result.Result::<u64, u8>::err(code)`; names and variant matches remain explicit even for none. Extract values by exhaustive match; an err variant is not intrinsic outcome syntax. Owners/resources/endpoints make these enums linear under spec 03 §25 and require exhaustive `match move`. Borrows remain invalid members; Copy classification helpers reject linear arguments with E7005. No must-use or implicit unwrap/default/conversion is introduced. [Checked example](../../examples/std/generics.aji) returns 42 without grants.
|
||||
|
||||
## Owning vectors
|
||||
|
||||
Import std.vec; every function supplies explicit `::<T>`. Vec<T> contains a buffer<T> and is always linear. No implicit growth or cleanup occurs. The storage field follows ordinary aggregate visibility/borrow rules. New/reserve require cap<mem.alloc> and effects [mem.alloc]; all other functions declare effects [].
|
||||
|
||||
| Function | Parameters | Result |
|
||||
|---|---|---|
|
||||
| new<T> | capacity: usize, heap: cap<mem.alloc> | NewResult<T>: ok(Vec<T>) / err(alloc_error) |
|
||||
| len<T> / capacity<T> | value: ref<Vec<T>> | usize |
|
||||
| reserve<T> | value: mut<Vec<T>>, capacity: usize, heap: cap<mem.alloc> | ReserveResult: ok / err(alloc_error) |
|
||||
| push<T> | value: mut<Vec<T>>, item: T | PushResult<T>: ok / full(T) |
|
||||
| pop<T> | value: mut<Vec<T>> | std.option.Option<T>: some(T) / none |
|
||||
| free<T> | value: Vec<T> | FreeResult<T>: ok / not_empty(Vec<T>) |
|
||||
| get<T: Copy> | value: ref<Vec<T>>, index: usize | std.option.Option<T>: some(T) / none |
|
||||
| replace<T> | value: mut<Vec<T>>, index: usize, item: T | ReplaceResult<T>: ok(old_value: T) / out_of_bounds(original_item: T) |
|
||||
|
||||
Growth has an old+new capacity allocation peak. Failure preserves capacity/length/elements; full push and out-of-bounds replacement return the exact input. Nonempty free returns the vector; pop/consume all elements before retrying. get returns none out of bounds, replace returns the old complete element on success. Generic moves compose Copy and linear types. Qualified variants require direct imports (including std.option for pop/get). [Executable owning vector](../../examples/std/vector.aji) returns 42 with heap=mem.alloc:256. Views and nested element borrows cannot escape or overlap shape changes. Normative contracts: spec 16 §2.10 and spec 03 §26.
|
||||
@@ -52,6 +52,8 @@ An `ArcSafe` value may be held by an `arc` (spec 03 §24): the last release dest
|
||||
|
||||
## Format-0 source constraints
|
||||
|
||||
Spec 15 §15 fixes the exact property queries used by explicit generic specialization. Copy includes integers, booleans, built-in enums, capabilities, `iref` and aggregates of Copy members; borrows and linear values are excluded. Send/Share use spec 04 §35. Freeze currently equals IslandSafe plain graph content; it does not promise conversion of arbitrary owners or resources. Local has task/scope/shield/guard/internal-storage base cases and propagates through borrow/own/own_array/mutex wrappers and arrays/aggregates containing Local content. It is not the complement of Send. These properties add no methods, effects, unsafe declarations or implicit resource actions.
|
||||
Spec 15 §15 fixes the exact property queries used by explicit generic specialization. Copy includes integers, booleans, built-in enums, capabilities, `iref` and aggregates of Copy members; borrows and linear values are excluded. Send/Share use spec 04 §35. Freeze currently equals IslandSafe plain graph content; it does not promise conversion of arbitrary owners or resources. Local has task/scope/shield/guard/internal-storage base cases and propagates through borrow/own/own_array/buffer/mutex wrappers and arrays/aggregates containing Local content. It is not the complement of Send. These properties add no methods, effects, unsafe declarations or implicit resource actions.
|
||||
|
||||
Under linear_aggregates (spec 03 §25), structs/enums/fixed arrays containing any linear member are linear as whole values. Every variant contributes, regardless of the active tag. Borrow/storage/function-bound members remain forbidden; whole-value unpack/take/exchange preserve exactly-once consumption.
|
||||
|
||||
Under linear_buffers (spec 03 §26), buffer<T> is always linear; Send/Share follow T, and Local propagates. Borrow/storage/task-bound content is forbidden. It is neither IslandSafe nor ArcSafe: its nested linear values require explicit draining.
|
||||
@@ -0,0 +1,62 @@
|
||||
# RFC 0024: Initialized linear buffers and safe vectors
|
||||
|
||||
Status: Proposed
|
||||
Scope: STD-6a storage / STD-6b Vec; vertical Phase 6, additive AIR format 0
|
||||
|
||||
## Motivation and invariant
|
||||
|
||||
Resolve Q-036 before promising Vec<File> or Vec<sender<Job>>. A uniquely owned buffer exposes exactly its contiguous initialized prefix. Every nested linear element is owned once; unused capacity holds no observable value. No holes, implicit destructor or hidden growth is introduced. Whole-value aggregates and Copy-only own.array cannot represent dynamic initialized storage and moving extraction.
|
||||
|
||||
## Decision
|
||||
|
||||
Spec 03 §26, spec 07a buffer contracts and source §17 define buffer<T>, exact-capacity allocation, explicit reserve, bounded push, LIFO pop, child prefix view and empty-only recoverable free. Growth charges the new allocation before releasing the old authority; failure preserves state. Full push returns the supplied value, nonempty free returns the original buffer. Ordinary linearity forces cleanup on every normal path without verifier length facts. Safe std.vec wrappers provide new/len/capacity/reserve/push/pop/free/get/replace. More collections remain separate work.
|
||||
|
||||
## Verifier and runtime rules
|
||||
|
||||
Whole availability and existing child-borrow/task-loan provenance suffice. buffer content must be complete, owning type graphs acyclic and Send/Share structural. Metadata-changing operations require exclusive access even on a dynamic no-op. Views expose only initialized values and use existing slice bounds/Copy access/exchange. The deterministic interpreter transfers complete values, preserves identity across tracing collection and accounts old/new allocation peaks. No new effect/capability/trap/diagnostic or synchronization policy is added.
|
||||
|
||||
## Generic transfer
|
||||
|
||||
A complete Copy binding inside a specialized generic body may be spelled move, retaining ordinary Copy availability. Linear specializations transfer once. Ordinary monomorphic move of Copy still rejects. This narrowly specified source rule lets one safe container implementation serve Copy and linear elements without overloads/type-case metaprogramming. It adds no AIR instruction or verifier ownership state.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
A valid program explicitly allocates Vec<own<u64>>, pushes with a mutable borrow, pops, own.takes the returned owner and frees the empty vector. Rejected examples leak a returned value, free/discard a nonempty vector, mutate/reserve while a view/task loan is live, duplicate an owner, copy a linear element or store borrowed/task-bound content. Checked AIR/source fixtures and a runnable example accompany implementation.
|
||||
|
||||
## Compatibility and scope
|
||||
|
||||
New type/opcodes belong to linear_buffers; baseline own/own_array/region operations retain semantics. New source cases extend previously rejected forms. Existing generic Copy code without move lowers identically; non-generic invalid Copy moves keep E7006. Q-034 from-returns, channel_transfer, guard/task gates and recursive ownership remain restricted. RFC remains Proposed for owner review. Deque/maps/heaps are not completed by this increment.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
New concepts: a contiguous initialized prefix, explicit capacity/peak-growth charge, ownership returned on full/nonempty and generic complete-value transfer. New verifier semantic state: none; primitive prefix state is runtime internal, with existing borrows/availability. New source syntax forms: none; buffer wrapper/typed allocator/builtin borrow binding compose existing forms. New diagnostics/effects/capabilities/traps: none. Eight operation names and eight AIR opcodes (len/capacity share a metadata-read contract), safe Vec wrapper signatures and their failure payloads replace opaque container behavior. Existing Copy storage cannot express resource extraction or cleanup obligations. Measured bundle costs and validation are recorded below; no MCC benefit is claimed without measurement.
|
||||
|
||||
The initial interpreter stores only the initialized prefix in its traced host representation; user-visible capacity is charged independently. Its push copies the prefix internally (O(length)); this increment makes no native Vec performance claim. A future backend may reserve physical backing while preserving the exact authority/failure contract.
|
||||
|
||||
The checked source example in Quick Reference §14 is a complete valid allocate/push/pop/drain/free program. The following rejects E2101 even when capacity does not grow:
|
||||
|
||||
```aji
|
||||
fn bad(b: mut<buffer<u64>>, heap: cap<mem.alloc>) -> void effects [mem.alloc] {
|
||||
ref values = buffer.view(b);
|
||||
buffer.reserve(b, 0usize, heap) or trap;
|
||||
}
|
||||
```
|
||||
|
||||
Missing move rejects E7003; duplicated owners reject E2002; omitted failure payload cleanup rejects E3002; a get specialization with an owner rejects E7005. Every instruction's operand/result/continuation types, ownership and memory transfer, capability/effect and runtime behavior are normative in spec 07a. AIR/source fixtures also cover empty/full, nested buffers, allocation overflow, failure preservation, old/new authority release, file closing and sender cleanup, task loans, borrowed content and recursive owning types.
|
||||
|
||||
### Measured reference costs
|
||||
|
||||
Relative to STD-5/RFC 0023, measured with the repository tool (offline tokenizers):
|
||||
|
||||
| Bundle | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---:|---:|---:|
|
||||
| Quick Reference | 7,225 → 7,667 | 7,251 → 7,697 | 7,455 → 7,902 |
|
||||
| Other source docs | 42,364 → 44,717 | 42,496 → 44,850 | 43,548 → 45,932 |
|
||||
| Full source excluding AIR | 49,589 → 52,384 | 49,747 → 52,547 | 51,003 → 53,834 |
|
||||
| AIR reference in source bundle | 43,966 → 45,520 | 44,114 → 45,667 | 45,403 → 46,981 |
|
||||
|
||||
New on-demand language/buffers.md: 1,175 cl100k tokens. library/std.md: 9,432. AIR standalone: 168,336 → 175,736 bytes (+4.4%), 19 files / 50 sections. Source output has 15 source files plus the AIR file. Full source cl100k growth is +5.6% relative to STD-5 and +54.2% since the 33,981-token pre-stdlib baseline. Quick Reference remains above the 4–6k target; the new prefix/returned-ownership contracts are necessary for one verified generic resource container and cannot be expressed by existing Copy-only dynamic storage. This cumulative cost is explicitly presented for owner review, not claimed as compression. Front-door consolidation and empirical MCC evaluation remain separate work.
|
||||
|
||||
### Validation
|
||||
|
||||
The implementation checks unit and parser/serializer round-trip tests, full AIR/source conformance, forced collection and schedule stress, extended interpreter memory tests, hosted OS smoke, package/generic/linear/buffer CLI integration, formatting, source construct coverage and generated reference bundles. Dedicated buffer fixtures cover 56 cases including the Quick Reference example; exact final check counts are recorded in the commit description. No held-out corpus or former smoke-task semantic tuning is involved.
|
||||
@@ -457,3 +457,16 @@ Construction (`struct.make`, `enum.make`, `array.make`) MUST consume every linea
|
||||
Among heap/frame/region storage forms, only individual `own<T>` may hold linear aggregate content in this phase; channels and mutexes retain their existing complete-value transfer rules. `own.pack` explicitly moves a value into an individually owned allocation: on failure, the error continuation receives both alloc_error and the original complete value. `own.take` consumes the owner, frees the allocation and returns its complete content, including all nested owners/resources. `own.free` MUST reject E1001 when content is linear. Repeated heap arrays, region allocations and frame locals MUST remain Copy-only; bulk freeing cannot destroy resources. Dynamic linear buffers require a separate feature/API with an explicit drain contract. Existing heap/region operations on Copy values retain their semantics.
|
||||
|
||||
Verifier state is whole-value availability, existing borrow provenance and initialization, with no per-field moved state. Structural Send/Share still apply, so transfer to workers/channels/mutexes requires their ordinary rules. The deterministic interpreter moves existing handles, performs swaps as one instruction and uses existing allocation budgets/fuel; it performs no user cleanup on normal paths or traps. AIR format 0 remains compatible: previously unsupported feature/type/opcode cases gain meanings; previously accepted Copy modules keep identical behavior.
|
||||
|
||||
|
||||
## 26. Dynamic initialized buffers
|
||||
|
||||
Feature `linear_buffers` adds the linear complete value `buffer<T>`, accounted handle size 24 bytes. T MUST be a complete value with ordinary linear_aggregates member rules: no borrow/storage/function-bound content. Ownership type graphs through buffer wrappers MUST be acyclic (E1003). `buffer<T>` is Send exactly when T is Send and Share exactly when T is Share, like own_array. Local propagates through T; no guard/task/channel-transfer gate is weakened.
|
||||
|
||||
A buffer uniquely owns capacity C and a contiguous initialized prefix of length L, 0 ≤ L ≤ C. Only [0,L) is observable. Every live linear element is owned exactly once inside that prefix. There are no observable holes, default values, implicit destructors or partially moved fields. Constructors start with L=0. Push/pop change the prefix by one complete value; pop is LIFO. Views borrow precisely the prefix. Metadata changes, growth and consumption obey ordinary exclusive alias and task-loan rules; a live view excludes those operations, even when a dynamic branch would perform no change.
|
||||
|
||||
Allocation charges C × accounted_size(T), using checked arithmetic and the named mem.alloc authority. Overflows/authority exhaustion return alloc_error::budget_exceeded. Zero capacity is valid and charged zero. Capacity is a target usize, not a format-0 fixed-array type length. Growth to C' > C allocates explicitly from the supplied authority: it MUST charge the complete new capacity before releasing the old charge to its original authority. Thus peak live charges include both allocations. Success transfers all initialized values and changes capacity/authority; failure preserves length, capacity, contents and old authority exactly. A request ≤ C succeeds without mutation/allocation, but public effects/capability requirements remain explicit. Unused capacity contains no user value and cannot be borrowed.
|
||||
|
||||
Push requires no allocation effect or capability: if L<C, it transfers one value and increments L; otherwise it returns that original value without mutation. Pop returns the last complete value and decrements L, or reports empty with no change. `buffer.free` consumes the whole handle: it frees storage only when L=0, otherwise returns that same complete buffer. This applies uniformly to Copy and linear T. Every normal path MUST explicitly transfer/drain nested resources; a caller MAY trap under the existing abnormal-path contract but no cleanup is inserted. Existing own.array, own.free and region/frame rules retain their meanings.
|
||||
|
||||
The verifier tracks whole buffer ownership and existing borrow provenance, not a symbolic length or per-slot initialization state. Prefix validity is enforced by the trusted primitive semantics. Views use existing slice borrow/end, load/store bounds and explicit value.swap rules. Copy loads/copies require Copy T; ordinary overwrite of linear T remains forbidden. The deterministic interpreter preserves buffer identity and initialized prefix across tracing collection, tasks and swaps; metadata accesses participate in race checks, and allocation uses existing deterministic budgets and fuel. No synchronization, ambient authority, implicit allocation or new trap is added. The feature is additive in AIR format 0.
|
||||
@@ -556,7 +556,7 @@ Example: two workers square the two halves of one buffer in parallel; both loans
|
||||
| integers, `bool`, built-in enums | yes | yes |
|
||||
| `cap<K>` (every kind) | yes | yes — the authority object is shared and its host side is synchronized |
|
||||
| `file<…>`, `listener`, `stream` | yes | no |
|
||||
| `own<T>`, `own_array<T>` | if `T` is | if `T` is |
|
||||
| `own<T>`, `own_array<T>`, `buffer<T>` | if `T` is | if `T` is |
|
||||
| `region` | yes | no — allocation through a shared borrow mutates the region |
|
||||
| `ref<T>` | if `T` is `Share` | if `T` is `Share` |
|
||||
| `mut<T>` | if `T` is `Send` | no |
|
||||
@@ -857,4 +857,3 @@ Common properties:
|
||||
- *Exact coverage, normative litmus corpus only.* For every test of `reference/concurrency-litmus.md`, the outcomes observed under exhaustive exploration equal the oracle's allowed set: `observed_exhaustive = allowed` (§20.5).
|
||||
- *Weak reads.* A read whose ordering is not `seq_cst` may read any write the model allows. The choice is a draw from the schedule generator (§36.2) and counts in `schedule.choices`.
|
||||
- *No weak access.* A run with no non-`seq_cst` access makes no extra draw, and every read reads the latest write.
|
||||
|
||||
@@ -333,3 +333,22 @@ Operands MUST be mut<T> and T; T MUST be an initialized value, never a borrow/st
|
||||
### `own.pack T %value, %cap, ok -> @success, err -> @failure`
|
||||
|
||||
Operands MUST be complete T and cap<mem.alloc> (E1001/E3201); T may be Copy or linear. No SSA result; success receives own<T>, failure receives (alloc_error,T) (E5002/E1001). Linear input is consumed on both edges; success owns it inside the allocation, failure owns the same original value. Memory: new allocation initialized with the complete value on success; none on failure. Effects: mem.alloc. Capability: explicit bounded mem.alloc. Synchronization/traps: none; ordinary alloc_error failure reasons/budget rules apply. Interpreter transfers handles without duplicating ownership and charges/frees the same accounted bytes as own.new/own.take.
|
||||
|
||||
|
||||
## Dynamic buffers (`linear_buffers`)
|
||||
|
||||
These instructions add no concurrency effects. Metadata access uses existing shared/exclusive race and task-loan checks; views carry child provenance. Valid buffer states MUST NOT trap; allocation failure is an outcome, while execution limits retain spec 11 behavior.
|
||||
|
||||
All operations require linear_buffers and its full dependency closure (arrays, capabilities, effects, heap, linear_aggregates, ownership, resources). buffer<T> content and lifetime rules are spec 03 §26. T MUST be a complete value. Counts/indices are usize. All continuations receive exactly the listed parameters (E5002 count, E1001 types), with no SSA result for terminators. New operations add no traps, except existing borrowed-index bounds checks applied to a view. No synchronization is performed.
|
||||
|
||||
| Instruction | Operands/result or continuations | Ownership/memory/transfer | Effects/capabilities |
|
||||
|---|---|---|---|
|
||||
| `buffer.new T %capacity, %cap, ok -> @ok, err -> @err` | usize, cap<mem.alloc>; ok(buffer<T>), err(alloc_error) | new initialized empty prefix; no consumed input; successful result owned | mem.alloc, explicit mem.alloc cap |
|
||||
| `%n = buffer.len %borrow` / `%n = buffer.capacity %borrow` | ref<buffer<T>> or mut<buffer<T>> → usize | shared metadata read through live borrow, no consumption | — |
|
||||
| `buffer.reserve %borrow, %capacity, %cap, ok -> @ok, err -> @err` | mut<buffer<T>>, usize, cap<mem.alloc>; ok(), err(alloc_error) | exclusive metadata/storage access; charge new backing before releasing old; failure preserves buffer; borrow remains live on both edges | mem.alloc, explicit mem.alloc cap |
|
||||
| `buffer.push %borrow, %value, ok -> @ok, err -> @err` | mut<buffer<T>>, T; ok(), err(T) | exclusive access; linear input consumed on both edges; success appends, failure returns original value; borrow remains live | — |
|
||||
| `buffer.pop %borrow, ok -> @ok, err -> @err` | mut<buffer<T>>; ok(T), err() | exclusive access; success removes/owns last value; empty preserves prefix; borrow remains live | — |
|
||||
| `%view = buffer.view %borrow` | ref<buffer<T>> → slice<T>; mut<buffer<T>> → slice_mut<T> | child borrow of initialized prefix, same shared/exclusive mode and provenance; MUST explicitly end; no ownership transferred | — |
|
||||
| `buffer.free %buffer, ok -> @ok, err -> @err` | buffer<T>; ok(), err(buffer<T>) | linear handle consumed on both edges; empty frees/releases charge, nonempty returns same complete buffer; live descendant borrows/task loans reject | — |
|
||||
|
||||
Verifier transfer uses existing whole-value availability for new/free and returned linear block parameters, and useThrough/child provenance for borrowed operations. Length/capacity/view are shared/exclusive access as declared above; all modifying operations require exclusive access even for an empty/full/no-op dynamic case (E2101/E4101). Runtime observes L/C, updates the initialized prefix atomically per instruction and selects the corresponding continuation deterministically. Allocation overflow/exhaustion selects err(alloc_error); no user value is destroyed by a failing operation. Local/borrow/task-bound element types, mismatches and copy/overwrite of linear contents reject E1001; cyclic ownership rejects E1003. Existing resource-leak/repeated-consumption errors apply. No new diagnostic/effect/capability/trap is introduced.
|
||||
@@ -120,6 +120,7 @@ The **accounted size** of a type is a normative, platform-independent metric of
|
||||
| enum | `tag + ` the largest sum over one variant's payload, where `tag` is the smallest of 1, 2, 4, 8 bytes that can hold the index of every variant |
|
||||
| `ref<T>`, `mut<T>` | 8 |
|
||||
| `slice<T>`, `slice_mut<T>` | 16 |
|
||||
| `buffer<T>` (linear_buffers) | 24 |
|
||||
|
||||
`void`, `never` and storage types (`local<T>`) are not materializable values and have no accounted size; the `T` inside a storage type does.
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ The AIR spellings are used (spec 07 §8):
|
||||
- integers `u8`…`u128`, `usize`, `i8`…`i128`, `isize`; `bool`, `void`, `never`;
|
||||
- named types;
|
||||
- `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`;
|
||||
- `own<T>`, `own_array<T>`, `region`;
|
||||
- `own<T>`, `own_array<T>`, `buffer<T>` (§17), `region`;
|
||||
- `cap<K>`;
|
||||
- `file<read|write|append>`, `listener`, `stream`;
|
||||
- `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>`;
|
||||
@@ -487,7 +487,7 @@ Standard enum types are named by their full path, for example `std.bytes.ReadU32
|
||||
|
||||
A constructor or pattern is written `std.bytes.ReadU32::ok(value)` or `std.bytes.ReadU32::short_input`. Constructors, payload typing and exhaustive enum matches obey §5/§6 without a library-specific exception. A wrong payload or variant from another enum is `E7005`, an unknown variant `E7002`, a missing arm `E7004`, and duplicate/wildcard enum arms `E7006`. These are ordinary Copy enum values; this increment does not add a must-use or linear-result rule. Source type diagnostics MUST name standard types by their public qualified source path, including inside compound types; AIR output still uses the generated identifiers. Library source uses the same full type paths in signatures, constructors and matches. Standard types lower with the collision-free naming rule above; their declarations precede function declarations as in §2.
|
||||
|
||||
The standard registry exports ordinary enums and generic enum templates (§15). Qualified named types and enum variants introduce no member methods, reflection, dependency resolution or aliases. Generic standard forms use §15. Package modules and qualified struct literals are specified in §14.
|
||||
The standard registry exports ordinary structs/enums and their generic templates (§15). Qualified named types and enum variants introduce no member methods, reflection, dependency resolution or aliases. Generic standard forms use §15. Package modules and qualified struct literals are specified in §14.
|
||||
|
||||
## 14. Package source modules
|
||||
|
||||
@@ -499,7 +499,7 @@ Each mapped source MUST declare exactly its mapped module name. An imported sour
|
||||
|
||||
Imports form an acyclic directed graph. The linker MUST parse each reachable module once, reject self-import/cycles, duplicate imports, duplicate mappings and mismatched headers with `E7006`, and unknown imports with `E7002`. Source syntax errors in a package module use `E7001` at that module's file/line/column. Imports are visited in source order for first-error selection; all complete non-generic declarations of reachable modules, including unused functions, enter verification; templates follow §15. Unreachable mapped source is not parsed or linked. Compiler input limits are 1,024 mapped modules and import depth 256; exceeding them is `E7006`. These are fixed implementation input limits, not runtime fuel or semantics-changing flags.
|
||||
|
||||
Module names use source paths. The first component of a package mapping MUST NOT be `std` or a namespace of a built-in operation (`slice`, `own`, `region`, `cap`, `task`, `channel`, `mutex`, `island`, `frozen`, `arc`, `atomic`, or the first component of a registered intrinsic). Such a mapping is `E7006` (a manifest error at the CLI). Root source names retain their existing grammar; duplicate entry/module identity is rejected when imported.
|
||||
Module names use source paths. The first component of a package mapping MUST NOT be `std` or a namespace of a built-in operation (`slice`, `own`, `buffer`, `region`, `cap`, `task`, `channel`, `mutex`, `island`, `frozen`, `arc`, `atomic`, or the first component of a registered intrinsic). Such a mapping is `E7006` (a manifest error at the CLI). Root source names retain their existing grammar; duplicate entry/module identity is rejected when imported.
|
||||
|
||||
### 14.2 Names and types
|
||||
|
||||
@@ -529,7 +529,7 @@ Templates are parsed and declaration parameter/constraint/duplicate rules, signa
|
||||
|
||||
### 15.2 Structural constraints
|
||||
|
||||
Constraints are requirements on concrete types, not compiler authority to infer effects or repair ownership. `Copy` follows existing value duplication: scalars, built-in enums, capabilities, `iref` and aggregates of Copy values; borrows and linear values are not Copy. `Send` and `Share` use exactly spec 04 §35. In format 0, `Freeze` is exactly `IslandSafe` (spec 03 §22): plain content accepted by deep graph conversion, including `iref`; it does not promise conversion of owners/resources/wrappers. `Local` identifies context-bound `task`, `scope`, `shield` and `guard` (and internal local storage); it propagates through borrows, own/own_array/mutex wrappers and arrays/aggregates containing Local content. Scalars, authority, resources, regions, endpoints and graph owners/handles are not Local. Local is not the complement of Send. No unsafe/manual property declarations are added.
|
||||
Constraints are requirements on concrete types, not compiler authority to infer effects or repair ownership. `Copy` follows existing value duplication: scalars, built-in enums, capabilities, `iref` and aggregates of Copy values; borrows and linear values are not Copy. `Send` and `Share` use exactly spec 04 §35. In format 0, `Freeze` is exactly `IslandSafe` (spec 03 §22): plain content accepted by deep graph conversion, including `iref`; it does not promise conversion of owners/resources/wrappers. `Local` identifies context-bound `task`, `scope`, `shield` and `guard` (and internal local storage); it propagates through borrows, own/own_array/buffer/mutex wrappers and arrays/aggregates containing Local content. Scalars, authority, resources, regions, endpoints and graph owners/handles are not Local. Local is not the complement of Send. No unsafe/manual property declarations are added.
|
||||
|
||||
A type can satisfy several constraints; each requirement MUST be checked. Constraints add no operations or trait dispatch: a body using arithmetic with `T: Copy` still requires an arithmetic-compatible concrete specialization. Effects, `from`, `move`, lends and cleanup remain explicit in every specialization.
|
||||
|
||||
@@ -548,3 +548,14 @@ Structs, enums and fixed arrays with linear members MUST obey spec 03 §25. Cons
|
||||
`value.swap(mut place, move replacement)` returns the previous complete value and stores the replacement; it lowers to value.swap with the existing borrow scope. The same spelling accepts Copy replacements without move. The caller MUST explicitly consume a returned linear value. `match own.pack(move value, heap) { ok(owner) => …, err(error, value) => … }` makes allocation authority/failure explicit and preserves ownership on both outcomes; `or trap` retains ordinary abnormal-path semantics. own.new/own.array/region storage and local storage remain Copy-only; own.take extracts whole linear content and own.free cannot destroy it.
|
||||
|
||||
The frontend MUST declare linear_aggregates plus its dependencies whenever any emitted aggregate has linear members or any of the new operations is emitted. Existing Source/AIR diagnostics and deterministic behavior apply. This phase does not implement partial moves, borrowed aggregates, dynamic linear buffers or source from-returns.
|
||||
|
||||
|
||||
## 17. Source dynamic buffers
|
||||
|
||||
`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.
|
||||
|
||||
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/storage/function-bound values. 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.
|
||||
|
||||
The frontend MUST emit linear_buffers and its full dependencies for buffer types/operations. Existing syntax suffices apart from admitting the buffer wrapper and the typed built-in allocator with the existing channel.make<T> type-argument form. General methods, borrowed aggregate storage, recursive ownership and from-return calls are not added.
|
||||
@@ -10,7 +10,7 @@ APIs SHOULD offer one canonical operation for a common need, small documentation
|
||||
|
||||
## 2. Bootstrap module registry
|
||||
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.math`, `std.option`, `std.result` and `std.utf8`. They are implemented in safe `.aji` with `effects []`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji` and `std/utf8.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile, have no concurrency effects and allocate no heap memory. Ordinary interpreter fuel limits apply.
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.math`, `std.option`, `std.result`, `std.utf8` and `std.vec`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji` and `std/vec.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec declare effects [] and allocate no heap memory. std.vec new/reserve declare mem.alloc and require explicit allocation authority (§2.10); its other functions allocate no heap. Ordinary interpreter fuel limits apply.
|
||||
|
||||
### 2.1 `std.math`
|
||||
|
||||
@@ -150,3 +150,14 @@ enum Result<T, E> { ok(T), err(E) }
|
||||
`std.option.is_some<T: Copy>(value: Option<T>) -> bool` and `std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool` declare `effects []`, allocate no heap and classify the active variant. They neither extract nor implicitly consume any payload. Call them using spec 15 §15's explicit expression arguments, e.g. `std.option.is_some::<u64>(value)`. Types/constructors/patterns are fully qualified and require a direct import; exhaustive matches extract payloads through ordinary enum rules. `none` still requires a type argument. `err(E)` is an ordinary enum variant, not the intrinsic outcome shorthand.
|
||||
|
||||
Option/Result accept ordinary complete value payloads, including owners/resources/endpoints under linear_aggregates (spec 03 §25, source §16). Their class is structural: an owning specialization is linear even when the active variant is none or a Copy error. It MUST be explicitly moved and exhaustively consumed; unused linear payloads reject E3002. Borrow/storage/function-bound payloads remain forbidden by ordinary member/type rules. is_some/is_ok retain Copy constraints and MUST reject E7005 for linear arguments; they do not consume a resource merely to classify it. Match an owning value explicitly instead. Existing Copy specializations retain behavior. No implicit unwrap/default/conversion or cleanup is added.
|
||||
|
||||
|
||||
### 2.10 Explicit owning vectors
|
||||
|
||||
Compiler-pinned `std.vec` MUST provide `Vec<T> { storage: buffer<T> }` and ordinary result enums: NewResult<T> { ok(Vec<T>), err(alloc_error) }, PushResult<T> { ok, full(T) }, ReserveResult { ok, err(alloc_error) }, FreeResult<T> { ok, not_empty(Vec<T>) }, ReplaceResult<T> { ok(T), out_of_bounds(T) }. All payloads follow ordinary complete-value/linearity rules; no implicit destruction occurs. Fields are ordinary visible source fields, not an opaque trusted container.
|
||||
|
||||
Public functions use explicit `::<T>` specialization: new<T>(capacity:usize,heap:cap<mem.alloc>)→NewResult<T>; len<T>(value:ref<Vec<T>>)→usize; capacity<T>(value:ref<Vec<T>>)→usize; reserve<T>(value:mut<Vec<T>>,capacity:usize,heap:cap<mem.alloc>)→ReserveResult; push<T>(value:mut<Vec<T>>,item:T)→PushResult<T>; pop<T>(value:mut<Vec<T>>)→std.option.Option<T>; free<T>(value:Vec<T>)→FreeResult<T>; get<T:Copy>(value:ref<Vec<T>>,index:usize)→std.option.Option<T>; replace<T>(value:mut<Vec<T>>,index:usize,item:T)→ReplaceResult<T>. Only new/reserve declare effects [mem.alloc]; all other functions declare effects [].
|
||||
|
||||
These are safe `.aji` wrappers over spec 03 §26. new chooses exact initial capacity, reserve chooses a minimum capacity without shrinking, and push never grows implicitly. len/capacity observe initialized length/backing capacity. pop removes the last complete value, returning none for empty. A full push returns the original item. get copies an in-bounds Copy item or returns none. replace exchanges an in-bounds initialized element and returns the previous item; out_of_bounds returns the original supplied item and preserves the vector. free releases only an empty vector; otherwise it returns the same vector. Returned owning result specializations need exhaustive match move; Copy results use ordinary matching. Callers drain and explicitly consume resource payloads before freeing.
|
||||
|
||||
Capacity/allocation failure, alias/task exclusion, deterministic profiles and diagnostics are those of buffer primitives and ordinary enum/call rules. Valid complete values include owners/files/endpoints; no collection bypasses Send/Share or channel_transfer gates. Imports grant no authority. Deque/HashMap/HashSet/BinaryHeap, owning strings and general borrowed function returns remain separate increments of STD-6.
|
||||
Reference in new issue
Block a user