From 4f084decce476d20814ed207be65426b6e677504 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Tue, 6 Oct 2026 21:23:52 +0300 Subject: [PATCH] cli: add whole-value linear aggregates Implement STD-5 through source, AIR, verifier and deterministic interpreter. Constructors consume nested owners; exhaustive unpack/take, explicit swap and own.pack preserve ownership on success and failure. Support owning Option and Result while keeping classification helpers Copy-only. Preserve borrow identity across whole replacement and collection; distinguish individual owned arrays from repeated heap arrays. Specify feature contracts, invariants, diagnostics, compatibility and measured source/AIR budgets in RFC 0023 and normative docs. Add canonical round trips, AIR/source acceptance and rejection fixtures, CLI integration and CI checks. Validate build, unit/extended tests, full conformance, forced-collection schedule stress (32 seeds per quantum), hosted smoke, CLI suites, source coverage (88/88), formatting and reference bundle generation. Source bundle grows 3.2%; Quick Reference grows 4.0%. No MCC improvement is claimed. Dynamic initialized linear buffers and explicit drain remain Q-036/STD-6; frame/region/repeated heap storage is Copy-only. RFC remains Proposed. --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 1 + docs/agent/README.md | 3 + docs/agent/bundle.txt | 3 + docs/agent/quick-reference.md | 18 +- docs/agent/source-bundle.txt | 6 +- docs/agent/source-notes.md | 3 +- docs/design/open-questions.md | 16 +- docs/plan/phase-6-source-language.md | 2 +- docs/plan/standard-library.md | 13 +- docs/reference/air-features.md | 2 +- docs/reference/air-text.ebnf | 9 + docs/reference/grammar.ebnf | 4 +- docs/reference/std.md | 6 +- docs/reference/type-properties.md | 2 + docs/rfcs/0023-linear-aggregates.md | 67 +++++++ docs/spec/03-memory-model.md | 18 +- docs/spec/04-concurrency-and-atomics.md | 4 +- docs/spec/06-resources-and-errors.md | 2 +- docs/spec/07-air.md | 4 +- docs/spec/07a-air-instructions.md | 26 ++- docs/spec/15-source-language.md | 18 +- docs/spec/16-standard-library.md | 8 +- examples/std/owning-option.aji | 12 ++ src/air/features.zig | 4 +- src/air/module.zig | 44 ++++- src/air/parse.zig | 38 +++- src/air/print.zig | 65 ++++++- src/frontend/ast.zig | 3 +- src/frontend/lower.zig | 169 +++++++++++++++--- src/frontend/parse.zig | 26 ++- src/interp/machine.zig | 82 ++++++--- src/report.zig | 2 +- src/verifier/borrow.zig | 52 +++++- src/verifier/budget.zig | 3 +- src/verifier/cfg.zig | 15 +- src/verifier/effects.zig | 2 +- src/verifier/types.zig | 88 +++++++-- std/README.md | 8 +- std/option.aji | 2 +- std/result.aji | 2 +- tests/conformance/linear/array_count.air | 12 ++ tests/conformance/linear/borrow_array.air | 12 ++ tests/conformance/linear/builtin_take.air | 13 ++ tests/conformance/linear/copy.air | 23 +++ tests/conformance/linear/enum_incomplete.air | 35 ++++ tests/conformance/linear/enum_switch.air | 35 ++++ tests/conformance/linear/exchange.air | 37 ++++ tests/conformance/linear/field.air | 23 +++ tests/conformance/linear/leak.air | 21 +++ tests/conformance/linear/owner_copy_array.air | 28 +++ tests/conformance/linear/pack.air | 25 +++ tests/conformance/linear/pack_failure.air | 25 +++ tests/conformance/linear/struct.air | 23 +++ tests/conformance/linear/swap_leak.air | 35 ++++ tests/conformance/linear/unpack_count.air | 35 ++++ tests/conformance/linear/without_feature.air | 13 ++ .../source/generics/linear_aggregate.aji | 2 +- .../source/generics/nested_owner_argument.aji | 3 +- .../source/generics/std_option_owner.aji | 2 +- .../source/generics/std_result_borrow.aji | 2 +- tests/conformance/source/linear/array.aji | 13 ++ .../source/linear/array_duplicate.aji | 13 ++ tests/conformance/source/linear/atomic.aji | 11 ++ .../source/linear/borrow_conflict.aji | 14 ++ .../source/linear/borrowed_atomic_swap.aji | 7 + tests/conformance/source/linear/channel.aji | 22 +++ .../source/linear/copy_borrowed.aji | 7 + .../declared_owner.aji} | 5 +- tests/conformance/source/linear/enum.aji | 15 ++ .../source/linear/enum_ignored_payload.aji | 16 ++ tests/conformance/source/linear/file.aji | 23 +++ .../source/linear/fixed_heap_array.aji | 14 ++ .../source/linear/free_linear_content.aji | 6 + tests/conformance/source/linear/graph.aji | 27 +++ .../source/linear/guard_member.aji | 6 + .../source/linear/heap_array_borrow.aji | 16 ++ .../source/linear/ignored_field.aji | 13 ++ .../source/linear/linear_projection.aji | 14 ++ .../linear/linear_region_allocation.aji | 7 + .../source/linear/missing_move.aji | 13 ++ tests/conformance/source/linear/mutex.aji | 13 ++ tests/conformance/source/linear/none_leak.aji | 9 + tests/conformance/source/linear/pack.aji | 14 ++ .../source/linear/pack_failure.aji | 14 ++ .../source/linear/pack_failure_leak.aji | 12 ++ .../source/linear/plain_enum_match.aji | 16 ++ .../source/linear/recursive_ownership.aji | 6 + tests/conformance/source/linear/region.aji | 13 ++ tests/conformance/source/linear/repeat.aji | 15 ++ .../source/linear/repeated_array.aji | 6 + .../source/linear/single_tuple.aji | 5 + .../conformance/source/linear/std_option.aji | 17 ++ .../conformance/source/linear/std_result.aji | 13 ++ .../source/linear/store_linear.aji | 6 + tests/conformance/source/linear/struct.aji | 14 ++ tests/conformance/source/linear/swap.aji | 17 ++ .../conformance/source/linear/swap_array.aji | 15 ++ tests/conformance/source/linear/swap_heap.aji | 18 ++ tests/conformance/source/linear/swap_loop.aji | 19 ++ .../conformance/source/linear/swap_twice.aji | 19 ++ tests/conformance/source/linear/task.aji | 16 ++ tests/conformance/source/linear/task_loan.aji | 24 +++ .../source/linear/task_loan_join.aji | 27 +++ .../conformance/source/linear/task_member.aji | 6 + .../source/linear/wrong_unpack_count.aji | 13 ++ tests/conformance/source/quickref/linear.aji | 13 ++ tests/hosted/source_linear.py | 71 ++++++++ tools/source_coverage.py | 6 + 109 files changed, 1814 insertions(+), 142 deletions(-) create mode 100644 docs/rfcs/0023-linear-aggregates.md create mode 100644 examples/std/owning-option.aji create mode 100644 tests/conformance/linear/array_count.air create mode 100644 tests/conformance/linear/borrow_array.air create mode 100644 tests/conformance/linear/builtin_take.air create mode 100644 tests/conformance/linear/copy.air create mode 100644 tests/conformance/linear/enum_incomplete.air create mode 100644 tests/conformance/linear/enum_switch.air create mode 100644 tests/conformance/linear/exchange.air create mode 100644 tests/conformance/linear/field.air create mode 100644 tests/conformance/linear/leak.air create mode 100644 tests/conformance/linear/owner_copy_array.air create mode 100644 tests/conformance/linear/pack.air create mode 100644 tests/conformance/linear/pack_failure.air create mode 100644 tests/conformance/linear/struct.air create mode 100644 tests/conformance/linear/swap_leak.air create mode 100644 tests/conformance/linear/unpack_count.air create mode 100644 tests/conformance/linear/without_feature.air create mode 100644 tests/conformance/source/linear/array.aji create mode 100644 tests/conformance/source/linear/array_duplicate.aji create mode 100644 tests/conformance/source/linear/atomic.aji create mode 100644 tests/conformance/source/linear/borrow_conflict.aji create mode 100644 tests/conformance/source/linear/borrowed_atomic_swap.aji create mode 100644 tests/conformance/source/linear/channel.aji create mode 100644 tests/conformance/source/linear/copy_borrowed.aji rename tests/conformance/source/{layer5/reject/linear_field.aji => linear/declared_owner.aji} (54%) create mode 100644 tests/conformance/source/linear/enum.aji create mode 100644 tests/conformance/source/linear/enum_ignored_payload.aji create mode 100644 tests/conformance/source/linear/file.aji create mode 100644 tests/conformance/source/linear/fixed_heap_array.aji create mode 100644 tests/conformance/source/linear/free_linear_content.aji create mode 100644 tests/conformance/source/linear/graph.aji create mode 100644 tests/conformance/source/linear/guard_member.aji create mode 100644 tests/conformance/source/linear/heap_array_borrow.aji create mode 100644 tests/conformance/source/linear/ignored_field.aji create mode 100644 tests/conformance/source/linear/linear_projection.aji create mode 100644 tests/conformance/source/linear/linear_region_allocation.aji create mode 100644 tests/conformance/source/linear/missing_move.aji create mode 100644 tests/conformance/source/linear/mutex.aji create mode 100644 tests/conformance/source/linear/none_leak.aji create mode 100644 tests/conformance/source/linear/pack.aji create mode 100644 tests/conformance/source/linear/pack_failure.aji create mode 100644 tests/conformance/source/linear/pack_failure_leak.aji create mode 100644 tests/conformance/source/linear/plain_enum_match.aji create mode 100644 tests/conformance/source/linear/recursive_ownership.aji create mode 100644 tests/conformance/source/linear/region.aji create mode 100644 tests/conformance/source/linear/repeat.aji create mode 100644 tests/conformance/source/linear/repeated_array.aji create mode 100644 tests/conformance/source/linear/single_tuple.aji create mode 100644 tests/conformance/source/linear/std_option.aji create mode 100644 tests/conformance/source/linear/std_result.aji create mode 100644 tests/conformance/source/linear/store_linear.aji create mode 100644 tests/conformance/source/linear/struct.aji create mode 100644 tests/conformance/source/linear/swap.aji create mode 100644 tests/conformance/source/linear/swap_array.aji create mode 100644 tests/conformance/source/linear/swap_heap.aji create mode 100644 tests/conformance/source/linear/swap_loop.aji create mode 100644 tests/conformance/source/linear/swap_twice.aji create mode 100644 tests/conformance/source/linear/task.aji create mode 100644 tests/conformance/source/linear/task_loan.aji create mode 100644 tests/conformance/source/linear/task_loan_join.aji create mode 100644 tests/conformance/source/linear/task_member.aji create mode 100644 tests/conformance/source/linear/wrong_unpack_count.aji create mode 100644 tests/conformance/source/quickref/linear.aji create mode 100644 tests/hosted/source_linear.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fb3453d..13feb87 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - run: zig build && python3 tests/hosted/smoke.py - run: python3 tests/hosted/source_modules.py - run: python3 tests/hosted/source_generics.py + - run: python3 tests/hosted/source_linear.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 0247167..58d7d11 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,7 @@ zig build run -- run f.air # verify and execute @main (deterministic profile) python3 tests/hosted/smoke.py # hosted profile against the real OS python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance +python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors (cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests zig fmt --check build.zig src tools ``` diff --git a/docs/agent/README.md b/docs/agent/README.md index 57c00f3..c7d6ba5 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -104,3 +104,6 @@ RFC 0020 supplied-buffer decimal formatting (cl100k, relative to text): Quick Re RFC 0021 package modules (cl100k, relative to formatting): Quick Reference 6,220 → 6,501 (+4.5%); other source docs 37,128 → 38,822 (+4.6%); full source docs excluding AIR 43,348 → 45,323 (+4.6%). New on-demand `language/modules.md` is 1,566 tokens, library/std.md and AIR remain unchanged. The front door has one checked module example; package input/name/loader contracts stay on demand. Cumulative source growth is +33.4%, documented for owner review; no compression benefit is claimed. Pure modules need no new AIR feature or verifier state. RFC 0022 explicit generics (cl100k, relative to modules): Quick Reference 6,501 → 6,948 (+6.9%); other source docs 38,822 → 41,086 (+5.8%); full source docs excluding AIR 45,323 → 48,034 (+6.0%). New on-demand `language/generics.md` is 1,324 tokens; `library/std.md` is 8,380 tokens. AIR remains 160,797 bytes. Cumulative source growth is +41.3%, and Quick Reference exceeds its 4–6k target; the RFC explains the cost for owner review and calls for separate front-door consolidation/selective API reading. Explicit specialization adds no AIR instruction or verifier transfer state; documentation growth alone does not establish a compression benefit. + + +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. diff --git a/docs/agent/bundle.txt b/docs/agent/bundle.txt index 9143118..069e8d2 100644 --- a/docs/agent/bundle.txt +++ b/docs/agent/bundle.txt @@ -86,3 +86,6 @@ docs/reference/air-features.md docs/reference/effects.md docs/reference/capabilities.md docs/reference/intrinsics.md + +# Whole-value linear aggregates (STD-5) +docs/spec/03-memory-model.md :: ## 25. Linear aggregates in AIR diff --git a/docs/agent/quick-reference.md b/docs/agent/quick-reference.md index 0a52ec5..935c458 100644 --- a/docs/agent/quick-reference.md +++ b/docs/agent/quick-reference.md @@ -407,6 +407,22 @@ fn main() -> u64 effects [] { } ``` -`std.option.Option` has `some(T)`/`none`; `std.result.Result` has `ok(T)`/`err(E)`. `is_some::` and `is_ok::` classify them; match to extract payloads. Owning/borrowed payloads still reject. Unknown names: `E7002`; missing/extra arguments, duplicate/unknown constraints or expansion limits: `E7006`; unsatisfied constraints: `E7005` with `parameter`, `constraint`, `found`. Borrow conflicts, moves, effects and cleanup keep their existing rules. +`std.option.Option` has `some(T)`/`none`; `std.result.Result` has `ok(T)`/`err(E)`. `is_some::` and `is_ok::` classify Copy specializations; match to extract payloads. Owning payloads follow §13; borrowed payloads reject. Unknown names: `E7002`; missing/extra arguments, duplicate/unknown constraints or expansion limits: `E7006`; unsatisfied constraints: `E7005` with `parameter`, `constraint`, `found`. Borrow conflicts, moves, effects and cleanup keep their existing rules. Each required specialization is checked as concrete code; an unused template body is not a proof for future types. `Copy` gives no arithmetic or ordering operation. Read `/docs/language/generics.md` for exact Copy/Send/Share/Freeze/Local rules, deterministic keys and fixed limits; `/docs/library/std.md` for option/result contracts. + +## 13. Linear aggregates + +A struct/enum/fixed array containing owners or resources is linear. Construct with `move`; consume it completely. Read Copy fields normally. A linear enum needs exhaustive `match move`; even none must be consumed. No partial moves or automatic cleanup. + +```aji +struct Item { owner: own } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let value = Item { owner: move owner }; + let (part) = struct.unpack(move value); + return own.take(move part); +} +``` + +`[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. diff --git a/docs/agent/source-bundle.txt b/docs/agent/source-bundle.txt index 1df6c57..eecb9e1 100644 --- a/docs/agent/source-bundle.txt +++ b/docs/agent/source-bundle.txt @@ -9,7 +9,7 @@ > QUICK.md docs/agent/quick-reference.md -docs/agent/source-notes.md :: ## 13. Where to read more +docs/agent/source-notes.md :: ## 14. Where to read more > language/syntax.md docs/reference/grammar.ebnf @@ -21,6 +21,10 @@ docs/spec/15-source-language.md :: ## 6. Fallible operations and `match` docs/spec/15-source-language.md :: ## 13. Built-in standard modules +> language/linear-aggregates.md +docs/spec/15-source-language.md :: ## 16. Source linear aggregates +docs/spec/03-memory-model.md :: ## 25. Linear aggregates in AIR + > 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 2f18a9f..d92f0eb 100644 --- a/docs/agent/source-notes.md +++ b/docs/agent/source-notes.md @@ -2,13 +2,14 @@ Text that exists only for the Source Reference Bundle (`source-bundle.txt`). Non-normative: it points at the normative files and states which source layers are implemented. -## 13. Where to read more +## 14. Where to read more The other files in `/docs` hold the full rules. Open one only when this page is not enough. | Need | Read | |---|---| | built-in bytes/math/UTF-8/hex/Base64/decimal integers, signatures and failure contracts | `/docs/library/std.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` | | exact syntax, every construct, `match` and outcomes | `/docs/language/syntax.md` | diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 5ff9209..82b50f5 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -27,7 +27,9 @@ Status values: `open`, `resolved`. | Q-019 | resolved | P3 | Non-terminating programs in test tooling | | Q-020 | resolved | P2 | Size bound for SSA array values | | Q-024 | resolved | P5 | Memory-model clarifications found by the independent oracle | -| Q-025 | open | — | No array construction from element values in AIR | +| 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-001 — Text AIR grammar @@ -203,6 +205,9 @@ Points 1–3 and 5 are editorial. Point 4 fixes FIFO, which spec 04 §38 already Found by the independent author of `program_atomic_stats.air` (P5-9b). AIR has `array.splat` but no way to build an array from distinct element values. A six-element constant array costs a mutable borrow, six `borrow.index`/`store`/`borrow.end` triples and six index constants. `.aji` has the same gap: it has `[e; N]` but no array literal. The options are an `array.make T (%a, %b, …)` instruction (a value constructor like `struct.make`) with an `.aji` literal `[a, b, c]`, or no change. This is a convenience question, not a correctness one. It is not urgent, and any RFC for it must report its agent-complexity cost. +**Resolved on STD-5 (RFC 0023 Proposed):** array.make and ordered source literals transfer complete linear elements. Copy-only frame stores/splat cannot express this ownership-preserving construction. The same constructor supports distinct Copy elements; its contract, feature gate, argument limits and measured complexity are specified with the vertical linear_aggregates feature. + + ## Q-026 — Standard library distribution and initial source imports The source frontend had no import resolution and the package manifest no dependencies. A source-only std therefore needed either manual concatenation or a specified import path. @@ -252,3 +257,12 @@ The source plan names monomorphized generics but does not define application syn ## Q-034 — Source calls returning borrows During STD-4 validation, existing `from` declarations still return the frontend's unimplemented outcome and borrow bindings accept places rather than borrow-returning calls. Generics preserve the syntax/metadata and this existing limitation; they do not add an implicit lifetime or a new binding spelling. A separate source/lifetime increment must specify and implement the binding/temporary-end rules vertically before public libraries return retained borrowed views. + +## Q-035 — Whole-value linear aggregates + +**Resolved on the STD-5 branch (RFC 0023 Proposed):** spec 03 §25 and source spec 15 §16 specify complete construction/exhaustive consumption, fixed arrays, explicit exchange and ownership-preserving allocation failure. No partial-move/field initialization state or destructor is introduced. Among heap/frame/region storage forms, only individual own may hold linear content; frame locals, repeated heap arrays and bulk regions retain Copy-only content. Dynamic linear buffers need a separately specified extension in the collection phase. + + +## 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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index dfea09b..7e8c994 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. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6. +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. diff --git a/docs/plan/standard-library.md b/docs/plan/standard-library.md index 736c587..99ced86 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` | reserved, unscheduled | independent vertical RFC/phase gate for owners/resources in containers | +| `linear_aggregates` | STD-5 branch implementation (RFC Proposed) | whole-value owning structs/enums/fixed arrays; dynamic buffer storage remains STD-6 prerequisite | | 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. @@ -53,8 +53,8 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob | STD-2b | done (branch implementation; RFC Proposed) | decimal u64/i64/usize/isize formatting into supplied buffers | STD-2a | minimal explicit format contract, no implicit heap, capacity/empty/maximal scalar tests and caller example | | 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 | todo | independent `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 | 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-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-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 | @@ -114,3 +114,10 @@ RFC 0021 records invariants, diagnostics, compatibility, complete validation and Explicit function/struct/enum generics specialize deterministically to ordinary AIR. Structural Copy/Send/Share/Freeze/Local constraints, header checking, nominal identity, direct-import visibility and fixed expansion limits are specified by spec 15 §15 and RFC 0022. Every concrete specialization passes ordinary ownership/effect/task verification; unused bodies make no validity promise for future types. The compiler registry adds safe Copy-only std.option/std.result with classification helpers. No allocation, implicit cleanup, AIR opcode or authority is added. The finite-layout E1003 check now traverses arrays, repairing a prior verifier gap with source/AIR fixtures. Existing source `from`-returns remain unimplemented and are logged as Q-034 rather than given an invented lifetime/binding contract. RFC 0022 records complete validation and source/AIR budget measurements. Next is STD-5: the independent linear_aggregates vertical feature, required before containers or option/result can own resources. P6-4's generic/structural specialization task is implemented on this branch; this does not complete Phase 6. + + +## STD-5 verification + +RFC 0023 and spec 03 §25 implement whole-value linear structs/enums/fixed arrays vertically. Construction consumes nested owners; complete unpack, exhaustive match move, explicit exchange and own.pack failure preserve ownership on every normal path. Standard option/result accept owning payloads; observational classification helpers keep Copy constraints. Existing availability, alias/task-loan, Send/Share, budget and scheduler rules apply without per-field holes or hidden cleanup. No new diagnostic/effect/capability is introduced. + +Source/AIR tests cover nested ownership, allocation success/failure, repeated exchange with a one-owner budget, enum replacement, borrowed fixed arrays, channels, tasks, mutexes, regions, atomics and rejected copies/leaks/aliases/recursive ownership. The interpreter preserves borrowed SSA identity across whole replacement and collection; individual own> is distinguished from a repeated own_array allocation. RFC 0023 records final checks and documentation budgets. STD-6 starts with Q-036: dynamic storage, initialized length and explicit drain must be specified before growing resource collections. STD-5 does not complete Vec or Std 0.1. diff --git a/docs/reference/air-features.md b/docs/reference/air-features.md index df47dbc..5f14ce9 100644 --- a/docs/reference/air-features.md +++ b/docs/reference/air-features.md @@ -42,7 +42,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It | `guard_transfer` | reserved | — | `cancellation`, `effects`, `ownership`, `sync`, `tasks` | `guard` as parameter, return type or aggregate member; unscheduled | | `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` | reserved | — | `capabilities`, `effects`, `ownership`, `resources` | resource types as struct fields, enum payloads and array elements; unscheduled | +| `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 | | `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 f1276f9..1718c04 100644 --- a/docs/reference/air-text.ebnf +++ b/docs/reference/air-text.ebnf @@ -65,6 +65,7 @@ operation = "const." int_type int_lit | "struct.get" global "." ident "," local | "enum.make" global "." ident "(" [ local_list ] ")" | "call" global "(" [ local_list ] ")" + | linear_aggregate_op | ownership_op | arrays_op | capability_op @@ -240,3 +241,11 @@ int_lit = [ "-" ] ( dec_digits | "0x" hex_digits | "0b" bin_digits ) ; (* "_" may separate digits; it carries no meaning. *) version_lit = digit { digit } "." digit { digit } ; string = '"' { string_char | '\\"' | '\\\\' | '\\n' } '"' ; (* not empty; only in `trusted` *) + +(* Feature linear_aggregates, spec 03 §25 and spec 07a. *) +linear_aggregate_op = "array.make" type "(" [ local_list ] ")" + | "struct.unpack" global local "," "next" "->" global + | "array.unpack" type local "," "next" "->" global + | "enum.take" global local "," enum_arm { "," enum_arm } + | "value.swap" local "," local + | "own.pack" type local "," local ok_err ; diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf index 109cca3..20d2cb6 100644 --- a/docs/reference/grammar.ebnf +++ b/docs/reference/grammar.ebnf @@ -57,7 +57,7 @@ statement = "let" binding [ ":" type ] "=" expr ";" | "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";" | expr ";" | block_stmt ; -binding = ident | "(" ident "," ident ")" ; (* the pair form only for `split_at` *) +binding = ident | "(" [ ( ident | "_" ) { "," ( ident | "_" ) } ] ")" ; (* complete unpack; pairs also split_at/compare_exchange *) block_stmt = if_expr | match_expr | select_stmt | block | "while" expr block | "for" ident "in" expr ".." expr block @@ -94,9 +94,11 @@ postfix = primary { application | "." member | "[" expr [ ".." expr ] "]" member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *) call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ; primary = int_lit | "true" | "false" | string + | "struct" "." "unpack" (* contextual built-in call, §16 *) | ident | path [ application ] "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *) | path [ application ] "::" ident (* enum variant; applied by a call *) | "[" expr ";" int_lit "]" + | "[" expr { "," expr } [ "," ] "]" | "(" expr ")" | if_expr | match_expr | block ; field_init = ident ":" expr ; diff --git a/docs/reference/std.md b/docs/reference/std.md index e90fde2..653be06 100644 --- a/docs/reference/std.md +++ b/docs/reference/std.md @@ -221,9 +221,9 @@ Requires direct `import std.option;` / `import std.result;`; explicit generic sp | Declaration | Contract | |---|---| -| `std.option.Option` | `some(T)`, `none` | +| `std.option.Option` | `some(T)`, `none` | | `std.option.is_some(value: Option) -> bool` | true for some; false for none; effects [] | -| `std.result.Result` | `ok(T)`, `err(E)` | +| `std.result.Result` | `ok(T)`, `err(E)` | | `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 and borrows fail Copy constraints with E7005, until a separate linear-aggregate feature supplies their contracts. No must-use or implicit unwrap/default/conversion is introduced. [Checked example](../../examples/std/generics.aji) returns 42 without grants. +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. diff --git a/docs/reference/type-properties.md b/docs/reference/type-properties.md index fe3fa77..d2e7e23 100644 --- a/docs/reference/type-properties.md +++ b/docs/reference/type-properties.md @@ -53,3 +53,5 @@ 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. + +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. diff --git a/docs/rfcs/0023-linear-aggregates.md b/docs/rfcs/0023-linear-aggregates.md new file mode 100644 index 0000000..b9c9c31 --- /dev/null +++ b/docs/rfcs/0023-linear-aggregates.md @@ -0,0 +1,67 @@ +# RFC 0023: Whole-value linear aggregates + +Status: Proposed +Scope: STD-5, vertical source/AIR/verifier/interpreter phase; AIR format 0 + +## Motivation + +Resources need explicit compositional ownership. The preserved invariant is that every normal path consumes each nested owner/resource exactly once, never hides allocation/destruction and never leaves a partial object. Q-035 resolves the scope in spec 03 §25, spec 07a contracts and source spec 15 §16. Ownership type graphs are acyclic; iref graph edges remain opaque. Dynamic linear buffers, partial moves and bulk resource cleanup require a separate collection storage contract. + +## Verifier and runtime + +Structural linearity flows through struct/enum/fixed-array members. Constructors move inputs; whole unpack/enum take move complete components; ordinary copying/overwriting and freeing linear contents reject. Whole-value availability and existing alias/task-loan state suffice. own.pack failure returns the original value; value.swap returns the replaced value, leaving an initialized place. Interpreter handle transfer, explicit budgets, fuel and race checks are deterministic, with no destructor. Existing diagnostics are reused; no new effect/capability/trap is added. + +## Valid and rejected examples + +Valid source constructs an owned field, unpacks the struct and calls own.take exactly once. Rejected counterparts copy a linear field, move one value twice, leak a component or consume an aggregate while borrowed. AIR/source fixtures cover both, plus allocation failure, enum none/some, arrays, exchange and task transfer. The checked positive example is examples/std/owning-option.aji. The following minimal pair exposes the ownership repair: + + +```aji +struct Item { owner: own } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let item = Item { owner: move owner }; + let (part) = struct.unpack(move item); + return own.take(move part); +} +``` + +Replacing `(part)` with `(_)` and returning `42` MUST reject E3002: the component is still owned. Repair by consuming it explicitly, as above. Copying `item.owner` MUST reject E1001; passing `item` to unpack without move MUST reject E7003. The AIR counterparts are linear/struct.air, copy.air, field.air and leak.air; source twins live in source/linear/ and source/quickref/linear.aji. + +## Compatibility + +linear_aggregates was reserved; previously accepted Copy modules retain canonical spelling and ownership behavior. Individual own> borrowing now follows its already-specified array place type rather than being misrepresented as a repeated own_array slice; a baseline-feature AIR regression covers this runtime correction. New instructions are additive under the registered feature. Guard/task-transfer gates, transitive channel_transfer restrictions, second-class borrows and IslandSafe graph contents remain unchanged. Owning option/result use explicit ordinary enum matching; classification helpers retain Copy constraints. Source diagnostics for forbidden Result borrow payloads now come from ordinary member validation (E1001 rather than the removed enum Copy constraint E7005). Owner acceptance remains separate from branch implementation. + +## Agent complexity impact + +New concepts: structural whole-value linearity, exhaustive unpacking, failure returning ownership and replacement returning old ownership. New verifier transfer state: none; ordinary availability/borrow state applies to aggregates. New source forms: ordered array literal and aggregate unpack calls with ordered multi-binding; existing move/match/outcome/borrow syntax composes. Five new AIR operation families expose transfers which Copy-only primitives cannot express. array.make also resolves Q-025: Copy-only frame stores and splat cannot assemble distinct linear elements, so this operation provides a new ownership transfer rather than solely syntax sugar. No per-field holes, implicit drop, trait inference, new effects or capabilities. Explicit errors retain direct repairs. Source/AIR/Quick Reference growth and final verification are recorded below; no MCC benefit is assumed from implementation or fixtures. + + +## Instruction and diagnostic contract + +Spec 07a gives operand/result types, ownership transfer, memory/synchronization, capabilities/effects, traps and verifier state for all five families. New operations require the published linear_aggregates feature and full dependency closure; own.pack additionally requires heap, and array forms require arrays. Existing format-0 constructs retain meanings; new opcodes extend only previously unsupported cases. own.pack carries T explicitly to account for differently sized owning handles without runtime guessing. + +No new diagnostic code is added. E1001 covers illegal copying, member/storage types and overwrite/free; E1003 covers cyclic ownership type graphs; E2001/E2002 cover use/repeated consumption; E3002 covers missing consumption; E2101/E4101 preserve alias/task-loan exclusion; E5002 covers complete continuation/variant shape; E7003/E7005/E7006 retain explicit move and source shape checks. Guards, task handles/scopes and borrows retain separate gates. Atomic cells continue to reject ordinary exchange through an atomic pointee (E4202). Normal paths require consumption; traps terminate without hidden resource cleanup, under the existing profile contract. + +The runtime transfers handles in initialized values, returns the original on failed allocation and performs exchange as one instruction. Borrowed SSA roots retain identity across whole replacement and tracing collection, including enum tags and fixed arrays. This uses internal frame-backed cells, not a new source allocation or verifier state. Structural Send/Share and synchronized-cell/channel rules remain authoritative; a task loan excludes exchange until join. Allocation charges and fuel/scheduler choices stay deterministic. + +## Validation + +Required build, unit tests, formatter check, source coverage and agent-reference checks pass (88/88 source constructs). Full conformance and forced-collection schedule stress pass; source/linear/task, channel and task_loan_join run 32 seeds per stress quantum. A 1,000-exchange loop with an eight-byte authority verifies explicit consumption, bounded live ownership and collection relocation. Long interpreter memory tests, hosted filesystem/stdin/TCP smoke and source CLI integration also pass. Canonical parsing/printing covers the new families; CLI integration covers success/failure ownership, imported nominal generic payloads, run/check/report/explore and ordinary diagnostic repair. Existing module and generic CLI suites pass (36 and 20 checks); new linear CLI integration passes 49 checks. File and Arc member fixtures explicitly borrow their fields through named bindings, following the existing intrinsic API. A payload-free owning Option that is never consumed still rejects E3002. + +## Measured documentation cost + +Relative to STD-4, using tools/agent_bundle_tokens.py --source after zig build agent-reference: + +| Group | cl100k | o200k | Qwen2.5 | +|---|---:|---:|---:| +| Quick Reference | 6,948 → 7,225 (+4.0%) | 6,972 → 7,251 (+4.0%) | 7,172 → 7,455 (+3.9%) | +| Other source docs | 41,086 → 42,364 (+3.1%) | 41,212 → 42,496 (+3.1%) | 42,228 → 43,548 (+3.1%) | +| Full source without AIR | 48,034 → 49,589 (+3.2%) | 48,184 → 49,747 (+3.2%) | 49,400 → 51,003 (+3.2%) | +| AIR docs | 42,454 → 43,966 (+3.6%) | 42,602 → 44,114 (+3.5%) | 43,827 → 45,403 (+3.6%) | + +AIR grows from 160,797 to 168,336 bytes (+4.7%), 19 files and 49 selected sections. New on-demand language/linear-aggregates.md is 1,133 cl100k tokens; library/std.md is 8,398. Quick Reference exceeds its 4–6k target. This growth buys explicit complete ownership transfer and recoverable allocation ownership, rather than per-field holes/destruction state. Cumulative full source growth from the pre-stdlib 33,981-token baseline is approximately 45.9%; front-door consolidation remains separately needed. Documentation growth and successful fixtures do not establish MCC improvement. No private held-out tasks or former smoke M/C guided this design or validation. + +## Next boundary + +Q-036 remains open for STD-6: dynamic storage needs initialized length, move extraction, failure-preserving growth and explicit drain before free. This RFC completes whole-value aggregates, not Vec or Std 0.1. Bulk frame/region/repeated heap storage remains Copy-only; recursive owning type graphs remain rejected. Those limits are explicit rather than implemented with partial-state heuristics or implicit destructors. diff --git a/docs/spec/03-memory-model.md b/docs/spec/03-memory-model.md index 1ed7dc2..b6d44ba 100644 --- a/docs/spec/03-memory-model.md +++ b/docs/spec/03-memory-model.md @@ -252,7 +252,7 @@ Invariants: 3. **No dangling access.** Heap and region memory is reached only through second-class borrows, which cannot outlive the owner (heap) or the region generation (regions). There are no runtime generation checks. 4. **Bounded memory.** Every allocation is charged against a budget held by the authority object of the capability. The budget limits the bytes that are **live at the same time**. 5. **Shared quota.** Copies of a capability refer to one authority object and share one budget; narrowing creates a child budget whose charges also count against every ancestor. -6. **No hidden destruction of linear values.** `own.free`, `own.take`, `region.reset` and `region.destroy` can never make a linear value disappear: until `linear_aggregates` is specified, values stored in `own`, `own_array` and region allocations MUST NOT transitively contain linear values (resources, owners, regions). +6. **No hidden destruction of linear values.** `own.free`, `own.take`, `region.reset` and `region.destroy` can never make a linear value disappear: Copy-only allocations retain this restriction. Feature `linear_aggregates` permits individual `own` content with ownership-preserving `own.pack`/`own.take` (§25); own.free and bulk arrays/regions cannot destroy linear content. ### 18.1 Budget semantics @@ -313,7 +313,7 @@ Both are linear and not copyable; as members of aggregates they need `linear_agg Heap memory is always initialized, so no initialization tracking is needed. `own.free` or `own.take` while a borrow of the owner is live is `E2101`. `own.take` is the inverse of `own.new` (`T → own → T`); an `own_array` has no `take`, since a runtime-sized array is not an SSA value. -`T` in `own` and `own_array` must be a value type; a linear `T` (for example `own>` or `own>`) needs `linear_aggregates` (`E0006` reason `feature_not_declared`), which will define extraction and destruction of nested linear values. An owner is passed to a function by value (moving it) or by borrow (lending it), exactly like a resource. +`T` in baseline `own` and in `own_array` must be Copy. Linear `T` in individual `own` needs `linear_aggregates` (`E0006` reason `feature_not_declared`), whose whole-value extraction/allocation rules are §25; bulk linear heap arrays remain unsupported. An owner is passed to a function by value (moving it) or by borrow (lending it), exactly like a resource. ## 20. Regions in AIR (feature `regions`) @@ -370,7 +370,7 @@ Decision record: RFC 0014. Depends on `heap` and its closure. - `island`: a graph owner; linear; `Send`, not `Share`. - `iref`: an opaque `{graph identity, slot}`; copyable, `IslandSafe`, `Send`, `Share`. -Graph owners may be parameters, returns, block arguments, channel elements and mutex contents. They may not be aggregate members (`linear_aggregates` stays reserved). +Graph owners may be parameters, returns, block arguments, channel elements and mutex contents. Their membership in aggregates requires `linear_aggregates` (§25); it does not weaken IslandSafe graph-content rules. **Identity.** A graph's identity comes from a per-execution counter and is never reused. A handle cannot be built from, cast to or inspected as an integer. @@ -445,3 +445,15 @@ The count is not a user atomic: no memory ordering is chosen by the program. Eac | `frozen.release` | − the graph | | `island.destroy` | − the graph | + +## 25. Linear aggregates in AIR + +Feature `linear_aggregates` permits resources, owners, regions, graph owners, atomic cells, channel endpoints and mutexes as struct fields, enum payloads and fixed-array elements. Borrows/storage, task/scope/shield and guards MUST NOT become aggregate members; their existing gates remain. A declared aggregate or fixed array is linear exactly when any transitive member is linear. All variants contribute to an enum's class, including a payload-free variant. Copy remains structural. Ownership type graphs through aggregate members and owning wrappers MUST be acyclic (E1003); `iref` graph edges remain opaque. This initial feature does not add partial moves, holes, automatic cleanup or dynamic linear buffers. + +Construction (`struct.make`, `enum.make`, `array.make`) MUST consume every linear input exactly once and produce one complete owned value. Every normal path MUST transfer or fully unpack that value; no nested resource may disappear. Copy projections of a live linear struct are allowed, but projecting a linear field with `struct.get`, or duplicating a linear value with `copy`, `load`, `local.load`, `array.splat` or `slice.copy`, MUST reject E1001. Ordinary `store` MUST NOT overwrite linear content. Borrowed fields/elements use existing exclusive/shared alias and task-loan rules; `value.swap` exchanges a complete initialized value with an explicitly supplied replacement and returns the previous value. No field is ever uninitialized. + +`struct.unpack` and `array.unpack` consume their whole operand and deliver every field/element in declaration/index order to one continuation. `enum.take` consumes its whole enum and delivers the selected payload to an exhaustive variant continuation. It MUST have every variant exactly once and no default. Payload-free variants still consume the enum. Copy operands may also be unpacked; they remain available. Existing `enum.switch` remains observational and MUST NOT read a linear enum. Existing linear diagnostics E2001/E2002/E3001/E3002 apply to moved, repeated or missing consumption, with E2101/E4101 for live borrows/task loans. + +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. diff --git a/docs/spec/04-concurrency-and-atomics.md b/docs/spec/04-concurrency-and-atomics.md index 160371f..28b5ff6 100644 --- a/docs/spec/04-concurrency-and-atomics.md +++ b/docs/spec/04-concurrency-and-atomics.md @@ -368,7 +368,7 @@ Any other `T` is `E1001`: 128-bit integers, aggregates, references, owners and h `atomic` is **linear**, `Send` and `Share`, and not copyable. - It may appear where graph owners may (spec 03 §22): SSA values, parameters, returns, block arguments, channel elements and mutex contents. -- As an aggregate member or as the contents of `local`, `own` or a region it needs `linear_aggregates` (`E0006`). +- As an aggregate member or individual own content it needs `linear_aggregates` (spec 03 §25; E0006 without it). Frame/bulk-region/heap-array content remains Copy-only. - It is not `IslandSafe` (`E2111`). - Size and alignment equal those of `T`. @@ -718,7 +718,7 @@ Decision record: RFC 0012. Depends on `cancellation`, `heap`. | `sender` | a sending endpoint | linear | | `receiver` | the receiving endpoint, exactly one per channel | linear | -Endpoints may be block arguments, function parameters and return values, and may be moved into tasks. They may not be aggregate members (reserved `linear_aggregates`) or heap contents. Channels are MPSC: several receivers are the reserved feature `receiver_dup`. +Endpoints may be block arguments, function parameters and return values, and may be moved into tasks. Aggregate membership and individual own content require `linear_aggregates` (spec 03 §25); bulk heap arrays remain Copy-only. Channels are MPSC: several receivers are the reserved feature `receiver_dup`. **Element rules** for `T` (also used by `mutex`, §40): diff --git a/docs/spec/06-resources-and-errors.md b/docs/spec/06-resources-and-errors.md index eb1ba2f..7e9701c 100644 --- a/docs/spec/06-resources-and-errors.md +++ b/docs/spec/06-resources-and-errors.md @@ -87,7 +87,7 @@ The mode of a file is part of its type, so using a file in the wrong mode is a v Resource types are **linear** and **authority-bearing** (spec 05 §10.1): not copyable (`copy` is `E1001`), not zeroable, not comparable, not serializable. -In format 0, resource types MUST NOT appear as struct fields, enum payloads or array elements; that requires the reserved feature `linear_aggregates` (`E0006` reason `feature_not_declared` without it). They may appear as function parameters, return types, block parameters and as operands of borrow instructions. +Resource types as struct fields, enum payloads or fixed-array elements require `linear_aggregates` (spec 03 §25) (`E0006` reason `feature_not_declared` without it). They may appear as function parameters, return types, block parameters and as operands of borrow instructions. ### 6.2 Consumption diff --git a/docs/spec/07-air.md b/docs/spec/07-air.md index 3535477..24188a5 100644 --- a/docs/spec/07-air.md +++ b/docs/spec/07-air.md @@ -222,7 +222,7 @@ Features describe what the implementation must understand. They grant no authori - Integer types, `bool`, `void` and `never` are built in. `usize`/`isize` are distinct from all fixed-width types; their width comes from the target description (spec 09 §9). - `type @T = struct { … }` and `type @T = enum { … }` declare nominal aggregate types. An aggregate MUST NOT contain itself by value, directly or through other aggregates (`E1003`). -- Every type defined in this section is copyable. Types added later under §8.7 (for example `Own` in Phase 1) may be move-only or linear; that does not change the types defined here. +- Baseline aggregate types are Copy. Under `linear_aggregates`, newly permitted linear members make structs/enums/fixed arrays linear structurally (spec 03 §25); baseline Copy aggregates retain their semantics. - `void` is only valid as a function return type. A `void` function returns with `ret` without operand; a call to it MUST NOT bind a result. A `never` function MUST NOT contain `ret`. ### 8.4 Reserved @@ -289,6 +289,6 @@ Feature membership: `local`, `ref`, `mut` and the `from` clause belong **Second-class rule.** Storage and borrow types MUST NOT appear as struct fields, enum payloads, array elements or the `T` of another storage or borrow type (`E1001`). A storage type MUST NOT appear as a function parameter, return type or block parameter (`E1001`). A borrow type MAY appear as a function parameter and, with `from`, as a return type (spec 08 §11.3). As a block parameter type it requires the reserved feature `borrow_joins` (spec 08 §11.6). -All value types of format 0 and Phase 1 are copyable. Move-only values arrive with `heap` in Phase 2. +Baseline value types are Copy; owners/resources and feature-gated linear aggregates obey whole-value consumption (spec 03 §25). Syntax additions (reference/air-text.ebnf): `-> type from %param` on function signatures, the type forms above, and `%a, %b = op` for instructions specified with two results (`slice.split`; `atomic.cmpxchg` with feature `atomics`, spec 04 §42). diff --git a/docs/spec/07a-air-instructions.md b/docs/spec/07a-air-instructions.md index 556307a..21374fe 100644 --- a/docs/spec/07a-air-instructions.md +++ b/docs/spec/07a-air-instructions.md @@ -6,7 +6,7 @@ This file covers the format-0 baseline (Phase 0) and the features `ownership` an ## Common contract for format version 0 -All format-version-0 instructions operate on copyable values only. Unless an entry says otherwise: +The baseline instructions operate on Copy values; feature-specific contracts below specify linear ownership. Unless an entry says otherwise: | Field | Value | |---|---| @@ -309,3 +309,27 @@ Programs that declare `capabilities` also get `"stdout"` and `"stderr"` (capture - every entry of `files`: always `{"encoding":"base64","data":"…"}`, since file contents are arbitrary bytes. Base64 is RFC 4648 with padding. Two records are equal exactly when their bytes are equal. When the deterministic runtime detects quiescence it reports `{"status":"blocked","kind":"no_future_event",…}` (spec 11 §8). When instantiation fails (spec 05 §10.2) the program does not start and the runner reports `{"status":"not_instantiated","reason":…,…}`. When the runner stops execution because an execution limit is exhausted (spec 11 §7), it reports `{"status":"limit_exceeded","kind":"fuel","limit":N,"steps":N}`. This is an outcome of the execution environment, not of the program, and is not a trap. + +## Linear aggregates (`linear_aggregates`) + +These contracts specialize ownership of newly enabled linear member types; baseline Copy instructions keep their prior semantics. All instructions require `linear_aggregates`; an array type also requires `arrays`, and `own.pack` also requires `heap`. Existing feature dependency closures apply. + +### `array.make array(%v0, …, %vN-1)` + +Operands MUST be exactly N complete values of T (E1001). Result is array. Linear inputs are consumed, each exactly once; Copy inputs remain available. Memory, synchronization, effects, capabilities and traps: none. Interpreter assembles elements in order. Verifier marks a linear result available. Normal SSA/size/argument limits apply. + +### `struct.unpack @S %value, next -> @block` and `array.unpack array %value, next -> @block` + +Operand MUST have the named struct/array type. No SSA result; the sole continuation MUST have all field/element parameters of exactly those types in order (E5002 counts, E1001 types). The whole linear operand is consumed and linear parameters become available; Copy operands remain available. Memory, synchronization, effects, capabilities and traps: none. Interpreter transfers every component and jumps. Block-parameter/size limits apply; there are no ignored components. + +### `enum.take @E %value, Variant -> @block, …` + +Operand MUST be the named enum type; every variant MUST appear exactly once with no default (E5002). No SSA result; target payload types/counts follow ordinary enum.switch rules. It consumes a linear operand and transfers its selected complete payload; Copy operands remain available. Memory, synchronization, effects, capabilities and traps: none. Interpreter selects the tag deterministically. Existing enum.switch MUST reject E1001 for a linear enum. + +### `%old = value.swap %borrow, %replacement` + +Operands MUST be mut and T; T MUST be an initialized value, never a borrow/storage/function-bound value (E1001). Result T. A linear replacement is consumed; a linear result becomes available. The borrowed place remains initialized with the complete replacement. Reads/writes: the whole place; exclusive alias and task-loan rules apply (E2101/E4101). Synchronization, effects, capabilities and traps: none; swapping an atomic cell through an ordinary borrow remains forbidden (E4202). Interpreter exchanges whole values in one instruction, retaining existing race instrumentation. + +### `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. diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index 44f696e..1397201 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -199,7 +199,7 @@ The value is evaluated first, then the place is borrowed for the store and the b **Arrays and byte strings.** -- `[e; N]` evaluates `e` once and copies the value N times (`array.splat`). The element must be copyable; a linear element is `E7006`. +- `[e; N]` evaluates `e` once and copies the value N times (`array.splat`). The element must be copyable; a linear element rejects (E1001 for the §16 surface). - `b"…"` is an immutable `[u8; N]` value held in frame storage, written there byte by byte, with no heap. The escapes are exactly `\n \r \t \\ \" \0 \xNN`. - Used where a `slice` is expected, it is borrowed for the operation. @@ -362,7 +362,7 @@ Passing the region itself is `E7005`; the frontend never creates a temporary reg **Container borrows are explicit, as for regions.** `.root`, `.at` and `island.alloc` take a named borrow binding of the graph's owner (`mut g = isl;`), which outlives the borrows derived from it. Passing the owner itself is `E7005`, with a hint. A container borrow written inline is `E7006`. `island.at`, `frozen.at` and `arc.at` appear only as the place of a `ref`/`mut` binding (`E7006` elsewhere). -**Linear aggregates.** A struct or enum with a linear field (`own`, `region`, a resource) needs the reserved feature `linear_aggregates`. The frontend lowers it as written and the AIR is rejected (`E0006`) until that feature is published. +**Linear aggregates.** A struct, enum or fixed array with linear members follows §16 and spec 03 §25. The frontend declares `linear_aggregates` and lowers complete explicit ownership transfers. A byte string or array used where a `slice` is expected is materialized in frame storage and borrowed for the operation. @@ -505,7 +505,7 @@ Module names use source paths. The first component of a package mapping MUST NOT A module sees its own functions and types by short name, and declarations of directly imported modules by full path. Imports MUST NOT inject short names, aliases or transitive visibility. An entry outside reserved built-in namespaces can also qualify its own declarations with its module name; built-in operations retain precedence. An inaccessible or unknown function/type/member is `E7002`, even if a different module linked the declaration. Qualified names resolve by module identity, independently of local bindings with the same prefix. A value may have a type inferred from a directly imported function contract without importing that type's defining module; spelling the type or its constructors by name still requires a direct import. Module-local calls MUST NOT capture an entry's similarly named function; named types from different modules are nominally distinct. -Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals remain forbidden in unparenthesized conditions, where `{` starts a block. This adds no methods, reflection or permission to store forbidden linear/borrowed values in aggregates. Generic forms are specified separately in §15. +Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals remain forbidden in unparenthesized conditions, where `{` starts a block. This adds no methods, reflection or permission to store forbidden borrowed values in aggregates; linear members follow §16. Generic forms are specified separately in §15. A qualified named function MAY be passed as the function operand of `task.spawn(scope, app.work.run, ...)`. Existing Send/effect/structured-lifetime rules still apply; there is no function value, dynamic dispatch or detached task. All other calls use the existing argument, borrow, move, failure and effect rules. @@ -523,7 +523,7 @@ Functions, structs and enums MAY declare 1–8 type parameters immediately after Every generic use MUST supply exactly its ordered type arguments. Type annotations use `Pair`; expression applications use `identity::(42)`, `Pair:: { left: 20, right: 22 }` and `Option::::some(42)`. Enum patterns use `Option::::some(value)` and `Option::::none`. The `::<...>` spelling separates generic application from comparisons; bare `f(...)` is outside the expression grammar. Qualified forms obey §14's direct-import rules. `task.spawn(s, worker::, ...)` statically specializes the worker; this creates no function value. Existing `channel.make(...)` retains its spelling and single type argument. -Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; parameters are types, not values or operations. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT enable linear or borrowed aggregate members. +Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; parameters are types, not values or operations. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT bypass the member restrictions; linear members require §16, and borrowed aggregate members remain forbidden. Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity, effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source. @@ -538,3 +538,13 @@ A type can satisfy several constraints; each requirement MUST be checked. Constr A specialization is keyed by template module identity, declaration kind/name and the ordered structural identity of concrete arguments. Named arguments use nominal defining-module identity, independent of source filename, short/qualified spelling or import/provider order. Each key MUST emit at most one concrete declaration; repeated same-key recursion reuses it. Type-specialization cycles still obey ordinary finite-layout rules. Expanding specialization is bounded by 4,096 generated declarations and active expansion depth 64 (`E7006`), with structural type traversal bounded at depth 64. These are fixed compiler input limits, not runtime fuel or semantic flags. Non-generic declarations retain their AIR names and order. Generated types and functions append in lexicographic specialization-key order within their categories. Their AIR identifier starts with `__aji_g_` followed by lowercase SHA-256 of the canonical key bytes; collisions with original names or earlier keys in sorted order receive the smallest unused `_1`, `_2`, … suffix. The canonical key is `type:` or `fn:`, full defining-module/declaration path, and ordered `<...>` arguments. Named arguments use full nominal paths, applied arguments recursively spell their template/arguments, arrays spell `[T;N]` with decimal N, wrappers/cap/file spell `name`; argument separators are commas without whitespace. Full keys, not hashes, determine identity and reuse. Keys are limited to 16,384 bytes (`E7006`). Every required body lowers to existing format-0 constructs, and the combined module MUST pass the ordinary verifier. There is no new AIR instruction/feature, verifier transfer state, runtime dispatch, implicit allocation/refcount/destructor, effect inference or authority. Source provenance retains template locations and the locations of supplied argument types. Generic borrow/owner/task contracts use the existing runtime/interpreter rules unchanged. Existing monomorphic source and AIR retain meaning and canonical lowering. The finite-layout verifier now visits array elements as well as direct nominal members, closing a prior E1003 implementation gap without changing the normative no-recursive-value rule. Existing unimplemented source `from`-returns remain unimplemented; specialization retains their contract rather than inventing borrow lifetimes. + +## 16. Source linear aggregates + +Structs, enums and fixed arrays with linear members MUST obey spec 03 §25. Constructors consume linear inputs with explicit `move`; whole aggregate calls/returns/bindings also require `move` on named values. No partial field move is allowed. Copy fields may be read without consumption. `let (a, b, …) = struct.unpack(move value);` and `let (a, b, …) = array.unpack(move value);` bind all fields/elements in order, including a one-element parenthesized binding. `_` is allowed only for Copy components; a linear ignored component MUST reject E3002 through the ordinary verifier. Array literals `[e0, e1, …]` use complete ordered inputs; repeated `[e;N]` remains Copy-only. Existing argument/block limits bound unpacking. + +`match move value { Enum::Variant(payload) => … }` exhaustively consumes a linear enum and lowers to enum.take. Ordinary Copy matches keep enum.switch. An arm MUST consume or transfer each linear payload, including those named `_`; there is no automatic destructor. Unused payload-free variants still consume the linear enum. + +`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. diff --git a/docs/spec/16-standard-library.md b/docs/spec/16-standard-library.md index ba4ee37..3d7cf2b 100644 --- a/docs/spec/16-standard-library.md +++ b/docs/spec/16-standard-library.md @@ -138,15 +138,15 @@ When dst can hold the complete representation, the function MUST write exactly t The preserved invariant is exclusive writes only within the supplied initialized slice, no escaping borrow, and no partial mutation on returned failure. Functions declare `effects []`, allocate no heap, use constant scalar auxiliary storage and O(decimal digit count) work. Existing call, initialization, alias, lifetime, bounds and enum verifier rules apply; conflicting live borrows MUST reject even on short output. No new verifier state, runtime rule, diagnostic, AIR feature or authority is added. Valid slices and every scalar value MUST NOT produce arithmetic, cast or bounds traps; interpreter fuel exhaustion remains an environment outcome and is outside the returned-error preservation guarantee. Behavior is identical in deterministic and hosted profiles. Existing APIs, source syntax and AIR format 0 retain their contracts. -### 2.9 Copy option and result +### 2.9 Option and result The compiler registry MUST also include `std.option` and `std.result`. They declare ordinary generic enums: ```aji -enum Option { some(T), none } -enum Result { ok(T), err(E) } +enum Option { some(T), none } +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. -These APIs are restricted to Copy arguments under format 0's existing aggregate-member rules. They MUST NOT accept owners, resources, endpoints or borrows as payloads. Invalid generic constraints use `E7005`; naming/arity/exhaustiveness/alias diagnostics remain the existing source/verifier codes. No must-use obligation, implicit default, prelude, borrow aggregate, new AIR primitive or failure conversion is introduced. Each specialization is a normal Copy enum/static function, deterministic under spec 15 §15. The later linear-aggregate feature is required before owning option/result types can be promised. +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. diff --git a/examples/std/owning-option.aji b/examples/std/owning-option.aji new file mode 100644 index 0000000..56e5cf8 --- /dev/null +++ b/examples/std/owning-option.aji @@ -0,0 +1,12 @@ +module test.linear +import std.option; +fn replace(value: mut>>) -> std.option.Option> effects [] { + return value.swap(mut value, std.option.Option::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + var value: std.option.Option> = std.option.Option::>::some(move owner); + let old = replace(mut value); + match move value { std.option.Option::>::none => {}, std.option.Option::>::some(extra) => { own.free(move extra); } } + match move old { std.option.Option::>::some(part) => { return own.take(move part); } std.option.Option::>::none => { return 0; } } +} diff --git a/src/air/features.zig b/src/air/features.zig index 271c855..20a7d16 100644 --- a/src/air/features.zig +++ b/src/air/features.zig @@ -34,7 +34,7 @@ pub const registry = [_]Feature{ .{ .name = "guard_transfer", .depends = &.{ "cancellation", "effects", "ownership", "sync", "tasks" }, .status = .reserved, .phase = null }, .{ .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 = .reserved, .phase = null }, + .{ .name = "linear_aggregates", .depends = &.{ "capabilities", "effects", "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 +49,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", "ownership", "regions", "resources", "sync", "tasks", "unsafe" }; +pub const supported = [_][]const u8{ "arc", "arrays", "atomics", "cancellation", "capabilities", "channels", "effects", "heap", "islands", "linear_aggregates", "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 e8b10d3..afe21b7 100644 --- a/src/air/module.zig +++ b/src/air/module.zig @@ -290,6 +290,9 @@ pub const Op = union(enum) { store: struct { borrow: ValueId, value: ValueId }, // Feature `arrays`. array_splat: struct { ty: Type, value: ValueId }, + array_make: struct { ty: Type, args: []const ValueId }, + aggregate_unpack: struct { ty: Type, value: ValueId, next: u32 }, + value_swap: struct { borrow: ValueId, value: ValueId }, borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool, unchecked: bool = false }, slice_make: ValueId, slice_len: ValueId, @@ -318,6 +321,7 @@ pub const Op = union(enum) { @"switch": struct { ty: IntType, value: ValueId, cases: []const Case, default: Target }, /// `ty` is a declared enum (`.named`) or a built-in enum (`.builtin`). enum_switch: struct { ty: Type, value: ValueId, arms: []const Arm, default: ?Target }, + enum_take: struct { ty: Type, value: ValueId, arms: []const Arm, default: ?Target }, /// Fallible narrowing (spec 05 §10.4): continues at `ok` with the new /// capability or at `err` with a `cap_error`, as block parameters. cap_narrow: struct { form: []const u8, cap: ValueId, args: []const ValueId, ok: u32, err: u32 }, @@ -327,6 +331,7 @@ pub const Op = union(enum) { // Features `heap` and `regions` (spec 03 §19–§20). Allocations are // fallible terminators delivering to `ok`/`err` block parameters. own_new: struct { value: ValueId, cap: ValueId, ok: u32, err: u32 }, + own_pack: struct { ty: Type, value: ValueId, cap: ValueId, ok: u32, err: u32 }, own_array: struct { n: ValueId, value: ValueId, cap: ValueId, ok: u32, err: u32 }, own_take: ValueId, own_free: ValueId, @@ -410,8 +415,8 @@ pub const Op = union(enum) { pub fn isTerminator(op: Op) bool { return switch (op) { - .br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true, - .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => true, + 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, .task_check_cancel, .task_join_cancel, .channel_make, .channel_send, .channel_recv, .channel_close_receiver, .select, .mutex_lock => true, .intrinsic => |x| x.ok != null, else => false, @@ -461,6 +466,24 @@ pub const Module = struct { return false; } + /// Whole-value linearity; well-formed nominal ownership graphs are acyclic. + pub fn isLinearType(m: Module, t: Type) bool { + if (t.isLinear()) return true; + return switch (t) { + .array => |a| m.isLinearType(a.elem), + .named => |i| switch (m.types[i].kind) { + .@"struct" => |fs| for (fs) |f| { + if (m.isLinearType(f.ty)) break true; + } else false, + .@"enum" => |vs| blk: { + for (vs) |v| for (v.payload) |p| if (m.isLinearType(p)) break :blk true; + break :blk false; + }, + }, + else => false, + }; + } + /// Variant names and payloads of a declared or built-in enum type. pub fn variantCount(m: Module, t: Type) usize { return switch (t) { @@ -533,7 +556,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v for (x.cases) |c| for (c.target.args) |v| f(ctx, v); for (x.default.args) |v| f(ctx, v); }, - .enum_switch => |x| { + inline .enum_switch, .enum_take => |x| { f(ctx, x.value); if (x.default) |d| for (d.args) |v| f(ctx, v); }, @@ -542,7 +565,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v for (x.args) |v| f(ctx, v); }, .intrinsic => |x| for (x.args) |v| f(ctx, v), - .own_new => |x| { + inline .own_new, .own_pack => |x| { f(ctx, x.value); f(ctx, x.cap); }, @@ -630,6 +653,12 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v f(ctx, x.value); }, .array_splat => |x| f(ctx, x.value), + .array_make => |x| for (x.args) |v| f(ctx, v), + .aggregate_unpack => |x| f(ctx, x.value), + .value_swap => |x| { + f(ctx, x.borrow); + f(ctx, x.value); + }, .borrow_index => |x| { f(ctx, x.borrow); f(ctx, x.index); @@ -654,7 +683,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v /// `ok`/`err` targets of a fallible allocation terminator. pub fn allocTargets(op: Op) ?struct { ok: u32, err: u32 } { return switch (op) { - inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| .{ .ok = x.ok, .err = x.err }, + inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| .{ .ok = x.ok, .err = x.err }, else => null, }; } @@ -670,10 +699,11 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std. for (x.cases) |c| try buf.append(gpa, c.target.block); try buf.append(gpa, x.default.block); }, - .enum_switch => |x| { + inline .enum_switch, .enum_take => |x| { for (x.arms) |a| try buf.append(gpa, a.block); if (x.default) |d| try buf.append(gpa, d.block); }, + .aggregate_unpack => |x| try buf.append(gpa, x.next), .cap_narrow => |x| { try buf.append(gpa, x.ok); try buf.append(gpa, x.err); @@ -682,7 +712,7 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std. try buf.append(gpa, ok); try buf.append(gpa, x.err.?); }, - inline .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| { + inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => |x| { try buf.append(gpa, x.ok); try buf.append(gpa, x.err); }, diff --git a/src/air/parse.zig b/src/air/parse.zig index 4e4c9ff..0b50417 100644 --- a/src/air/parse.zig +++ b/src/air/parse.zig @@ -640,7 +640,7 @@ const Parser = struct { }; } - /// Resources inside aggregates need the reserved feature `linear_aggregates`. + /// Resources inside aggregates need the feature `linear_aggregates`. fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void { if (t == .guard) return p.requireFeature("guard_transfer", span, "lock guard as a member"); if (t.isTaskBound()) return p.requireFeature("task_transfer", span, "task handle or scope as a member"); @@ -909,6 +909,26 @@ 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 (eql(op_tok.text, "array.make")) { + try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text); + const ty = try p.parseType(); + break :op .{ .array_make = .{ .ty = ty, .args = try p.valueList() } }; + } + if (eql(op_tok.text, "struct.unpack") or eql(op_tok.text, "array.unpack")) { + try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text); + const ty: air.Type = if (eql(op_tok.text, "struct.unpack")) .{ .named = try p.typeRef(.@"struct") } else try p.parseType(); + if (eql(op_tok.text, "array.unpack") and ty != .array) try p.report("E1001", op_tok.span, "array.unpack requires an array type", &.{}); + const v = try p.useValue(); + _ = try p.expect(.comma, "`,`"); + _ = try p.expectWord("next"); + _ = try p.expect(.arrow, "`->`"); + break :op .{ .aggregate_unpack = .{ .ty = ty, .value = v, .next = try p.blockRef() } }; + } + if (eql(op_tok.text, "value.swap")) { + try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text); + const a, const b = try p.twoOperands(); + break :op .{ .value_swap = .{ .borrow = a, .value = b } }; + } if (eql(op_tok.text, "struct.make")) { const decl = try p.typeRef(.@"struct"); break :op .{ .struct_make = .{ .decl = decl, .args = try p.valueList() } }; @@ -962,7 +982,9 @@ const Parser = struct { _ = try p.expect(.arrow, "`->`"); break :op .{ .@"switch" = .{ .ty = it, .value = value, .cases = cases.items, .default = try p.target() } }; } - if (eql(op_tok.text, "enum.switch")) { + if (eql(op_tok.text, "enum.switch") or eql(op_tok.text, "enum.take")) { + const taking = eql(op_tok.text, "enum.take"); + if (taking) try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text); // A declared enum (`@E`) or a built-in enum (`cap_error`). const ety: air.Type = if (p.peek().tag == .word) blk: { const t = p.next(); @@ -990,7 +1012,7 @@ const Parser = struct { const blk = try p.blockRef(); try arms.append(p.arena, .{ .variant = variant, .block = blk, .span = span }); } - break :op .{ .enum_switch = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } }; + break :op if (taking) .{ .enum_take = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } } else .{ .enum_switch = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } }; } if (eql(op_tok.text, "ret")) { break :op .{ .ret = if (p.peek().tag == .local) try p.useValue() else null }; @@ -1055,7 +1077,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, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true, + .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; @@ -1333,14 +1355,16 @@ const Parser = struct { /// Instructions of the features `heap` and `regions` (spec 03 §19–§20). fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op { - const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" }; + const Name = enum { @"own.new", @"own.pack", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" }; const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null; try p.requireFeature(if (std.mem.startsWith(u8, op_tok.text, "own.")) "heap" else "regions", op_tok.span, op_tok.text); switch (name) { - .@"own.new" => { + .@"own.new", .@"own.pack" => { + if (name == .@"own.pack") try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text); + const pack_ty: air.Type = if (name == .@"own.pack") try p.parseType() else .void; const v, const c = try p.twoOperands(); const ok, const err = try p.okErr(); - return .{ .own_new = .{ .value = v, .cap = c, .ok = ok, .err = err } }; + return if (name == .@"own.pack") .{ .own_pack = .{ .ty = pack_ty, .value = v, .cap = c, .ok = ok, .err = err } } else .{ .own_new = .{ .value = v, .cap = c, .ok = ok, .err = err } }; }, .@"own.array" => { const n, const v = try p.twoOperands(); diff --git a/src/air/print.zig b/src/air/print.zig index 5e31fde..89f17ed 100644 --- a/src/air/print.zig +++ b/src/air/print.zig @@ -209,6 +209,19 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error! try w.print("cast.{s}.{s} ", .{ @tagName(x.mode), @tagName(x.to) }); try value(f, x.a, w); }, + .array_make => |x| { + try w.writeAll("array.make "); + try printType(m, x.ty, w); + try values(f, x.args, w); + }, + .aggregate_unpack => |x| { + try w.writeAll(if (x.ty == .array) "array.unpack " else "struct.unpack "); + try printType(m, x.ty, w); + try w.writeByte(' '); + try value(f, x.value, w); + try w.print(", next -> @{s}", .{f.blocks[x.next].name}); + }, + .value_swap => |x| try two(f, w, "value.swap", x.borrow, x.value), .struct_make => |x| { try w.print("struct.make @{s}", .{m.types[x.decl].name}); try values(f, x.args, w); @@ -251,8 +264,8 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error! try w.writeAll(", default -> "); try target(f, x.default, w); }, - .enum_switch => |x| { - try w.writeAll("enum.switch "); + inline .enum_switch, .enum_take => |x| { + try w.writeAll(if (op == .enum_take) "enum.take " else "enum.switch "); try printType(m, x.ty, w); try w.writeByte(' '); try value(f, x.value, w); @@ -310,8 +323,15 @@ 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 }); }, - .own_new => |x| { - try two(f, w, "own.new", x.value, x.cap); + inline .own_new, .own_pack => |x, tag| { + if (tag == .own_pack) { + try w.writeAll("own.pack "); + try printType(m, x.ty, w); + try w.writeByte(' '); + try value(f, x.value, w); + try w.writeAll(", "); + try value(f, x.cap, w); + } else try two(f, w, "own.new", x.value, x.cap); try okErr(f, w, x.ok, x.err); }, .own_array => |x| { @@ -635,3 +655,40 @@ test "round-trip of ownership and arrays forms" { \\ ); } + +test "round-trip whole-value linear operations" { + try roundTrip( + \\module test.linear + \\air 0 + \\lang 0.1 + \\features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] + \\type @Maybe = enum { some(own), none } + \\fn @main(%heap: cap) -> u64 + \\effects [mem.alloc] + \\entry: + \\ %n = const.u64 42 + \\ own.pack u64 %n, %heap, ok -> @got, err -> @failed + \\got(%owner: own): + \\ %items = array.make array,1>(%owner) + \\ array.unpack array,1> %items, next -> @element + \\element(%part: own): + \\ %slot = enum.make @Maybe.some(%part) + \\ %empty = enum.make @Maybe.none() + \\ %borrow = borrow.mut %slot + \\ %old = value.swap %borrow, %empty + \\ borrow.end %borrow + \\ enum.take @Maybe %slot, some -> @extra, none -> @replaced + \\extra(%extra_owner: own): + \\ own.free %extra_owner + \\ enum.take @Maybe %old, some -> @answer, none -> @no_answer + \\replaced: + \\ enum.take @Maybe %old, some -> @answer, none -> @no_answer + \\answer(%answer_owner: own): + \\ %value = own.take %answer_owner + \\ ret %value + \\no_answer: + \\ ret %n + \\failed(%e: alloc_error, %original: u64): + \\ ret %n + ); +} diff --git a/src/frontend/ast.zig b/src/frontend/ast.zig index a1dbc66..4e37afe 100644 --- a/src/frontend/ast.zig +++ b/src/frontend/ast.zig @@ -79,6 +79,7 @@ pub const Expr = struct { index: struct { e: *const Expr, lo: *const Expr, hi: ?*const Expr }, struct_lit: struct { name: []const u8, fields: []const FieldInit, type_args: []const Type = &.{} }, array_rep: struct { e: *const Expr, len: u64 }, + array_list: []const Expr, or_trap: *const Expr, if_expr: *const If, match_expr: *const Match, @@ -141,7 +142,7 @@ pub const Select = struct { pub const Stmt = struct { span: Span, kind: union(enum) { - let: struct { names: []const []const u8, ty: ?Type, e: Expr }, + let: struct { names: []const []const u8, ty: ?Type, e: Expr, tuple: bool = false }, /// `init == null` is `= zero`. @"var": struct { name: []const u8, ty: Type, init: ?Expr }, assign: struct { place: Expr, e: Expr }, diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index a8599fa..f8e6867 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -315,6 +315,43 @@ const Lowerer = struct { scope_binding_start: usize = 0, fns: std.ArrayList(FnOut) = .empty, + linear_enabled: bool = false, + + fn probeType(l: *Lowerer, t: ast.Type) ?Ty { + const previous = l.problem; + defer l.problem = previous; + return l.typeOf(t) catch null; + } + fn needsLinearType(l: *Lowerer, t: Ty, depth: usize) bool { + if (depth > l.m.types.len + 32) return false; + if (t == .named) return l.isLinear(t); + if (t.inner()) |inner| { + if ((t == .array or t == .own or t == .own_array or t == .slice or t == .slice_mut) and l.isLinear(inner)) return true; + return l.needsLinearType(inner, depth + 1); + } + return false; + } + fn isLinear(l: *Lowerer, t: Ty) bool { + return l.linearAt(t, 0); + } + fn linearAt(l: *Lowerer, t: Ty, depth: usize) bool { + if (t.isLinear()) return true; + if (depth > l.m.types.len + 32) return false; + return switch (t) { + .array => |a| l.linearAt(a.elem, depth + 1), + .named => |i| switch (l.m.types[i].kind) { + .@"struct" => |fs| for (fs) |f| { + if (l.probeType(f.ty)) |ty| if (l.linearAt(ty, depth + 1)) break true; + } else false, + .@"enum" => |vs| blk: { + for (vs) |v| for (v.payload) |p| if (l.probeType(p)) |ty| if (l.linearAt(ty, depth + 1)) break :blk true; + break :blk false; + }, + }, + else => false, + }; + } + fn fail(l: *Lowerer, code: []const u8, span: Span, message: []const u8, fields: []const Problem.Field) Error { // `fields` usually points at a temporary array: keep a copy. l.problem = .{ .code = code, .span = span, .message = message, .fields = try l.arena.dupe(Problem.Field, fields) }; @@ -465,7 +502,6 @@ const Lowerer = struct { } fn checkRequirements(l: *Lowerer) Error!void { - if (l.m.requirements.len == 0) return; const types = try l.arena.alloc(air_module.TypeDecl, l.m.types.len); for (l.m.types, types, 0..) |d, *out, index| { out.* = .{ .name = d.air_name orelse d.name, .span = .{ .line = @intCast(index + 1), .col = 1 }, .kind = undefined }; @@ -486,7 +522,10 @@ const Lowerer = struct { }, } } - const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = types, .functions = &.{} }; + for (l.m.types, 0..) |_, i| if (l.isLinear(.{ .named = @intCast(i) })) { + l.linear_enabled = true; + }; + const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{"linear_aggregates"}, .types = types, .functions = &.{} }; var layout_context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "", .module = m }; try verifier_types.checkFiniteLayouts(&layout_context); if (layout_context.diags.items.len != 0) { @@ -528,10 +567,19 @@ const Lowerer = struct { } var roots: std.ArrayList([]const u8) = .empty; try roots.append(l.arena, "effects"); + var signatures = l.sigs.valueIterator(); + while (signatures.next()) |f| { + for (f.params) |t| if (l.needsLinearType(t, 0)) { + l.linear_enabled = true; + }; + if (l.needsLinearType(f.ret, 0)) l.linear_enabled = true; + } + if (l.linear_enabled) try roots.append(l.arena, "linear_aggregates"); const Rule = struct { []const u8, []const []const u8 }; const rules = [_]Rule{ .{ "arrays", &.{ "array<", "slice", "array.splat", "borrow.index" } }, .{ "ownership", &.{ "local.", "borrow.", " load ", "= load ", "store ", "ref<", "mut<" } }, + .{ "linear_aggregates", &.{ "array.make ", "struct.unpack ", "array.unpack ", "enum.take ", "value.swap ", "own.pack " } }, .{ "heap", &.{ "own.", "own<", "own_array<", "alloc_error" } }, .{ "regions", &.{"region"} }, .{ "capabilities", &.{ "cap<", "cap.narrow", "cap_error" } }, @@ -953,7 +1001,10 @@ const Lowerer = struct { fn stmt(l: *Lowerer, s: ast.Stmt) Error!void { switch (s.kind) { .let => |x| { - if (x.names.len == 2) { + if (x.e.kind == .call) if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "struct.unpack") or std.mem.eql(u8, p, "array.unpack")) return l.unpackLet(s, x.names, x.e, x.tuple); + if (x.tuple and x.names.len == 1) return l.fail("E7006", s.span, "a single parenthesized binding requires aggregate unpack", &.{}); + if (x.names.len != 1) { + if (x.e.kind != .call or x.names.len != 2) return l.fail("E7006", s.span, "this multi-binding requires aggregate unpack", &.{}); if (pathOf(x.e.kind.call.callee.*)) |p| if (std.mem.eql(u8, p, "atomic.compare_exchange")) return l.compareExchangeLet(s, x.names, x.e); return l.splitLet(s, x.names, x.e); } @@ -983,7 +1034,7 @@ const Lowerer = struct { if (v.ty.isBorrow()) return l.fail("E7006", x.e.span, "bind a borrow with `ref name = place;` or `mut name = place;`", &.{}); // Linear values (owners, regions, resources, endpoints, tasks, // mutexes) are borrowed in place, never moved to frame storage. - if (l.addressable.contains(x.names[0]) and !v.ty.isLinear()) { + if (l.addressable.contains(x.names[0]) and !l.isLinear(v.ty)) { const st = try l.storageFor(x.names[0], v.ty, s.span); try l.emit(try l.fmt("local.store %{s}, %{s}", .{ st, v.name }), s.span); try l.bindings.append(l.arena, .{ .name = x.names[0], .mutable = false, .value = st, .ty = v.ty, .kind = .storage }); @@ -992,7 +1043,7 @@ const Lowerer = struct { .@"var" => |x| { const ty = try l.typeOf(x.ty); if (ty.isBorrow()) return l.fail("E7006", s.span, "a `var` holds a value; bind a borrow with `ref` or `mut`", &.{}); - if (l.addressable.contains(x.name) and !ty.isLinear()) { + if (l.addressable.contains(x.name) and !l.isLinear(ty)) { const st = try l.storageFor(x.name, ty, s.span); if (x.init) |e| { const v = try l.consuming(e, ty); @@ -1238,6 +1289,7 @@ const Lowerer = struct { .deref => |x| if (l.peekType(x.*)) |t| t.inner() else null, .index => |x| if (x.hi == null) (if (l.peekType(x.e.*)) |t| elemOf(t) else null) else null, .array_rep => |x| if (l.peekType(x.e.*)) |t| (l.arrayOf(t, x.len) catch null) else null, + .array_list => |xs| if (xs.len != 0) (if (l.peekType(xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null, .neg => |x| l.peekType(x.*), .not => .bool, .cast => |x| l.typeOfNoFail(x.ty), @@ -1396,6 +1448,18 @@ const Lowerer = struct { try l.endNow(p.ends, e.span); return v; }, + .array_list => |xs| { + if (xs.len == 0 or xs.len > 64) return l.fail("E7006", e.span, "array literal requires 1..64 complete elements", &.{}); + var ty: ?Ty = if (want) |w| if (w == .array) w.array.elem else null else null; + var names: std.ArrayList(u8) = .empty; + for (xs, 0..) |x, i| { + const v = try l.consuming(x, ty); + if (ty) |t| try l.checkTy(x.span, v.ty, t) else ty = v.ty; + try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); + } + const at = try l.arrayOf(ty.?, xs.len); + return l.def("arr", at, try l.fmt("array.make {s}({s})", .{ l.tyText(at), names.items }), e.span); + }, .array_rep => |x| { const want_elem: ?Ty = if (want) |w| (if (w == .array) w.array.elem else null) else null; const v = try l.expr(x.e.*, want_elem); @@ -1464,7 +1528,7 @@ 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 (!b.ty.isLinear()) 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)) 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) } }); return .{ .name = b.value, .ty = b.ty }; }, } @@ -1543,6 +1607,19 @@ const Lowerer = struct { } fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value { + 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; + const p = try l.placeBorrow(b.place.*, true, false, e.span); + if (p.v.ty != .mut) return l.fail("E7005", e.span, "value.swap requires mut", &.{}); + const ty = p.v.ty.inner().?; + const replacement = try l.consuming(args[1], ty); + try l.checkTy(args[1].span, replacement.ty, ty); + const result = try l.def("old", ty, try l.fmt("value.swap %{s}, %{s}", .{ p.v.name, replacement.name }), e.span); + try l.endNow(p.ends, e.span); + l.linear_enabled = true; + return result; + }; if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args); if (try l.moduleCall(callee)) |name| { // Reuse ordinary call typing/borrowing/lowering, including E7002. @@ -1652,7 +1729,7 @@ const Lowerer = struct { if (std.mem.eql(u8, x.name, f.name)) break x; } else return l.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } }); const ft = try l.typeOf(f.ty); - const v = try l.expr(fi.e, ft); + const v = try l.consuming(fi.e, ft); try l.checkTy(fi.e.span, v.ty, ft); try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); } @@ -1669,7 +1746,7 @@ const Lowerer = struct { var names: std.ArrayList(u8) = .empty; for (args, v.payload, 0..) |a, pt, i| { const ty = try l.typeOf(pt); - const av = try l.expr(a, ty); + const av = try l.consuming(a, ty); try l.checkTy(a.span, av.ty, ty); try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name })); } @@ -1743,7 +1820,7 @@ const Lowerer = struct { if (m.kind == .outcome) return l.outcomeMatch(m, want); const st = l.peekType(m.scrutinee) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{}); if (st == .builtin) return l.builtinMatch(m, st.builtin, want); - const sv = try l.expr(m.scrutinee, st); + const sv = try l.consuming(m.scrutinee, st); const depth = l.bindings.items.len; const vars = try l.carriedLive(depth, m.span, .{ .match = m }); const before = try l.snapshot(); @@ -1754,7 +1831,7 @@ const Lowerer = struct { const vs = d.kind.@"enum"; const blocks = try l.arena.alloc(usize, m.arms.len); var head: std.ArrayList(u8) = .empty; - try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ l.tyText(st), sv.name })); + try head.appendSlice(l.arena, try l.fmt("{s} {s} %{s}", .{ if (l.isLinear(st)) "enum.take" else "enum.switch", l.tyText(st), sv.name })); for (m.arms, blocks, 0..) |arm, *blk, i| { if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null) return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }}); @@ -1995,7 +2072,7 @@ const Lowerer = struct { /// written `move x` (spec 15 §5). Use after move, double consumption and /// leaks are the verifier's (E2001, E2002, E3001, E3002). fn consuming(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value { - if (e.kind == .name) if (l.lookup(e.kind.name)) |b| if (b.ty.isLinear() and b.kind == .ssa) + if (e.kind == .name) if (l.lookup(e.kind.name)) |b| if (l.isLinear(b.ty) and b.kind == .ssa) return l.fail("E7003", e.span, "a linear value is consumed here: write `move` to transfer it, or borrow it with `ref`/`mut`", &.{ .{ .name = "name", .value = e.kind.name }, .{ .name = "suggestion", .value = try l.fmt("move {s}", .{e.kind.name}) } }); return l.expr(e, want); } @@ -2059,6 +2136,7 @@ const Lowerer = struct { .ssa => { // A linear value (owner, region) is borrowed in place. const bt: ?Ty = switch (b.ty) { + .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.*), .region => if (mutable) try l.wrap(.mut, .region) else try l.wrap(.ref, .region), @@ -2186,6 +2264,30 @@ const Lowerer = struct { /// `let (left, right) = s.split_at(k);`: two disjoint borrows of `s`, /// bound for the rest of the block (spec 15 §5). + fn unpackLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr, tuple: bool) Error!void { + if (!tuple or s.kind.let.ty != null or e.kind.call.args.len != 1) return l.fail("E7006", s.span, "unpack requires a parenthesized complete binding and one argument", &.{}); + const v = try l.consuming(e.kind.call.args[0], null); + const operation = pathOf(e.kind.call.callee.*).?; + var components: std.ArrayList(Ty) = .empty; + if (std.mem.eql(u8, operation, "struct.unpack") and v.ty == .named and l.m.types[v.ty.named].kind == .@"struct") { + for (l.m.types[v.ty.named].kind.@"struct") |f| try components.append(l.arena, try l.typeOf(f.ty)); + } else if (std.mem.eql(u8, operation, "array.unpack") and v.ty == .array) { + if (v.ty.array.len > 64) return l.fail("E7006", s.span, "unpack exceeds 64 block parameters", &.{}); + for (0..@intCast(v.ty.array.len)) |_| try components.append(l.arena, v.ty.array.elem); + } else return l.fail("E7005", e.span, "unpack needs the corresponding struct or array", &.{}); + if (names.len != components.items.len or names.len > 64) return l.fail("E7005", s.span, "unpack must bind every component", &.{}); + const next = try l.newBlock("unpacked"); + for (names, components.items, 0..) |n, t, i| { + for (names[0..i]) |previous| if (!std.mem.eql(u8, n, "_") and std.mem.eql(u8, n, previous)) return l.fail("E7006", s.span, "duplicate unpack binding", &.{}); + const pn = try l.freshName(if (std.mem.eql(u8, n, "_")) "unused" else n); + try l.blocks.items[next].params.append(l.arena, .{ .name = pn, .ty = t }); + if (!std.mem.eql(u8, n, "_")) try l.bindings.append(l.arena, .{ .name = n, .value = pn, .ty = t, .mutable = false }); + } + try l.term(try l.fmt("{s} {s} %{s}, next -> @{s}", .{ operation, l.tyText(v.ty), v.name, l.blocks.items[next].name }), s.span); + l.cur = next; + l.linear_enabled = true; + } + fn splitLet(l: *Lowerer, s: ast.Stmt, names: []const []const u8, e: ast.Expr) Error!void { if (e.kind != .call or e.kind.call.callee.kind != .field or !std.mem.eql(u8, e.kind.call.callee.kind.field.name, "split_at") or e.kind.call.args.len != 1) return l.fail("E7006", e.span, "`let (a, b) = …` is only for `s.split_at(k)`", &.{}); @@ -2293,6 +2395,7 @@ const Lowerer = struct { .field => |x| try l.markExpr(x.e.*), .struct_lit => |x| for (x.fields) |f| try l.markExpr(f.e), .array_rep => |x| try l.markExpr(x.e.*), + .array_list => |xs| for (xs) |x| try l.markExpr(x), .if_expr => |x| { try l.markExpr(x.cond); try l.markBlock(x.then); @@ -2322,7 +2425,7 @@ const Lowerer = struct { fn fallible(l: *Lowerer, path: []const u8) ?void { _ = l; - const ops = [_][]const u8{ "own.new", "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{ "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; @@ -2893,6 +2996,13 @@ const Lowerer = struct { }.n; const alloc_err: Ty = .{ .builtin = .alloc_error }; const usize_ty: Ty = .{ .int = "usize" }; + if (std.mem.eql(u8, path, "own.pack")) { + try want(l, e.span, args, 2, path); + const v = try l.consuming(args[0], null); + const c = try l.expectCap(args[1], "mem.alloc"); + l.linear_enabled = true; + return .{ .text = try l.fmt("own.pack {s} %{s}, %{s}", .{ l.tyText(v.ty), v.name, c.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{try l.wrap(.own, v.ty)} }, .{ .role = "err", .params = &.{ alloc_err, v.ty } } }) }; + } if (std.mem.eql(u8, path, "own.new")) { try want(l, e.span, args, 2, path); const v = try l.consuming(args[0], null); @@ -3186,17 +3296,21 @@ fn elemOf(t: Ty) ?Ty { /// `cap.narrow.budget`; null for anything else. fn pathOf(e: ast.Expr) ?[]const u8 { const known = [_][]const u8{ - "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", + "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; const text = dotted(e, &buf) orelse return null; @@ -3314,6 +3428,9 @@ fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool { break :blk false; }, .array_rep => |x| exprReads(x.e.*, name, skip), + .array_list => |xs| for (xs) |x| { + if (exprReads(x, name, skip)) break true; + } else false, .if_expr => |x| ifReads(x.*, name, skip), .match_expr => |x| blk: { if (exprReads(x.scrutinee, name, skip)) break :blk true; @@ -3375,6 +3492,9 @@ const After = struct { break :blk false; }, .array_rep => |x| w.expr(x.e.*), + .array_list => |xs| for (xs) |x| { + if (w.expr(x)) break true; + } else false, .if_expr => |x| w.ifExpr(x.*), .match_expr => |x| blk: { if (w.expr(x.scrutinee)) break :blk true; @@ -3533,6 +3653,9 @@ fn exprAssigns(e: ast.Expr, name: []const u8) bool { .field => |x| exprAssigns(x.e.*, name), .index => |x| exprAssigns(x.e.*, name) or exprAssigns(x.lo.*, name) or (if (x.hi) |h| exprAssigns(h.*, name) else false), .array_rep => |x| exprAssigns(x.e.*, name), + .array_list => |xs| for (xs) |x| { + if (exprAssigns(x, name)) break true; + } else false, else => false, }; } diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index f51dd17..8cbdd4e 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -331,11 +331,14 @@ const Parser = struct { if (isWord(t, "let")) { _ = p.next(); var names: std.ArrayList([]const u8) = .empty; - if (p.peek().tag == .l_paren) { + const tuple = p.peek().tag == .l_paren; + if (tuple) { _ = p.next(); - try names.append(p.arena, try p.ident("a name")); - _ = try p.expect(.comma, "`,`"); - try names.append(p.arena, try p.ident("a name")); + while (p.peek().tag != .r_paren) { + try names.append(p.arena, if (p.peek().tag == .underscore) p.next().text else try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } _ = try p.expect(.r_paren, "`)`"); } else try names.append(p.arena, try p.ident("a name")); var ty: ?ast.Type = null; @@ -346,7 +349,7 @@ const Parser = struct { _ = try p.expect(.eq, "`=`"); const e = try p.expr(); _ = try p.expect(.semicolon, "`;`"); - return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e } } }; + return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e, .tuple = tuple } } }; } const unchecked_borrow = isWord(p.peekAt(1), "unchecked") and p.peekAt(2).tag == .ident and p.peekAt(3).tag == .eq; if ((isWord(t, "ref") or isWord(t, "mut")) and ((p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) or unchecked_borrow)) { @@ -822,6 +825,17 @@ const Parser = struct { .l_bracket => { _ = p.next(); const e = try p.expr(); + if (p.peek().tag != .semicolon) { + var items: std.ArrayList(ast.Expr) = .empty; + try items.append(p.arena, e); + while (p.peek().tag == .comma) { + _ = p.next(); + if (p.peek().tag == .r_bracket) break; + try items.append(p.arena, try p.expr()); + } + _ = try p.expect(.r_bracket, "`]`"); + return .{ .span = p.span(start), .kind = .{ .array_list = items.items } }; + } _ = try p.expect(.semicolon, "`;` in `[e; N]`"); const n = try p.expect(.int, "array length"); _ = try p.expect(.r_bracket, "`]`"); @@ -853,7 +867,7 @@ const Parser = struct { }; return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } }; } - if (isKeyword(t.text)) return p.fail(t, "an expression"); + if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.fail(t, "an expression"); _ = p.next(); if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) { _ = p.next(); diff --git a/src/interp/machine.zig b/src/interp/machine.zig index 9ec38c8..9856d3f 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -109,6 +109,9 @@ pub const Value = union(enum) { pub const Cell = struct { value: Value, ty: air.Type, + /// An SSA root borrowed in place; its frame outlives every loan. + backing: ?struct { values: []Value, index: u32 } = null, + owner_array: bool = false, /// Accesses seen by the race detector (`Options.detect_races`). shadow: ?*race.Shadow = null, }; @@ -374,6 +377,8 @@ const Copier = struct { const n = try c.to.create(Value.Cell); try c.cells.put(c.tmp, old, n); n.* = .{ .value = .void, .ty = old.ty, .shadow = if (old.shadow) |sh| try sh.copy(c.to) else null }; + n.owner_array = old.owner_array; + if (old.backing) |b| n.backing = .{ .values = try c.items(b.values), .index = b.index }; n.value = try c.value(old.value); return n; } @@ -858,6 +863,12 @@ 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 }, + .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; + for (f.blocks[x.next].params, fields) |p, v| vals[p.value] = v; + return .{ .jump = x.next }; + }, .struct_make => |x| return bind(vals, inst.result, .{ .aggregate = .{ .decl = x.decl, .variant = 0, @@ -877,7 +888,7 @@ const Machine = struct { for (x.cases) |c| if (c.bits == v) return m.jump(f, vals, c.target); return m.jump(f, vals, x.default); }, - .enum_switch => |x| { + inline .enum_switch, .enum_take => |x| { const variant: u32, const fields: []const Value = switch (vals[x.value]) { .aggregate => |agg| .{ agg.variant, agg.fields }, .builtin => |b| .{ b.variant, &.{} }, @@ -934,13 +945,13 @@ const Machine = struct { .task_check_cancel, .task_join_cancel, .task_shield_begin, .task_shield_end => return m.execCancellation(f, vals, inst), .channel_make, .channel_dup, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => return m.execChannel(f, vals, inst), .mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst), - .own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst), + inline .own_new, .own_pack, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst), .island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst), .atomic_new, .atomic_take, .atomic_load, .atomic_store, .atomic_rmw, .atomic_cmpxchg, .atomic_fence => return m.execAtomic(vals, inst), .intrinsic => |x| return m.intrinsic(f, vals, inst, x), .ret => |v| return .{ .ret = if (v) |x| vals[x] else .void }, .trap => return .{ .trap = .explicit }, - .local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard, .assume => return m.execMemory(vals, inst), + .local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .value_swap, .guard, .assume => return m.execMemory(vals, inst), } } @@ -968,7 +979,7 @@ const Machine = struct { const ch = endpointOf(vals[arm.endpoint]); if ((if (arm.value == null) m.recvState(ch) else m.sendState(ch)) != .none) break true; } else false, - .mutex_lock => |x| !vals[x.mutex].mutex.locked, + .mutex_lock => |x| !mutexOf(vals[x.mutex]).locked, else => unreachable, }; } @@ -976,7 +987,7 @@ const Machine = struct { fn endpointOf(v: Value) u32 { return switch (v) { .sender, .receiver => |c| c, - .place => |p| endpointOf(p.cell.value), + .place => |p| endpointOf(placePtr(p).*), else => unreachable, }; } @@ -1453,7 +1464,7 @@ const Machine = struct { fn mutexOf(v: Value) *Value.MutexCell { return switch (v) { .mutex => |mc| mc, - .place => |p| mutexOf(p.cell.value), + .place => |p| mutexOf(placePtr(p).*), else => unreachable, }; } @@ -1501,7 +1512,7 @@ const Machine = struct { } fn placePtr(p: Value.Place) *Value { - var v = &p.cell.value; + var v = if (p.cell.backing) |b| &b.values[b.index] else &p.cell.value; for (p.path) |i| v = switch (v.*) { .aggregate => |a| &a.fields[i], .array => |items| &items[i], @@ -1567,7 +1578,7 @@ const Machine = struct { fn resourceOf(v: Value) u32 { return switch (v) { .resource => |hd| hd, - .place => |p| p.cell.value.resource, + .place => |p| placePtr(p).resource, else => unreachable, }; } @@ -1761,6 +1772,19 @@ const Machine = struct { fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step { _ = types_of; switch (inst.op) { + .own_pack => |x| { + const a = vals[x.cap].cap; + const bytes = budget.accountedSize(m.module, x.ty, 0); + if (!m.charge(a, bytes)) { + vals[f.blocks[x.err].params[1].value] = vals[x.value]; + return allocFailed(f, vals, x.err); + } + const cell = try m.heap().create(Value.Cell); + cell.* = .{ .value = try m.deepCopy(vals[x.value]), .ty = x.ty }; + try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? }); + vals[f.blocks[x.ok].params[0].value] = .{ .own = cell }; + return .{ .jump = x.ok }; + }, .own_new => |x| { const v = vals[x.value]; const bytes = m.valueBytes(vals[x.value]); @@ -1780,7 +1804,7 @@ const Machine = struct { const items = try m.heap().alloc(Value, n); for (items) |*it| it.* = try m.deepCopy(vals[x.value]); const cell = try m.heap().create(Value.Cell); - cell.* = .{ .value = .{ .array = items }, .ty = .void }; + cell.* = .{ .value = .{ .array = items }, .ty = .void, .owner_array = true }; try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? }); vals[f.blocks[x.ok].params[0].value] = .{ .own = cell }; return .{ .jump = x.ok }; @@ -1949,6 +1973,20 @@ const Machine = struct { return @truncate(v.int.bits); } + fn ssaCell(m: *Machine, vals: []Value, index: u32) !*Value.Cell { + for (vals) |v| { + const cell: ?*Value.Cell = switch (v) { + .place => |p| p.cell, + .slice => |s| s.place.cell, + else => null, + }; + if (cell) |c| if (c.backing) |b| if (b.values.ptr == vals.ptr and b.index == index) return c; + } + const cell = try m.heap().create(Value.Cell); + cell.* = .{ .value = .void, .ty = .void, .backing = .{ .values = vals, .index = index } }; + return cell; + } + fn execMemory(m: *Machine, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step { switch (inst.op) { .local_alloc => |t| { @@ -1973,22 +2011,9 @@ const Machine = struct { }, .borrow_ref, .borrow_mut => |v| return bind(vals, inst.result, switch (vals[v]) { .local => |c| .{ .place = .{ .cell = c, .path = &.{} } }, - // A borrowed resource: a place whose cell holds the handle. - // Owners: the heap cell itself; arrays are borrowed as slices. - .own => |cell| switch (cell.value) { - .array => |items| .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = items.len } }, - else => .{ .place = .{ .cell = cell, .path = &.{} } }, - }, - .region => |r| blk: { - const cell = try m.heap().create(Value.Cell); - cell.* = .{ .value = .{ .region = r }, .ty = .void }; - break :blk .{ .place = .{ .cell = cell, .path = &.{} } }; - }, - .resource => |hd| blk: { - const cell = try m.heap().create(Value.Cell); - cell.* = .{ .value = .{ .resource = hd }, .ty = .void }; - break :blk .{ .place = .{ .cell = cell, .path = &.{} } }; - }, + .own => |cell| if (cell.owner_array) .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = cell.value.array.len } } else .{ .place = .{ .cell = cell, .path = &.{} } }, + .aggregate, .array, .resource, .region => .{ .place = .{ .cell = try m.ssaCell(vals, v), .path = &.{} } }, + .graph => if (inst.op == .borrow_mut) .{ .place = .{ .cell = try m.ssaCell(vals, v), .path = &.{} } } else vals[v], else => |x| x, }), .borrow_field => |x| return bind(vals, inst.result, .{ .place = try m.extend(asPlace(vals[x.borrow]), x.field) }), @@ -2004,6 +2029,13 @@ const Machine = struct { placePtr(p).* = try m.deepCopy(vals[x.value]); return .next; }, + .value_swap => |x| { + const p = asPlace(vals[x.borrow]); + if (try m.raceCheck(p.cell, p.path, true)) |r| return r; + const old = placePtr(p).*; + placePtr(p).* = try m.deepCopy(vals[x.value]); + return bind(vals, inst.result, old); + }, .array_splat => |x| { const items = try m.heap().alloc(Value, x.ty.array.len); for (items) |*it| it.* = try m.deepCopy(vals[x.value]); diff --git a/src/report.zig b/src/report.zig index df78a21..53d4ac2 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_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => { + .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 3e16a72..80e00b2 100644 --- a/src/verifier/borrow.zig +++ b/src/verifier/borrow.zig @@ -191,7 +191,7 @@ const Walker = struct { /// Linear values: resources, owners and regions (spec 06 §6, spec 03 §19–§20). fn isResource(w: *Walker, v: ValueId) bool { - return w.types[v].isLinear(); + return w.c.module.isLinearType(w.types[v]); } /// A non-consuming use of resource `v` (a borrow of it). @@ -252,10 +252,11 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args }); try out.append(arena, .{ .target = x.default.block, .args = x.default.args }); }, - .enum_switch => |x| { + inline .enum_switch, .enum_take => |x| { for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} }); if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args }); }, + .aggregate_unpack => |x| try out.append(arena, .{ .target = x.next, .args = &.{} }), .cap_narrow => |x| { try out.append(arena, .{ .target = x.ok, .args = &.{} }); try out.append(arena, .{ .target = x.err, .args = &.{} }); @@ -264,7 +265,7 @@ fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void try out.append(arena, .{ .target = ok, .args = &.{} }); try out.append(arena, .{ .target = x.err.?, .args = &.{} }); }, - .own_new, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => { + inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => { const t = air.allocTargets(op).?; try out.append(arena, .{ .target = t.ok, .args = &.{} }); try out.append(arena, .{ .target = t.err, .args = &.{} }); @@ -302,7 +303,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { .parent = null, }; // Linear parameters were moved in: the function owns them (spec 06 §6.3). - if (p.ty.isLinear()) w.live[p.value] = true; + if (c.module.isLinearType(p.ty)) w.live[p.value] = true; } const dom = try ssa.dominators(c.arena, f); @@ -318,7 +319,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { const blk = f.blocks[b]; // Linear block parameters own their argument from here on; the // parameter of a region allocation's `ok` target is a live borrow. - for (blk.params) |p| if (p.ty.isLinear() or (p.ty.isBorrow() and w.info[p.value] != null)) { + for (blk.params) |p| if (c.module.isLinearType(p.ty) or (p.ty.isBorrow() and w.info[p.value] != null)) { w.live[p.value] = true; w.dead[p.value] = .none; }; @@ -337,19 +338,19 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { for (out.items) |e| { @memcpy(w.live, base); @memcpy(w.dead, base_dead); - for (e.args) |a| if (types[a].isLinear()) try w.consume(a, .moved); + for (e.args) |a| if (c.module.isLinearType(types[a])) try w.consume(a, .moved); // A linear parameter of the target that is still live on this // edge would be overwritten: that instance leaks. Parameters are // not part of the incoming state; they come alive in the block. for (f.blocks[e.target].params) |p| { - if (p.ty.isLinear() and w.live[p.value]) try w.report("E3002", "linear value not consumed before it is redefined", p.value, null); + if (c.module.isLinearType(p.ty) and w.live[p.value]) try w.report("E3002", "linear value not consumed before it is redefined", p.value, null); w.live[p.value] = false; } if (entry_state[e.target]) |expected| { if (!std.mem.eql(bool, expected, w.live) and !reported_join[e.target]) { reported_join[e.target] = true; for (expected, w.live, 0..) |a, x, v| if (a != x) { - const is_res = types[v].isLinear(); + const is_res = c.module.isLinearType(types[v]); try c.report(if (is_res) "E3002" else "E2105", f.blocks[e.target].span, if (is_res) "resource state differs between edges into this block" else "borrow state differs between edges into this block", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "block", .value = .{ .str = f.blocks[e.target].name } }, @@ -433,7 +434,40 @@ fn step(w: *Walker, inst: air.Inst) !void { w.live[r] = true; }; }, - .own_free, .own_take => |v| try w.consume(v, .closed), + inline .struct_make, .enum_make, .array_make => |x| { + for (x.args) |v| if (w.isResource(v)) try w.consume(v, .moved); + if (inst.result) |r| { + if (w.isResource(r)) w.live[r] = true; + } + }, + .struct_get => |x| { + if (w.isResource(x.a)) { + _ = try w.resourceUsable(x.a); + try w.access(x.a, &.{.{ .field = x.field }}, .shared, null, x.a); + } + }, + .aggregate_unpack => |x| { + if (w.isResource(x.value)) try w.consume(x.value, .moved); + }, + .enum_take => |x| { + if (w.isResource(x.value)) try w.consume(x.value, .moved); + }, + .own_pack => |x| { + if (w.isResource(x.value)) try w.consume(x.value, .moved); + }, + .value_swap => |x| { + try w.useThrough(x.borrow, .exclusive); + if (w.isResource(x.value)) try w.consume(x.value, .moved); + if (inst.result) |r| { + if (w.isResource(r)) w.live[r] = true; + } + }, + .own_free, .own_take => |v| { + try w.consume(v, .closed); + if (inst.result) |r| { + if (w.isResource(r)) w.live[r] = true; + } + }, .task_scope_begin => w.live[inst.result.?] = true, .task_spawn => |x| { try noWaitUnderLock(w, "task.spawn"); diff --git a/src/verifier/budget.zig b/src/verifier/budget.zig index f3b8b3d..dc0db12 100644 --- a/src/verifier/budget.zig +++ b/src/verifier/budget.zig @@ -87,6 +87,7 @@ pub fn check(c: *verifier.Context) !void { for (b.insts) |inst| switch (inst.op) { .call => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len), .struct_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len), + .array_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len), .enum_make => |x| try limit(c, inst.span, "arguments per call", Limits.params, x.args.len), .@"switch" => |x| try limit(c, inst.span, "cases per switch", Limits.cases, x.cases.len), else => {}, @@ -150,7 +151,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), - .array_splat => |x| try v.visit(inst.span, x.ty), + inline .array_splat, .array_make, .aggregate_unpack, .own_pack => |x| try v.visit(inst.span, x.ty), else => {}, }; } diff --git a/src/verifier/cfg.zig b/src/verifier/cfg.zig index 3e6eb93..b66887e 100644 --- a/src/verifier/cfg.zig +++ b/src/verifier/cfg.zig @@ -53,7 +53,8 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void { } try arity(c, f, inst.span, x.default); }, - .enum_switch => |x| { + inline .enum_switch, .enum_take => |x| { + if (inst.op == .enum_take and x.default != null) try invalid(c, f, inst.span, "enum.take cannot have a default", null); const m = c.module; for (x.arms, 0..) |arm, i| { for (x.arms[0..i]) |prev| if (prev.variant == arm.variant) @@ -74,6 +75,18 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void { } } }, + .aggregate_unpack => |x| { + const n: usize = switch (x.ty) { + .array => |a| @intCast(a.len), + .named => |i| if (c.module.types[i].kind == .@"struct") c.module.types[i].kind.@"struct".len else 0, + else => 0, + }; + try paramCount(c, f, inst.span, x.next, n, "unpack target must receive every component"); + }, + .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"); + }, // `ok` receives the narrowed capability, `err` the `cap_error` (spec 05 §10.4). .cap_narrow => |x| { try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter"); diff --git a/src/verifier/effects.zig b/src/verifier/effects.zig index 7fd0bb8..a5ea27d 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_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) { + .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 e8866d9..7606153 100644 --- a/src/verifier/types.zig +++ b/src/verifier/types.zig @@ -23,6 +23,10 @@ pub fn check(c: *Context) !void { fn checkDeclarations(c: *Context) !void { const m = c.module; + if (m.declares("linear_aggregates")) { + try checkFiniteLayouts(c); + if (c.diags.items.len != 0) return; + } for (m.types) |d| switch (d.kind) { .@"struct" => |fs| for (fs) |fld| try wellFormed(c, d.span, fld.ty, .member, d.name), .@"enum" => |vs| for (vs) |v| for (v.payload) |t| try wellFormed(c, d.span, t, .member, d.name), @@ -44,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), - .array_splat => |x| try wellFormed(c, inst.span, x.ty, .member, f.name), + inline .array_splat, .array_make, .aggregate_unpack, .own_pack => |x| try wellFormed(c, inst.span, x.ty, .param, f.name), else => {}, }; } @@ -81,6 +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.*), else => {}, } } @@ -98,9 +103,11 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons .void, .never => pos == .ret, .local => false, .ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed, - .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => pos != .member, + .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"), 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", &.{}); // An atomic cell holds an AtomicScalar (spec 04 §23). if (t == .atomic and !isAtomicScalar(t.atomic.*)) try c.report("E1001", span, "atomic needs bool or an integer of at most 64 bits", &.{ .{ .name = "in", .value = .{ .str = owner } }, @@ -269,7 +276,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type { if (reg.fallible or reg.results.len == 0) break :blk .void; break :blk intrinsicResult(reg.results[0]); }, - .array_splat => |x| x.ty, + inline .array_splat, .array_make => |x| x.ty, else => null, }; } @@ -595,6 +602,10 @@ fn checkSelect(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "select")) !voi _ = f; } +pub fn complete(t: Type) bool { + return t != .void and t != .never and t != .local and !t.isBorrow() and !t.isTaskBound() and t != .guard; +} + fn boxed(arena: std.mem.Allocator, t: Type) !*const Type { const b = try arena.create(Type); b.* = t; @@ -612,6 +623,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { .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, + .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, .slice_sub => |x| fc.ty[x.slice] orelse return null, @@ -632,9 +644,11 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { }; const invalid: Type = .void; return switch (op) { + .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) }, .own => |inner| .{ .ref = inner }, .own_array => |inner| .{ .slice = inner }, @@ -643,6 +657,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) }, .own => |inner| .{ .mut = inner }, .own_array => |inner| .{ .slice_mut = inner }, @@ -771,11 +786,12 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { const span = inst.span; switch (inst.op) { .@"const", .trap => {}, - .copy => |v| if (!fc.typeOf(v).isValue()) try fc.c.report("E1001", span, "only value types can be copied", &.{ + .copy => |v| if (!fc.typeOf(v).isValue() or m.isLinearType(fc.typeOf(v))) try fc.c.report("E1001", span, "only value types can be copied", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } }, }), - .local_alloc, .slice_len => {}, + .local_alloc => |t| if (m.isLinearType(t)) try fc.c.report("E1001", span, "frame storage requires Copy content", &.{}), + .slice_len => {}, .local_store => |x| { const t = fc.typeOf(x.local); if (t != .local) return fc.kindError(span, x.local, "local"); @@ -789,7 +805,9 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { .{ .name = "found", .value = .{ .str = try fc.c.typeName(t.local.*) } }, }); }, - .local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local"), + .local_load => |v| { + if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local"); + }, .borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local, a resource, ref, mut, slice or slice_mut"), .borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local, a resource, mut or slice_mut"), .borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"), @@ -797,12 +815,38 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { .load => |v| { if (atomicPointee(fc.typeOf(v))) return ordinaryAtomicAccess(fc, span, v, "atomic.load"); if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref or mut"); + if (m.isLinearType(resultOf(fc, inst))) try fc.c.report("E1001", span, "load cannot copy linear content; exchange or unpack", &.{}); }, .store => |x| { const t = fc.typeOf(x.borrow); if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic.store"); if (t != .mut) return fc.kindError(span, x.borrow, "mut"); try fc.expectValue(span, x.value, t.mut.*); + if (m.isLinearType(t.mut.*)) try fc.c.report("E1001", span, "store cannot overwrite linear content; use value.swap", &.{}); + }, + .value_swap => |x| { + const t = fc.typeOf(x.borrow); + if (atomicPointee(t)) return ordinaryAtomicAccess(fc, span, x.borrow, "atomic operations"); + if (t != .mut) return fc.kindError(span, x.borrow, "mut"); + try fc.expectValue(span, x.value, t.mut.*); + if (!complete(t.mut.*)) try fc.kindError(span, x.value, "a complete value"); + }, + .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", &.{}); + for (x.args) |arg| try fc.expectValue(span, arg, x.ty.array.elem); + }, + .aggregate_unpack => |x| { + try fc.expectValue(span, x.value, x.ty); + switch (x.ty) { + .array => |a| for (f.blocks[x.next].params) |p| { + if (!p.ty.eql(a.elem)) try fc.mismatch(span, try fc.c.valueName(f, p.value), a.elem, p.ty); + }, + .named => |i| if (m.types[i].kind == .@"struct") { + for (f.blocks[x.next].params, m.types[i].kind.@"struct") |p, field| if (!p.ty.eql(field.ty)) try fc.mismatch(span, try fc.c.valueName(f, p.value), field.ty, p.ty); + } else try fc.c.report("E1001", span, "unpack requires a struct or array", &.{}), + else => try fc.c.report("E1001", span, "unpack requires a struct or array", &.{}), + } }, .array_splat => |x| { if (x.ty != .array) return fc.c.report("E1001", span, "array.splat needs an array type", &.{ @@ -810,6 +854,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { .{ .name = "found", .value = .{ .str = try fc.c.typeName(x.ty) } }, }); try fc.expectValue(span, x.value, x.ty.array.elem); + if (m.isLinearType(x.ty.array.elem)) try fc.c.report("E1001", span, "array.splat cannot duplicate linear elements", &.{}); }, .borrow_index => |x| { if (resultOf(fc, inst) == .void) return fc.kindError(span, x.borrow, "a borrow of an array, or a slice"); @@ -827,6 +872,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { }, .slice_copy => |x| { const d = fc.typeOf(x.dst); + if (d == .slice_mut and m.isLinearType(d.inner().?)) return fc.c.report("E1001", span, "slice.copy cannot copy linear elements", &.{}); if (d != .slice_mut) return fc.kindError(span, x.dst, "slice_mut"); const s = fc.typeOf(x.src); if (!s.isSlice() or !s.inner().?.eql(d.inner().?)) return fc.kindError(span, x.src, try std.fmt.allocPrint(fc.c.arena, "slice<{s}> or slice_mut<{s}>", .{ try fc.c.typeName(d.inner().?), try fc.c.typeName(d.inner().?) })); @@ -859,7 +905,10 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { for (fields, tys) |fld, *t| t.* = fld.ty; try fc.expectArgs(span, x.args, tys); }, - .struct_get => |x| try fc.expectValue(span, x.a, .{ .named = x.decl }), + .struct_get => |x| { + try fc.expectValue(span, x.a, .{ .named = x.decl }); + if (m.isLinearType(m.types[x.decl].kind.@"struct"[x.field].ty)) try fc.c.report("E1001", span, "linear fields require whole unpack or borrowed exchange", &.{}); + }, .enum_make => |x| try fc.expectArgs(span, x.args, m.types[x.decl].kind.@"enum"[x.variant].payload), .call => |x| { const callee = m.functions[x.callee]; @@ -889,7 +938,9 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { for (x.cases) |case| try fc.expectTarget(case.span, case.target); try fc.expectTarget(span, x.default); }, - .enum_switch => |x| { + inline .enum_switch, .enum_take => |x| { + if (inst.op == .enum_take and x.ty != .named) try fc.c.report("E1001", span, "enum.take requires a declared enum", &.{}); + if (inst.op == .enum_switch and m.isLinearType(x.ty)) try fc.c.report("E1001", span, "linear enums require enum.take", &.{}); try fc.expectValue(span, x.value, x.ty); for (x.arms) |arm| { const params = f.blocks[arm.block].params; @@ -900,21 +951,32 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { if (x.default) |d| try fc.expectTarget(span, d); }, .intrinsic => |x| try checkIntrinsic(fc, inst, x), + .own_pack => |x| { + try fc.expectAllocCap(span, x.cap); + try fc.expectValue(span, x.value, x.ty); + if (!complete(x.ty)) return fc.kindError(span, x.value, "a complete value"); + try fc.expectParams(span, x.ok, &.{.{ .own = try boxed(fc.c.arena, x.ty) }}); + try fc.expectParams(span, x.err, &.{ .{ .builtin = .alloc_error }, x.ty }); + }, .own_new => |x| { try fc.expectAllocCap(span, x.cap); const t = fc.typeOf(x.value); - if (!t.isValue()) return fc.kindError(span, x.value, "a value type"); + if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .own = try boxed(fc.c.arena, t) }); }, .own_array => |x| { try fc.expectValue(span, x.n, .{ .int = .usize }); try fc.expectAllocCap(span, x.cap); const t = fc.typeOf(x.value); - if (!t.isValue()) return fc.kindError(span, x.value, "a value type"); + if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .own_array = try boxed(fc.c.arena, t) }); }, .own_take => |v| if (fc.typeOf(v) != .own) try fc.kindError(span, v, "own"), - .own_free => |v| if (fc.typeOf(v) != .own and fc.typeOf(v) != .own_array) try fc.kindError(span, v, "own or own_array"), + .own_free => |v| { + const t = fc.typeOf(v); + if (t != .own and t != .own_array) return fc.kindError(span, v, "own or own_array"); + if (m.isLinearType(t.inner().?)) try fc.c.report("E1001", span, "own.free cannot destroy linear content; use own.take", &.{}); + }, .region_create => |x| { try fc.expectAllocCap(span, x.cap); try fc.expectOkErr(span, x.ok, x.err, .region); @@ -922,14 +984,14 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { .region_new => |x| { try fc.expectRegionRef(span, x.region); const t = fc.typeOf(x.value); - if (!t.isValue()) return fc.kindError(span, x.value, "a value type"); + if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .mut = try boxed(fc.c.arena, t) }); }, .region_array => |x| { try fc.expectRegionRef(span, x.region); try fc.expectValue(span, x.n, .{ .int = .usize }); const t = fc.typeOf(x.value); - if (!t.isValue()) return fc.kindError(span, x.value, "a value type"); + if (!t.isValue() or m.isLinearType(t)) return fc.kindError(span, x.value, "a Copy value type"); try fc.expectOkErr(span, x.ok, x.err, .{ .slice_mut = try boxed(fc.c.arena, t) }); }, .region_reset, .region_destroy => |v| if (fc.typeOf(v) != .region) try fc.kindError(span, v, "region"), diff --git a/std/README.md b/std/README.md index f4fee31..2f15da7 100644 --- a/std/README.md +++ b/std/README.md @@ -1,6 +1,6 @@ # Aji standard library -Implementation in ordinary safe `.aji`: bytes, math, UTF-8, hex, Base64 and integer formatting, with 39 monomorphic functions, 14 monomorphic result enums and Copy option/result templates with two generic helpers. They are embedded with the compiler and compiled through the normal frontend/verifier when imported. They are library modules, not standalone `main` programs. +Implementation in ordinary safe `.aji`: bytes, math, UTF-8, hex, Base64 and integer formatting, with 39 monomorphic functions, 14 monomorphic result enums and option/result templates with two Copy classification helpers. They are embedded with the compiler and compiled through the normal frontend/verifier when imported. They are library modules, not standalone `main` programs. ```aji module example @@ -27,10 +27,12 @@ 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 Copy option/result templates are implemented; owning collections still require linear_aggregates. +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. [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) [Formatting RFC](../docs/rfcs/0020-supplied-buffer-integer-formatting.md) -`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/borrows are excluded by the Copy constraint. +`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. diff --git a/std/option.aji b/std/option.aji index 5d68197..b29d719 100644 --- a/std/option.aji +++ b/std/option.aji @@ -1,6 +1,6 @@ module std.option -enum Option { some(T), none } +enum Option { some(T), none } fn is_some(value: Option) -> bool effects [] diff --git a/std/result.aji b/std/result.aji index 6678564..d31bc63 100644 --- a/std/result.aji +++ b/std/result.aji @@ -1,6 +1,6 @@ module std.result -enum Result { ok(T), err(E) } +enum Result { ok(T), err(E) } fn is_ok(value: Result) -> bool effects [] diff --git a/tests/conformance/linear/array_count.air b/tests/conformance/linear/array_count.air new file mode 100644 index 0000000..37ab316 --- /dev/null +++ b/tests/conformance/linear/array_count.air @@ -0,0 +1,12 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +fn @bad(%owner: own) -> void +effects [] +entry: + %items = array.make array,2>(%owner) + trap diff --git a/tests/conformance/linear/borrow_array.air b/tests/conformance/linear/borrow_array.air new file mode 100644 index 0000000..8526e2e --- /dev/null +++ b/tests/conformance/linear/borrow_array.air @@ -0,0 +1,12 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [arrays, capabilities, effects, linear_aggregates, ownership, resources] +fn @f(%r: ref) -> void +effects [] +entry: + %bad = array.make array, 1>(%r) + ret diff --git a/tests/conformance/linear/builtin_take.air b/tests/conformance/linear/builtin_take.air new file mode 100644 index 0000000..bdc9c9f --- /dev/null +++ b/tests/conformance/linear/builtin_take.air @@ -0,0 +1,13 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear + air 0 + lang 0.1 + features [capabilities, effects, heap, linear_aggregates, ownership, resources] +fn @bad(%error: alloc_error) -> void +effects [] +entry: + enum.take alloc_error %error, budget_exceeded -> @done, out_of_memory -> @done +done: + ret diff --git a/tests/conformance/linear/copy.air b/tests/conformance/linear/copy.air new file mode 100644 index 0000000..bfb250f --- /dev/null +++ b/tests/conformance/linear/copy.air @@ -0,0 +1,23 @@ +; expect: reject E1001 +; grant: heap=mem.alloc:64 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Pair = struct { value: own, tag: u64 } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %record = struct.make @Pair(%owner, %n) + %duplicate = copy %record + struct.unpack @Pair %record, next -> @parts +parts(%part: own, %tag: u64): + %answer = own.take %part + ret %answer +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/enum_incomplete.air b/tests/conformance/linear/enum_incomplete.air new file mode 100644 index 0000000..167eb5f --- /dev/null +++ b/tests/conformance/linear/enum_incomplete.air @@ -0,0 +1,35 @@ +; expect: reject E5002 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Maybe = enum { some(own), none } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %items = array.make array,1>(%owner) + array.unpack array,1> %items, next -> @element +element(%part: own): + %slot = enum.make @Maybe.some(%part) + %empty = enum.make @Maybe.none() + %borrow = borrow.mut %slot + %old = value.swap %borrow, %empty + borrow.end %borrow + enum.take @Maybe %slot, some -> @extra +extra(%extra_owner: own): + own.free %extra_owner + enum.take @Maybe %old, some -> @answer, none -> @no_answer +replaced: + enum.take @Maybe %old, some -> @answer, none -> @no_answer +answer(%answer_owner: own): + %value = own.take %answer_owner + ret %value +no_answer: + ret %n +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/enum_switch.air b/tests/conformance/linear/enum_switch.air new file mode 100644 index 0000000..63475f1 --- /dev/null +++ b/tests/conformance/linear/enum_switch.air @@ -0,0 +1,35 @@ +; expect: reject E1001 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Maybe = enum { some(own), none } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %items = array.make array,1>(%owner) + array.unpack array,1> %items, next -> @element +element(%part: own): + %slot = enum.make @Maybe.some(%part) + %empty = enum.make @Maybe.none() + %borrow = borrow.mut %slot + %old = value.swap %borrow, %empty + borrow.end %borrow + enum.switch @Maybe %slot, some -> @extra, none -> @replaced +extra(%extra_owner: own): + own.free %extra_owner + enum.take @Maybe %old, some -> @answer, none -> @no_answer +replaced: + enum.take @Maybe %old, some -> @answer, none -> @no_answer +answer(%answer_owner: own): + %value = own.take %answer_owner + ret %value +no_answer: + ret %n +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/exchange.air b/tests/conformance/linear/exchange.air new file mode 100644 index 0000000..d4adcb5 --- /dev/null +++ b/tests/conformance/linear/exchange.air @@ -0,0 +1,37 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:64 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Maybe = enum { some(own), none } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %items = array.make array,1>(%owner) + array.unpack array,1> %items, next -> @element +element(%part: own): + %slot = enum.make @Maybe.some(%part) + %empty = enum.make @Maybe.none() + %borrow = borrow.mut %slot + %old = value.swap %borrow, %empty + borrow.end %borrow + enum.take @Maybe %slot, some -> @extra, none -> @replaced +extra(%extra_owner: own): + own.free %extra_owner + enum.take @Maybe %old, some -> @answer, none -> @no_answer +replaced: + enum.take @Maybe %old, some -> @answer, none -> @no_answer +answer(%answer_owner: own): + %value = own.take %answer_owner + ret %value +no_answer: + ret %n +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/field.air b/tests/conformance/linear/field.air new file mode 100644 index 0000000..3ed7c0b --- /dev/null +++ b/tests/conformance/linear/field.air @@ -0,0 +1,23 @@ +; expect: reject E1001 +; grant: heap=mem.alloc:64 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Pair = struct { value: own, tag: u64 } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %record = struct.make @Pair(%owner, %n) + %bad = struct.get @Pair.value, %record + struct.unpack @Pair %record, next -> @parts +parts(%part: own, %tag: u64): + %answer = own.take %part + ret %answer +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/leak.air b/tests/conformance/linear/leak.air new file mode 100644 index 0000000..5ab5081 --- /dev/null +++ b/tests/conformance/linear/leak.air @@ -0,0 +1,21 @@ +; expect: reject E3002 +; grant: heap=mem.alloc:64 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Pair = struct { value: own, tag: u64 } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %record = struct.make @Pair(%owner, %n) + struct.unpack @Pair %record, next -> @parts +parts(%part: own, %tag: u64): + ret %tag +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/owner_copy_array.air b/tests/conformance/linear/owner_copy_array.air new file mode 100644 index 0000000..c99de2e --- /dev/null +++ b/tests/conformance/linear/owner_copy_array.air @@ -0,0 +1,28 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:8 +; phase: 6 +; spec: docs/spec/03-memory-model.md §13 +module test.linear_compat + air 0 + lang 0.1 + features [arrays, capabilities, effects, heap, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + %array = array.splat array %n + own.new %array, %heap, ok -> @got, err -> @failed +got(%owner: own>): + %borrow = borrow.mut %owner + %slice = slice.make %borrow + %zero = const.usize 0 + %element = borrow.index %slice, %zero + %answer = load %element + borrow.end %element + borrow.end %slice + borrow.end %borrow + own.free %owner + ret %answer +failed(%error: alloc_error): + ret %n diff --git a/tests/conformance/linear/pack.air b/tests/conformance/linear/pack.air new file mode 100644 index 0000000..5bb7162 --- /dev/null +++ b/tests/conformance/linear/pack.air @@ -0,0 +1,25 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:64 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [capabilities, effects, heap, linear_aggregates, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + own.pack own %owner, %heap, ok -> @packed, err -> @back +packed(%outer: own>): + %inner = own.take %outer + %answer = own.take %inner + ret %answer +back(%error: alloc_error, %original: own): + %answer2 = own.take %original + ret %answer2 +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/pack_failure.air b/tests/conformance/linear/pack_failure.air new file mode 100644 index 0000000..b9300e6 --- /dev/null +++ b/tests/conformance/linear/pack_failure.air @@ -0,0 +1,25 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:8 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [capabilities, effects, heap, linear_aggregates, ownership, resources] +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + own.pack own %owner, %heap, ok -> @packed, err -> @back +packed(%outer: own>): + %inner = own.take %outer + %answer = own.take %inner + ret %answer +back(%error: alloc_error, %original: own): + %answer2 = own.take %original + ret %answer2 +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/struct.air b/tests/conformance/linear/struct.air new file mode 100644 index 0000000..94a1289 --- /dev/null +++ b/tests/conformance/linear/struct.air @@ -0,0 +1,23 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:64 +; phase: 6 +; spec: docs/spec/03-memory-model.md §25 +module test.linear +air 0 +lang 0.1 +features [capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Pair = struct { value: own, tag: u64 } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %record = struct.make @Pair(%owner, %n) + struct.unpack @Pair %record, next -> @parts +parts(%part: own, %tag: u64): + %answer = own.take %part + ret %answer +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/swap_leak.air b/tests/conformance/linear/swap_leak.air new file mode 100644 index 0000000..a0b00e6 --- /dev/null +++ b/tests/conformance/linear/swap_leak.air @@ -0,0 +1,35 @@ +; expect: reject E3002 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Maybe = enum { some(own), none } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %items = array.make array,1>(%owner) + array.unpack array,1> %items, next -> @element +element(%part: own): + %slot = enum.make @Maybe.some(%part) + %empty = enum.make @Maybe.none() + %borrow = borrow.mut %slot + %old = value.swap %borrow, %empty + borrow.end %borrow + enum.take @Maybe %slot, some -> @extra, none -> @replaced +extra(%extra_owner: own): + own.free %extra_owner + enum.take @Maybe %old, some -> @answer, none -> @no_answer +replaced: + ret %n +answer(%answer_owner: own): + %value = own.take %answer_owner + ret %value +no_answer: + ret %n +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/unpack_count.air b/tests/conformance/linear/unpack_count.air new file mode 100644 index 0000000..ee06a91 --- /dev/null +++ b/tests/conformance/linear/unpack_count.air @@ -0,0 +1,35 @@ +; expect: reject E5002 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] +type @Maybe = enum { some(own), none } +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %n = const.u64 42 + own.new %n, %heap, ok -> @got, err -> @failed +got(%owner: own): + %items = array.make array,1>(%owner) + array.unpack array,1> %items, next -> @element +element(%part: own, %other: u64): + %slot = enum.make @Maybe.some(%part) + %empty = enum.make @Maybe.none() + %borrow = borrow.mut %slot + %old = value.swap %borrow, %empty + borrow.end %borrow + enum.take @Maybe %slot, some -> @extra, none -> @replaced +extra(%extra_owner: own): + own.free %extra_owner + enum.take @Maybe %old, some -> @answer, none -> @no_answer +replaced: + enum.take @Maybe %old, some -> @answer, none -> @no_answer +answer(%answer_owner: own): + %value = own.take %answer_owner + ret %value +no_answer: + ret %n +failed(%e: alloc_error): + ret %n diff --git a/tests/conformance/linear/without_feature.air b/tests/conformance/linear/without_feature.air new file mode 100644 index 0000000..18e9ee4 --- /dev/null +++ b/tests/conformance/linear/without_feature.air @@ -0,0 +1,13 @@ +; expect: reject E0006 +; phase: 6 +; spec: docs/spec/07a-air-instructions.md Linear aggregates +module test.linear + air 0 + lang 0.1 + features [arrays, ownership] +fn @main() -> u64 +effects [] +entry: + %n = const.u64 42 + %items = array.make array(%n) + ret %n diff --git a/tests/conformance/source/generics/linear_aggregate.aji b/tests/conformance/source/generics/linear_aggregate.aji index 4f7c501..fb420f1 100644 --- a/tests/conformance/source/generics/linear_aggregate.aji +++ b/tests/conformance/source/generics/linear_aggregate.aji @@ -1,4 +1,4 @@ -// expect: reject E0006 +// expect: reject E3002 // phase: 6 // spec: docs/spec/15-source-language.md §15 module demo.generic diff --git a/tests/conformance/source/generics/nested_owner_argument.aji b/tests/conformance/source/generics/nested_owner_argument.aji index 7b96e96..6517fcf 100644 --- a/tests/conformance/source/generics/nested_owner_argument.aji +++ b/tests/conformance/source/generics/nested_owner_argument.aji @@ -1,4 +1,5 @@ -// expect: reject E7005 +// expect: run +// result: 42 // phase: 6 // spec: docs/spec/15-source-language.md §15 module demo.generic diff --git a/tests/conformance/source/generics/std_option_owner.aji b/tests/conformance/source/generics/std_option_owner.aji index a572fd5..1b9b3e4 100644 --- a/tests/conformance/source/generics/std_option_owner.aji +++ b/tests/conformance/source/generics/std_option_owner.aji @@ -3,5 +3,5 @@ // spec: docs/spec/15-source-language.md §15 module demo.generic import std.option; -fn unused(value: std.option.Option>) -> u64 effects [] { return 42; } +fn unused(value: std.option.Option>) -> u64 effects [] { return std.option.is_some::>(move value); } fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/generics/std_result_borrow.aji b/tests/conformance/source/generics/std_result_borrow.aji index 8c41816..18784bf 100644 --- a/tests/conformance/source/generics/std_result_borrow.aji +++ b/tests/conformance/source/generics/std_result_borrow.aji @@ -1,4 +1,4 @@ -// expect: reject E7005 +// expect: reject E1001 // phase: 6 // spec: docs/spec/15-source-language.md §15 module demo.generic diff --git a/tests/conformance/source/linear/array.aji b/tests/conformance/source/linear/array.aji new file mode 100644 index 0000000..9d894f0 --- /dev/null +++ b/tests/conformance/source/linear/array.aji @@ -0,0 +1,13 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let a = own.new(20u64, heap) or trap; + let b = own.new(22u64, heap) or trap; + let data = [move a, move b]; + let (left, right) = array.unpack(move data); + return own.take(move left) + own.take(move right); +} diff --git a/tests/conformance/source/linear/array_duplicate.aji b/tests/conformance/source/linear/array_duplicate.aji new file mode 100644 index 0000000..7e1ec90 --- /dev/null +++ b/tests/conformance/source/linear/array_duplicate.aji @@ -0,0 +1,13 @@ +// expect: reject E2002 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let a = own.new(20u64, heap) or trap; + let b = own.new(22u64, heap) or trap; + own.free(move b); + let data = [move a, move a]; + let (left, right) = array.unpack(move data); + return own.take(move left) + own.take(move right); +} diff --git a/tests/conformance/source/linear/atomic.aji b/tests/conformance/source/linear/atomic.aji new file mode 100644 index 0000000..2ce441d --- /dev/null +++ b/tests/conformance/source/linear/atomic.aji @@ -0,0 +1,11 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Cell { cell: atomic } +fn main() -> u64 effects [] { + let cell = atomic.new(42u64); + let value = Cell { cell: move cell }; + let (part) = struct.unpack(move value); return atomic.take(move part); +} diff --git a/tests/conformance/source/linear/borrow_conflict.aji b/tests/conformance/source/linear/borrow_conflict.aji new file mode 100644 index 0000000..394bbeb --- /dev/null +++ b/tests/conformance/source/linear/borrow_conflict.aji @@ -0,0 +1,14 @@ +// expect: reject E2101 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: move owner, tag: 1u64 }; + ref borrowed = record; + let (part, tag) = struct.unpack(move record); + assert(tag == 1); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/borrowed_atomic_swap.aji b/tests/conformance/source/linear/borrowed_atomic_swap.aji new file mode 100644 index 0000000..5b3de00 --- /dev/null +++ b/tests/conformance/source/linear/borrowed_atomic_swap.aji @@ -0,0 +1,7 @@ +// expect: reject E4202 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +struct Cell { cell: atomic } +fn change(value: mut, replacement: atomic) -> atomic effects [] { return value.swap(mut value.cell, move replacement); } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/linear/channel.aji b/tests/conformance/source/linear/channel.aji new file mode 100644 index 0000000..946ffd8 --- /dev/null +++ b/tests/conformance/source/linear/channel.aji @@ -0,0 +1,22 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:128 +// schedules: 8 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +struct Item { owner: own } +fn main(heap: cap) -> u64 effects [mem.alloc, task.wait] { + match channel.make(1, heap) { + ok(tx, rx) => { + let owner = own.new(42u64, heap) or trap; + channel.send(tx, Item { owner: move owner }) or trap; + let value = channel.recv(rx) or trap; + channel.close_sender(move tx); + channel.close_receiver(move rx) or trap; + let (part) = struct.unpack(move value); + return own.take(move part); + } + err(error) => { return 42; } + } +} diff --git a/tests/conformance/source/linear/copy_borrowed.aji b/tests/conformance/source/linear/copy_borrowed.aji new file mode 100644 index 0000000..7219046 --- /dev/null +++ b/tests/conformance/source/linear/copy_borrowed.aji @@ -0,0 +1,7 @@ +// expect: reject E1001 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Item { owner: own } +fn peek(value: ref) -> Item effects [] { return *value; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/layer5/reject/linear_field.aji b/tests/conformance/source/linear/declared_owner.aji similarity index 54% rename from tests/conformance/source/layer5/reject/linear_field.aji rename to tests/conformance/source/linear/declared_owner.aji index 3daa9c9..b7cd1e1 100644 --- a/tests/conformance/source/layer5/reject/linear_field.aji +++ b/tests/conformance/source/linear/declared_owner.aji @@ -1,5 +1,6 @@ -// A struct with a linear field needs the unpublished linear_aggregates feature: AIR rejects it. -// expect: reject E0006 +// A declared owner field is accepted under the frontend-declared linear_aggregates feature. +// expect: run +// result: 0 // phase: 6 // spec: docs/spec/15-source-language.md module demo.linearfield diff --git a/tests/conformance/source/linear/enum.aji b/tests/conformance/source/linear/enum.aji new file mode 100644 index 0000000..1d1ccf9 --- /dev/null +++ b/tests/conformance/source/linear/enum.aji @@ -0,0 +1,15 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +enum Maybe { some(T), none } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let value = Maybe::>::some(move owner); + match move value { + Maybe::>::some(part) => { return own.take(move part); } + Maybe::>::none => { return 0; } + } +} diff --git a/tests/conformance/source/linear/enum_ignored_payload.aji b/tests/conformance/source/linear/enum_ignored_payload.aji new file mode 100644 index 0000000..fb85c26 --- /dev/null +++ b/tests/conformance/source/linear/enum_ignored_payload.aji @@ -0,0 +1,16 @@ +// expect: reject E3002 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +enum Maybe { some(T), none } +fn replace(value: mut>>) -> Maybe> effects [] { + return value.swap(mut value, Maybe::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + var value: Maybe> = Maybe::>::some(move owner); + let old = replace(mut value); + match move value { Maybe::>::none => {}, Maybe::>::some(extra) => { own.free(move extra); } } + match move old { Maybe::>::some(_) => { return 42; } Maybe::>::none => { return 0; } } +} diff --git a/tests/conformance/source/linear/file.aji b/tests/conformance/source/linear/file.aji new file mode 100644 index 0000000..9bcef6b --- /dev/null +++ b/tests/conformance/source/linear/file.aji @@ -0,0 +1,23 @@ +// expect: run +// result: 42 +// grant: fs=fs.read:/in +// vfs: /in/data=x +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +struct Input { file: file } +fn main(fs: cap) -> u64 effects [fs.read] { + let file = fs.open_read(fs, b"/in/data") or trap; + let value = Input { file: move file }; + var bytes: [u8; 1] = zero; + { + mut input = value; + mut file = input.file; + let count = fs.read(file, mut bytes) or trap; + assert(count == 1); + assert(bytes[0] == 120); + } + let (file) = struct.unpack(move value); + fs.close(move file) or trap; + return 42; +} diff --git a/tests/conformance/source/linear/fixed_heap_array.aji b/tests/conformance/source/linear/fixed_heap_array.aji new file mode 100644 index 0000000..c76a0e1 --- /dev/null +++ b/tests/conformance/source/linear/fixed_heap_array.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let a = own.new(20u64, heap) or trap; + let b = own.new(22u64, heap) or trap; + let storage = own.pack([move a, move b], heap) or trap; + let data = own.take(move storage); + let (left, right) = array.unpack(move data); + return own.take(move left) + own.take(move right); +} diff --git a/tests/conformance/source/linear/free_linear_content.aji b/tests/conformance/source/linear/free_linear_content.aji new file mode 100644 index 0000000..5608698 --- /dev/null +++ b/tests/conformance/source/linear/free_linear_content.aji @@ -0,0 +1,6 @@ +// expect: reject E1001 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { let owner = own.new(42u64, heap) or trap; let outer = own.pack(move owner, heap) or trap; own.free(move outer); return 42; } diff --git a/tests/conformance/source/linear/graph.aji b/tests/conformance/source/linear/graph.aji new file mode 100644 index 0000000..8bcc65f --- /dev/null +++ b/tests/conformance/source/linear/graph.aji @@ -0,0 +1,27 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +struct Shared { graph: arc } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let graph = arc.new(42u64, heap) or trap; + let value = Shared { graph: move graph }; + { + ref shared = value; + ref graph = shared.graph; + let cloned = arc.clone(graph); + arc.release(move cloned); + } + let (graph) = struct.unpack(move value); + var result: u64 = 0; + { + ref shared = graph; + let root = arc.root(shared); + ref number = arc.at(shared, root); + result = *number; + } + arc.release(move graph); + return result; +} diff --git a/tests/conformance/source/linear/guard_member.aji b/tests/conformance/source/linear/guard_member.aji new file mode 100644 index 0000000..b47c42f --- /dev/null +++ b/tests/conformance/source/linear/guard_member.aji @@ -0,0 +1,6 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Item { guard: guard } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/linear/heap_array_borrow.aji b/tests/conformance/source/linear/heap_array_borrow.aji new file mode 100644 index 0000000..032785e --- /dev/null +++ b/tests/conformance/source/linear/heap_array_borrow.aji @@ -0,0 +1,16 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let a = own.new(20u64, heap) or trap; let b = own.new(22u64, heap) or trap; + let c = own.new(99u64, heap) or trap; + let storage = own.pack([move a, move b], heap) or trap; + let previous = value.swap(mut storage[0], move c); + let data = own.take(move storage); + let (replacement, second) = array.unpack(move data); + own.free(move replacement); + return own.take(move previous) + own.take(move second); +} diff --git a/tests/conformance/source/linear/ignored_field.aji b/tests/conformance/source/linear/ignored_field.aji new file mode 100644 index 0000000..cf377c4 --- /dev/null +++ b/tests/conformance/source/linear/ignored_field.aji @@ -0,0 +1,13 @@ +// expect: reject E3002 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: move owner, tag: 1u64 }; + let (_, tag) = struct.unpack(move record); + assert(tag == 1); + return 42; +} diff --git a/tests/conformance/source/linear/linear_projection.aji b/tests/conformance/source/linear/linear_projection.aji new file mode 100644 index 0000000..3459b42 --- /dev/null +++ b/tests/conformance/source/linear/linear_projection.aji @@ -0,0 +1,14 @@ +// expect: reject E1001 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: move owner, tag: 1u64 }; + let bad = record.value; + let (part, tag) = struct.unpack(move record); + assert(tag == 1); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/linear_region_allocation.aji b/tests/conformance/source/linear/linear_region_allocation.aji new file mode 100644 index 0000000..0a3ff8e --- /dev/null +++ b/tests/conformance/source/linear/linear_region_allocation.aji @@ -0,0 +1,7 @@ +// expect: reject E1001 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Item { owner: own } +fn main(heap: cap) -> u64 effects [mem.alloc] { let owner = own.new(42u64, heap) or trap; let arena = region.create(heap) or trap; ref r = arena; let pointer = region.new(r, Item { owner: move owner }) or trap; return 42; } diff --git a/tests/conformance/source/linear/missing_move.aji b/tests/conformance/source/linear/missing_move.aji new file mode 100644 index 0000000..64e9cd8 --- /dev/null +++ b/tests/conformance/source/linear/missing_move.aji @@ -0,0 +1,13 @@ +// expect: reject E7003 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: owner, tag: 1u64 }; + let (part, tag) = struct.unpack(move record); + assert(tag == 1); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/mutex.aji b/tests/conformance/source/linear/mutex.aji new file mode 100644 index 0000000..7081ee0 --- /dev/null +++ b/tests/conformance/source/linear/mutex.aji @@ -0,0 +1,13 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +struct Item { mutex: mutex } +fn main() -> u64 effects [task.wait] { + let mutex = mutex.make(20u64); + let value = Item { mutex: move mutex }; + { ref r = value; ref m = r.mutex; lock ref m as data { *data = 42; } cancelled { trap; } } + let (mutex) = struct.unpack(move value); + return mutex.take(move mutex); +} diff --git a/tests/conformance/source/linear/none_leak.aji b/tests/conformance/source/linear/none_leak.aji new file mode 100644 index 0000000..63ebeb8 --- /dev/null +++ b/tests/conformance/source/linear/none_leak.aji @@ -0,0 +1,9 @@ +// expect: reject E3002 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +import std.option; +fn main() -> u64 effects [] { + let value = std.option.Option::>::none; + return 42; +} diff --git a/tests/conformance/source/linear/pack.aji b/tests/conformance/source/linear/pack.aji new file mode 100644 index 0000000..50f53b2 --- /dev/null +++ b/tests/conformance/source/linear/pack.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// equivalent: linear/pack.air +// spec: docs/spec/03-memory-model.md §25 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + match own.pack(move owner, heap) { + ok(outer) => { let inner = own.take(move outer); return own.take(move inner); } + err(error, returned) => { return own.take(move returned); } + } +} diff --git a/tests/conformance/source/linear/pack_failure.aji b/tests/conformance/source/linear/pack_failure.aji new file mode 100644 index 0000000..6cca330 --- /dev/null +++ b/tests/conformance/source/linear/pack_failure.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:8 +// phase: 6 +// equivalent: linear/pack_failure.air +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + match own.pack(move owner, heap) { + ok(outer) => { let inner = own.take(move outer); return own.take(move inner); } + err(error, returned) => { return own.take(move returned); } + } +} diff --git a/tests/conformance/source/linear/pack_failure_leak.aji b/tests/conformance/source/linear/pack_failure_leak.aji new file mode 100644 index 0000000..62f2d30 --- /dev/null +++ b/tests/conformance/source/linear/pack_failure_leak.aji @@ -0,0 +1,12 @@ +// expect: reject E3002 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + match own.pack(move owner, heap) { + ok(outer) => { let inner = own.take(move outer); return own.take(move inner); } + err(error, _) => { return 0; } + } +} diff --git a/tests/conformance/source/linear/plain_enum_match.aji b/tests/conformance/source/linear/plain_enum_match.aji new file mode 100644 index 0000000..0924978 --- /dev/null +++ b/tests/conformance/source/linear/plain_enum_match.aji @@ -0,0 +1,16 @@ +// expect: reject E7003 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +enum Maybe { some(T), none } +fn replace(value: mut>>) -> Maybe> effects [] { + return value.swap(mut value, Maybe::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + var value: Maybe> = Maybe::>::some(move owner); + let old = replace(mut value); + match move value { Maybe::>::none => {}, Maybe::>::some(extra) => { own.free(move extra); } } + match old { Maybe::>::some(part) => { return own.take(move part); } Maybe::>::none => { return 0; } } +} diff --git a/tests/conformance/source/linear/recursive_ownership.aji b/tests/conformance/source/linear/recursive_ownership.aji new file mode 100644 index 0000000..dca1aad --- /dev/null +++ b/tests/conformance/source/linear/recursive_ownership.aji @@ -0,0 +1,6 @@ +// expect: reject E1003 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Node { next: own } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/linear/region.aji b/tests/conformance/source/linear/region.aji new file mode 100644 index 0000000..f12a240 --- /dev/null +++ b/tests/conformance/source/linear/region.aji @@ -0,0 +1,13 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Arena { region: region } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let region = region.create(heap) or trap; + let value = Arena { region: move region }; + let (part) = struct.unpack(move value); + region.destroy(move part); return 42; +} diff --git a/tests/conformance/source/linear/repeat.aji b/tests/conformance/source/linear/repeat.aji new file mode 100644 index 0000000..f93796e --- /dev/null +++ b/tests/conformance/source/linear/repeat.aji @@ -0,0 +1,15 @@ +// expect: reject E2002 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: move owner, tag: 1u64 }; + let (part, tag) = struct.unpack(move record); + let (again, _) = struct.unpack(move record); + own.free(move again); + assert(tag == 1); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/repeated_array.aji b/tests/conformance/source/linear/repeated_array.aji new file mode 100644 index 0000000..f77c1a5 --- /dev/null +++ b/tests/conformance/source/linear/repeated_array.aji @@ -0,0 +1,6 @@ +// expect: reject E1001 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { let owner = own.new(42u64, heap) or trap; let data = [move owner; 2]; let (a,b) = array.unpack(move data); own.free(move a); own.free(move b); return 42; } diff --git a/tests/conformance/source/linear/single_tuple.aji b/tests/conformance/source/linear/single_tuple.aji new file mode 100644 index 0000000..2d669d6 --- /dev/null +++ b/tests/conformance/source/linear/single_tuple.aji @@ -0,0 +1,5 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §16 +module test.linear +fn main() -> u64 effects [] { let (value) = 42u64; return value; } diff --git a/tests/conformance/source/linear/std_option.aji b/tests/conformance/source/linear/std_option.aji new file mode 100644 index 0000000..1111deb --- /dev/null +++ b/tests/conformance/source/linear/std_option.aji @@ -0,0 +1,17 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +import std.option; +fn replace(value: mut>>) -> std.option.Option> effects [] { + return value.swap(mut value, std.option.Option::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + var value: std.option.Option> = std.option.Option::>::some(move owner); + let old = replace(mut value); + match move value { std.option.Option::>::none => {}, std.option.Option::>::some(extra) => { own.free(move extra); } } + match move old { std.option.Option::>::some(part) => { return own.take(move part); } std.option.Option::>::none => { return 0; } } +} diff --git a/tests/conformance/source/linear/std_result.aji b/tests/conformance/source/linear/std_result.aji new file mode 100644 index 0000000..51f8d68 --- /dev/null +++ b/tests/conformance/source/linear/std_result.aji @@ -0,0 +1,13 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +import std.result; +fn pass(value: std.result.Result) -> std.result.Result effects [] { return move value; } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let result = pass::>(std.result.Result::, u64>::ok(move owner)); + match move result { std.result.Result::, u64>::ok(part) => { return own.take(move part); } std.result.Result::, u64>::err(error) => { return error; } } +} diff --git a/tests/conformance/source/linear/store_linear.aji b/tests/conformance/source/linear/store_linear.aji new file mode 100644 index 0000000..27f3e13 --- /dev/null +++ b/tests/conformance/source/linear/store_linear.aji @@ -0,0 +1,6 @@ +// expect: reject E1001 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn replace(value: mut>, replacement: own) -> void effects [] { *value = move replacement; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/linear/struct.aji b/tests/conformance/source/linear/struct.aji new file mode 100644 index 0000000..82737e2 --- /dev/null +++ b/tests/conformance/source/linear/struct.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: move owner, tag: 1u64 }; + let (part, tag) = struct.unpack(move record); + assert(tag == 1); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/swap.aji b/tests/conformance/source/linear/swap.aji new file mode 100644 index 0000000..0e6d672 --- /dev/null +++ b/tests/conformance/source/linear/swap.aji @@ -0,0 +1,17 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +enum Maybe { some(T), none } +fn replace(value: mut>>) -> Maybe> effects [] { + return value.swap(mut value, Maybe::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + var value: Maybe> = Maybe::>::some(move owner); + let old = replace(mut value); + match move value { Maybe::>::none => {}, Maybe::>::some(extra) => { own.free(move extra); } } + match move old { Maybe::>::some(part) => { return own.take(move part); } Maybe::>::none => { return 0; } } +} diff --git a/tests/conformance/source/linear/swap_array.aji b/tests/conformance/source/linear/swap_array.aji new file mode 100644 index 0000000..f27c0c6 --- /dev/null +++ b/tests/conformance/source/linear/swap_array.aji @@ -0,0 +1,15 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +fn main(heap: cap) -> u64 effects [mem.alloc] { + let a = own.new(20u64, heap) or trap; let b = own.new(22u64, heap) or trap; + let c = own.new(99u64, heap) or trap; + var data: [own; 2] = [move a, move b]; + let previous = value.swap(mut data[0], move c); + let (replacement, second) = array.unpack(move data); + own.free(move replacement); + return own.take(move previous) + own.take(move second); +} diff --git a/tests/conformance/source/linear/swap_heap.aji b/tests/conformance/source/linear/swap_heap.aji new file mode 100644 index 0000000..40f89d2 --- /dev/null +++ b/tests/conformance/source/linear/swap_heap.aji @@ -0,0 +1,18 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +enum Maybe { some(T), none } +fn replace(value: mut>>) -> Maybe> effects [] { + return value.swap(mut value, Maybe::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let storage = own.pack(Maybe::>::some(move owner), heap) or trap; + let old = replace(mut storage); + let value = own.take(move storage); + match move value { Maybe::>::none => {}, Maybe::>::some(extra) => { own.free(move extra); } } + match move old { Maybe::>::some(part) => { return own.take(move part); } Maybe::>::none => { return 0; } } +} diff --git a/tests/conformance/source/linear/swap_loop.aji b/tests/conformance/source/linear/swap_loop.aji new file mode 100644 index 0000000..23b9c79 --- /dev/null +++ b/tests/conformance/source/linear/swap_loop.aji @@ -0,0 +1,19 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:8 +// fuel: 1000000 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module test.linear +import std.option; +fn main(heap: cap) -> u64 effects [mem.alloc] { + var slot: std.option.Option> = std.option.Option::>::none; + for i in 0usize..1000usize { + let owner = own.new(42u64, heap) or trap; + let old = value.swap(mut slot, std.option.Option::>::some(move owner)); + match move old { std.option.Option::>::some(part) => { own.free(move part); } std.option.Option::>::none => {} } + let current = value.swap(mut slot, std.option.Option::>::none); + match move current { std.option.Option::>::some(part) => { own.free(move part); } std.option.Option::>::none => {} } + } + match move slot { std.option.Option::>::some(part) => { return own.take(move part); } std.option.Option::>::none => { return 42; } } +} diff --git a/tests/conformance/source/linear/swap_twice.aji b/tests/conformance/source/linear/swap_twice.aji new file mode 100644 index 0000000..62b403d --- /dev/null +++ b/tests/conformance/source/linear/swap_twice.aji @@ -0,0 +1,19 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +enum Maybe { some(T), none } +fn replace(value: mut>>) -> Maybe> effects [] { + return value.swap(mut value, Maybe::>::none); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + var value: Maybe> = Maybe::>::some(move owner); + let old = replace(mut value); + let empty = replace(mut value); + match move empty { Maybe::>::none => {}, Maybe::>::some(unexpected) => { own.free(move unexpected); } } + match move value { Maybe::>::none => {}, Maybe::>::some(extra) => { own.free(move extra); } } + match move old { Maybe::>::some(part) => { return own.take(move part); } Maybe::>::none => { return 0; } } +} diff --git a/tests/conformance/source/linear/task.aji b/tests/conformance/source/linear/task.aji new file mode 100644 index 0000000..ebb4ba1 --- /dev/null +++ b/tests/conformance/source/linear/task.aji @@ -0,0 +1,16 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// schedules: 8 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Payload { owner: own } +fn worker(value: Payload) -> u64 effects [] { let (part) = struct.unpack(move value); return own.take(move part); } +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + let owner = own.new(42u64, heap) or trap; + let value = Payload { owner: move owner }; + var result: u64 = 0; + scope s { let task = task.spawn(s, worker, move value); result = task.join(move task); } + return result; +} diff --git a/tests/conformance/source/linear/task_loan.aji b/tests/conformance/source/linear/task_loan.aji new file mode 100644 index 0000000..719159c --- /dev/null +++ b/tests/conformance/source/linear/task_loan.aji @@ -0,0 +1,24 @@ +// expect: reject E4101 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/04-concurrency-and-atomics.md §34 +module test.linear +struct Payload { owner: own } +fn worker(value: mut) -> void effects [] {} +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + let owner = own.new(42u64, heap) or trap; + var value: Payload = Payload { owner: move owner }; + let replacement_owner = own.new(42u64, heap) or trap; + let replacement = Payload { owner: move replacement_owner }; + { + mut borrowed = value; + scope s { + let task = task.spawn(s, worker, borrowed); + let old = value.swap(mut borrowed, move replacement); + let (part) = struct.unpack(move old); + own.free(move part); + task.join(move task); + } + } + let (part) = struct.unpack(move value); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/task_loan_join.aji b/tests/conformance/source/linear/task_loan_join.aji new file mode 100644 index 0000000..5880f55 --- /dev/null +++ b/tests/conformance/source/linear/task_loan_join.aji @@ -0,0 +1,27 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// schedules: 8 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/04-concurrency-and-atomics.md §34 +module test.linear +struct Payload { owner: own } +fn worker(value: mut) -> void effects [] {} +fn main(heap: cap) -> u64 effects [mem.alloc, task.spawn, task.wait] { + let owner = own.new(42u64, heap) or trap; + var value: Payload = Payload { owner: move owner }; + let replacement_owner = own.new(42u64, heap) or trap; + let replacement = Payload { owner: move replacement_owner }; + { + mut borrowed = value; + scope s { + let task = task.spawn(s, worker, borrowed); + task.join(move task); + let old = value.swap(mut borrowed, move replacement); + let (part) = struct.unpack(move old); + own.free(move part); + } + } + let (part) = struct.unpack(move value); + return own.take(move part); +} diff --git a/tests/conformance/source/linear/task_member.aji b/tests/conformance/source/linear/task_member.aji new file mode 100644 index 0000000..65a0c5d --- /dev/null +++ b/tests/conformance/source/linear/task_member.aji @@ -0,0 +1,6 @@ +// expect: reject E0006 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Item { task: task } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/linear/wrong_unpack_count.aji b/tests/conformance/source/linear/wrong_unpack_count.aji new file mode 100644 index 0000000..813c79c --- /dev/null +++ b/tests/conformance/source/linear/wrong_unpack_count.aji @@ -0,0 +1,13 @@ +// expect: reject E7005 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25; docs/spec/15-source-language.md §16 +module test.linear +struct Pair { value: own, tag: u64 } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let record = Pair { value: move owner, tag: 1u64 }; + let (part) = struct.unpack(move record); + assert(tag == 1); + return own.take(move part); +} diff --git a/tests/conformance/source/quickref/linear.aji b/tests/conformance/source/quickref/linear.aji new file mode 100644 index 0000000..3be2c71 --- /dev/null +++ b/tests/conformance/source/quickref/linear.aji @@ -0,0 +1,13 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:64 +// phase: 6 +// spec: docs/spec/03-memory-model.md §25 +module demo.linear +struct Item { owner: own } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let owner = own.new(42u64, heap) or trap; + let value = Item { owner: move owner }; + let (part) = struct.unpack(move value); + return own.take(move part); +} diff --git a/tests/hosted/source_linear.py b/tests/hosted/source_linear.py new file mode 100644 index 0000000..909381b --- /dev/null +++ b/tests/hosted/source_linear.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Whole-value ownership through source, canonical AIR, and CLI entry points.""" +import json +from pathlib import Path +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / "zig-out/bin/aji" +checks = 0 + + +def cli(*args, code=0): + global checks + run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True) + assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr) + checks += 1 + return run.stdout + + +def returned(path, *args): + record = json.loads(cli("run", "--fuel", "1000000", *args, path)) + assert record["status"] == "returned" and record["value"] == 42, record + + +features = json.loads(cli("features")) +assert "linear_aggregates" in features["features"] +source = REPO / "examples/std/owning-option.aji" +returned(source, "--grant", "heap=mem.alloc:64") +cli("check", source) +canonical = cli("lower", source) +assert cli("lower", source) == canonical +assert "enum.take" in canonical and "value.swap" in canonical +with tempfile.TemporaryDirectory(prefix="aji-linear-") as directory: + root = Path(directory) + air = root / "result.air" + air.write_text(canonical) + cli("check", air) + returned(air, "--grant", "heap=mem.alloc:64") + for fixture, grant in (("pack", 64), ("pack_failure", 8), ("swap_loop", 8), ("heap_array_borrow", 64)): + path = REPO / f"tests/conformance/source/linear/{fixture}.aji" + lowered = cli("lower", path) + assert cli("lower", path) == lowered + air.write_text(lowered) + cli("check", air) + returned(air, "--grant", f"heap=mem.alloc:{grant}") + # Resource-bearing nominal types imported across a package boundary. + (root / "lib.aji").write_text("module app.lib\nstruct Box { value: T }\nfn extract(box: Box) -> T effects [] { let (value) = struct.unpack(move box); return move value; }\n") + (root / "main.aji").write_text("module app.main\nimport app.lib;\nfn main(heap: cap) -> u64 effects [mem.alloc] { let owner = own.new(42u64, heap) or trap; let box = app.lib.Box::> { value: move owner }; let value = app.lib.extract::>(move box); return own.take(move value); }\n") + manifest = root / "aji.toml" + manifest.write_text('[package]\nname = "fixture"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.lib = "lib.aji"\n') + assert json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest, "--grant", "heap=mem.alloc:64"))["value"] == 42 + cli("check", "--manifest", manifest) + cli("report", "--manifest", manifest) + cli("lower", "--manifest", manifest) + cli("explore", "--max-runs", "8", "--manifest", manifest, "--grant", "heap=mem.alloc:64") + +for fixture, expected in (("missing_move", "E7003"), ("ignored_field", "E3002"), ("borrow_conflict", "E2101"), ("recursive_ownership", "E1003")): + path = REPO / f"tests/conformance/source/linear/{fixture}.aji" + commands = ("check", "lower", "report", "run", "explore") if fixture in ("missing_move", "recursive_ownership") else ("check", "report", "run", "explore") + for command in commands: + diagnostics = [json.loads(line) for line in cli(command, path, code=1).splitlines()] + assert diagnostics[0]["code"] == expected, diagnostics + +pack = REPO / "tests/conformance/source/linear/pack.aji" +report = json.loads(cli("report", pack)) +assert sum(function["allocations"] for function in report["functions"]) == 2, report +for fixture in ("task", "channel"): + path = REPO / f"tests/conformance/source/linear/{fixture}.aji" + cli("explore", "--max-runs", "8", "--grant", "heap=mem.alloc:64", path) +print(f"source linear CLI integration passed ({checks} checks)") diff --git a/tools/source_coverage.py b/tools/source_coverage.py index f336a40..42e00b5 100644 --- a/tools/source_coverage.py +++ b/tools/source_coverage.py @@ -20,6 +20,12 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source") # (area, construct, regex, needs a reject test) CHECKLIST = [ + ("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), + ("linear aggregates", "consuming enum match", r"match move ", True), + ("linear aggregates", "borrowed complete exchange", r"value\.swap\(", True), + ("linear aggregates", "ownership-preserving heap allocation", r"own\.pack\(", True), ("generics", "generic function declaration", r"fn \w+<", True), ("generics", "generic struct/enum declaration", r"(?:struct|enum) \w+<", True), ("generics", "explicit function/worker application", r"[a-z]\w*::<", True),