From 4138a52af61423e05d71f23856a43ae4085c60ff Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Tue, 6 Oct 2026 23:26:41 +0300 Subject: [PATCH] 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. --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 1 + build.zig | 1 + docs/agent/README.md | 2 + docs/agent/bundle.txt | 3 + docs/agent/quick-reference.md | 23 +++ docs/agent/source-bundle.txt | 4 + docs/agent/source-notes.md | 3 +- docs/design/open-questions.md | 4 +- docs/plan/phase-6-source-language.md | 2 +- docs/plan/standard-library.md | 6 +- docs/reference/air-features.md | 1 + docs/reference/air-text.ebnf | 6 + docs/reference/grammar.ebnf | 6 +- docs/reference/std.md | 21 ++- docs/reference/type-properties.md | 4 +- docs/rfcs/0024-linear-buffers-and-vectors.md | 62 +++++++ docs/spec/03-memory-model.md | 13 ++ docs/spec/04-concurrency-and-atomics.md | 3 +- docs/spec/07a-air-instructions.md | 19 +++ docs/spec/08-verifier.md | 1 + docs/spec/15-source-language.md | 19 ++- docs/spec/16-standard-library.md | 13 +- examples/std/vector.aji | 37 +++++ src/air/features.zig | 3 +- src/air/module.zig | 46 +++++- src/air/parse.zig | 39 ++++- src/air/print.zig | 73 ++++++++- src/frontend/ast.zig | 4 +- src/frontend/generics.zig | 1 + src/frontend/lower.zig | 116 +++++++++++--- src/frontend/modules.zig | 2 +- src/frontend/parse.zig | 4 +- src/frontend/stdlib.zig | 1 + src/interp/machine.zig | 110 ++++++++++++- src/report.zig | 2 +- src/verifier/borrow.zig | 16 +- src/verifier/budget.zig | 3 +- src/verifier/cfg.zig | 20 +++ src/verifier/effects.zig | 2 +- src/verifier/types.zig | 58 +++++-- std/README.md | 6 +- std/vec.aji | 77 +++++++++ .../conformance/buffers/borrowed_element.air | 16 ++ tests/conformance/buffers/empty_free_leak.air | 45 ++++++ tests/conformance/buffers/free_failure.air | 46 ++++++ .../conformance/buffers/free_return_type.air | 45 ++++++ tests/conformance/buffers/metadata_owner.air | 45 ++++++ tests/conformance/buffers/new_count_type.air | 45 ++++++ tests/conformance/buffers/new_return_type.air | 45 ++++++ tests/conformance/buffers/owner.air | 47 ++++++ tests/conformance/buffers/pop_return_type.air | 20 +++ .../buffers/push_continuation_count.air | 45 ++++++ tests/conformance/buffers/push_failure.air | 38 +++++ tests/conformance/buffers/push_type.air | 45 ++++++ .../buffers/readonly_view_push.air | 23 +++ .../buffers/reserve_count_type.air | 45 ++++++ tests/conformance/buffers/reserve_failure.air | 55 +++++++ .../buffers/reserve_missing_effect.air | 21 +++ tests/conformance/buffers/task_loan_join.air | 52 ++++++ tests/conformance/buffers/undeclared.air | 16 ++ tests/conformance/buffers/vec_sender.air | 151 ++++++++++++++++++ tests/conformance/buffers/view.air | 64 ++++++++ tests/conformance/buffers/view_mutation.air | 22 +++ .../conformance/buffers/wrong_capability.air | 21 +++ tests/conformance/buffers/zero.air | 46 ++++++ .../source/buffers/borrow_conflict.aji | 17 ++ .../source/buffers/borrowed_element.aji | 10 ++ .../conformance/source/buffers/copy_move.aji | 5 + .../source/buffers/copy_owner_view.aji | 9 ++ .../source/buffers/duplicate_owner.aji | 9 ++ .../source/buffers/free_failure.aji | 20 +++ .../source/buffers/free_failure_leak.aji | 9 ++ .../source/buffers/generic_borrow_move.aji | 6 + .../source/buffers/generic_move.aji | 7 + .../source/buffers/generic_storage.aji | 13 ++ .../conformance/source/buffers/long_reuse.aji | 17 ++ .../source/buffers/missing_move.aji | 9 ++ tests/conformance/source/buffers/nested.aji | 21 +++ .../source/buffers/new_overflow.aji | 12 ++ tests/conformance/source/buffers/owner.aji | 25 +++ .../source/buffers/push_failure.aji | 17 ++ .../source/buffers/push_failure_leak.aji | 9 ++ .../source/buffers/readonly_push.aji | 6 + .../conformance/source/buffers/recursive.aji | 6 + .../source/buffers/reserve_authority.aji | 21 +++ .../source/buffers/reserve_failure.aji | 20 +++ .../conformance/source/buffers/task_loan.aji | 11 ++ .../source/buffers/task_loan_join.aji | 17 ++ tests/conformance/source/buffers/vec_copy.aji | 31 ++++ tests/conformance/source/buffers/vec_file.aji | 21 +++ tests/conformance/source/buffers/vec_full.aji | 20 +++ .../source/buffers/vec_get_owner.aji | 10 ++ .../conformance/source/buffers/vec_owner.aji | 24 +++ .../source/buffers/vec_replace_owner.aji | 29 ++++ .../conformance/source/buffers/vec_sender.aji | 26 +++ tests/conformance/source/buffers/view.aji | 19 +++ tests/conformance/source/buffers/zero.aji | 17 ++ tests/conformance/source/quickref/buffers.aji | 18 +++ tests/hosted/source_buffers.py | 98 ++++++++++++ tools/source_coverage.py | 3 + 101 files changed, 2377 insertions(+), 71 deletions(-) create mode 100644 docs/rfcs/0024-linear-buffers-and-vectors.md create mode 100644 examples/std/vector.aji create mode 100644 std/vec.aji create mode 100644 tests/conformance/buffers/borrowed_element.air create mode 100644 tests/conformance/buffers/empty_free_leak.air create mode 100644 tests/conformance/buffers/free_failure.air create mode 100644 tests/conformance/buffers/free_return_type.air create mode 100644 tests/conformance/buffers/metadata_owner.air create mode 100644 tests/conformance/buffers/new_count_type.air create mode 100644 tests/conformance/buffers/new_return_type.air create mode 100644 tests/conformance/buffers/owner.air create mode 100644 tests/conformance/buffers/pop_return_type.air create mode 100644 tests/conformance/buffers/push_continuation_count.air create mode 100644 tests/conformance/buffers/push_failure.air create mode 100644 tests/conformance/buffers/push_type.air create mode 100644 tests/conformance/buffers/readonly_view_push.air create mode 100644 tests/conformance/buffers/reserve_count_type.air create mode 100644 tests/conformance/buffers/reserve_failure.air create mode 100644 tests/conformance/buffers/reserve_missing_effect.air create mode 100644 tests/conformance/buffers/task_loan_join.air create mode 100644 tests/conformance/buffers/undeclared.air create mode 100644 tests/conformance/buffers/vec_sender.air create mode 100644 tests/conformance/buffers/view.air create mode 100644 tests/conformance/buffers/view_mutation.air create mode 100644 tests/conformance/buffers/wrong_capability.air create mode 100644 tests/conformance/buffers/zero.air create mode 100644 tests/conformance/source/buffers/borrow_conflict.aji create mode 100644 tests/conformance/source/buffers/borrowed_element.aji create mode 100644 tests/conformance/source/buffers/copy_move.aji create mode 100644 tests/conformance/source/buffers/copy_owner_view.aji create mode 100644 tests/conformance/source/buffers/duplicate_owner.aji create mode 100644 tests/conformance/source/buffers/free_failure.aji create mode 100644 tests/conformance/source/buffers/free_failure_leak.aji create mode 100644 tests/conformance/source/buffers/generic_borrow_move.aji create mode 100644 tests/conformance/source/buffers/generic_move.aji create mode 100644 tests/conformance/source/buffers/generic_storage.aji create mode 100644 tests/conformance/source/buffers/long_reuse.aji create mode 100644 tests/conformance/source/buffers/missing_move.aji create mode 100644 tests/conformance/source/buffers/nested.aji create mode 100644 tests/conformance/source/buffers/new_overflow.aji create mode 100644 tests/conformance/source/buffers/owner.aji create mode 100644 tests/conformance/source/buffers/push_failure.aji create mode 100644 tests/conformance/source/buffers/push_failure_leak.aji create mode 100644 tests/conformance/source/buffers/readonly_push.aji create mode 100644 tests/conformance/source/buffers/recursive.aji create mode 100644 tests/conformance/source/buffers/reserve_authority.aji create mode 100644 tests/conformance/source/buffers/reserve_failure.aji create mode 100644 tests/conformance/source/buffers/task_loan.aji create mode 100644 tests/conformance/source/buffers/task_loan_join.aji create mode 100644 tests/conformance/source/buffers/vec_copy.aji create mode 100644 tests/conformance/source/buffers/vec_file.aji create mode 100644 tests/conformance/source/buffers/vec_full.aji create mode 100644 tests/conformance/source/buffers/vec_get_owner.aji create mode 100644 tests/conformance/source/buffers/vec_owner.aji create mode 100644 tests/conformance/source/buffers/vec_replace_owner.aji create mode 100644 tests/conformance/source/buffers/vec_sender.aji create mode 100644 tests/conformance/source/buffers/view.aji create mode 100644 tests/conformance/source/buffers/zero.aji create mode 100644 tests/conformance/source/quickref/buffers.aji create mode 100644 tests/hosted/source_buffers.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 13feb87..b449730 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: - run: python3 tests/hosted/source_modules.py - run: python3 tests/hosted/source_generics.py - run: python3 tests/hosted/source_linear.py + - run: python3 tests/hosted/source_buffers.py - run: zig-out/bin/aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air - run: zig build agent-reference - name: Source construct coverage (Phase 6A) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 58d7d11..f97ecf7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,6 +19,7 @@ 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_linear.py # whole-value owners, canonical AIR and CLI errors +python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts (cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests zig fmt --check build.zig src tools ``` diff --git a/build.zig b/build.zig index 658c1e7..48610c9 100644 --- a/build.zig +++ b/build.zig @@ -35,6 +35,7 @@ pub fn build(b: *std.Build) void { mod.addAnonymousImport("std_option_aji", .{ .root_source_file = b.path("std/option.aji") }); mod.addAnonymousImport("std_result_aji", .{ .root_source_file = b.path("std/result.aji") }); mod.addAnonymousImport("std_utf8_aji", .{ .root_source_file = b.path("std/utf8.aji") }); + mod.addAnonymousImport("std_vec_aji", .{ .root_source_file = b.path("std/vec.aji") }); // CLI: `aji`. const exe = b.addExecutable(.{ diff --git a/docs/agent/README.md b/docs/agent/README.md index c7d6ba5..8ab6061 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -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. diff --git a/docs/agent/bundle.txt b/docs/agent/bundle.txt index 069e8d2..e7760c2 100644 --- a/docs/agent/bundle.txt +++ b/docs/agent/bundle.txt @@ -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 diff --git a/docs/agent/quick-reference.md b/docs/agent/quick-reference.md index 935c458..6f99f02 100644 --- a/docs/agent/quick-reference.md +++ b/docs/agent/quick-reference.md @@ -426,3 +426,26 @@ fn main(heap: cap) -> 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` uniquely owns capacity and an initialized prefix, including owners/resources. Allocate with `buffer.new(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) -> u64 effects [mem.alloc] { + let data = buffer.new>(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` and new/len/capacity/reserve/push/pop/free/get/replace, each explicitly specialized `::`. new/reserve require mem.alloc; push is bounded, get requires Copy, pop returns std.option.Option. 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. diff --git a/docs/agent/source-bundle.txt b/docs/agent/source-bundle.txt index eecb9e1..e1b0d64 100644 --- a/docs/agent/source-bundle.txt +++ b/docs/agent/source-bundle.txt @@ -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 diff --git a/docs/agent/source-notes.md b/docs/agent/source-notes.md index d92f0eb..d092b5d 100644 --- a/docs/agent/source-notes.md +++ b/docs/agent/source-notes.md @@ -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` | diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 82b50f5..b170888 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.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, Vec> 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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 7e8c994..5ece0b9 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -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 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. diff --git a/docs/plan/standard-library.md b/docs/plan/standard-library.md index 99ced86..1230b05 100644 --- a/docs/plan/standard-library.md +++ b/docs/plan/standard-library.md @@ -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`, `HashMap`, 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/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` prototype is not completion of `Vec`. The collection gate requires valid and rejected examples for `Vec`, `HashMap>` and `Vec>`, 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 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>, 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 | diff --git a/docs/reference/air-features.md b/docs/reference/air-features.md index 5f14ce9..a0976d6 100644 --- a/docs/reference/air-features.md +++ b/docs/reference/air-features.md @@ -43,6 +43,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It | `heap` | published | 2 | `capabilities`, `effects`, `ownership`, `resources` | `own`, `own_array`, `own.*`, built-in `alloc_error`, `mem.alloc` budgets and `budget` narrowing (spec 03 §18–§19) | | `islands` | published | 4 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `island`, `frozen`, `iref`, `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, explicit growth/push/pop/view/empty-only free; spec 03 §26 | | `ownership` | published | 1 | — | frame storage `local`, second-class borrows `ref`/`mut`, `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) | diff --git a/docs/reference/air-text.ebnf b/docs/reference/air-text.ebnf index 1718c04..af07a8b 100644 --- a/docs/reference/air-text.ebnf +++ b/docs/reference/air-text.ebnf @@ -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 *) + | "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 *) | "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 *) | "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 *) diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf index 20d2cb6..b954c91 100644 --- a/docs/reference/grammar.ebnf +++ b/docs/reference/grammar.ebnf @@ -41,7 +41,7 @@ type = int_type | "bool" | "void" | "never" | path | "file" "<" ( "read" | "write" | "append" ) ">" ; (* `>>` closes two type arguments: mut> *) 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 ] ; diff --git a/docs/reference/std.md b/docs/reference/std.md index 653be06..1eed788 100644 --- a/docs/reference/std.md +++ b/docs/reference/std.md @@ -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(value: Result) -> 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::(value)` / `is_ok::(value)`. Constructors and patterns use `std.option.Option::::some(value)` or `std.result.Result::::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 `::`. Vec contains a buffer and is always linear. No implicit growth or cleanup occurs. The storage field follows ordinary aggregate visibility/borrow rules. New/reserve require cap and effects [mem.alloc]; all other functions declare effects []. + +| Function | Parameters | Result | +|---|---|---| +| new | capacity: usize, heap: cap | NewResult: ok(Vec) / err(alloc_error) | +| len / capacity | value: ref> | usize | +| reserve | value: mut>, capacity: usize, heap: cap | ReserveResult: ok / err(alloc_error) | +| push | value: mut>, item: T | PushResult: ok / full(T) | +| pop | value: mut> | std.option.Option: some(T) / none | +| free | value: Vec | FreeResult: ok / not_empty(Vec) | +| get | value: ref>, index: usize | std.option.Option: some(T) / none | +| replace | value: mut>, index: usize, item: T | ReplaceResult: 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. diff --git a/docs/reference/type-properties.md b/docs/reference/type-properties.md index d2e7e23..5e0008c 100644 --- a/docs/reference/type-properties.md +++ b/docs/reference/type-properties.md @@ -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 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. diff --git a/docs/rfcs/0024-linear-buffers-and-vectors.md b/docs/rfcs/0024-linear-buffers-and-vectors.md new file mode 100644 index 0000000..6bb00f5 --- /dev/null +++ b/docs/rfcs/0024-linear-buffers-and-vectors.md @@ -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 or Vec>. 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, 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>, 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>, heap: cap) -> 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. diff --git a/docs/spec/03-memory-model.md b/docs/spec/03-memory-model.md index b6d44ba..d3162f3 100644 --- a/docs/spec/03-memory-model.md +++ b/docs/spec/03-memory-model.md @@ -457,3 +457,16 @@ Construction (`struct.make`, `enum.make`, `array.make`) MUST consume every linea Among heap/frame/region storage forms, only individual `own` 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`, 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` 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` (every kind) | yes | yes — the authority object is shared and its host side is synchronized | | `file<…>`, `listener`, `stream` | yes | no | -| `own`, `own_array` | if `T` is | if `T` is | +| `own`, `own_array`, `buffer` | if `T` is | if `T` is | | `region` | yes | no — allocation through a shared borrow mutates the region | | `ref` | if `T` is `Share` | if `T` is `Share` | | `mut` | 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. - diff --git a/docs/spec/07a-air-instructions.md b/docs/spec/07a-air-instructions.md index 21374fe..df2f926 100644 --- a/docs/spec/07a-air-instructions.md +++ b/docs/spec/07a-air-instructions.md @@ -333,3 +333,22 @@ Operands MUST be mut 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 (E1001/E3201); T may be Copy or linear. No SSA result; success receives own, 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 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; ok(buffer), 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> or mut> → usize | shared metadata read through live borrow, no consumption | — | +| `buffer.reserve %borrow, %capacity, %cap, ok -> @ok, err -> @err` | mut>, usize, cap; 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>, 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>; ok(T), err() | exclusive access; success removes/owns last value; empty preserves prefix; borrow remains live | — | +| `%view = buffer.view %borrow` | ref> → slice; mut> → slice_mut | 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; ok(), err(buffer) | 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. diff --git a/docs/spec/08-verifier.md b/docs/spec/08-verifier.md index d137023..2d6a92b 100644 --- a/docs/spec/08-verifier.md +++ b/docs/spec/08-verifier.md @@ -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`, `mut` | 8 | | `slice`, `slice_mut` | 16 | +| `buffer` (linear_buffers) | 24 | `void`, `never` and storage types (`local`) are not materializable values and have no accounted size; the `T` inside a storage type does. diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index 1397201..f563260 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -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`, `mut`, `slice`, `slice_mut`; -- `own`, `own_array`, `region`; +- `own`, `own_array`, `buffer` (§17), `region`; - `cap`; - `file`, `listener`, `stream`; - `task`, `sender`, `receiver`, `mutex`; @@ -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` is the linear initialized-prefix owner of spec 03 §26. Built-ins use ordinary explicit borrows, moves and outcome matches: `buffer.new(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> 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 type-argument form. General methods, borrowed aggregate storage, recursive ownership and from-return calls are not added. diff --git a/docs/spec/16-standard-library.md b/docs/spec/16-standard-library.md index 3d7cf2b..479936e 100644 --- a/docs/spec/16-standard-library.md +++ b/docs/spec/16-standard-library.md @@ -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 { ok(T), err(E) } `std.option.is_some(value: Option) -> bool` and `std.result.is_ok(value: Result) -> 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::(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 { storage: buffer }` and ordinary result enums: NewResult { ok(Vec), err(alloc_error) }, PushResult { ok, full(T) }, ReserveResult { ok, err(alloc_error) }, FreeResult { ok, not_empty(Vec) }, ReplaceResult { 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 `::` specialization: new(capacity:usize,heap:cap)→NewResult; len(value:ref>)→usize; capacity(value:ref>)→usize; reserve(value:mut>,capacity:usize,heap:cap)→ReserveResult; push(value:mut>,item:T)→PushResult; pop(value:mut>)→std.option.Option; free(value:Vec)→FreeResult; get(value:ref>,index:usize)→std.option.Option; replace(value:mut>,index:usize,item:T)→ReplaceResult. 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. diff --git a/examples/std/vector.aji b/examples/std/vector.aji new file mode 100644 index 0000000..9dac2eb --- /dev/null +++ b/examples/std/vector.aji @@ -0,0 +1,37 @@ +module example.vector +import std.vec; +import std.option; + +fn main(heap: cap) -> u64 effects [mem.alloc] { + match std.vec.new::>(1, heap) { + std.vec.NewResult::>::ok(value) => { + let owner = own.new(42u64, heap) or trap; + { + mut v = value; + match std.vec.push::>(v, move owner) { + std.vec.PushResult::>::ok => {} + std.vec.PushResult::>::full(returned) => { + own.free(move returned); + trap; + } + } + } + var answer: u64 = 0; + { + mut v = value; + match std.vec.pop::>(v) { + std.option.Option::>::some(item) => { + answer = own.take(move item); + } + std.option.Option::>::none => { trap; } + } + } + match std.vec.free::>(move value) { + std.vec.FreeResult::>::ok => {} + std.vec.FreeResult::>::not_empty(returned) => { trap; } + } + return answer; + } + std.vec.NewResult::>::err(e) => { trap; } + } +} diff --git a/src/air/features.zig b/src/air/features.zig index 20a7d16..0961ef7 100644 --- a/src/air/features.zig +++ b/src/air/features.zig @@ -35,6 +35,7 @@ pub const registry = [_]Feature{ .{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .published, .phase = 2 }, .{ .name = "islands", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 4 }, .{ .name = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .published, .phase = 6 }, + .{ .name = "linear_buffers", .depends = &.{ "arrays", "capabilities", "effects", "heap", "linear_aggregates", "ownership", "resources" }, .status = .published, .phase = 6 }, .{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 }, .{ .name = "receiver_dup", .depends = &.{ "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "resources", "tasks" }, .status = .reserved, .phase = null }, .{ .name = "regions", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 2 }, @@ -49,7 +50,7 @@ pub const registry = [_]Feature{ }; /// Features implemented by this toolchain, sorted. -pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "linear_aggregates", "ownership", "regions", "resources", "sync", "tasks", "unsafe" }; +pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "linear_aggregates", "linear_buffers", "ownership", "regions", "resources", "sync", "tasks", "unsafe" }; pub const Reason = enum { unknown_feature, diff --git a/src/air/module.zig b/src/air/module.zig index afe21b7..890b2b5 100644 --- a/src/air/module.zig +++ b/src/air/module.zig @@ -82,6 +82,7 @@ pub const Type = union(enum) { // Features `heap` and `regions` (spec 03 §18–§20). own: *const Type, own_array: *const Type, + buffer: *const Type, region, // Feature `tasks` (spec 04 §33). scope, @@ -109,7 +110,7 @@ pub const Type = union(enum) { return switch (a) { .int => |x| b.int == x, .named => |x| b.named == x, - .local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(b.inner().?), + .local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(b.inner().?), .region, .scope, .shield => true, .array => |x| x.len == b.array.len and x.elem.eql(b.array.elem), .cap => |k| b.cap == k, @@ -122,7 +123,7 @@ pub const Type = union(enum) { /// Element or pointee type of storage, borrow and slice types. pub fn inner(t: Type) ?Type { return switch (t) { - .local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*, + .local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*, .array => |a| a.elem, else => null, }; @@ -139,7 +140,7 @@ pub const Type = union(enum) { /// Linear values: consumed exactly once (spec 06 §6.2–§6.3). pub fn isLinear(t: Type) bool { return switch (t) { - .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => true, + .resource, .own, .own_array, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => true, else => false, }; } @@ -173,7 +174,7 @@ pub const Type = union(enum) { /// Linear resources are neither values nor borrows: they are moved. pub fn isValue(t: Type) bool { return switch (t) { - .void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => false, + .void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => false, else => true, }; } @@ -340,6 +341,15 @@ pub const Op = union(enum) { region_array: struct { region: ValueId, n: ValueId, value: ValueId, ok: u32, err: u32 }, region_reset: ValueId, region_destroy: ValueId, + // Feature linear_buffers (spec 03 §26). + buffer_new: struct { ty: Type, n: ValueId, cap: ValueId, ok: u32, err: u32 }, + buffer_len: ValueId, + buffer_capacity: ValueId, + buffer_view: ValueId, + buffer_reserve: struct { borrow: ValueId, n: ValueId, cap: ValueId, ok: u32, err: u32 }, + buffer_push: struct { borrow: ValueId, value: ValueId, ok: u32, err: u32 }, + buffer_pop: struct { value: ValueId, ok: u32, err: u32 }, + buffer_free: struct { value: ValueId, ok: u32, err: u32 }, // Feature `tasks` (spec 04 §33). task_scope_begin, task_spawn: struct { scope: ValueId, callee: u32, args: []const ValueId }, @@ -413,7 +423,15 @@ pub const Op = union(enum) { return buf[0..n]; } + pub fn bufferTargets(op: Op) ?struct { ok: u32, err: u32 } { + return switch (op) { + inline .buffer_new, .buffer_reserve, .buffer_push, .buffer_pop, .buffer_free => |x| .{ .ok = x.ok, .err = x.err }, + else => null, + }; + } + pub fn isTerminator(op: Op) bool { + if (op.bufferTargets() != null) return true; return switch (op) { inline .br, .cbr, .@"switch", .enum_switch, .enum_take, .aggregate_unpack, .cap_narrow, .ret, .trap => true, inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => true, @@ -526,6 +544,21 @@ pub const Module = struct { /// of terminators are included. pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) void) void { switch (op) { + .buffer_new => |x| { + f(ctx, x.n); + f(ctx, x.cap); + }, + .buffer_reserve => |x| { + f(ctx, x.borrow); + f(ctx, x.n); + f(ctx, x.cap); + }, + .buffer_push => |x| { + f(ctx, x.borrow); + f(ctx, x.value); + }, + inline .buffer_pop, .buffer_free => |x| f(ctx, x.value), + .buffer_len, .buffer_capacity, .buffer_view => |v| f(ctx, v), .@"const", .trap => {}, .copy, .assert => |v| f(ctx, v), .arith => |x| { @@ -689,6 +722,11 @@ pub fn allocTargets(op: Op) ?struct { ok: u32, err: u32 } { } pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std.mem.Allocator.Error!void { + if (op.bufferTargets()) |t| { + try buf.append(gpa, t.ok); + try buf.append(gpa, t.err); + return; + } switch (op) { .br => |t| try buf.append(gpa, t.block), .cbr => |x| { diff --git a/src/air/parse.zig b/src/air/parse.zig index 0b50417..bfa6b28 100644 --- a/src/air/parse.zig +++ b/src/air/parse.zig @@ -560,7 +560,7 @@ const Parser = struct { boxed.* = inner; return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed }; } - const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref, atomic }; + const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref, atomic, buffer }; if (std.meta.stringToEnum(Wrapper, t.text)) |which| { try p.requireFeature(switch (which) { .task => "tasks", @@ -569,6 +569,7 @@ const Parser = struct { .island, .frozen, .iref => "islands", .arc => "arc", .atomic => "atomics", + .buffer => "linear_buffers", }, t.span, t.text); _ = try p.expect(.lt, "`<`"); // Element rules (spec 04 §38.1) are checked by the type stage. @@ -587,6 +588,7 @@ const Parser = struct { .arc => .{ .arc = boxed }, .iref => .{ .iref = boxed }, .atomic => .{ .atomic = boxed }, + .buffer => .{ .buffer = boxed }, }; } if (eql(t.text, "cap")) { @@ -909,6 +911,39 @@ const Parser = struct { const it = std.meta.stringToEnum(air.IntType, parts[2]) orelse return p.unknownOpcode(op_tok); break :op .{ .cast = .{ .mode = mode, .to = it, .a = try p.useValue() } }; } + if (std.mem.startsWith(u8, op_tok.text, "buffer.")) { + try p.requireFeature("linear_buffers", op_tok.span, op_tok.text); + const Name = enum { new, len, capacity, view, reserve, push, pop, free }; + const name = std.meta.stringToEnum(Name, op_tok.text[7..]) orelse return p.unknownOpcode(op_tok); + switch (name) { + .new => { + const ty = try p.parseType(); + const n, const cap = try p.twoOperands(); + const ok, const err = try p.okErr(); + break :op .{ .buffer_new = .{ .ty = ty, .n = n, .cap = cap, .ok = ok, .err = err } }; + }, + .len => break :op .{ .buffer_len = try p.useValue() }, + .capacity => break :op .{ .buffer_capacity = try p.useValue() }, + .view => break :op .{ .buffer_view = try p.useValue() }, + .reserve => { + const borrow, const n = try p.twoOperands(); + _ = try p.expect(.comma, "`,`"); + const cap = try p.useValue(); + const ok, const err = try p.okErr(); + break :op .{ .buffer_reserve = .{ .borrow = borrow, .n = n, .cap = cap, .ok = ok, .err = err } }; + }, + .push => { + const borrow, const value = try p.twoOperands(); + const ok, const err = try p.okErr(); + break :op .{ .buffer_push = .{ .borrow = borrow, .value = value, .ok = ok, .err = err } }; + }, + .pop, .free => { + const value = try p.useValue(); + const ok, const err = try p.okErr(); + break :op if (name == .pop) .{ .buffer_pop = .{ .value = value, .ok = ok, .err = err } } else .{ .buffer_free = .{ .value = value, .ok = ok, .err = err } }; + }, + } + } if (eql(op_tok.text, "array.make")) { try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text); const ty = try p.parseType(); @@ -1077,7 +1112,7 @@ const Parser = struct { .atomic_new, .atomic_take, .atomic_load, .atomic_rmw, .atomic_cmpxchg => true, .@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true, .local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true, - .array_splat, .array_make, .value_swap, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true, + .buffer_len, .buffer_capacity, .buffer_view, .array_splat, .array_make, .value_swap, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true, else => false, }; const may_bind = produces_value or op == .call or op == .intrinsic or op == .task_join; diff --git a/src/air/print.zig b/src/air/print.zig index 89f17ed..125aeae 100644 --- a/src/air/print.zig +++ b/src/air/print.zig @@ -115,7 +115,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void { .cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}), .builtin => |b| try w.writeAll(@tagName(b)), .resource => |r| try w.writeAll(r.text()), - .own, .own_array => |inner| { + .own, .own_array, .buffer => |inner| { try w.print("{s}<", .{@tagName(t)}); try printType(m, inner.*, w); try w.writeByte('>'); @@ -323,6 +323,30 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error! try values(f, x.args, w); if (x.ok) |ok| try w.print(", ok -> @{s}, err -> @{s}", .{ f.blocks[ok].name, f.blocks[x.err.?].name }); }, + .buffer_new => |x| { + try w.writeAll("buffer.new "); + try printType(m, x.ty, w); + try w.print(" %{s}, %{s}", .{ f.values[x.n].name, f.values[x.cap].name }); + try okErr(f, w, x.ok, x.err); + }, + inline .buffer_len, .buffer_capacity, .buffer_view => |v, tag| try one(f, w, switch (tag) { + .buffer_len => "buffer.len", + .buffer_capacity => "buffer.capacity", + .buffer_view => "buffer.view", + else => unreachable, + }, v), + .buffer_reserve => |x| { + try w.print("buffer.reserve %{s}, %{s}, %{s}", .{ f.values[x.borrow].name, f.values[x.n].name, f.values[x.cap].name }); + try okErr(f, w, x.ok, x.err); + }, + .buffer_push => |x| { + try two(f, w, "buffer.push", x.borrow, x.value); + try okErr(f, w, x.ok, x.err); + }, + inline .buffer_pop, .buffer_free => |x, tag| { + try one(f, w, if (tag == .buffer_pop) "buffer.pop" else "buffer.free", x.value); + try okErr(f, w, x.ok, x.err); + }, inline .own_new, .own_pack => |x, tag| { if (tag == .own_pack) { try w.writeAll("own.pack "); @@ -692,3 +716,50 @@ test "round-trip whole-value linear operations" { \\ ret %n ); } + +test "round-trip initialized buffers" { + try roundTrip( + \\module test.buffers + \\ air 0 + \\ lang 0.1 + \\ features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] + \\fn @main(%heap: cap) -> u64 + \\effects [mem.alloc] + \\entry: + \\ %capacity = const.usize 1 + \\ %n = const.u64 42 + \\ buffer.new own %capacity, %heap, ok -> @made, err -> @failed + \\made(%data: buffer>): + \\ own.new %n, %heap, ok -> @owned, err -> @owner_failed + \\owned(%owner: own): + \\ %b = borrow.mut %data + \\ buffer.push %b, %owner, ok -> @pushed, err -> @full + \\full(%returned: own): + \\ trap + \\pushed: + \\ %next_capacity = const.usize 2 + \\ buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed + \\grown: + \\ %length = buffer.len %b + \\ %capacity_after = buffer.capacity %b + \\ %view = buffer.view %b + \\ borrow.end %view + \\ buffer.pop %b, ok -> @popped, err -> @empty + \\popped(%part: own): + \\ %answer = own.take %part + \\ borrow.end %b + \\ buffer.free %data, ok -> @done, err -> @nonempty + \\nonempty(%original: buffer>): + \\ trap + \\done: + \\ ret %answer + \\empty: + \\ trap + \\failed(%error: alloc_error): + \\ trap + \\owner_failed(%owner_error: alloc_error): + \\ trap + \\reserve_failed(%reserve_error: alloc_error): + \\ trap + ); +} diff --git a/src/frontend/ast.zig b/src/frontend/ast.zig index 4e37afe..16bce0a 100644 --- a/src/frontend/ast.zig +++ b/src/frontend/ast.zig @@ -55,6 +55,8 @@ pub const CastMode = enum { widen, checked, wrap }; pub const Expr = struct { span: Span, + /// Complete Copy transfer is admitted only in a specialized template body. + generic_transfer: bool = false, kind: Kind, pub const Kind = union(enum) { @@ -72,7 +74,7 @@ pub const Expr = struct { move: []const u8, binary: struct { op: BinOp, l: *const Expr, r: *const Expr }, cast: struct { mode: CastMode, e: *const Expr, ty: Type }, - /// `callee(args)`; `type_arg` only for `channel.make`. + /// `callee(args)`; `type_arg` for `channel.make` / `buffer.new`. call: struct { callee: *const Expr, type_arg: ?Type, args: []const Expr }, field: struct { e: *const Expr, name: []const u8 }, /// `e[lo]` or `e[lo..hi]`. diff --git a/src/frontend/generics.zig b/src/frontend/generics.zig index de16533..6cf5883 100644 --- a/src/frontend/generics.zig +++ b/src/frontend/generics.zig @@ -303,6 +303,7 @@ const Generator = struct { fn expression(g: *Generator, e: ast.Expr, env: Env) Error!ast.Expr { var out = e; + if (e.kind == .move and env.params.len != 0) out.generic_transfer = true; switch (e.kind) { .specialize => |x| { const name = path(g.arena, x.base.*) catch return error.OutOfMemory; diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index f8e6867..f1bd91a 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -50,6 +50,7 @@ pub const Ty = union(enum) { slice_mut: *const Ty, own: *const Ty, own_array: *const Ty, + buffer: *const Ty, region, /// `cap`: the kind. cap: []const u8, @@ -81,7 +82,7 @@ pub const Ty = union(enum) { /// Linear: consumed exactly once, by `move` (spec 15 §5). fn isLinear(t: Ty) bool { return switch (t) { - .own, .own_array, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true, + .own, .own_array, .buffer, .region, .resource, .task, .sender, .receiver, .scope, .mutex, .guard, .shield, .island, .frozen, .arc, .atomic => true, else => false, }; } @@ -92,7 +93,7 @@ pub const Ty = union(enum) { .int => |x| std.mem.eql(u8, x, b.int), .named => |i| i == b.named, .array => |x| x.len == b.array.len and x.elem.eql(b.array.elem), - .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(inner(b).?), + .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(inner(b).?), .cap => |k| std.mem.eql(u8, k, b.cap), .builtin => |e| e == b.builtin, .resource => |r| r == b.resource, @@ -102,7 +103,7 @@ pub const Ty = union(enum) { fn inner(t: Ty) ?Ty { return switch (t) { - .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*, + .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*, .array => |a| a.elem, else => null, }; @@ -379,7 +380,7 @@ const Lowerer = struct { .never => "never", .named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i], .array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.typeText(a.elem, source_names), a.len }) catch "array", - .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow", + .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow", .scope => "scope", .shield => "shield", .region => "region", @@ -487,7 +488,7 @@ const Lowerer = struct { out.* = .{ .elem = try l.airType(a.elem), .len = a.len }; break :blk .{ .array = out }; }, - inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: { + inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: { const out = try l.arena.create(air_module.Type); out.* = try l.airType(inner.*); break :blk @unionInit(air_module.Type, @tagName(tag), out); @@ -579,6 +580,7 @@ const Lowerer = struct { const rules = [_]Rule{ .{ "arrays", &.{ "array<", "slice", "array.splat", "borrow.index" } }, .{ "ownership", &.{ "local.", "borrow.", " load ", "= load ", "store ", "ref<", "mut<" } }, + .{ "linear_buffers", &.{ "buffer<", "buffer." } }, .{ "linear_aggregates", &.{ "array.make ", "struct.unpack ", "array.unpack ", "enum.take ", "value.swap ", "own.pack " } }, .{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } }, .{ "regions", &.{"region"} }, @@ -663,7 +665,7 @@ const Lowerer = struct { }, .array => |a| return l.arrayOf(try l.memberType(a.elem.*), a.len), .wrapped => |w| { - const Wr = enum { ref, mut, slice, slice_mut, own, own_array, task, sender, receiver, mutex, island, frozen, arc, iref, atomic }; + 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)"); const in = try l.typeOf(w.inner.*); return switch (which) { @@ -673,6 +675,7 @@ const Lowerer = struct { .slice_mut => l.wrap(.slice_mut, in), .own => l.wrap(.own, in), .own_array => l.wrap(.own_array, in), + .buffer => l.wrap(.buffer, in), .task => l.wrap(.task, in), .sender => l.wrap(.sender, in), .receiver => l.wrap(.receiver, in), @@ -1082,6 +1085,7 @@ const Lowerer = struct { const scope_start = l.scopeBindingStart(); for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name)) return l.fail("E7006", s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }}); + if (x.place.kind == .call) if (pathOf(x.place.kind.call.callee.*)) |p| if (std.mem.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); @@ -1528,7 +1532,8 @@ const Lowerer = struct { .or_trap => |x| return l.orTrap(e, x.*), .move => |n| { const b = l.lookup(n) orelse return l.unknown(e.span, n); - if (!l.isLinear(b.ty)) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } }); + if (!l.isLinear(b.ty) and !(e.generic_transfer and b.ty != .void and b.ty != .never and !b.ty.isBorrow() and b.ty != .task and b.ty != .scope and b.ty != .guard and b.ty != .shield)) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } }); + if (b.kind == .storage) return l.def(n, b.ty, try l.fmt("local.load %{s}", .{b.value}), e.span); return .{ .name = b.value, .ty = b.ty }; }, } @@ -1607,6 +1612,14 @@ const Lowerer = struct { } fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) 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", &.{}); + const b = try l.bufferBorrow(args[0], false); + return l.def("size", .{ .int = "usize" }, try l.fmt("{s} %{s}", .{ p, b.name }), e.span); + } + if (std.mem.eql(u8, p, "buffer.view")) return l.fail("E7006", e.span, "bind a buffer view with ref/mut name = buffer.view(borrow)", &.{}); + } if (pathOf(callee)) |path| if (std.mem.eql(u8, path, "value.swap")) { if (args.len != 2 or args[0].kind != .borrow or !args[0].kind.borrow.mutable) return l.fail("E7006", e.span, "value.swap requires mut place and replacement", &.{}); const b = args[0].kind.borrow; @@ -1956,6 +1969,7 @@ const Lowerer = struct { /// without lowering it. fn peekPath(l: *Lowerer, p: []const u8, args: []const ast.Expr) ?Ty { const eq = std.mem.eql; + if (eq(u8, p, "buffer.len") or eq(u8, p, "buffer.capacity")) return .{ .int = "usize" }; if ((eq(u8, p, "own.take") or eq(u8, p, "task.join")) and args.len == 1) return if (l.peekType(args[0])) |t| t.inner() else null; if (eq(u8, p, "task.cancelled")) return .bool; if (std.mem.startsWith(u8, p, "atomic.") and args.len >= 1) { @@ -2139,6 +2153,7 @@ const Lowerer = struct { .named, .array => if (l.isLinear(b.ty)) (if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty)) else null, .own => |in| if (mutable) try l.wrap(.mut, in.*) else try l.wrap(.ref, in.*), .own_array => |in| if (mutable) try l.wrap(.slice_mut, in.*) else try l.wrap(.slice, in.*), + .buffer => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), .region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region), .resource, .mutex, .sender, .receiver, .task, .island => if (mutable) try l.wrap(.mut, b.ty) else try l.wrap(.ref, b.ty), .frozen, .arc => if (mutable) return l.fail("E7005", place.span, "frozen graphs and arcs are immutable: borrow them with `ref`", &.{.{ .name = "name", .value = n }}) else try l.wrap(.ref, b.ty), @@ -2425,7 +2440,7 @@ const Lowerer = struct { fn fallible(l: *Lowerer, path: []const u8) ?void { _ = l; - const ops = [_][]const u8{ "own.new", "own.pack", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" }; + const ops = [_][]const u8{ "buffer.new", "buffer.reserve", "buffer.push", "buffer.pop", "buffer.free", "own.new", "own.pack", "own.array", "region.create", "region.new", "region.array", "cap.narrow.budget", "cap.narrow.prefix", "channel.make", "channel.send", "channel.recv", "channel.close_receiver", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", "arc.new" }; for (ops) |o| if (std.mem.eql(u8, o, path)) return {}; if (authority.intrinsicIndex(path)) |i| if (authority.intrinsics[i].fallible) return {}; return null; @@ -2860,7 +2875,7 @@ const Lowerer = struct { return switch (t) { .ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => t, .array => |a| l.forbiddenIn(a.elem, depth + 1), - .own, .own_array, .mutex => |x| l.forbiddenIn(x.*, depth + 1), + .own, .own_array, .buffer, .mutex => |x| l.forbiddenIn(x.*, depth + 1), .named => |i| blk: { const d = l.m.types[i]; switch (d.kind) { @@ -2886,8 +2901,33 @@ const Lowerer = struct { return .{ .name = b.value, .ty = b.ty }; } - /// `ref x = island.at(g, r);` / `mut x = island.at(g, r);`, and - /// `frozen.at`, `arc.at` (`ref` only): a child borrow of `g`. + /// Buffer operations require an explicit named borrow of the handle. + fn bufferBorrow(l: *Lowerer, e: ast.Expr, mutable: bool) Error!Value { + if (e.kind == .name) if (l.lookup(e.kind.name)) |b| { + if ((b.ty == .mut or (!mutable and b.ty == .ref)) and b.ty.inner().? == .buffer) return .{ .name = b.value, .ty = b.ty }; + }; + return l.fail("E7005", e.span, if (mutable) "bind a named mut> first" else "bind a named ref/mut> first", &.{}); + } + + fn bufferView(l: *Lowerer, s: ast.Stmt, name_: []const u8, mutable: bool, place: ast.Expr) Error!void { + const args = place.kind.call.args; + if (args.len != 1) return l.fail("E7005", place.span, "buffer.view takes one named buffer borrow", &.{}); + const parent = try l.bufferBorrow(args[0], mutable); + // A shared view from a mutable parent uses an explicit shared reborrow. + 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); + 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); + 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 }); + } + + /// Graph access binds a child borrow of its named graph borrow. fn graphAccess(l: *Lowerer, s: ast.Stmt, name: []const u8, mutable: bool, place: ast.Expr) Error!void { const ac = place.kind.call; const p = pathOf(ac.callee.*).?; @@ -2996,6 +3036,38 @@ const Lowerer = struct { }.n; const alloc_err: Ty = .{ .builtin = .alloc_error }; const usize_ty: Ty = .{ .int = "usize" }; + if (std.mem.eql(u8, path, "buffer.new")) { + try want(l, e.span, args, 2, path); + const source_ty = e.kind.call.type_arg orelse return l.fail("E7005", e.span, "buffer.new needs an explicit content type", &.{}); + const ty = try l.typeOf(source_ty); + const n = try l.expr(args[0], usize_ty); + try l.checkTy(args[0].span, n.ty, usize_ty); + const cap = try l.expectCap(args[1], "mem.alloc"); + return .{ .text = try l.fmt("buffer.new {s} %{s}, %{s}", .{ l.tyText(ty), n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.buffer, ty)} }, .{ .role = "err", .params = &.{alloc_err} } }) }; + } + if (std.mem.eql(u8, path, "buffer.free")) { + try want(l, e.span, args, 1, path); + const v = try l.consuming(args[0], null); + if (v.ty != .buffer) return l.fail("E7005", e.span, "buffer.free consumes a buffer", &.{}); + return .{ .text = try l.fmt("buffer.free %{s}", .{v.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{v.ty} } }) }; + } + if (std.mem.eql(u8, path, "buffer.push") or std.mem.eql(u8, path, "buffer.pop") or std.mem.eql(u8, path, "buffer.reserve")) { + const is_push = std.mem.eql(u8, path, "buffer.push"); + const is_pop = std.mem.eql(u8, path, "buffer.pop"); + try want(l, e.span, args, if (is_push) 2 else if (is_pop) 1 else 3, path); + const b = try l.bufferBorrow(args[0], true); + const ty = b.ty.inner().?.buffer.*; + if (is_push) { + const v = try l.consuming(args[1], ty); + try l.checkTy(args[1].span, v.ty, ty); + return .{ .text = try l.fmt("buffer.push %{s}, %{s}", .{ b.name, v.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{ty} } }) }; + } + if (is_pop) return .{ .text = try l.fmt("buffer.pop %{s}", .{b.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{ty} }, .{ .role = "err", .params = &.{} } }) }; + const n = try l.expr(args[1], usize_ty); + try l.checkTy(args[1].span, n.ty, usize_ty); + const cap = try l.expectCap(args[2], "mem.alloc"); + return .{ .text = try l.fmt("buffer.reserve %{s}, %{s}, %{s}", .{ b.name, n.name, cap.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "err", .params = &.{alloc_err} } }) }; + } if (std.mem.eql(u8, path, "own.pack")) { try want(l, e.span, args, 2, path); const v = try l.consuming(args[0], null); @@ -3296,20 +3368,14 @@ fn elemOf(t: Ty) ?Ty { /// `cap.narrow.budget`; null for anything else. fn pathOf(e: ast.Expr) ?[]const u8 { const known = [_][]const u8{ - "struct.unpack", "array.unpack", "value.swap", "own.pack", - "slice.copy", "own.new", "own.array", "own.take", - "own.free", "region.create", "region.new", "region.array", - "region.reset", "region.destroy", "cap.narrow.budget", "cap.narrow.prefix", - "task.spawn", "task.join", "task.cancel", "task.cancelled", - "channel.make", "channel.dup", "channel.send", "channel.recv", - "channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", - "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", - "island.root", "island.at", "island.freeze", "island.destroy", - "frozen.root", "frozen.at", "frozen.release", "arc.from_frozen", - "arc.new", "arc.clone", "arc.release", "arc.root", - "arc.at", "atomic.new", "atomic.take", "atomic.load", - "atomic.store", "atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", - "atomic.and", "atomic.or", "atomic.xor", "atomic.compare_exchange", + "buffer.new", "buffer.len", "buffer.capacity", "buffer.reserve", "buffer.push", "buffer.pop", "buffer.view", "buffer.free", + "struct.unpack", "array.unpack", "value.swap", "own.pack", "slice.copy", "own.new", "own.array", "own.take", + "own.free", "region.create", "region.new", "region.array", "region.reset", "region.destroy", "cap.narrow.budget", "cap.narrow.prefix", + "task.spawn", "task.join", "task.cancel", "task.cancelled", "channel.make", "channel.dup", "channel.send", "channel.recv", + "channel.close_sender", "channel.close_receiver", "mutex.make", "mutex.take", "task.check_cancel", "task.join_cancel", "island.create", "island.alloc", + "island.root", "island.at", "island.freeze", "island.destroy", "frozen.root", "frozen.at", "frozen.release", "arc.from_frozen", + "arc.new", "arc.clone", "arc.release", "arc.root", "arc.at", "atomic.new", "atomic.take", "atomic.load", + "atomic.store", "atomic.swap", "atomic.add.wrap", "atomic.sub.wrap", "atomic.and", "atomic.or", "atomic.xor", "atomic.compare_exchange", "atomic.fence", }; var buf: [64]u8 = undefined; diff --git a/src/frontend/modules.zig b/src/frontend/modules.zig index faae3fa..092b8de 100644 --- a/src/frontend/modules.zig +++ b/src/frontend/modules.zig @@ -13,7 +13,7 @@ const Node = struct { module: ast.Module, active: bool, height: usize = 0 }; pub fn reserved(name: []const u8) bool { const first = if (std.mem.indexOfScalar(u8, name, '.')) |at| name[0..at] else name; - for ([_][]const u8{ "std", "slice", "own", "region", "cap", "task", "channel", "mutex", "island", "frozen", "arc", "atomic" }) |word| { + for ([_][]const u8{ "std", "slice", "buffer", "own", "region", "cap", "task", "channel", "mutex", "island", "frozen", "arc", "atomic" }) |word| { if (std.mem.eql(u8, first, word)) return true; } for (authority.intrinsics) |intrinsic| { diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index 8cbdd4e..5bb2565 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -263,7 +263,7 @@ const Parser = struct { return .{ .span = p.span(start), .kind = if (std.mem.eql(u8, name, "cap")) .{ .cap = value } else .{ .file = value } }; } const args = try p.typeArgs(); - const wrappers = [_][]const u8{ "ref", "mut", "slice", "slice_mut", "own", "own_array", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "iref", "atomic" }; + const wrappers = [_][]const u8{ "ref", "mut", "slice", "slice_mut", "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "iref", "atomic" }; for (wrappers) |wrapper| if (std.mem.eql(u8, name, wrapper)) { if (args.len != 1) return p.fail(t, "one wrapper type argument"); return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = name, .inner = try p.box(ast.Type, args[0]) } } }; @@ -701,7 +701,7 @@ const Parser = struct { const base = try p.box(ast.Expr, e); e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } }; // `channel.make(…)`: the only explicit type argument. - if (std.mem.eql(u8, name, "make") and p.peek().tag == .lt and e.kind.field.e.kind == .name and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) { + if (p.peek().tag == .lt and e.kind.field.e.kind == .name and ((std.mem.eql(u8, name, "make") and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) or (std.mem.eql(u8, name, "new") and std.mem.eql(u8, e.kind.field.e.kind.name, "buffer")))) { _ = p.next(); const ty = try p.typeExpr(); try p.closeAngle(); diff --git a/src/frontend/stdlib.zig b/src/frontend/stdlib.zig index 31a1275..bf55644 100644 --- a/src/frontend/stdlib.zig +++ b/src/frontend/stdlib.zig @@ -11,4 +11,5 @@ pub const registry = [_]Source{ .{ .name = "std.option", .file = "std/option.aji", .source = @embedFile("std_option_aji") }, .{ .name = "std.result", .file = "std/result.aji", .source = @embedFile("std_result_aji") }, .{ .name = "std.utf8", .file = "std/utf8.aji", .source = @embedFile("std_utf8_aji") }, + .{ .name = "std.vec", .file = "std/vec.aji", .source = @embedFile("std_vec_aji") }, }; diff --git a/src/interp/machine.zig b/src/interp/machine.zig index 9856d3f..d9c3e9b 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -76,6 +76,16 @@ pub const Value = union(enum) { iref: struct { id: u64, slot: u32 }, /// `atomic`: index into the machine's atomic cells (spec 04 §42). atomic: u32, + buffer: *Buffer, + + pub const Buffer = struct { + // The interpreter stores only the initialized prefix. Capacity is + // charged to Aji authority independently of this host representation; + // push's Value-array bookkeeping does not allocate from that authority. + cell: *Cell, + capacity: u64, + elem: air.Type, + }; /// The guarded value is a separate cell, so a place borrowed through a /// guard points at an ordinary cell. @@ -344,6 +354,7 @@ const Copier = struct { mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty, payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty, graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty, + buffers: std.AutoHashMapUnmanaged(*Value.Buffer, *Value.Buffer) = .empty, fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value { return switch (v) { @@ -351,6 +362,7 @@ const Copier = struct { .array => |xs| .{ .array = try c.items(xs) }, .local => |cl| .{ .local = try c.cell(cl) }, .own => |cl| .{ .own = try c.cell(cl) }, + .buffer => |b| .{ .buffer = try c.buffer(b) }, .place => |p| .{ .place = try c.place(p) }, .slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } }, .mutex => |mc| .{ .mutex = try c.mutex(mc) }, @@ -383,6 +395,14 @@ const Copier = struct { return n; } + fn buffer(c: *Copier, old: *Value.Buffer) std.mem.Allocator.Error!*Value.Buffer { + if (c.buffers.get(old)) |n| return n; + const n = try c.to.create(Value.Buffer); + try c.buffers.put(c.tmp, old, n); + n.* = .{ .cell = try c.cell(old.cell), .capacity = old.capacity, .elem = old.elem }; + return n; + } + fn mutex(c: *Copier, old: *Value.MutexCell) std.mem.Allocator.Error!*Value.MutexCell { if (c.mutexes.get(old)) |n| return n; const n = try c.to.create(Value.MutexCell); @@ -863,6 +883,7 @@ const Machine = struct { return bind(vals, inst.result, .{ .int = .{ .ty = x.to, .bits = bits } }); }, .assert => |v| return if (vals[v].boolean) .next else .{ .trap = .assert }, + .buffer_new, .buffer_len, .buffer_capacity, .buffer_view, .buffer_reserve, .buffer_push, .buffer_pop, .buffer_free => return m.execBuffer(f, vals, inst), .array_make => |x| return bind(vals, inst.result, .{ .array = try m.gatherMut(vals, x.args) }), .aggregate_unpack => |x| { const fields = if (x.ty == .array) vals[x.value].array else vals[x.value].aggregate.fields; @@ -1763,6 +1784,93 @@ const Machine = struct { } } + fn bufferOf(v: Value) *Value.Buffer { + return switch (v) { + .buffer => |b| b, + .place => |p| bufferOf(placePtr(p).*), + else => unreachable, + }; + } + + fn execBuffer(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step { + switch (inst.op) { + .buffer_new => |x| { + const capacity = usize_(vals[x.n]); + const size = budget.accountedSize(m.module, x.ty, 0).?; + const bytes = std.math.mul(u64, capacity, size) catch null; + const authority_ = vals[x.cap].cap; + if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err); + const cell = try m.heap().create(Value.Cell); + cell.* = .{ .value = .{ .array = &.{} }, .ty = .void }; + const b = try m.heap().create(Value.Buffer); + b.* = .{ .cell = cell, .capacity = capacity, .elem = x.ty }; + try m.owners.put(m.heap(), cell, .{ .authority = authority_, .bytes = bytes.? }); + vals[f.blocks[x.ok].params[0].value] = .{ .buffer = b }; + return .{ .jump = x.ok }; + }, + .buffer_len, .buffer_capacity => |v| { + const b = bufferOf(vals[v]); + if (try m.raceCheck(b.cell, &.{}, false)) |r| return r; + return bind(vals, inst.result, .{ .int = .{ .ty = .usize, .bits = if (inst.op == .buffer_len) b.cell.value.array.len else b.capacity } }); + }, + .buffer_view => |v| { + const b = bufferOf(vals[v]); + if (try m.raceCheck(b.cell, &.{}, false)) |r| return r; + return bind(vals, inst.result, .{ .slice = .{ .place = .{ .cell = b.cell, .path = &.{} }, .start = 0, .len = b.cell.value.array.len } }); + }, + .buffer_reserve => |x| { + const b = bufferOf(vals[x.borrow]); + if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; + const capacity = usize_(vals[x.n]); + if (capacity <= b.capacity) return .{ .jump = x.ok }; + const size = budget.accountedSize(m.module, b.elem, 0).?; + const bytes = std.math.mul(u64, capacity, size) catch null; + const authority_ = vals[x.cap].cap; + if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err); + const old = m.owners.get(b.cell).?; + m.uncharge(old.authority, old.bytes); + try m.owners.put(m.heap(), b.cell, .{ .authority = authority_, .bytes = bytes.? }); + b.capacity = capacity; + return .{ .jump = x.ok }; + }, + .buffer_push => |x| { + const b = bufferOf(vals[x.borrow]); + if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; + const old = b.cell.value.array; + if (old.len == b.capacity) { + vals[f.blocks[x.err].params[0].value] = vals[x.value]; + return .{ .jump = x.err }; + } + const items = try m.heap().alloc(Value, old.len + 1); + @memcpy(items[0..old.len], old); + items[old.len] = try m.deepCopy(vals[x.value]); + b.cell.value = .{ .array = items }; + return .{ .jump = x.ok }; + }, + .buffer_pop => |x| { + const b = bufferOf(vals[x.value]); + if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; + const old = b.cell.value.array; + if (old.len == 0) return .{ .jump = x.err }; + vals[f.blocks[x.ok].params[0].value] = old[old.len - 1]; + b.cell.value = .{ .array = old[0 .. old.len - 1] }; + return .{ .jump = x.ok }; + }, + .buffer_free => |x| { + const b = bufferOf(vals[x.value]); + if (try m.raceCheck(b.cell, &.{}, true)) |r| return r; + if (b.cell.value.array.len != 0) { + vals[f.blocks[x.err].params[0].value] = vals[x.value]; + return .{ .jump = x.err }; + } + const allocation = m.owners.fetchRemove(b.cell).?.value; + m.uncharge(allocation.authority, allocation.bytes); + return .{ .jump = x.ok }; + }, + else => unreachable, + } + } + fn allocFailed(f: air.Function, vals: []Value, err: u32) Step { vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } }; return .{ .jump = err }; @@ -2234,7 +2342,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W }, // Storage and borrows cannot be returned from `@main` (spec 08 §11.3). .local, .place, .slice => try s.write(null), - .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null), + .resource, .own, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null), // A capability is opaque: only its kind is shown, never its identity. .cap => { try s.beginObject(); diff --git a/src/report.zig b/src/report.zig index 53d4ac2..1066eda 100644 --- a/src/report.zig +++ b/src/report.zig @@ -64,7 +64,7 @@ fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo { _ = try addOnce(arena, &info.intrinsics, reg.name); if (reg.effect) |e| _ = try addOnce(arena, &info.direct, e); }, - .own_new, .own_pack, .own_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => { + .buffer_new, .buffer_reserve, .own_new, .own_pack, .own_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => { info.allocations += 1; _ = try addOnce(arena, &info.direct, "mem.alloc"); }, diff --git a/src/verifier/borrow.zig b/src/verifier/borrow.zig index 80e00b2..9e6e3e7 100644 --- a/src/verifier/borrow.zig +++ b/src/verifier/borrow.zig @@ -242,6 +242,11 @@ pub fn overlap(a: []const Seg, b: []const Seg) bool { const Edge = struct { target: u32, args: []const ValueId }; fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void { + if (op.bufferTargets()) |t| { + try out.append(arena, .{ .target = t.ok, .args = &.{} }); + try out.append(arena, .{ .target = t.err, .args = &.{} }); + return; + } switch (op) { .br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }), .cbr => |x| { @@ -385,7 +390,7 @@ fn step(w: *Walker, inst: air.Inst) !void { }, .borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }), .borrow_index => |x| try w.derive(inst.result.?, x.borrow, .elem), - .slice_make => |v| try w.derive(inst.result.?, v, null), + .buffer_view, .slice_make => |v| try w.derive(inst.result.?, v, null), .slice_sub => |x| try w.derive(inst.result.?, x.slice, .elem), .slice_split => |x| { const l = inst.result.?; @@ -452,6 +457,15 @@ fn step(w: *Walker, inst: air.Inst) !void { .enum_take => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, + .buffer_new => {}, + .buffer_len, .buffer_capacity => |v| try w.useThrough(v, .shared), + .buffer_reserve => |x| try w.useThrough(x.borrow, .exclusive), + .buffer_push => |x| { + try w.useThrough(x.borrow, .exclusive); + if (w.isResource(x.value)) try w.consume(x.value, .moved); + }, + .buffer_pop => |x| try w.useThrough(x.value, .exclusive), + .buffer_free => |x| try w.consume(x.value, .moved), .own_pack => |x| { if (w.isResource(x.value)) try w.consume(x.value, .moved); }, diff --git a/src/verifier/budget.zig b/src/verifier/budget.zig index dc0db12..720a00e 100644 --- a/src/verifier/budget.zig +++ b/src/verifier/budget.zig @@ -33,6 +33,7 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 { .atomic => |inner| accountedSize(m, inner.*, depth + 1), .mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null, .own_array => 16, + .buffer => 24, .slice, .slice_mut => 16, .builtin => |b| tagSize(b.variants().len), .array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1) orelse return null) catch null, @@ -151,7 +152,7 @@ fn checkValueSizes(c: *verifier.Context) !void { for (b.params) |p| try v.visit(b.span, p.ty); for (b.insts) |inst| switch (inst.op) { .local_alloc => |t| try v.visit(inst.span, t), - inline .array_splat, .array_make, .aggregate_unpack, .own_pack => |x| try v.visit(inst.span, x.ty), + inline .array_splat, .array_make, .aggregate_unpack, .own_pack, .buffer_new => |x| try v.visit(inst.span, x.ty), else => {}, }; } diff --git a/src/verifier/cfg.zig b/src/verifier/cfg.zig index b66887e..fc05b43 100644 --- a/src/verifier/cfg.zig +++ b/src/verifier/cfg.zig @@ -83,6 +83,26 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void { }; try paramCount(c, f, inst.span, x.next, n, "unpack target must receive every component"); }, + .buffer_new => |x| { + try paramCount(c, f, inst.span, x.ok, 1, "buffer.new success takes buffer"); + try paramCount(c, f, inst.span, x.err, 1, "buffer.new failure takes alloc_error"); + }, + .buffer_reserve => |x| { + try paramCount(c, f, inst.span, x.ok, 0, "buffer.reserve success takes no values"); + try paramCount(c, f, inst.span, x.err, 1, "buffer.reserve failure takes alloc_error"); + }, + .buffer_push => |x| { + try paramCount(c, f, inst.span, x.ok, 0, "buffer.push success takes no values"); + try paramCount(c, f, inst.span, x.err, 1, "buffer.push failure returns value"); + }, + .buffer_pop => |x| { + try paramCount(c, f, inst.span, x.ok, 1, "buffer.pop success takes value"); + try paramCount(c, f, inst.span, x.err, 0, "buffer.pop empty takes no values"); + }, + .buffer_free => |x| { + try paramCount(c, f, inst.span, x.ok, 0, "buffer.free success takes no values"); + try paramCount(c, f, inst.span, x.err, 1, "buffer.free nonempty returns buffer"); + }, .own_pack => |x| { try paramCount(c, f, inst.span, x.ok, 1, "own.pack success takes owner"); try paramCount(c, f, inst.span, x.err, 2, "own.pack failure takes error and original value"); diff --git a/src/verifier/effects.zig b/src/verifier/effects.zig index a5ea27d..7813870 100644 --- a/src/verifier/effects.zig +++ b/src/verifier/effects.zig @@ -57,7 +57,7 @@ pub fn check(c: *Context) !void { .atomic_store => |x| try needAtomic(c, f, inst, x.ord != .seq_cst), .atomic_rmw => |x| try needAtomic(c, f, inst, x.ord != .seq_cst), .atomic_cmpxchg => |x| try needAtomic(c, f, inst, x.success != .seq_cst or x.failure != .seq_cst), - .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) { + .buffer_new, .buffer_reserve, .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) { try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "effect", .value = .{ .str = "mem.alloc" } }, diff --git a/src/verifier/types.zig b/src/verifier/types.zig index 7606153..f79cc9a 100644 --- a/src/verifier/types.zig +++ b/src/verifier/types.zig @@ -48,7 +48,7 @@ fn checkDeclarations(c: *Context) !void { for (b.params) |p| try wellFormed(c, b.span, p.ty, .block_param, f.name); for (b.insts) |inst| switch (inst.op) { .local_alloc => |t| try wellFormed(c, inst.span, t, .member, f.name), - inline .array_splat, .array_make, .aggregate_unpack, .own_pack => |x| try wellFormed(c, inst.span, x.ty, .param, f.name), + inline .array_splat, .array_make, .aggregate_unpack, .own_pack, .buffer_new => |x| try wellFormed(c, inst.span, x.ty, .param, f.name), else => {}, }; } @@ -85,7 +85,7 @@ fn visitValue(c: *Context, state: anytype, t: Type) std.mem.Allocator.Error!void switch (t) { .named => |i| try visitDecl(c, state, i), .array => |a| try visitValue(c, state, a.elem), - .own, .own_array, .sender, .receiver, .mutex, .ref, .mut, .slice, .slice_mut, .guard, .task, .local => |inner| if (c.module.declares("linear_aggregates")) try visitValue(c, state, inner.*), + .own, .own_array, .buffer, .sender, .receiver, .mutex, .ref, .mut, .slice, .slice_mut, .guard, .task, .local => |inner| if (c.module.declares("linear_aggregates")) try visitValue(c, state, inner.*), else => {}, } } @@ -104,7 +104,7 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons .local => false, .ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed, .scope, .task, .shield, .guard => pos != .member, - .resource, .own, .own_array, .region, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => pos != .member or c.module.declares("linear_aggregates"), + .resource, .own, .own_array, .buffer, .region, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => pos != .member or c.module.declares("linear_aggregates"), else => true, }; if (t == .own_array and c.module.declares("linear_aggregates") and c.module.isLinearType(t.own_array.*)) try c.report("E1001", span, "dynamic heap arrays require Copy content", &.{}); @@ -266,7 +266,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type { .struct_get => |x| m.types[x.decl].kind.@"struct"[x.field].ty, .enum_make => |x| .{ .named = x.decl }, .call => |x| m.functions[x.callee].ret, - .slice_len => .{ .int = .usize }, + .slice_len, .buffer_len, .buffer_capacity => .{ .int = .usize }, .task_scope_begin => .scope, .task_cancelled => .bool, .task_shield_begin => .shield, @@ -382,7 +382,7 @@ pub fn isCopy(m: air.Module, t: Type) bool { pub fn isLocalType(m: air.Module, t: Type) bool { return switch (t) { .local, .task, .scope, .shield, .guard => true, - .ref, .mut, .slice, .slice_mut, .own, .own_array, .mutex => |inner| isLocalType(m, inner.*), + .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .mutex => |inner| isLocalType(m, inner.*), .array => |a| isLocalType(m, a.elem), .named => |i| switch (m.types[i].kind) { .@"struct" => |fs| for (fs) |f| { @@ -405,7 +405,7 @@ pub fn isSend(m: air.Module, t: Type) bool { .island, .frozen, .arc, .iref => true, // Every access to a cell is an atomic operation (spec 04 §23). .atomic => true, - .own, .own_array, .mutex => |inner| isSend(m, inner.*), + .own, .own_array, .buffer, .mutex => |inner| isSend(m, inner.*), .ref, .slice => |inner| isShare(m, inner.*), .mut, .slice_mut => |inner| isSend(m, inner.*), .array => |a| isSend(m, a.elem), @@ -422,7 +422,7 @@ pub fn isShare(m: air.Module, t: Type) bool { // Its owner may mutate it: freeze to share (spec 04 §35). .island => false, .resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false, - .own, .own_array, .ref, .slice => |inner| isShare(m, inner.*), + .own, .own_array, .buffer, .ref, .slice => |inner| isShare(m, inner.*), // The lock synchronizes access (spec 04 §35, §40). .mutex => |inner| isSend(m, inner.*), .array => |a| isShare(m, a.elem), @@ -602,6 +602,13 @@ fn checkSelect(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "select")) !voi _ = f; } +fn bufferElement(fc: *FnCtx, span: air.Span, v: air.ValueId, mutable: bool) !?Type { + const t = fc.typeOf(v); + if ((t == .mut or (!mutable and t == .ref)) and t.inner().? == .buffer) return t.inner().?.buffer.*; + try fc.kindError(span, v, if (mutable) "mut>" else "ref> or mut>"); + return null; +} + pub fn complete(t: Type) bool { return t != .void and t != .never and t != .local and !t.isBorrow() and !t.isTaskBound() and t != .guard; } @@ -622,7 +629,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { .copy => |v| return fc.ty[v], .local_alloc => |inner| return .{ .local = try boxed(a, inner) }, .local_load => |v| fc.ty[v] orelse return null, - .borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null, + .buffer_view, .borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null, .value_swap => |x| fc.ty[x.borrow] orelse return null, .borrow_field => |x| fc.ty[x.borrow] orelse return null, .borrow_index => |x| fc.ty[x.borrow] orelse return null, @@ -644,12 +651,13 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { }; const invalid: Type = .void; return switch (op) { + .buffer_view => if ((t == .ref or t == .mut) and t.inner().? == .buffer) (if (t == .mut) .{ .slice_mut = try boxed(a, t.inner().?.buffer.*) } else .{ .slice = try boxed(a, t.inner().?.buffer.*) }) else invalid, .value_swap => if (t == .mut) t.mut.* else invalid, .local_load => if (t == .local) t.local.* else invalid, .borrow_ref => switch (t) { .local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) }, .named, .array => if (m.isLinearType(t)) .{ .ref = try boxed(a, t) } else invalid, - .resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) }, + .resource, .region, .task, .scope, .sender, .receiver, .mutex, .buffer, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) }, .own => |inner| .{ .ref = inner }, .own_array => |inner| .{ .slice = inner }, .slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) }, @@ -658,7 +666,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { .borrow_mut => switch (t) { .local, .mut => .{ .mut = try boxed(a, t.inner().?) }, .named, .array => if (m.isLinearType(t)) .{ .mut = try boxed(a, t) } else invalid, - .resource, .region, .task, .scope, .sender, .receiver, .island => .{ .mut = try boxed(a, t) }, + .resource, .region, .task, .scope, .sender, .receiver, .buffer, .island => .{ .mut = try boxed(a, t) }, .own => |inner| .{ .mut = inner }, .own_array => |inner| .{ .slice_mut = inner }, .slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) }, @@ -831,6 +839,36 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { try fc.expectValue(span, x.value, t.mut.*); if (!complete(t.mut.*)) try fc.kindError(span, x.value, "a complete value"); }, + .buffer_new => |x| { + try fc.expectValue(span, x.n, .{ .int = .usize }); + try fc.expectAllocCap(span, x.cap); + if (!complete(x.ty)) return fc.kindError(span, x.n, "complete buffer content"); + try fc.expectParams(span, x.ok, &.{.{ .buffer = try boxed(fc.c.arena, x.ty) }}); + try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }}); + }, + .buffer_len, .buffer_capacity, .buffer_view => |v| { + _ = try bufferElement(fc, span, v, false); + }, + .buffer_reserve => |x| { + _ = try bufferElement(fc, span, x.borrow, true); + try fc.expectValue(span, x.n, .{ .int = .usize }); + try fc.expectAllocCap(span, x.cap); + try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }}); + }, + .buffer_push => |x| { + const t = try bufferElement(fc, span, x.borrow, true) orelse return; + try fc.expectValue(span, x.value, t); + try fc.expectParams(span, x.err, &.{t}); + }, + .buffer_pop => |x| { + const t = try bufferElement(fc, span, x.value, true) orelse return; + try fc.expectParams(span, x.ok, &.{t}); + }, + .buffer_free => |x| { + const t = fc.typeOf(x.value); + if (t != .buffer) return fc.kindError(span, x.value, "buffer"); + try fc.expectParams(span, x.err, &.{t}); + }, .array_make => |x| { if (x.ty != .array) return fc.c.report("E1001", span, "array.make needs an array type", &.{}); if (x.args.len != x.ty.array.len) return fc.c.report("E1001", span, "array.make requires every element", &.{}); diff --git a/std/README.md b/std/README.md index 2f15da7..470f9eb 100644 --- a/std/README.md +++ b/std/README.md @@ -27,7 +27,7 @@ Endian APIs read/write u16/u32/u64 in LE/BE order. Reads return `std.bytes.ReadU `std.fmt.write_u64/i64/usize/isize` write decimal ASCII into supplied buffers with `WriteResult::ok(count)` / `short_output`. Counts include a negative sign; short output stays unchanged, suffixes stay unchanged on success and no terminator is written. The [formatting example](../examples/std/format.aji) composes `value=-42 count=7` with explicit offsets and returns 17 without grants. -The compiler uses its embedded copy, so rebuild after editing these files. An installed compiler needs neither this checkout nor a runtime std search path. Standard enum types use fully qualified names in signatures, constructors and matches. Package imports and imported struct literals use explicit manifest mappings ([example](../examples/modules/aji.toml), spec 15 §14). Explicit generics and whole-value owning option/result templates are implemented; growing owning collections still require the STD-6 dynamic storage contract. +The compiler uses its embedded copy, so rebuild after editing these files. An installed compiler needs neither this checkout nor a runtime std search path. Standard enum types use fully qualified names in signatures, constructors and matches. Package imports and imported struct literals use explicit manifest mappings ([example](../examples/modules/aji.toml), spec 15 §14). Explicit generics and whole-value owning option/result templates are implemented; std.vec uses the initialized buffer contract with explicit reserve, bounded push and empty-only free. [API reference](../docs/reference/std.md) · [Specification](../docs/spec/16-standard-library.md) · [Plan](../docs/plan/standard-library.md) · [Import RFC](../docs/rfcs/0016-standard-library-bootstrap.md) · [Endian RFC](../docs/rfcs/0017-standard-endian-results.md) · [Bounded operations RFC](../docs/rfcs/0018-bounded-standard-operations.md) · [Text RFC](../docs/rfcs/0019-standard-text-encodings.md) @@ -35,4 +35,6 @@ The compiler uses its embedded copy, so rebuild after editing these files. An in `std.option.Option` and `std.result.Result` use explicit specialization and ordinary exhaustive enum matching. `is_some::`/`is_ok::` classify variants without allocation. [Generic example](../examples/std/generics.aji) returns 42; owners/resources are supported by linear_aggregates with exhaustive `match move`; borrows remain invalid members. The classification helpers keep Copy constraints. -STD-5 supports whole-value owning structs/enums/fixed arrays and individual own content. Dynamic linear heap buffers remain a separately specified STD-6 storage prerequisite; no bulk operation hides nested cleanup. +STD-5 supports whole-value owning structs/enums/fixed arrays and individual own content. STD-6a/b adds initialized buffer and std.vec; no bulk operation hides nested cleanup. + +`std.vec` provides nine generic functions over Copy/owning values, including files and channel endpoints. Explicit new/reserve require allocation authority; push never grows, free requires empty contents. [Vector example](../examples/std/vector.aji) and [RFC 0024](../docs/rfcs/0024-linear-buffers-and-vectors.md). diff --git a/std/vec.aji b/std/vec.aji new file mode 100644 index 0000000..7864257 --- /dev/null +++ b/std/vec.aji @@ -0,0 +1,77 @@ +module std.vec +import std.option; + +struct Vec { storage: buffer } +enum NewResult { ok(Vec), err(alloc_error) } +enum PushResult { ok, full(T) } +enum ReserveResult { ok, err(alloc_error) } +enum FreeResult { ok, not_empty(Vec) } +enum ReplaceResult { ok(T), out_of_bounds(T) } + +fn new(capacity: usize, heap: cap) -> NewResult +effects [mem.alloc] +{ + match buffer.new(capacity, heap) { + ok(storage) => { return NewResult::::ok(Vec:: { storage: move storage }); } + err(error) => { return NewResult::::err(error); } + } +} + +fn len(value: ref>) -> usize effects [] { + ref storage = value.storage; + return buffer.len(storage); +} + +fn capacity(value: ref>) -> usize effects [] { + ref storage = value.storage; + return buffer.capacity(storage); +} + +fn reserve(value: mut>, capacity: usize, heap: cap) -> ReserveResult +effects [mem.alloc] +{ + mut storage = value.storage; + match buffer.reserve(storage, capacity, heap) { + ok() => { return ReserveResult::ok; } + err(error) => { return ReserveResult::err(error); } + } +} + +fn push(value: mut>, item: T) -> PushResult effects [] { + mut storage = value.storage; + match buffer.push(storage, move item) { + ok() => { return PushResult::::ok; } + err(returned) => { return PushResult::::full(move returned); } + } +} + +fn pop(value: mut>) -> std.option.Option effects [] { + mut storage = value.storage; + match buffer.pop(storage) { + ok(item) => { return std.option.Option::::some(move item); } + err() => { return std.option.Option::::none; } + } +} + +fn free(value: Vec) -> FreeResult effects [] { + let (storage) = struct.unpack(move value); + match buffer.free(move storage) { + ok() => { return FreeResult::::ok; } + err(returned) => { return FreeResult::::not_empty(Vec:: { storage: move returned }); } + } +} + +fn get(value: ref>, index: usize) -> std.option.Option effects [] { + ref storage = value.storage; + if index >= buffer.len(storage) { return std.option.Option::::none; } + ref values = buffer.view(storage); + return std.option.Option::::some(values[index]); +} + +fn replace(value: mut>, index: usize, item: T) -> ReplaceResult effects [] { + mut storage = value.storage; + if index >= buffer.len(storage) { return ReplaceResult::::out_of_bounds(move item); } + mut values = buffer.view(storage); + let previous = value.swap(mut values[index], move item); + return ReplaceResult::::ok(move previous); +} diff --git a/tests/conformance/buffers/borrowed_element.air b/tests/conformance/buffers/borrowed_element.air new file mode 100644 index 0000000..e89ff15 --- /dev/null +++ b/tests/conformance/buffers/borrowed_element.air @@ -0,0 +1,16 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @bad(%b: buffer>) -> void +effects [] +entry: + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/empty_free_leak.air b/tests/conformance/buffers/empty_free_leak.air new file mode 100644 index 0000000..0ee75cd --- /dev/null +++ b/tests/conformance/buffers/empty_free_leak.air @@ -0,0 +1,45 @@ +; expect: reject E3002 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + ret %answer +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/free_failure.air b/tests/conformance/buffers/free_failure.air new file mode 100644 index 0000000..638d603 --- /dev/null +++ b/tests/conformance/buffers/free_failure.air @@ -0,0 +1,46 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:128 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %c_1 = const.usize 1 + buffer.new own %c_1, %heap, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: buffer>): + %c_6 = const.u64 42 + own.new %c_6, %heap, ok -> @ok_7, err -> @err_9 +err_4(%err_5: alloc_error): + trap +ok_7(%ok_8: own): + %data_11 = borrow.mut %ok_3 + buffer.push %data_11, %ok_8, ok -> @ok_12, err -> @err_13 +err_9(%err_10: alloc_error): + trap +ok_12: + borrow.end %data_11 + buffer.free %ok_3, ok -> @ok_15, err -> @err_16 +err_13(%err_14: own): + trap +ok_15: + trap +err_16(%err_17: buffer>): + %c_18 = const.u64 0 + %returned_19 = borrow.mut %err_17 + buffer.pop %returned_19, ok -> @ok_20, err -> @err_22 +ok_20(%ok_21: own): + %v_23 = own.take %ok_21 + borrow.end %returned_19 + buffer.free %err_17, ok -> @ok_24, err -> @err_25 +err_22: + trap +ok_24: + ret %v_23 +err_25(%err_26: buffer>): + trap diff --git a/tests/conformance/buffers/free_return_type.air b/tests/conformance/buffers/free_return_type.air new file mode 100644 index 0000000..ffee467 --- /dev/null +++ b/tests/conformance/buffers/free_return_type.air @@ -0,0 +1,45 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: own): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/metadata_owner.air b/tests/conformance/buffers/metadata_owner.air new file mode 100644 index 0000000..e74630d --- /dev/null +++ b/tests/conformance/buffers/metadata_owner.air @@ -0,0 +1,45 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %data + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/new_count_type.air b/tests/conformance/buffers/new_count_type.air new file mode 100644 index 0000000..1d3c225 --- /dev/null +++ b/tests/conformance/buffers/new_count_type.air @@ -0,0 +1,45 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.u64 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/new_return_type.air b/tests/conformance/buffers/new_return_type.air new file mode 100644 index 0000000..610914b --- /dev/null +++ b/tests/conformance/buffers/new_return_type.air @@ -0,0 +1,45 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: own_array>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/owner.air b/tests/conformance/buffers/owner.air new file mode 100644 index 0000000..cb7adbe --- /dev/null +++ b/tests/conformance/buffers/owner.air @@ -0,0 +1,47 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:128 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/pop_return_type.air b/tests/conformance/buffers/pop_return_type.air new file mode 100644 index 0000000..9e6e717 --- /dev/null +++ b/tests/conformance/buffers/pop_return_type.air @@ -0,0 +1,20 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @bad(%b: mut>>) -> void +effects [] +entry: + buffer.pop %b, ok -> @ok, err -> @err +ok(%item: u64): + trap +err: + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/push_continuation_count.air b/tests/conformance/buffers/push_continuation_count.air new file mode 100644 index 0000000..8de8ec1 --- /dev/null +++ b/tests/conformance/buffers/push_continuation_count.air @@ -0,0 +1,45 @@ +; expect: reject E5002 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed(%unwanted: u64): + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/push_failure.air b/tests/conformance/buffers/push_failure.air new file mode 100644 index 0000000..e8cde41 --- /dev/null +++ b/tests/conformance/buffers/push_failure.air @@ -0,0 +1,38 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:8 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %c_1 = const.usize 0 + buffer.new own %c_1, %heap, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: buffer>): + %c_6 = const.u64 42 + own.new %c_6, %heap, ok -> @ok_7, err -> @err_9 +err_4(%err_5: alloc_error): + trap +ok_7(%ok_8: own): + %c_11 = const.u64 0 + %data_12 = borrow.mut %ok_3 + buffer.push %data_12, %ok_8, ok -> @ok_13, err -> @err_14 +err_9(%err_10: alloc_error): + trap +ok_13: + trap +err_14(%err_15: own): + %v_16 = own.take %err_15 + br @endmatch_17(%v_16) +endmatch_17(%answer_18: u64): + borrow.end %data_12 + buffer.free %ok_3, ok -> @ok_19, err -> @err_20 +ok_19: + ret %answer_18 +err_20(%err_21: buffer>): + trap diff --git a/tests/conformance/buffers/push_type.air b/tests/conformance/buffers/push_type.air new file mode 100644 index 0000000..8b818f1 --- /dev/null +++ b/tests/conformance/buffers/push_type.air @@ -0,0 +1,45 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %n, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.usize 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/readonly_view_push.air b/tests/conformance/buffers/readonly_view_push.air new file mode 100644 index 0000000..6ba05db --- /dev/null +++ b/tests/conformance/buffers/readonly_view_push.air @@ -0,0 +1,23 @@ +; expect: reject E2101 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @bad(%b: mut>) -> void +effects [] +entry: + %r = borrow.ref %b + %view = buffer.view %r + %item = const.u64 42 + buffer.push %b, %item, ok -> @ok, err -> @err +ok: + trap +err(%original: u64): + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/reserve_count_type.air b/tests/conformance/buffers/reserve_count_type.air new file mode 100644 index 0000000..e2b60ab --- /dev/null +++ b/tests/conformance/buffers/reserve_count_type.air @@ -0,0 +1,45 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module test.buffers + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %capacity = const.usize 1 + %n = const.u64 42 + buffer.new own %capacity, %heap, ok -> @made, err -> @failed +made(%data: buffer>): + own.new %n, %heap, ok -> @owned, err -> @owner_failed +owned(%owner: own): + %b = borrow.mut %data + buffer.push %b, %owner, ok -> @pushed, err -> @full +full(%returned: own): + trap +pushed: + %next_capacity = const.u64 2 + buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed +grown: + %length = buffer.len %b + %capacity_after = buffer.capacity %b + %view = buffer.view %b + borrow.end %view + buffer.pop %b, ok -> @popped, err -> @empty +popped(%part: own): + %answer = own.take %part + borrow.end %b + buffer.free %data, ok -> @done, err -> @nonempty +nonempty(%original: buffer>): + trap +done: + ret %answer +empty: + trap +failed(%error: alloc_error): + trap +owner_failed(%owner_error: alloc_error): + trap +reserve_failed(%reserve_error: alloc_error): + trap diff --git a/tests/conformance/buffers/reserve_failure.air b/tests/conformance/buffers/reserve_failure.air new file mode 100644 index 0000000..f4d604c --- /dev/null +++ b/tests/conformance/buffers/reserve_failure.air @@ -0,0 +1,55 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:24 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %c_1 = const.usize 1 + buffer.new own %c_1, %heap, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: buffer>): + %c_6 = const.u64 42 + own.new %c_6, %heap, ok -> @ok_7, err -> @err_9 +err_4(%err_5: alloc_error): + trap +ok_7(%ok_8: own): + %c_11 = const.u64 0 + %data_12 = borrow.mut %ok_3 + buffer.push %data_12, %ok_8, ok -> @ok_13, err -> @err_14 +err_9(%err_10: alloc_error): + trap +ok_13: + %c_16 = const.usize 2 + buffer.reserve %data_12, %c_16, %heap, ok -> @ok_17, err -> @err_18 +err_14(%err_15: own): + trap +ok_17: + trap +err_18(%err_19: alloc_error): + br @endmatch_20() +endmatch_20: + %size_21 = buffer.len %data_12 + %c_22 = const.usize 1 + %cmp_23 = eq.usize %size_21, %c_22 + assert %cmp_23 + %size_24 = buffer.capacity %data_12 + %c_25 = const.usize 1 + %cmp_26 = eq.usize %size_24, %c_25 + assert %cmp_26 + buffer.pop %data_12, ok -> @ok_27, err -> @err_29 +ok_27(%ok_28: own): + %v_30 = own.take %ok_28 + borrow.end %data_12 + buffer.free %ok_3, ok -> @ok_31, err -> @err_32 +err_29: + trap +ok_31: + ret %v_30 +err_32(%err_33: buffer>): + trap diff --git a/tests/conformance/buffers/reserve_missing_effect.air b/tests/conformance/buffers/reserve_missing_effect.air new file mode 100644 index 0000000..a8877c9 --- /dev/null +++ b/tests/conformance/buffers/reserve_missing_effect.air @@ -0,0 +1,21 @@ +; expect: reject E3101 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @bad(%b: mut>, %heap: cap) -> void +effects [] +entry: + %n = const.usize 2 + buffer.reserve %b, %n, %heap, ok -> @ok, err -> @err +ok: + trap +err(%error: alloc_error): + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/task_loan_join.air b/tests/conformance/buffers/task_loan_join.air new file mode 100644 index 0000000..6494bce --- /dev/null +++ b/tests/conformance/buffers/task_loan_join.air @@ -0,0 +1,52 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:8 +; schedules: 8 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources, tasks] + +fn @worker(%b: mut>) -> void +effects [] +entry: + %values_1 = buffer.view %b + %c_2 = const.u64 42 + %c_3 = const.usize 0 + %e_4 = borrow.index %values_1, %c_3 + store %e_4, %c_2 + borrow.end %e_4 + borrow.end %values_1 + ret + +fn @main(%heap: cap) -> u64 +effects [mem.alloc, task.spawn, task.wait] +entry: + %c_1 = const.usize 1 + buffer.new u64 %c_1, %heap, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: buffer): + %c_6 = const.u64 0 + %data_7 = borrow.mut %ok_3 + %c_8 = const.u64 0 + buffer.push %data_7, %c_8, ok -> @ok_9, err -> @err_10 +err_4(%err_5: alloc_error): + trap +ok_9: + %s_12 = task.scope.begin + %t_13 = task.spawn %s_12, @worker(%data_7) + task.join %t_13 + buffer.pop %data_7, ok -> @ok_14, err -> @err_16 +err_10(%err_11: u64): + trap +ok_14(%ok_15: u64): + task.scope.end %s_12 + borrow.end %data_7 + buffer.free %ok_3, ok -> @ok_17, err -> @err_18 +err_16: + trap +ok_17: + ret %ok_15 +err_18(%err_19: buffer): + trap diff --git a/tests/conformance/buffers/undeclared.air b/tests/conformance/buffers/undeclared.air new file mode 100644 index 0000000..57c4c49 --- /dev/null +++ b/tests/conformance/buffers/undeclared.air @@ -0,0 +1,16 @@ +; expect: reject E0006 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +fn @bad(%b: buffer) -> void +effects [] +entry: + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/vec_sender.air b/tests/conformance/buffers/vec_sender.air new file mode 100644 index 0000000..b9e6615 --- /dev/null +++ b/tests/conformance/buffers/vec_sender.air @@ -0,0 +1,151 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:256 +; schedules: 8 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +air 0 +lang 0.1 +features [arrays, cancellation, capabilities, channels, effects, heap, linear_aggregates, linear_buffers, ownership, resources, tasks] + +type @Job = struct { number: u64 } +type @__aji_std_vec_ReserveResult = enum { ok, err(alloc_error) } +type @__aji_g_030fbb9d89a7b1d26bd24ed3bdf33aeb0f973c9877aea5a3ab590df0d069cd9c = enum { some(sender<@Job>), none } +type @__aji_g_adf9ab506f225116b4e63940ab764bfcf831b362013f39a9cce1f9da40a5d25f = enum { ok, not_empty(@__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd) } +type @__aji_g_678f796d99d95f5e4ab04650d6a2af4225cf23c28867f2c8b9b7f9a6f3523c53 = enum { ok(@__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd), err(alloc_error) } +type @__aji_g_9979c1f74e57d64560456fdd7003b9a1397c206d9b6ffa0f2828572f0b21745b = enum { ok, full(sender<@Job>) } +type @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd = struct { storage: buffer> } + +fn @worker(%value: @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd) -> void +effects [task.wait] +entry: + %value_1 = borrow.mut %value + %generic_call_2 = call @__aji_g_05e8ce97baf6d44b66d79d478b43e291c51a47c06f6dd0d5b46a43d38e237a5e(%value_1) + enum.take @__aji_g_030fbb9d89a7b1d26bd24ed3bdf33aeb0f973c9877aea5a3ab590df0d069cd9c %generic_call_2, some -> @case_some_3, none -> @case_none_5 +case_some_3(%tx_4: sender<@Job>): + %tx_6 = borrow.mut %tx_4 + %c_7 = const.u64 42 + %s_8 = struct.make @Job(%c_7) + channel.send %tx_6, %s_8, ok -> @ok_9, closed -> @closed_10, cancelled -> @cancelled_12 +case_none_5: + trap +ok_9: + borrow.end %tx_6 + channel.close_sender %tx_4 + br @endmatch_14() +closed_10(%closed_11: @Job): + borrow.end %tx_6 + trap +cancelled_12(%cancelled_13: @Job): + borrow.end %tx_6 + trap +endmatch_14: + borrow.end %value_1 + %generic_call_15 = call @__aji_g_c3dfdd6f0d003fa9cc11d939d0324808c052768cff10a2925e95c10178c18f56(%value) + enum.take @__aji_g_adf9ab506f225116b4e63940ab764bfcf831b362013f39a9cce1f9da40a5d25f %generic_call_15, ok -> @case_ok_16, not_empty -> @case_not_empty_17 +case_ok_16: + br @endmatch_19() +case_not_empty_17(%returned_18: @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd): + trap +endmatch_19: + ret + +fn @main(%heap: cap) -> u64 +effects [mem.alloc, task.spawn, task.wait] +entry: + %c_1 = const.usize 1 + channel.make @Job, %c_1, %heap, ok -> @ok_2, err -> @err_5 +ok_2(%ok_3: sender<@Job>, %ok_4: receiver<@Job>): + %c_7 = const.usize 1 + %generic_call_8 = call @__aji_g_85108950b46229b59504ce70316fec0d38c98bc75d7860ef8431efa39d94328f(%c_7, %heap) + enum.take @__aji_g_678f796d99d95f5e4ab04650d6a2af4225cf23c28867f2c8b9b7f9a6f3523c53 %generic_call_8, ok -> @case_ok_9, err -> @case_err_11 +err_5(%err_6: alloc_error): + trap +case_ok_9(%value_10: @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd): + %value_13 = borrow.mut %value_10 + %generic_call_14 = call @__aji_g_cc938739a2436bdd418386dd703e9615d44ed6b51baa426156f2f300b87fff47(%value_13, %ok_3) + enum.take @__aji_g_9979c1f74e57d64560456fdd7003b9a1397c206d9b6ffa0f2828572f0b21745b %generic_call_14, ok -> @case_ok_15, full -> @case_full_16 +case_err_11(%error_12: alloc_error): + trap +case_ok_15: + br @endmatch_18() +case_full_16(%returned_17: sender<@Job>): + channel.close_sender %returned_17 + trap +endmatch_18: + borrow.end %value_13 + %s_19 = task.scope.begin + %t_20 = task.spawn %s_19, @worker(%value_10) + %rx_21 = borrow.mut %ok_4 + channel.recv %rx_21, ok -> @ok_22, closed -> @closed_24, cancelled -> @cancelled_25 +ok_22(%ok_23: @Job): + borrow.end %rx_21 + task.join %t_20 + channel.close_receiver %ok_4, ok -> @ok_26, pending -> @pending_27 +closed_24: + borrow.end %rx_21 + trap +cancelled_25: + borrow.end %rx_21 + trap +ok_26: + %number_29 = struct.get @Job.number, %ok_23 + task.scope.end %s_19 + ret %number_29 +pending_27(%pending_28: receiver<@Job>): + trap + +fn @__aji_g_c3dfdd6f0d003fa9cc11d939d0324808c052768cff10a2925e95c10178c18f56(%value: @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd) -> @__aji_g_adf9ab506f225116b4e63940ab764bfcf831b362013f39a9cce1f9da40a5d25f +effects [] +entry: + struct.unpack @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd %value, next -> @unpacked_1 +unpacked_1(%storage_2: buffer>): + buffer.free %storage_2, ok -> @ok_3, err -> @err_4 +ok_3: + %e_6 = enum.make @__aji_g_adf9ab506f225116b4e63940ab764bfcf831b362013f39a9cce1f9da40a5d25f.ok() + ret %e_6 +err_4(%err_5: buffer>): + %s_7 = struct.make @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd(%err_5) + %e_8 = enum.make @__aji_g_adf9ab506f225116b4e63940ab764bfcf831b362013f39a9cce1f9da40a5d25f.not_empty(%s_7) + ret %e_8 + +fn @__aji_g_85108950b46229b59504ce70316fec0d38c98bc75d7860ef8431efa39d94328f(%capacity: usize, %heap: cap) -> @__aji_g_678f796d99d95f5e4ab04650d6a2af4225cf23c28867f2c8b9b7f9a6f3523c53 +effects [mem.alloc] +entry: + buffer.new sender<@Job> %capacity, %heap, ok -> @ok_1, err -> @err_3 +ok_1(%ok_2: buffer>): + %s_5 = struct.make @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd(%ok_2) + %e_6 = enum.make @__aji_g_678f796d99d95f5e4ab04650d6a2af4225cf23c28867f2c8b9b7f9a6f3523c53.ok(%s_5) + ret %e_6 +err_3(%err_4: alloc_error): + %e_7 = enum.make @__aji_g_678f796d99d95f5e4ab04650d6a2af4225cf23c28867f2c8b9b7f9a6f3523c53.err(%err_4) + ret %e_7 + +fn @__aji_g_05e8ce97baf6d44b66d79d478b43e291c51a47c06f6dd0d5b46a43d38e237a5e(%value: mut<@__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd>) -> @__aji_g_030fbb9d89a7b1d26bd24ed3bdf33aeb0f973c9877aea5a3ab590df0d069cd9c +effects [] +entry: + %storage_1 = borrow.field @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd.storage, %value + buffer.pop %storage_1, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: sender<@Job>): + %e_5 = enum.make @__aji_g_030fbb9d89a7b1d26bd24ed3bdf33aeb0f973c9877aea5a3ab590df0d069cd9c.some(%ok_3) + borrow.end %storage_1 + ret %e_5 +err_4: + %e_6 = enum.make @__aji_g_030fbb9d89a7b1d26bd24ed3bdf33aeb0f973c9877aea5a3ab590df0d069cd9c.none() + borrow.end %storage_1 + ret %e_6 + +fn @__aji_g_cc938739a2436bdd418386dd703e9615d44ed6b51baa426156f2f300b87fff47(%value: mut<@__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd>, %item: sender<@Job>) -> @__aji_g_9979c1f74e57d64560456fdd7003b9a1397c206d9b6ffa0f2828572f0b21745b +effects [] +entry: + %storage_1 = borrow.field @__aji_g_ea026a1e94735341330b23660939aafc27c5ea0adb84d993a6694eb8588118dd.storage, %value + buffer.push %storage_1, %item, ok -> @ok_2, err -> @err_3 +ok_2: + %e_5 = enum.make @__aji_g_9979c1f74e57d64560456fdd7003b9a1397c206d9b6ffa0f2828572f0b21745b.ok() + borrow.end %storage_1 + ret %e_5 +err_3(%err_4: sender<@Job>): + %e_6 = enum.make @__aji_g_9979c1f74e57d64560456fdd7003b9a1397c206d9b6ffa0f2828572f0b21745b.full(%err_4) + borrow.end %storage_1 + ret %e_6 diff --git a/tests/conformance/buffers/view.air b/tests/conformance/buffers/view.air new file mode 100644 index 0000000..4411ee9 --- /dev/null +++ b/tests/conformance/buffers/view.air @@ -0,0 +1,64 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:128 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %c_1 = const.usize 2 + buffer.new u64 %c_1, %heap, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: buffer): + %data_6 = borrow.mut %ok_3 + %c_7 = const.u64 41 + buffer.push %data_6, %c_7, ok -> @ok_8, err -> @err_9 +err_4(%err_5: alloc_error): + trap +ok_8: + %values_11 = buffer.view %data_6 + %len_12 = slice.len %values_11 + %c_13 = const.usize 1 + %cmp_14 = eq.usize %len_12, %c_13 + assert %cmp_14 + %c_15 = const.usize 0 + %e_16 = borrow.index %values_11, %c_15 + %v_17 = load %e_16 + borrow.end %e_16 + %c_18 = const.u64 1 + %t_19 = add.checked.u64 %v_17, %c_18 + %c_20 = const.usize 0 + %e_21 = borrow.index %values_11, %c_20 + store %e_21, %t_19 + borrow.end %e_21 + borrow.end %values_11 + %buffer_ref_22 = borrow.ref %data_6 + %values_23 = buffer.view %buffer_ref_22 + %c_24 = const.usize 0 + %e_25 = borrow.index %values_23, %c_24 + %v_26 = load %e_25 + borrow.end %e_25 + %c_27 = const.u64 42 + %cmp_28 = eq.u64 %v_26, %c_27 + assert %cmp_28 + borrow.end %values_23 + borrow.end %buffer_ref_22 + borrow.end %data_6 + %c_29 = const.u64 0 + %data_30 = borrow.mut %ok_3 + buffer.pop %data_30, ok -> @ok_31, err -> @err_33 +err_9(%err_10: u64): + trap +ok_31(%ok_32: u64): + borrow.end %data_30 + buffer.free %ok_3, ok -> @ok_34, err -> @err_35 +err_33: + trap +ok_34: + ret %ok_32 +err_35(%err_36: buffer): + trap diff --git a/tests/conformance/buffers/view_mutation.air b/tests/conformance/buffers/view_mutation.air new file mode 100644 index 0000000..7955571 --- /dev/null +++ b/tests/conformance/buffers/view_mutation.air @@ -0,0 +1,22 @@ +; expect: reject E2101 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @bad(%b: mut>, %heap: cap) -> void +effects [mem.alloc] +entry: + %n = const.usize 0 + %view = buffer.view %b + buffer.reserve %b, %n, %heap, ok -> @ok, err -> @err +ok: + trap +err(%error: alloc_error): + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/wrong_capability.air b/tests/conformance/buffers/wrong_capability.air new file mode 100644 index 0000000..630795d --- /dev/null +++ b/tests/conformance/buffers/wrong_capability.air @@ -0,0 +1,21 @@ +; expect: reject E3201 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Dynamic buffers +module buffer.contract +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] +fn @bad(%b: mut>, %cap: cap) -> void +effects [mem.alloc] +entry: + %n = const.usize 0 + buffer.reserve %b, %n, %cap, ok -> @ok, err -> @err +ok: + trap +err(%error: alloc_error): + trap +fn @main() -> u64 +effects [] +entry: + %answer = const.u64 42 + ret %answer diff --git a/tests/conformance/buffers/zero.air b/tests/conformance/buffers/zero.air new file mode 100644 index 0000000..ecece69 --- /dev/null +++ b/tests/conformance/buffers/zero.air @@ -0,0 +1,46 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:0 +; phase: 6 +; spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources] + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %c_1 = const.usize 0 + buffer.new u64 %c_1, %heap, ok -> @ok_2, err -> @err_4 +ok_2(%ok_3: buffer): + %data_6 = borrow.mut %ok_3 + buffer.pop %data_6, ok -> @ok_7, err -> @err_9 +err_4(%err_5: alloc_error): + trap +ok_7(%ok_8: u64): + trap +err_9: + br @endmatch_10() +endmatch_10: + %c_11 = const.u64 42 + buffer.push %data_6, %c_11, ok -> @ok_12, err -> @err_13 +ok_12: + trap +err_13(%err_14: u64): + %c_15 = const.u64 42 + %cmp_16 = eq.u64 %err_14, %c_15 + assert %cmp_16 + br @endmatch_17() +endmatch_17: + %size_18 = buffer.len %data_6 + %c_19 = const.usize 0 + %cmp_20 = eq.usize %size_18, %c_19 + assert %cmp_20 + borrow.end %data_6 + buffer.free %ok_3, ok -> @ok_21, err -> @err_22 +ok_21: + %c_24 = const.u64 42 + ret %c_24 +err_22(%err_23: buffer): + trap diff --git a/tests/conformance/source/buffers/borrow_conflict.aji b/tests/conformance/source/buffers/borrow_conflict.aji new file mode 100644 index 0000000..e76a1b7 --- /dev/null +++ b/tests/conformance/source/buffers/borrow_conflict.aji @@ -0,0 +1,17 @@ +// expect: reject E2101 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new(1, heap) or trap; + { + mut b = data; + buffer.push(b, 42u64) or trap; + mut values = buffer.view(b); + buffer.reserve(b, 1, heap) or trap; + assert(values[0] == 42); + } + { mut b = data; let ignored = buffer.pop(b) or trap; } + buffer.free(move data) or trap; return 42; +} diff --git a/tests/conformance/source/buffers/borrowed_element.aji b/tests/conformance/source/buffers/borrowed_element.aji new file mode 100644 index 0000000..cf1201f --- /dev/null +++ b/tests/conformance/source/buffers/borrowed_element.aji @@ -0,0 +1,10 @@ +// expect: reject E1001 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn bad(heap: cap, value: ref) -> void effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; + buffer.free(move data) or trap; +} +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/buffers/copy_move.aji b/tests/conformance/source/buffers/copy_move.aji new file mode 100644 index 0000000..03f142a --- /dev/null +++ b/tests/conformance/source/buffers/copy_move.aji @@ -0,0 +1,5 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main() -> u64 effects [] { let n = 42u64; return move n; } diff --git a/tests/conformance/source/buffers/copy_owner_view.aji b/tests/conformance/source/buffers/copy_owner_view.aji new file mode 100644 index 0000000..9baf459 --- /dev/null +++ b/tests/conformance/source/buffers/copy_owner_view.aji @@ -0,0 +1,9 @@ +// expect: reject E1001 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; let item = own.new(42u64, heap) or trap; + { mut b = data; buffer.push(b, move item) or trap; ref values = buffer.view(b); let copied = values[0]; own.free(move copied); } trap; +} diff --git a/tests/conformance/source/buffers/duplicate_owner.aji b/tests/conformance/source/buffers/duplicate_owner.aji new file mode 100644 index 0000000..bbd8d00 --- /dev/null +++ b/tests/conformance/source/buffers/duplicate_owner.aji @@ -0,0 +1,9 @@ +// expect: reject E2002 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(2, heap) or trap; let item = own.new(42u64, heap) or trap; + { mut b = data; buffer.push(b, move item) or trap; buffer.push(b, move item) or trap; } trap; +} diff --git a/tests/conformance/source/buffers/free_failure.aji b/tests/conformance/source/buffers/free_failure.aji new file mode 100644 index 0000000..27dbd72 --- /dev/null +++ b/tests/conformance/source/buffers/free_failure.aji @@ -0,0 +1,20 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; + let owner = own.new(42u64, heap) or trap; + { mut b = data; buffer.push(b, move owner) or trap; } + match buffer.free(move data) { + ok() => { trap; } + err(returned) => { + var answer: u64 = 0; + { mut b = returned; let value = buffer.pop(b) or trap; answer = own.take(move value); } + buffer.free(move returned) or trap; + return answer; + } + } +} diff --git a/tests/conformance/source/buffers/free_failure_leak.aji b/tests/conformance/source/buffers/free_failure_leak.aji new file mode 100644 index 0000000..087c16e --- /dev/null +++ b/tests/conformance/source/buffers/free_failure_leak.aji @@ -0,0 +1,9 @@ +// expect: reject E3002 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(0, heap) or trap; + match buffer.free(move data) { ok() => { return 42; } err(value) => { return 42; } } +} diff --git a/tests/conformance/source/buffers/generic_borrow_move.aji b/tests/conformance/source/buffers/generic_borrow_move.aji new file mode 100644 index 0000000..c4d6004 --- /dev/null +++ b/tests/conformance/source/buffers/generic_borrow_move.aji @@ -0,0 +1,6 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn transfer(value: ref) -> ref from value effects [] { return move value; } +fn main() -> u64 effects [] { let n = 42u64; ref borrowed = n; ref result = transfer::(borrowed); return *result; } diff --git a/tests/conformance/source/buffers/generic_move.aji b/tests/conformance/source/buffers/generic_move.aji new file mode 100644 index 0000000..1643dfd --- /dev/null +++ b/tests/conformance/source/buffers/generic_move.aji @@ -0,0 +1,7 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn transfer(value: T) -> T effects [] { return move value; } +fn main() -> u64 effects [] { let n = 42u64; let answer = transfer::(n); assert(n == answer); return answer; } diff --git a/tests/conformance/source/buffers/generic_storage.aji b/tests/conformance/source/buffers/generic_storage.aji new file mode 100644 index 0000000..e7dd7d9 --- /dev/null +++ b/tests/conformance/source/buffers/generic_storage.aji @@ -0,0 +1,13 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn transfer(value: T) -> T effects [] { + var stored: T = value; + { ref borrowed = stored; let copy = *borrowed; } + let transferred = move stored; + let still_available = stored; + return transferred; +} +fn main() -> u64 effects [] { return transfer::(42); } diff --git a/tests/conformance/source/buffers/long_reuse.aji b/tests/conformance/source/buffers/long_reuse.aji new file mode 100644 index 0000000..387d064 --- /dev/null +++ b/tests/conformance/source/buffers/long_reuse.aji @@ -0,0 +1,17 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:16 +// fuel: 200000 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; + for iteration in 0usize..2000usize { + let item = own.new(42u64, heap) or trap; + { mut b = data; buffer.push(b, move item) or trap; let popped = buffer.pop(b) or trap; assert(own.take(move popped) == 42u64); } + } + buffer.free(move data) or trap; + let answer = own.new(42u64, heap) or trap; + return own.take(move answer); +} diff --git a/tests/conformance/source/buffers/missing_move.aji b/tests/conformance/source/buffers/missing_move.aji new file mode 100644 index 0000000..0a23a00 --- /dev/null +++ b/tests/conformance/source/buffers/missing_move.aji @@ -0,0 +1,9 @@ +// expect: reject E7003 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; let item = own.new(42u64, heap) or trap; + { mut b = data; buffer.push(b, item) or trap; } trap; +} diff --git a/tests/conformance/source/buffers/nested.aji b/tests/conformance/source/buffers/nested.aji new file mode 100644 index 0000000..72a349e --- /dev/null +++ b/tests/conformance/source/buffers/nested.aji @@ -0,0 +1,21 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26 +module buffer.nested +fn main(heap: cap) -> u64 effects [mem.alloc] { + let inside = buffer.new>(1, heap) or trap; + let item = own.new(42u64, heap) or trap; + { mut b = inside; buffer.push(b, move item) or trap; } + let outer = buffer.new>>(1, heap) or trap; + { mut b = outer; buffer.push(b, move inside) or trap; } + var answer: u64 = 0; + { mut b = outer; + let recovered = buffer.pop(b) or trap; + { mut inner = recovered; let owner = buffer.pop(inner) or trap; answer = own.take(move owner); } + buffer.free(move recovered) or trap; + } + buffer.free(move outer) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/new_overflow.aji b/tests/conformance/source/buffers/new_overflow.aji new file mode 100644 index 0000000..503cb8e --- /dev/null +++ b/tests/conformance/source/buffers/new_overflow.aji @@ -0,0 +1,12 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:18446744073709551615 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26 +module buffer.overflow +fn main(heap: cap) -> u64 effects [mem.alloc] { + match buffer.new(18446744073709551615usize, heap) { + ok(data) => { buffer.free(move data) or trap; trap; } + err(error) => { return 42; } + } +} diff --git a/tests/conformance/source/buffers/owner.aji b/tests/conformance/source/buffers/owner.aji new file mode 100644 index 0000000..6bba84a --- /dev/null +++ b/tests/conformance/source/buffers/owner.aji @@ -0,0 +1,25 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; + let owner = own.new(42u64, heap) or trap; + var answer: u64 = 0; + { + mut b = data; + assert(buffer.len(b) == 0); + assert(buffer.capacity(b) == 1); + buffer.push(b, move owner) or trap; + assert(buffer.len(b) == 1); + buffer.reserve(b, 2, heap) or trap; + assert(buffer.capacity(b) == 2); + let value = buffer.pop(b) or trap; + answer = own.take(move value); + assert(buffer.len(b) == 0); + } + buffer.free(move data) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/push_failure.aji b/tests/conformance/source/buffers/push_failure.aji new file mode 100644 index 0000000..0a13424 --- /dev/null +++ b/tests/conformance/source/buffers/push_failure.aji @@ -0,0 +1,17 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:8 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(0, heap) or trap; + let owner = own.new(42u64, heap) or trap; + var answer: u64 = 0; + { + mut b = data; + match buffer.push(b, move owner) { ok() => { trap; } err(value) => { answer = own.take(move value); } } + } + buffer.free(move data) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/push_failure_leak.aji b/tests/conformance/source/buffers/push_failure_leak.aji new file mode 100644 index 0000000..803c547 --- /dev/null +++ b/tests/conformance/source/buffers/push_failure_leak.aji @@ -0,0 +1,9 @@ +// expect: reject E3002 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn bad(b: mut>>, owner: own) -> void effects [] { + match buffer.push(b, move owner) { ok() => { return; } err(value) => { return; } } +} +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/buffers/readonly_push.aji b/tests/conformance/source/buffers/readonly_push.aji new file mode 100644 index 0000000..5b4faae --- /dev/null +++ b/tests/conformance/source/buffers/readonly_push.aji @@ -0,0 +1,6 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn bad(b: ref>) -> void effects [] { buffer.push(b, 42u64) or trap; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/buffers/recursive.aji b/tests/conformance/source/buffers/recursive.aji new file mode 100644 index 0000000..fa3093a --- /dev/null +++ b/tests/conformance/source/buffers/recursive.aji @@ -0,0 +1,6 @@ +// expect: reject E1003 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +struct Node { children: buffer } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/buffers/reserve_authority.aji b/tests/conformance/source/buffers/reserve_authority.aji new file mode 100644 index 0000000..50fe4d8 --- /dev/null +++ b/tests/conformance/source/buffers/reserve_authority.aji @@ -0,0 +1,21 @@ +// expect: run +// result: 42 +// grant: first=mem.alloc:8 +// grant: second=mem.alloc:16 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26 +module buffer.authority +fn main(first: cap, second: cap) -> u64 effects [mem.alloc] { + let data = buffer.new(1, first) or trap; + { mut b = data; buffer.push(b, 42u64) or trap; buffer.reserve(b, 2, second) or trap; } + // Growth releases the original authority while data remains live. + let original_budget = own.new(7u64, first) or trap; + own.free(move original_budget); + var answer: u64 = 0; + { mut b = data; answer = buffer.pop(b) or trap; } + buffer.free(move data) or trap; + // Free releases the new authority, not the original one. + let replacement = buffer.new(2, second) or trap; + buffer.free(move replacement) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/reserve_failure.aji b/tests/conformance/source/buffers/reserve_failure.aji new file mode 100644 index 0000000..bf02a43 --- /dev/null +++ b/tests/conformance/source/buffers/reserve_failure.aji @@ -0,0 +1,20 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:24 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(1, heap) or trap; + let owner = own.new(42u64, heap) or trap; + var answer: u64 = 0; + { + mut b = data; + buffer.push(b, move owner) or trap; + match buffer.reserve(b, 2, heap) { ok() => { trap; } err(e) => {} } + assert(buffer.len(b) == 1); assert(buffer.capacity(b) == 1); + let value = buffer.pop(b) or trap; answer = own.take(move value); + } + buffer.free(move data) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/task_loan.aji b/tests/conformance/source/buffers/task_loan.aji new file mode 100644 index 0000000..5e85e5e --- /dev/null +++ b/tests/conformance/source/buffers/task_loan.aji @@ -0,0 +1,11 @@ +// expect: reject E4101 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn worker(b: mut>) -> void effects [] {} +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + let data = buffer.new(1, heap) or trap; + { mut b = data; scope s { let task = task.spawn(s, worker, b); buffer.reserve(b, 1usize, heap) or trap; task.join(move task); } } + buffer.free(move data) or trap; return 42; +} diff --git a/tests/conformance/source/buffers/task_loan_join.aji b/tests/conformance/source/buffers/task_loan_join.aji new file mode 100644 index 0000000..831dca7 --- /dev/null +++ b/tests/conformance/source/buffers/task_loan_join.aji @@ -0,0 +1,17 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:8 +// schedules: 8 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +fn worker(b: mut>) -> void effects [] { mut values = buffer.view(b); values[0] = 42; } +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + let data = buffer.new(1, heap) or trap; + var answer: u64 = 0; + { mut b = data; buffer.push(b, 0u64) or trap; + scope s { let task = task.spawn(s, worker, b); task.join(move task); answer = buffer.pop(b) or trap; } + } + buffer.free(move data) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/vec_copy.aji b/tests/conformance/source/buffers/vec_copy.aji new file mode 100644 index 0000000..31f4a5e --- /dev/null +++ b/tests/conformance/source/buffers/vec_copy.aji @@ -0,0 +1,31 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.10 +module test.vec +import std.vec; +import std.option; +fn main(heap: cap) -> u64 effects [mem.alloc] { + match std.vec.new::(1, heap) { + std.vec.NewResult::::ok(value) => { + { + mut v = value; + match std.vec.push::(v, 41u64) { std.vec.PushResult::::ok => {}, std.vec.PushResult::::full(item) => { trap; } } + match std.vec.reserve::(v, 2, heap) { std.vec.ReserveResult::ok => {}, std.vec.ReserveResult::err(e) => { trap; } } + match std.vec.replace::(v, 0, 42u64) { std.vec.ReplaceResult::::ok(old) => { assert(old == 41); }, std.vec.ReplaceResult::::out_of_bounds(item) => { trap; } } + } + { + ref v = value; + assert(std.vec.len::(v) == 1usize); assert(std.vec.capacity::(v) == 2usize); + match std.vec.get::(v, 0) { std.option.Option::::some(item) => { assert(item == 42); }, std.option.Option::::none => { trap; } } + match std.vec.get::(v, 1) { std.option.Option::::some(item) => { trap; }, std.option.Option::::none => {} } + } + var answer: u64 = 0; + { mut v = value; match std.vec.pop::(v) { std.option.Option::::some(item) => { answer = item; }, std.option.Option::::none => { trap; } } } + match std.vec.free::(move value) { std.vec.FreeResult::::ok => {}, std.vec.FreeResult::::not_empty(returned) => { trap; } } + return answer; + } + std.vec.NewResult::::err(e) => { trap; } + } +} diff --git a/tests/conformance/source/buffers/vec_file.aji b/tests/conformance/source/buffers/vec_file.aji new file mode 100644 index 0000000..9ed9ff8 --- /dev/null +++ b/tests/conformance/source/buffers/vec_file.aji @@ -0,0 +1,21 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:256 +// grant: dst=fs.write:/out +// file: /out/vector.txt=42 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +import std.vec; +import std.option; +fn main(heap: cap, dst: cap) -> u64 effects [mem.alloc, fs.write] { + match std.vec.new::>(1, heap) { + std.vec.NewResult::>::ok(value) => { + let file = fs.create(dst, b"/out/vector.txt") or trap; + { mut v = value; match std.vec.push::>(v, move file) { std.vec.PushResult::>::ok => {}, std.vec.PushResult::>::full(returned) => { fs.close(move returned) or trap; trap; } } } + { mut v = value; match std.vec.pop::>(v) { std.option.Option::>::some(item) => { fs.write_all(item, ref b"42") or trap; fs.close(move item) or trap; }, std.option.Option::>::none => { trap; } } } + match std.vec.free::>(move value) { std.vec.FreeResult::>::ok => {}, std.vec.FreeResult::>::not_empty(returned) => { trap; } } + return 42; + }, std.vec.NewResult::>::err(error) => { trap; } + } +} diff --git a/tests/conformance/source/buffers/vec_full.aji b/tests/conformance/source/buffers/vec_full.aji new file mode 100644 index 0000000..87fb548 --- /dev/null +++ b/tests/conformance/source/buffers/vec_full.aji @@ -0,0 +1,20 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:8 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.10 +module test.vec +import std.vec; +import std.option; +fn main(heap: cap) -> u64 effects [mem.alloc] { + match std.vec.new::>(0, heap) { + std.vec.NewResult::>::ok(value) => { + let owner = own.new(42u64, heap) or trap; + var answer: u64 = 0; + { mut v = value; match std.vec.push::>(v, move owner) { std.vec.PushResult::>::ok => { trap; }, std.vec.PushResult::>::full(returned) => { answer = own.take(move returned); } } } + match std.vec.free::>(move value) { std.vec.FreeResult::>::ok => {}, std.vec.FreeResult::>::not_empty(returned) => { trap; } } + return answer; + } + std.vec.NewResult::>::err(e) => { trap; } + } +} diff --git a/tests/conformance/source/buffers/vec_get_owner.aji b/tests/conformance/source/buffers/vec_get_owner.aji new file mode 100644 index 0000000..5e18c4c --- /dev/null +++ b/tests/conformance/source/buffers/vec_get_owner.aji @@ -0,0 +1,10 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.10 +module test.vec +import std.vec; +import std.option; +fn bad(value: ref>>) -> void effects [] { + let result = std.vec.get::>(value, 0); +} +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/buffers/vec_owner.aji b/tests/conformance/source/buffers/vec_owner.aji new file mode 100644 index 0000000..1b073bb --- /dev/null +++ b/tests/conformance/source/buffers/vec_owner.aji @@ -0,0 +1,24 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.10 +module test.vec +import std.vec; +import std.option; +fn main(heap: cap) -> u64 effects [mem.alloc] { + match std.vec.new::>(1, heap) { + std.vec.NewResult::>::ok(value) => { + let owner = own.new(42u64, heap) or trap; + { + mut v = value; + match std.vec.push::>(v, move owner) { std.vec.PushResult::>::ok => {}, std.vec.PushResult::>::full(returned) => { own.free(move returned); trap; } } + } + var answer: u64 = 0; + { mut v = value; match std.vec.pop::>(v) { std.option.Option::>::some(item) => { answer = own.take(move item); }, std.option.Option::>::none => { trap; } } } + match std.vec.free::>(move value) { std.vec.FreeResult::>::ok => {}, std.vec.FreeResult::>::not_empty(returned) => { trap; } } + return answer; + } + std.vec.NewResult::>::err(e) => { trap; } + } +} diff --git a/tests/conformance/source/buffers/vec_replace_owner.aji b/tests/conformance/source/buffers/vec_replace_owner.aji new file mode 100644 index 0000000..a060948 --- /dev/null +++ b/tests/conformance/source/buffers/vec_replace_owner.aji @@ -0,0 +1,29 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:256 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +import std.vec; +import std.option; +fn drain(value: std.vec.Vec>) -> u64 effects [] { + var answer: u64 = 0; + { mut v = value; match std.vec.pop::>(v) { std.option.Option::>::some(item) => { answer = own.take(move item); }, std.option.Option::>::none => { trap; } } } + match std.vec.free::>(move value) { std.vec.FreeResult::>::ok => {}, std.vec.FreeResult::>::not_empty(returned) => { trap; } } + return answer; +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + match std.vec.new::>(1, heap) { + std.vec.NewResult::>::ok(value) => { + let original = own.new(7u64, heap) or trap; + { mut v = value; + match std.vec.push::>(v, move original) { std.vec.PushResult::>::ok => {}, std.vec.PushResult::>::full(returned) => { trap; } } + let replacement = own.new(42u64, heap) or trap; + match std.vec.replace::>(v, 0, move replacement) { std.vec.ReplaceResult::>::ok(old) => { assert(own.take(move old) == 7u64); }, std.vec.ReplaceResult::>::out_of_bounds(returned) => { trap; } } + let outside = own.new(99u64, heap) or trap; + match std.vec.replace::>(v, 1, move outside) { std.vec.ReplaceResult::>::ok(old) => { trap; }, std.vec.ReplaceResult::>::out_of_bounds(returned) => { assert(own.take(move returned) == 99u64); } } + } + match std.vec.free::>(move value) { std.vec.FreeResult::>::ok => { trap; }, std.vec.FreeResult::>::not_empty(returned) => { return drain(move returned); } } + }, std.vec.NewResult::>::err(error) => { trap; } + } +} diff --git a/tests/conformance/source/buffers/vec_sender.aji b/tests/conformance/source/buffers/vec_sender.aji new file mode 100644 index 0000000..ca830ef --- /dev/null +++ b/tests/conformance/source/buffers/vec_sender.aji @@ -0,0 +1,26 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:256 +// schedules: 8 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffer +import std.vec; +import std.option; +struct Job { number: u64 } +fn worker(value: std.vec.Vec>) -> void effects [task.wait] { + { mut v = value; match std.vec.pop::>(v) { std.option.Option::>::some(tx) => { channel.send(tx, Job { number: 42 }) or trap; channel.close_sender(move tx); }, std.option.Option::>::none => { trap; } } } + match std.vec.free::>(move value) { std.vec.FreeResult::>::ok => {}, std.vec.FreeResult::>::not_empty(returned) => { trap; } } +} +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + match channel.make(1, heap) { + ok(tx, rx) => { + match std.vec.new::>(1, heap) { + std.vec.NewResult::>::ok(value) => { + { mut v = value; match std.vec.push::>(v, move tx) { std.vec.PushResult::>::ok => {}, std.vec.PushResult::>::full(returned) => { channel.close_sender(move returned); trap; } } } + scope s { let task = task.spawn(s, worker, move value); let job = channel.recv(rx) or trap; task.join(move task); channel.close_receiver(move rx) or trap; return job.number; } + }, std.vec.NewResult::>::err(error) => { trap; } + } + }, err(error) => { trap; } + } +} diff --git a/tests/conformance/source/buffers/view.aji b/tests/conformance/source/buffers/view.aji new file mode 100644 index 0000000..3a76737 --- /dev/null +++ b/tests/conformance/source/buffers/view.aji @@ -0,0 +1,19 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:128 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new(2, heap) or trap; + { + mut b = data; + buffer.push(b, 41u64) or trap; + { mut values = buffer.view(b); assert(values.len == 1usize); values[0] = values[0] + 1; } + { ref values = buffer.view(b); assert(values[0] == 42); } + } + var answer: u64 = 0; + { mut b = data; answer = buffer.pop(b) or trap; } + buffer.free(move data) or trap; + return answer; +} diff --git a/tests/conformance/source/buffers/zero.aji b/tests/conformance/source/buffers/zero.aji new file mode 100644 index 0000000..26c51a8 --- /dev/null +++ b/tests/conformance/source/buffers/zero.aji @@ -0,0 +1,17 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:0 +// phase: 6 +// spec: docs/spec/03-memory-model.md §26; docs/spec/15-source-language.md §17 +module test.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new(0, heap) or trap; + { + mut b = data; + match buffer.pop(b) { ok(v) => { trap; } err() => {} } + match buffer.push(b, 42u64) { ok() => { trap; } err(v) => { assert(v == 42); } } + assert(buffer.len(b) == 0); + } + buffer.free(move data) or trap; + return 42; +} diff --git a/tests/conformance/source/quickref/buffers.aji b/tests/conformance/source/quickref/buffers.aji new file mode 100644 index 0000000..c8356d2 --- /dev/null +++ b/tests/conformance/source/quickref/buffers.aji @@ -0,0 +1,18 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:16 +// phase: 6 +// spec: docs/agent/quick-reference.md §14 +module quickref.buffers +fn main(heap: cap) -> u64 effects [mem.alloc] { + let data = buffer.new>(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; +} diff --git a/tests/hosted/source_buffers.py b/tests/hosted/source_buffers.py new file mode 100644 index 0000000..28461b7 --- /dev/null +++ b/tests/hosted/source_buffers.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Initialized storage, resource vectors, canonical AIR and CLI contracts.""" +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/buffers" +checks = 0 + + +def cli(*args, code=0): + global checks + result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True) + assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr) + checks += 1 + return result.stdout + + +def returned(path, *grants): + arguments = [argument for grant in grants for argument in ("--grant", grant)] + record = json.loads(cli("run", "--fuel", "200000", *arguments, path)) + assert record["status"] == "returned" and record["value"] == 42, record + return record + + +assert "linear_buffers" in json.loads(cli("features"))["features"] +example = REPO / "examples/std/vector.aji" +returned(example, "heap=mem.alloc:256") +report = json.loads(cli("report", FIXTURES / "owner.aji")) +assert sum(function["allocations"] for function in report["functions"]) == 3, report +with tempfile.TemporaryDirectory(prefix="aji-buffers-") as directory: + root = Path(directory) + air = root / "result.air" + for fixture, grants in ( + ("owner", ("heap=mem.alloc:128",)), + ("push_failure", ("heap=mem.alloc:8",)), + ("free_failure", ("heap=mem.alloc:128",)), + ("reserve_failure", ("heap=mem.alloc:24",)), + ("reserve_authority", ("first=mem.alloc:8", "second=mem.alloc:16")), + ("long_reuse", ("heap=mem.alloc:16",)), + ("nested", ("heap=mem.alloc:128",)), + ("view", ("heap=mem.alloc:16",)), + ("vec_copy", ("heap=mem.alloc:128",)), + ("vec_replace_owner", ("heap=mem.alloc:128",)), + ("vec_file", ("heap=mem.alloc:128", "dst=fs.write:/out")), + ("vec_sender", ("heap=mem.alloc:128",)), + ): + source = FIXTURES / f"{fixture}.aji" + cli("check", source) + canonical = cli("lower", source) + assert cli("lower", source) == canonical + assert "linear_buffers" in canonical + air.write_text(canonical) + cli("check", air) + direct = returned(source, *grants) + round_trip = returned(air, *grants) + assert direct == round_trip, (direct, round_trip) + # Compiler-pinned vectors retain nominal ownership across package modules. + (root / "lib.aji").write_text( + "module app.lib\nimport std.vec;\n" + "fn identity(value: std.vec.Vec) -> std.vec.Vec effects [] { return move value; }\n" + ) + source = example.read_text().replace("module example.vector", "module app.main") + source = source.replace("import std.vec;", "import std.vec;\nimport app.lib;") + source = source.replace("::ok(value) => {", "::ok(value) => {\n let value = app.lib.identity::>(move value);") + (root / "main.aji").write_text(source) + manifest = root / "aji.toml" + manifest.write_text('[package]\nname = "buffers"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.lib = "lib.aji"\n') + cli("check", "--manifest", manifest) + cli("report", "--manifest", manifest) + assert json.loads(cli("run", "--fuel", "200000", "--manifest", manifest, "--grant", "heap=mem.alloc:128"))["value"] == 42 + cli("explore", "--max-runs", "8", "--manifest", manifest, "--grant", "heap=mem.alloc:128") + # Same buffer/Vec runtime in hosted mode; the run record is explicitly directed to a file. + result_path = root / "hosted.json" + cli("run", "--profile", "hosted", "--result-file", result_path, "--fuel", "200000", "--grant", "heap=mem.alloc:128", example) + record = json.loads(result_path.read_text()) + assert record["status"] == "returned" and record["value"] == 42, record + +for fixture, expected in ( + ("borrow_conflict", "E2101"), + ("task_loan", "E4101"), + ("push_failure_leak", "E3002"), + ("free_failure_leak", "E3002"), + ("missing_move", "E7003"), + ("duplicate_owner", "E2002"), + ("recursive", "E1003"), + ("vec_get_owner", "E7005"), + ("generic_borrow_move", "E7006"), +): + for command in ("check", "report", "run", "explore"): + diagnostics = [json.loads(line) for line in cli(command, FIXTURES / f"{fixture}.aji", code=1).splitlines()] + assert diagnostics[0]["code"] == expected, diagnostics +for fixture in ("task_loan_join", "vec_sender"): + cli("explore", "--max-runs", "16", "--grant", "heap=mem.alloc:128", FIXTURES / f"{fixture}.aji") +print(f"source buffers CLI integration passed ({checks} checks)") diff --git a/tools/source_coverage.py b/tools/source_coverage.py index 42e00b5..eab1fa4 100644 --- a/tools/source_coverage.py +++ b/tools/source_coverage.py @@ -20,6 +20,9 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source") # (area, construct, regex, needs a reject test) CHECKLIST = [ + ("buffers", "initialized buffer allocation and drain", r"buffer\.(new|push|pop|free)", True), + ("buffers", "explicit reserve and borrowed views", r"buffer\.(reserve|view)", True), + ("buffers", "safe owning Vec", r"std\.vec\.", True), ("linear aggregates", "complete struct unpack", r"struct\.unpack\(", True), ("linear aggregates", "complete array unpack", r"array\.unpack\(", True), ("linear aggregates", "ordered array literal", r"\[move \w+,", True),