Merge intermediate standard library foundation
Integrate feat/std-bootstrap through STD-7: nineteen safe pinned modules, explicit owning collections, bytes/text/encoding/formatting, bounded and buffered I/O, and caller-buffer lexical paths. Include source modules, generics, linear aggregates/buffers and exact static operation contracts. All 1079 conformance cases pass. New path cases pass per-step collection and schedule stress; source/std CLI, hosted smoke, unit, formatting, reference budgets and source coverage gates pass. Remaining Std 0.1 and service work stays in the backlog; resume Phase 6 with Q-034/P6-11.
This commit is contained in:
commit
715a8be491
807 files changed
+40824
-392
No files matched your search
@@ -20,6 +20,30 @@ jobs:
|
||||
- run: zig build conformance
|
||||
- run: zig build conformance -- --stress 200
|
||||
- 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_static_functions.py
|
||||
- run: python3 tests/hosted/source_linear.py
|
||||
- run: python3 tests/hosted/source_buffers.py
|
||||
- run: python3 tests/hosted/source_deque.py
|
||||
- run: python3 tools/deque_vectors.py
|
||||
- run: python3 tests/hosted/source_hash.py
|
||||
- run: python3 tools/hash_vectors.py
|
||||
- run: python3 tests/hosted/source_errors.py
|
||||
- run: python3 tests/hosted/source_map.py
|
||||
- run: python3 tools/map_vectors.py
|
||||
- run: python3 tests/hosted/source_hashmap.py
|
||||
- run: python3 tools/hashmap_vectors.py
|
||||
- run: python3 tests/hosted/source_hashset.py
|
||||
- run: python3 tools/hashset_vectors.py
|
||||
- run: python3 tests/hosted/source_heap.py
|
||||
- run: python3 tools/heap_vectors.py
|
||||
- run: python3 tests/hosted/source_io.py
|
||||
- run: python3 tools/io_vectors.py
|
||||
- run: python3 tests/hosted/source_buffered_io.py
|
||||
- run: python3 tools/buffered_io_vectors.py
|
||||
- run: python3 tests/hosted/source_path.py
|
||||
- run: python3 tools/path_vectors.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)
|
||||
|
||||
@@ -16,6 +16,28 @@ zig build conformance # conformance suite, see tests/conformance/README.m
|
||||
zig build run -- check f.air # verify a text AIR module
|
||||
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_static_functions.py # explicit operations, effects, nominal policy identity and workers
|
||||
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
|
||||
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
|
||||
python3 tests/hosted/source_deque.py # ring order, returned owners and CLI contracts
|
||||
python3 tests/hosted/source_hash.py # pure hashes, chunks and source/package/hosted contracts
|
||||
python3 tests/hosted/source_errors.py # pure built-in error construction and authority separation
|
||||
python3 tests/hosted/source_map.py # exact numeric keys, owning values and profile/package parity
|
||||
python3 tools/map_vectors.py # independent dictionary oracle for public map traces
|
||||
python3 tests/hosted/source_hashmap.py # explicit general key policies, profiles and returned ownership
|
||||
python3 tools/hashmap_vectors.py # independent dict and dense-order oracle, Copy/owning values
|
||||
python3 tests/hosted/source_hashset.py # duplicate key ownership, source/AIR, packages and profiles
|
||||
python3 tools/hashset_vectors.py # independent set and representative oracle, Copy/owning keys
|
||||
python3 tests/hosted/source_heap.py # explicit ordering, owning extraction and profile/package parity
|
||||
python3 tools/heap_vectors.py # independent heapq traces and exhaustive small permutations
|
||||
python3 tests/hosted/source_io.py # bounded I/O, profiles, partial errors and explicit resources
|
||||
python3 tools/io_vectors.py # independent byte/count/cursor oracle for read/copy boundaries
|
||||
python3 tests/hosted/source_buffered_io.py # owning adapters, partial failures and no retry
|
||||
python3 tools/buffered_io_vectors.py # independent read-prefix and segmented-write bytes
|
||||
python3 tests/hosted/source_path.py # pure paths, ranges, profiles and independent authority
|
||||
python3 tools/path_vectors.py # independent forward-stack path/query/capacity oracle
|
||||
(cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests
|
||||
zig fmt --check build.zig src tools
|
||||
```
|
||||
@@ -41,6 +63,7 @@ src/ reference implementation (Zig)
|
||||
main.zig `aji` CLI
|
||||
tools/conformance.zig conformance runner
|
||||
tests/conformance/ .air conformance tests
|
||||
std/ safe Aji standard modules embedded with the compiler
|
||||
examples/ illustrative Aji source programs
|
||||
```
|
||||
|
||||
|
||||
@@ -54,7 +54,8 @@ docs/plan/ Implementation plan and per-phase task breakdowns
|
||||
docs/dev/ Reference implementation architecture and testing
|
||||
src/ Reference implementation (Zig): diagnostics, AIR, verifier, interpreter
|
||||
tools/ Conformance runner
|
||||
tests/ Conformance suite (.air accept/reject tests)
|
||||
tests/ Conformance suite (.air and .aji accept/reject/run tests)
|
||||
std/ Safe compiler-pinned .aji standard modules
|
||||
examples/ Illustrative Aji programs
|
||||
AGENTS.md Instructions for AI coding agents
|
||||
CONTRIBUTING.md Toolchain, commands, workflow, definition of done
|
||||
@@ -70,7 +71,7 @@ zig build test # unit tests
|
||||
zig build conformance # conformance suite
|
||||
```
|
||||
|
||||
Current state: Phases 0–2 are complete. AIR format 0 has frame storage and second-class borrows, arrays and slices with bounds proofs, flat effects and unforgeable capabilities, linear I/O resources (files, TCP), heap owners and regions with allocation budgets, and explicit unsafe boundaries. `aji run` executes programs in a reproducible deterministic world by default and against the real OS with `--profile hosted`. Phase 3 (structured concurrency) is next; see [`docs/plan/README.md`](docs/plan/README.md).
|
||||
Current state: Phases 0–5 and the Phase 6A `.aji` frontend are implemented. Source modules, explicit generics/static operations, linear aggregates and initialized owning buffers support the intermediate standard-library foundation: owning collections, bytes/text/formatting/encodings, bounded and buffered I/O, and lexical paths. Full Phase 6 and Std 0.1 remain in progress; see the [language plan](docs/plan/README.md) and [std API](docs/reference/std.md). `aji run` uses a reproducible deterministic world by default and the real OS with `--profile hosted`.
|
||||
|
||||
```sh
|
||||
zig build
|
||||
|
||||
@@ -27,6 +27,25 @@ pub fn build(b: *std.Build) void {
|
||||
mod.addAnonymousImport("intrinsics_md", .{
|
||||
.root_source_file = b.path("docs/reference/intrinsics.md"),
|
||||
});
|
||||
mod.addAnonymousImport("std_bytes_aji", .{ .root_source_file = b.path("std/bytes.aji") });
|
||||
mod.addAnonymousImport("std_deque_aji", .{ .root_source_file = b.path("std/deque.aji") });
|
||||
mod.addAnonymousImport("std_encoding_base64_aji", .{ .root_source_file = b.path("std/encoding/base64.aji") });
|
||||
mod.addAnonymousImport("std_encoding_hex_aji", .{ .root_source_file = b.path("std/encoding/hex.aji") });
|
||||
mod.addAnonymousImport("std_fmt_aji", .{ .root_source_file = b.path("std/fmt.aji") });
|
||||
mod.addAnonymousImport("std_hash_aji", .{ .root_source_file = b.path("std/hash.aji") });
|
||||
mod.addAnonymousImport("std_hashmap_aji", .{ .root_source_file = b.path("std/hashmap.aji") });
|
||||
mod.addAnonymousImport("std_hashset_aji", .{ .root_source_file = b.path("std/hashset.aji") });
|
||||
mod.addAnonymousImport("std_heap_aji", .{ .root_source_file = b.path("std/heap.aji") });
|
||||
mod.addAnonymousImport("std_io_aji", .{ .root_source_file = b.path("std/io.aji") });
|
||||
mod.addAnonymousImport("std_io_reader_aji", .{ .root_source_file = b.path("std/io/reader.aji") });
|
||||
mod.addAnonymousImport("std_io_writer_aji", .{ .root_source_file = b.path("std/io/writer.aji") });
|
||||
mod.addAnonymousImport("std_map_aji", .{ .root_source_file = b.path("std/map.aji") });
|
||||
mod.addAnonymousImport("std_math_aji", .{ .root_source_file = b.path("std/math.aji") });
|
||||
mod.addAnonymousImport("std_option_aji", .{ .root_source_file = b.path("std/option.aji") });
|
||||
mod.addAnonymousImport("std_path_aji", .{ .root_source_file = b.path("std/path.aji") });
|
||||
mod.addAnonymousImport("std_result_aji", .{ .root_source_file = b.path("std/result.aji") });
|
||||
mod.addAnonymousImport("std_utf8_aji", .{ .root_source_file = b.path("std/utf8.aji") });
|
||||
mod.addAnonymousImport("std_vec_aji", .{ .root_source_file = b.path("std/vec.aji") });
|
||||
|
||||
// CLI: `aji`.
|
||||
const exe = b.addExecutable(.{
|
||||
|
||||
@@ -86,3 +86,48 @@ The groups `quick_reference`, `source_docs` and `air_docs` come from the `doc_gr
|
||||
[`quick-reference.md`](quick-reference.md) is the front door of the Source Reference Bundle (`QUICK.md`). It targets 4–6k tokens (about 4.4k with the navigation table, cl100k), covers most programs, and is kept consistent with spec 15.
|
||||
|
||||
**Its examples are checked.** Every ```aji block must be an excerpt of a program in `tests/conformance/source/quickref/`. Comments and whitespace are ignored, and `…` matches any text. Those programs are conformance tests, so each example is part of a program that verifies and runs. `zig build test` and `zig build agent-reference` fail on an example that is not. The concurrency programs (§7) are PENDING until layers 7–8 exist.
|
||||
|
||||
## Standard library bootstrap
|
||||
|
||||
`language/syntax.md` includes the built-in import rules (spec 15 §13). The on-demand `library/std.md` includes spec 16 and the signature table in `reference/std.md`. The source profile counts `library/` with `source_docs`. Pure library source is verified through the ordinary pipeline; no AIR bundle addition is needed. RFC 0016 records bootstrap complexity growth; RFC 0017 records endian APIs and qualified standard enum types. The plan tracks the next APIs.
|
||||
|
||||
RFC 0016 bootstrap measurement (cl100k): Quick Reference 5,511 → 5,777 (+4.8%); other source docs 28,470 → 30,461 (+7.0%); full source docs excluding AIR 33,981 → 36,238 (+6.6%). The on-demand library page is 1,346 tokens. The AIR bundle stays 160,797 bytes. The RFC also records o200k and Qwen2.5 counts.
|
||||
|
||||
RFC 0017 endian increment (cl100k, relative to bootstrap): Quick Reference 5,777 → 6,000 (+3.9%); other source docs 30,461 → 31,918 (+4.8%); full source docs excluding AIR 36,238 → 37,918 (+4.6%). The library page is 2,533 tokens. AIR remains unchanged. The additional Quick Reference example shows explicit typed success/short-buffer handling; future API catalogs stay on demand.
|
||||
|
||||
RFC 0018 bounded operations (cl100k, relative to endian): Quick Reference 6,000 → 6,082 (+1.4%); other source docs 31,918 → 33,628 (+5.4%); full source docs excluding AIR 37,918 → 39,710 (+4.7%). The library page is 4,223 tokens. AIR remains unchanged. Copy, substring lookup and recoverable arithmetic reuse existing verified primitives; detailed contracts and the checked sizing example stay on demand.
|
||||
|
||||
RFC 0019 text/encodings (cl100k, relative to bounded): Quick Reference 6,082 → 6,163 (+1.3%); other source docs 33,628 → 36,042 (+7.2%); full source docs excluding AIR 39,710 → 42,205 (+6.3%). The library page is 6,644 tokens. AIR remains unchanged. UTF-8, hex and canonical Base64 use existing primitives and fixed frame tables. Cumulative full source growth since the pre-stdlib baseline is +24.2%, above the 20% review line; RFC 0019 records the justification and owner-review scope. Future API references should be split/read selectively instead of expanding the front-door catalog.
|
||||
|
||||
RFC 0020 supplied-buffer decimal formatting (cl100k, relative to text): Quick Reference 6,163 → 6,220 (+0.9%); other source docs 36,042 → 37,128 (+3.0%); full source docs excluding AIR 42,205 → 43,348 (+2.7%). The library page is 7,730 tokens. AIR remains unchanged. Four scalar writers reuse ordinary source and one Copy enum; full contracts and explicit record composition stay on demand. Cumulative source growth from the pre-stdlib baseline is +27.6%, with the existing owner-review justification recorded in RFC 0020. No compression benefit is inferred from documentation or fixtures.
|
||||
|
||||
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.
|
||||
|
||||
RFC 0024 initialized buffers and safe Vec (cl100k, relative to linear aggregates): Quick Reference 7,225 → 7,667 (+6.1%); other source docs 42,364 → 44,717 (+5.6%); full source excluding AIR 49,589 → 52,384 (+5.6%). New on-demand language/buffers.md is 1,175 tokens; library/std.md is 9,432. AIR grows to 175,736 bytes (+4.4%). Initialized prefixes, explicit reserve, returned failure ownership and empty-only free permit safe resource containers without per-slot verifier state. Cumulative full source growth is +54.2%, with the RFC's owner-review justification; Quick Reference consolidation remains separate work and no empirical MCC improvement is claimed.
|
||||
|
||||
RFC 0025 safe owning Deque (cl100k, relative to buffer/Vec): Quick Reference 7,667 → 7,747 (+1.0%); other source docs 44,717 → 46,246 (+3.4%); full source excluding AIR 52,384 → 53,993 (+3.1%). library/std.md is 10,961 tokens; AIR remains 175,736 bytes. Eleven generic safe functions reuse buffer/Option/exchange and existing ownership/borrow rules without semantic or verifier-state growth. Full ring invariants and accounting stay on demand; cumulative full-source growth is +58.9%, with the RFC's owner-review justification and no empirical MCC claim.
|
||||
|
||||
RFC 0026 std.hash (cl100k, relative to Deque): Quick Reference 7,747 → 7,806 (+0.8%); other source docs 46,246 → 47,475; full source excluding AIR 53,993 → 55,281 (+2.4%). library/std.md is 12,190 tokens; AIR remains 175,736 bytes. Four pure functions expose exact FNV/CRC continuation with no semantic, verifier or authority growth. Cumulative full-source growth is +62.7%, justified in the RFC for owner review without an empirical MCC claim. The proposed map contract stays outside the bundles.
|
||||
|
||||
RFC 0027 explicit error values (cl100k, relative to hashes): Quick Reference 7,806 → 7,863; other source docs 47,475 → 48,061; full source excluding AIR 55,281 → 55,924 (+1.2%). AIR is 179,282 bytes / 51 sections, and its source-bundle copy is 46,300 tokens. The measurement excludes the developing map contract. Existing variant syntax gains pure built-in error values; no authority, resource or ownership state is added. Cumulative source growth is +64.6%; the RFC records the complexity justification, without claiming MCC improvement.
|
||||
|
||||
RFC 0028 numeric-key owning map (cl100k, relative to error_values; includes the separate integer-pattern clarification): Quick Reference stays 7,863, other source docs 48,061 → 50,079, full source excluding AIR 55,924 → 57,942 (+3.6%). The on-demand library page is 14,167 tokens. AIR remains 179,282 bytes / 51 sections. No map-specific instruction, source form, verifier state or diagnostic is added; general keys remain Q-037. Cumulative source growth is +70.5%, with review justification in the RFC and no claimed MCC benefit.
|
||||
|
||||
RFC 0029 static function parameters (cl100k, relative to numeric maps): Quick Reference 7,863 → 8,051 (+2.4%); other source docs 50,079 → 51,002 (+1.8%); full source excluding AIR 57,942 → 59,053 (+1.9%). language/generics.md is 2,194 tokens; AIR remains 179,282 bytes / 51 sections. One explicit operation-selection concept adds two source forms and bounded frontend state, with no runtime/verifier state or new AIR construct/diagnostic. Cumulative growth is +73.8%; the RFC justifies the general hash/equality/order prerequisite, keeps general collections open and makes no empirical MCC claim.
|
||||
|
||||
RFC 0030 general owning HashMap (cl100k, relative to static operations): Quick Reference 8,051 → 8,124 (+0.9%), other source docs 51,002 → 53,363 (+4.6%), full source excluding AIR 59,053 → 61,487 (+4.1%). library/std.md is 16,504 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe source functions use explicit static policies and complete key/value transfer, with no new language form, verifier/runtime state or diagnostic. Cumulative source growth is +80.9%, justified in the RFC without an empirical MCC claim; full policies/failure/dense-index invariants stay on demand.
|
||||
|
||||
RFC 0031 general owning HashSet (cl100k, relative to HashMap): Quick Reference 8,124 → 8,201 (+0.9%), other source docs 53,363 → 54,798 (+2.7%), full source excluding AIR 61,487 → 62,999 (+2.5%). library/std.md is 17,939 tokens; AIR remains 179,282 bytes / 51 sections. Nine safe wrappers return duplicate/full incoming keys and transfer stored keys through ordinary ownership rules. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +85.4%, justified by explicit ownership/accounting contracts without an empirical MCC claim.
|
||||
|
||||
RFC 0032 owning BinaryHeap (cl100k, relative to HashSet): Quick Reference 8,201 → 8,284 (+1.0%), other source docs 54,798 → 56,770 (+3.6%), full source excluding AIR 62,999 → 65,054 (+3.3%). library/std.md is 19,911 tokens; AIR remains 179,282 bytes / 51 sections. Eight safe source operations bind explicit pure order and sift Copy indices while complete owners remain in initialized storage. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +91.4%, justified by visible ordering/ownership/failure/accounting contracts without an empirical MCC claim.
|
||||
|
||||
RFC 0033 bounded I/O (cl100k, relative to BinaryHeap): Quick Reference 8,284 → 8,350 (+0.8%), other source docs 56,770 → 58,473 (+3.0%), full source excluding AIR 65,054 → 66,823 (+2.7%). library/std.md is 21,614 tokens; AIR remains 179,282 bytes / 51 sections. Six safe concrete compositions retain exact effects and caller resource loans, distinguishing EOF/limits from partial failure. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +96.6%, justified by progress/authority/cleanup contracts without an empirical MCC claim.
|
||||
|
||||
RFC 0034 owning buffered files (cl100k, relative to bounded I/O): Quick Reference 8,350 → 8,445 (+1.1%), other source docs 58,473 → 61,223 (+4.7%), full source excluding AIR 66,823 → 69,668 (+4.3%). library/std.md is 24,364 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe concrete operations keep fixed allocation, file transfer, prefetch and first-error/partial-write cleanup visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +105.0%, justified by these contracts without an empirical MCC claim. Full representation/API details stay on demand; front-door consolidation remains separate work.
|
||||
|
||||
RFC 0035 caller-buffer paths (cl100k, relative to buffered files): Quick Reference 8,445 → 8,518 (+0.9%), other source docs 61,223 → 63,296 (+3.4%), full source excluding AIR 69,668 → 71,814 (+3.1%). library/std.md is 26,437 tokens; AIR remains 179,282 bytes / 51 sections. Six pure operations return raw Copy ranges or write a measured canonical prefix, keeping lifetime, byte syntax, capacity failure and authority visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +111.3%, justified by these contracts without an empirical MCC claim. API details stay on demand; front-door consolidation remains separate work.
|
||||
@@ -59,6 +59,7 @@ docs/spec/05-effects-and-capabilities.md :: ## 9. Effects in AIR
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 10. Capabilities in AIR
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 11. Intrinsic calls
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 12. Runtime
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 14. Explicit error values
|
||||
|
||||
# Resources and I/O errors
|
||||
docs/spec/06-resources-and-errors.md :: ## 6. Resources in AIR
|
||||
@@ -86,3 +87,9 @@ 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
|
||||
|
||||
# Dynamic initialized storage (STD-6a)
|
||||
docs/spec/03-memory-model.md :: ## 26. Dynamic initialized buffers
|
||||
@@ -149,6 +149,8 @@ region.reset(r);
|
||||
|
||||
`err(e)` binds a real value: `match e { alloc_error::budget_exceeded => …, alloc_error::out_of_memory => … }`.
|
||||
|
||||
Built-in errors are Copy data: `let e = alloc_error::budget_exceeded;` constructs a payload-free value without effects, allocation or authority. All registered `alloc_error`, `cap_error` and `io_error` variants work this way (spec 05 §14).
|
||||
|
||||
- **Narrowing:** `cap.narrow.prefix(c, b"/data")` and `cap.narrow.budget(heap, 4096)`, each giving `ok(c2) / err(e)`.
|
||||
- Resource operands (`f`, `s`, `l`, endpoints) are borrowed automatically for an operation; a region is not (bind `ref arena = r;`); data borrows (`mut buf`, `ref bytes`) are always written.
|
||||
- Memory budgets count live bytes, so freeing returns them. In the deterministic profile `mem.alloc` needs a grant with a budget: `--grant heap=mem.alloc:4096`.
|
||||
@@ -316,3 +318,163 @@ scope s { // every task spawned in s must
|
||||
| E2111 | graph content not plain data | store only integers, booleans, enums, structs/arrays of them and `iref`s in a graph |
|
||||
| T0010 | `iref` of another graph | use a handle with the graph it came from |
|
||||
| T0001–T0009 | runtime trap | see `kind` and `source_location` |
|
||||
|
||||
## 10. Standard library
|
||||
|
||||
Import a bundled module after the module header; call its functions by their full path. `std.bytes` and `std.math` are safe source, declare `effects []` and allocate no heap. No grants are needed. Read `/docs/library/std.md` for the API.
|
||||
|
||||
```aji
|
||||
module demo.standard
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var data: [u8; 4] = zero;
|
||||
std.bytes.fill(mut data, 65);
|
||||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||||
let index = std.bytes.find(ref data, 65);
|
||||
if index < data.len { assert(data[index] == 65); }
|
||||
return std.math.clamp_u64(42, 0, 100);
|
||||
}
|
||||
```
|
||||
|
||||
`find` returns the searched slice's length when absent; check before indexing. `clamp_u64` traps `T0002` for an inverted range. Missing import/module/member: `E7002`; duplicate import: `E7006`; wrong arguments: `E7005`. Aliases are unavailable; explicit generics use §12.
|
||||
|
||||
Endian reads/writes cover `u16/u32/u64` in LE and BE. Pass a sub-slice for an offset. Reads return `std.bytes.ReadUW` with `ok(uW)`/`short_input`; writes return `std.bytes.WriteResult` with `ok`/`short_output`. A short destination is unchanged. Handle them with qualified enum patterns (not intrinsic outcome patterns):
|
||||
|
||||
```aji
|
||||
match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.bytes.read_u32_be(ref wire[1..5]) {
|
||||
std.bytes.ReadU32::ok(value) => { return value; }
|
||||
std.bytes.ReadU32::short_input => { return 0; }
|
||||
}
|
||||
```
|
||||
|
||||
The usual enum rules apply: missing arm `E7004`, wrong enum/payload `E7005`, unknown type/variant `E7002`. See `/docs/library/std.md` for signatures.
|
||||
|
||||
`std.bytes.copy` returns `WriteResult`; short output is unchanged and overlap rejects. `find_slice` returns `FindResult::found(index)` / `not_found` (empty needle: found at 0). Recoverable `u64`/`usize` arithmetic, split composition and a checked example are in `/docs/library/std.md`; wrapping stays `+%`, `-%`, `*%`.
|
||||
|
||||
`std.utf8` validates bytes and decodes the next scalar with an explicit consumed count. `std.encoding.hex` and `std.encoding.base64` encode/decode into `mut` output slices; ordinary enum results expose malformed input and short capacity, leaving output unchanged on errors. Base64 accepts canonical padded standard encoding. Signatures and a checked example are in `/docs/library/std.md`.
|
||||
|
||||
`std.fmt.write_u64/i64/usize/isize` write decimal integers into supplied output slices; `WriteResult::ok(count)` / `short_output` expose capacity, with unchanged output on failure. Composition and signatures are in `/docs/library/std.md`.
|
||||
|
||||
`std.hashmap.HashMap<K,V,fn hash,fn equal>` supports general owning keys/values through explicit pure ref-key operations (§12). Insert returns replaced/full key/value pairs; remove/pop move both out, get requires only V: Copy, growth is explicit and free returns nonempty maps. Full contracts are in `/docs/library/std.md`.
|
||||
|
||||
`std.hashset.HashSet<K,fn hash,fn equal>` uses the same policies for complete owning keys. Insert returns `present(input)` for duplicates, preserving the stored key, or `full(input)`; remove/pop move stored keys out. Only new/reserve allocate with explicit authority; free returns nonempty sets. Full contracts are in `/docs/library/std.md`.
|
||||
|
||||
`std.heap.BinaryHeap<T,fn before>` binds pure `fn(ref<T>,ref<T>)->bool effects []` as a stable strict weak order. Push returns full input; pop moves the priority root; peek requires T: Copy. Only new/reserve allocate with explicit authority; free returns nonempty heaps. Ties have no stable-order guarantee. Full contracts are in `/docs/library/std.md`.
|
||||
|
||||
`std.io` supplies exact stdin/file/stream reads, bounded file read-to-end and limited file copy/append with caller slices and explicit effects/authority. EOF differs from full/limit; errors report confirmed progress. Resources stay borrowed, no heap or close is hidden, and failed external writes may be partial. Full contracts are in `/docs/library/std.md`.
|
||||
|
||||
`std.io.reader`/`std.io.writer` own a file and an explicitly allocated fixed byte buffer. Use new, read/read_exact or write/flush, then finish to return the file for explicit close. Unread/failed finish returns the whole adapter; discard explicitly abandons buffered bytes and frees storage. A failed writer preserves its first error and never retries. Capacity zero uses direct I/O. Effects and ownership remain explicit; see `/docs/library/std.md`.
|
||||
|
||||
`std.path` provides pure slash-based is_absolute/basename/parent/extension and supplied-buffer normalize/join. Queries return Copy Range{start,end}; explicitly borrow that range from the original path. Writers preserve output on error and return the successful prefix size, with no heap or filesystem authority. Dot/parent and root rules are in `/docs/library/std.md`.
|
||||
|
||||
`std.hash.fnv1a64` and `crc32c` hash byte slices without allocation; their `_extend` forms continue from a previous result. Hashes do not establish key equality or authentication. Exact algorithms and chunk/byte-order conventions are in `/docs/library/std.md`.
|
||||
|
||||
## 11. Package modules
|
||||
|
||||
Declare package inputs explicitly in `aji.toml`:
|
||||
|
||||
```toml
|
||||
[package]
|
||||
entry = "main.aji"
|
||||
[modules]
|
||||
app.model = "model.aji"
|
||||
```
|
||||
|
||||
`model.aji` declares `module app.model`. Import it directly; functions, structs and enums use full names. Short names stay local to their defining module; imports grant no authority or transitive name visibility.
|
||||
|
||||
```aji
|
||||
module app.entry
|
||||
import app.model;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
let pair = app.model.Pair { left: 20, right: 22 };
|
||||
return app.model.total(pair);
|
||||
}
|
||||
```
|
||||
|
||||
Use `aji check|lower|report|run|explore --manifest aji.toml`; `run` and `explore` instantiate manifest grants. A file-only command does not discover packages. Qualified workers work in `task.spawn(s, app.work.run, args)` with ordinary `move`, borrow and join rules. Missing/direct-import names: `E7002`; cycles/header mismatch/duplicates: `E7006`. Read `/docs/language/modules.md` for limits and file-loading rules. `lower --stats` counts entry source against combined AIR, so it is not a whole-package size metric.
|
||||
|
||||
## 12. Generics
|
||||
|
||||
Declare type parameters on functions, structs or enums: `<T>`, `<T: Copy>` or `<T: Copy + Send>`. Every use supplies all types: `Pair<u64>` in annotations, `Pair::<u64> { ... }`, `identity::<u64>(42)` and `Option::<u64>::some(42)` in expressions/patterns. Qualified forms require a direct import. No inference, traits, defaults or overloads. `task.spawn(s, worker::<u64>, args)` specializes a static worker with the ordinary ownership/effect rules.
|
||||
|
||||
```aji
|
||||
module demo.generic
|
||||
import std.option;
|
||||
|
||||
fn identity<T: Copy>(value: T) -> T effects [] { return value; }
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
let value = std.option.Option::<u64>::some(identity::<u64>(42));
|
||||
match value {
|
||||
std.option.Option::<u64>::some(n) => { return n; }
|
||||
std.option.Option::<u64>::none => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`std.option.Option<T>` has `some(T)`/`none`; `std.result.Result<T, E>` has `ok(T)`/`err(E)`. `is_some::<T>` and `is_ok::<T, E>` 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.
|
||||
|
||||
An operation is an explicit static parameter, with exact parameter/return types and effect set. Select a declared function with `fn path` (generic: `fn path::<args>`); `fn F` forwards a bound operation. It has no runtime value or captures; F is only a direct call or `task.spawn` worker. Different operations produce distinct nominal instances. Mismatch: `E7005`; escaping/shadowing F or borrowed return contracts: `E7006`. Effects and capability arguments remain explicit.
|
||||
|
||||
```aji
|
||||
module demo.static_functions
|
||||
fn identity(value: u64) -> u64 effects [] { return value; }
|
||||
fn apply<T, F: fn(T) -> T effects []>(value: T) -> T effects [] {
|
||||
return F(move value);
|
||||
}
|
||||
fn main() -> u64 effects [] { return apply::<u64, fn identity>(42u64); }
|
||||
```
|
||||
|
||||
## 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<u64> }
|
||||
fn main(heap: cap<mem.alloc>) -> 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.
|
||||
|
||||
## 14. Buffers and Vec
|
||||
|
||||
`buffer<T>` uniquely owns capacity and an initialized prefix, including owners/resources. Allocate with `buffer.new<T>(capacity, heap)` (mem.alloc); borrow the handle first for len/capacity/reserve/push/pop/view. `reserve(b, capacity, heap)` grows explicitly, charging old+new capacity at the peak. Push never grows: full returns the original item. Pop moves the last element out. Free succeeds only when empty; otherwise it returns the buffer. No destructor drains it.
|
||||
|
||||
```aji
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let data = buffer.new<own<u64>>(1, heap) or trap;
|
||||
let item = own.new(42u64, heap) or trap;
|
||||
var answer: u64 = 0;
|
||||
{ mut b = data;
|
||||
buffer.push(b, move item) or trap;
|
||||
let last = buffer.pop(b) or trap;
|
||||
answer = own.take(move last);
|
||||
}
|
||||
buffer.free(move data) or trap;
|
||||
return answer;
|
||||
}
|
||||
```
|
||||
|
||||
`ref values = buffer.view(b);` / `mut values = buffer.view(b);` borrow only the prefix. A live child view/task loan blocks shape changes, even a no-op reserve. Read Copy elements; use value.swap to replace linear elements, consuming the returned old value. Full contracts: language/buffers.md.
|
||||
|
||||
Import `std.vec` for `Vec<T>` and new/len/capacity/reserve/push/pop/free/get/replace, each explicitly specialized `::<T>`. new/reserve require mem.alloc; push is bounded, get requires Copy, pop returns std.option.Option<T>. Failure variants retain ownership: full(item), out_of_bounds(item), not_empty(vector). Match move on linear results; import std.option to name its variants. Signatures: library/std.md. Inside a specialized generic body, `move name` also accepts complete Copy bindings and retains their availability; monomorphic Copy moves and moves of borrows still reject.
|
||||
|
||||
`std.deque` uses the same explicit allocation, returned-ownership and empty-only free contract, with push_front/push_back and pop_front/pop_back. Indices count from the front. Each capacity slot charges Option<T> (tag plus payload); reserve preserves order and needs old+new quota. It uses existing source primitives; signatures and representation invariants stay in library/std.md.
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
> QUICK.md
|
||||
docs/agent/quick-reference.md
|
||||
docs/agent/source-notes.md :: ## 10. Where to read more
|
||||
docs/agent/source-notes.md :: ## 14. Where to read more
|
||||
|
||||
> language/syntax.md
|
||||
docs/reference/grammar.ebnf
|
||||
@@ -19,6 +19,28 @@ docs/spec/15-source-language.md :: ## 4. Statements and control flow
|
||||
docs/spec/15-source-language.md :: ## 5. Expressions
|
||||
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/buffers.md
|
||||
docs/spec/15-source-language.md :: ## 17. Source dynamic buffers
|
||||
docs/spec/03-memory-model.md :: ## 26. Dynamic initialized buffers
|
||||
|
||||
> language/generics.md
|
||||
docs/spec/15-source-language.md :: ## 15. Explicit source generics
|
||||
docs/spec/15-source-language.md :: ## 18. Static function parameters
|
||||
|
||||
> language/modules.md
|
||||
docs/spec/15-source-language.md :: ## 14. Package source modules
|
||||
docs/spec/12-packages-and-build.md :: ### 1.3 Package source mapping
|
||||
|
||||
> library/std.md
|
||||
docs/spec/16-standard-library.md
|
||||
docs/reference/std.md
|
||||
|
||||
> language/types.md
|
||||
docs/spec/15-source-language.md :: ## 3. Types
|
||||
docs/spec/02-types-and-values.md :: ## 2. Integer semantics
|
||||
@@ -51,6 +73,7 @@ docs/spec/05-effects-and-capabilities.md :: ## 4. Narrowing
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 5. Capability transfer
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 9. Effects in AIR
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 10. Capabilities in AIR
|
||||
docs/spec/05-effects-and-capabilities.md :: ## 14. Explicit error values
|
||||
docs/reference/effects.md
|
||||
docs/reference/capabilities.md
|
||||
|
||||
|
||||
@@ -2,12 +2,17 @@
|
||||
|
||||
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.
|
||||
|
||||
## 10. 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/text/formatting/hash, option/result, owning collections and bounded I/O, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| initialized buffer storage, explicit growth/drain and child views | `/docs/language/buffers.md` |
|
||||
| whole-value linear aggregates, unpack, exchange and allocation failure | `/docs/language/linear-aggregates.md` |
|
||||
| generic declarations/applications, property constraints, static function contracts 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` |
|
||||
| integer semantics, conversions, Copy/Send/Share, traps | `/docs/language/types.md` |
|
||||
| borrows, scopes, frame storage, slices, initialization | `/docs/language/ownership.md` |
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Owning hash map design
|
||||
|
||||
Status: STD-6d.2 numeric-key and STD-6d.4/5 general-key branch implementations validated (RFCs 0028/0030/0031 Proposed); Q-037 resolved. Spec 16 §2.13–§2.15 is normative for std.map/std.hashmap/std.hashset. This document records design rationale and does not override the specification.
|
||||
|
||||
## Key policy and scope
|
||||
|
||||
The eventual collection gate still requires HashMap<Key, Own<Value>>. At the numeric-map decision, type parameters supplied no hashing/equality operations (spec 15 §15); Copy supplies neither. RFC 0029/spec 15 §18 now supplies explicit static functions without runtime callbacks, methods, user traits or captured values. Treating a digest as key identity is incorrect because different keys can collide. Adding a language feature solely to make this API look generic would add more agent concepts before establishing their general value.
|
||||
|
||||
The initial branch increment was `std.map.U64Map<V>`: exact u64 keys, generic Copy or linear values, initialized buffer primitives and explicit error construction (RFC 0027). Users with genuine numeric identifiers can use it directly. Bytes/struct keys cannot be converted to digests and then treated as unique numeric keys; general key hashing/equality was Q-037, now resolved by explicit static policies and dense complete owning entries (spec 16 §2.14–§2.15). Byte-key ownership uses that general owning representation contract. Do not name this specialization HashMap<K,V> or claim that it satisfies the general-key gate.
|
||||
|
||||
## Public API
|
||||
|
||||
Ten generic functions, each explicitly specialized `::<V>`; only new/reserve declare effects [mem.alloc] and take cap<mem.alloc>. All other functions declare effects []. The numeric-key names/types below are implemented on the branch; spec 16 §2.13 is authoritative.
|
||||
|
||||
| Function | Result/ownership |
|
||||
|---|---|
|
||||
| `new<V>(capacity: usize, heap: cap<mem.alloc>)` | `NewResult<V>::ok(U64Map<V>)` / `err(alloc_error)` |
|
||||
| `len<V>(map: ref<U64Map<V>>) -> usize` | occupied entries |
|
||||
| `capacity<V>(map: ref<U64Map<V>>) -> usize` | guaranteed maximum entries before new-key insert returns full |
|
||||
| `reserve<V>(map: mut<U64Map<V>>, capacity: usize, heap: cap<mem.alloc>)` | `ReserveResult::ok` / `err(alloc_error)`; <= current capacity is an unchanged no-op |
|
||||
| `insert<V>(map: mut<U64Map<V>>, key: u64, value: V)` | `InsertResult<V>::inserted` / `replaced(V)` / `full(V)` |
|
||||
| `contains<V>(map: ref<U64Map<V>>, key: u64) -> bool` | presence without copying V |
|
||||
| `get<V: Copy>(map: ref<U64Map<V>>, key: u64) -> std.option.Option<V>` | copied value or none |
|
||||
| `remove<V>(map: mut<U64Map<V>>, key: u64) -> std.option.Option<V>` | moves out value or none; missing key leaves state unchanged |
|
||||
| `pop<V>(map: mut<U64Map<V>>) -> std.option.Option<Entry<V>>` | moves out one key/value or none; Entry<V> has key: u64 and value: V |
|
||||
| `free<V>(map: U64Map<V>)` | `FreeResult<V>::ok` / `not_empty(U64Map<V>)` |
|
||||
|
||||
Insert first searches for exact key equality. Replacing an existing key succeeds even when full and returns the old complete value; the new input is consumed exactly once. A new key at capacity returns its unchanged input without modifying any slot or metadata. It never allocates or grows. Keys 0 and 2^64-1 are ordinary valid keys, not empty/tombstone sentinels. pop permits explicit cleanup without requiring a Copy value, iterator or returned borrow; no clear/drop helper is planned.
|
||||
|
||||
## Representation, lookup and accounting
|
||||
|
||||
Use initialized `buffer<Slot<V>>`, with Slot<V> an ordinary struct containing key: u64, state: SlotState and value: Option<V>. SlotState is a Copy enum empty/deleted/occupied. Copy key/state fields remain readable through ref even when V is linear (spec 15 §16); a linear enum containing the key/value would not support observational lookup with existing enum.switch. The representation therefore needs no borrowed-enum or partial-move feature. A capacity N uses exactly 2N physical slots and limits live entries to N. N=0 has zero slots and no live entries; no modulo is evaluated. Capacity multiplication/byte-charge overflow returns existing budget_exceeded, before allocation or mutation. Slot quota includes the key, SlotState tag and Option<V> tag/maximum payload, including vacant/deleted slots; no hidden allocation owns payloads. Manual field construction/mutation must preserve the documented invariant, as for Vec/Deque.
|
||||
|
||||
A deterministic hash hashes exactly eight little-endian key bytes using std.hash.fnv1a64; it never hashes host padding or object addresses. Linear probing begins at hash modulo the physical slot count, visits at most that count, and advances with an overflow-free wrapped index. Hash only chooses the probe start; occupied keys always compare by exact u64 equality. Lookup passes deleted slots and stops at empty or after the full bounded probe. Insert remembers the first deleted slot but continues searching for an existing key until empty/end, so deletion cannot create a duplicate. At least half the slots are non-occupied, but deletion may leave no empty slots: deleted-only probe termination must work.
|
||||
|
||||
Remove/pop exchange a complete Option<V> for none, set the Copy state to deleted, decrement length and return user ownership. No tombstone compaction is required during remove/pop; this keeps them allocation-free and avoids partial holes. When logically empty, free examines/consumes all physical slots; invalid metadata cannot make it normally discard an occupied value. This is explicit internal cleanup only. pop chooses the first occupied physical index, so order is deterministic for the operation history, not insertion or key order. Rehash may change that order; callers requiring sorted output must sort explicitly.
|
||||
|
||||
Reserve first allocates and initializes the whole new table, while the old table and every user owner remain unchanged. Failure refunds temporary storage to its authority and preserves old slots, length, capacity and iteration order exactly. Once allocation succeeds, no recoverable operation may fail: exchange each complete occupied slot into the new table in old physical-index order, then explicitly consume internal none payloads and free old empty/deleted storage. Peak quota includes both full tables plus separately charged user owners. Refund the old table to its recorded authority, even when reserve uses another capability. A successful growth clears tombstones and preserves every key/value association. Do not build this on buffer.reserve alone: rehash needs both old and new layouts until transfer finishes.
|
||||
|
||||
Expected probing depends on collisions/history; worst-case lookup/insert/remove is O(N). Pop/empty free inspect O(N) slots. New/reserve perform O(N) slot work, with possible O(N²) rehash collision work and the interpreter's existing prefix-copy overhead. Fixed non-cryptographic FNV is not an adversarial hashing guarantee. Fuel and capacity bound work explicitly; no random seed or ambient entropy is introduced.
|
||||
|
||||
## Ownership and implementation gate
|
||||
|
||||
Preserved invariant: every live entry holds one complete V, occupied count equals length, keys are unique, and each occupied slot is reachable by its probe sequence. Occupied state corresponds exactly to some(V); vacant/deleted states correspond to none and own no V. Unused keys remain initialized Copy values, never identity sentinels. Existing aggregate/enum availability, exchange, slice bounds, mutable exclusion and task-loan rules verify every operation. Runtime uses ordinary deterministic AIR, initialized buffer accounting and no new instruction. No new diagnostic is expected: bad moves/leaks use E7003/E2002/E3002, alias/task conflicts E2101/E4101, Copy/Send/Share restrictions E7005/E4002. User owners, files and endpoints remain subject to ordinary resource/task rules; no destructor closes them. Existing AIR/APIs retain meaning; map support is an additive registry entry, with its spec/reference delivered alongside code.
|
||||
|
||||
The checked [slot prerequisite](../../tests/conformance/source/hash/map_storage.aji) already demonstrates read-only key/state access without consuming an owning payload, complete extraction and explicit cleanup; it does not implement a map. A valid owning use creates U64Map<own<u64>>, inserts a moved owner under key 7, handles replaced/full payloads, removes or pops and explicitly consumes the returned owner, then handles empty free. Rejected uses omit the move, ignore a linear replaced/full/pop result, copy an owner through get, free without consuming not_empty, mutate while a slice/task loan exists or share a file-valued map with workers. Executable valid/rejected examples are in tests/conformance/source/map; RFC 0028 records validation.
|
||||
|
||||
Before marking the specialization done, test exact collisions, tombstones before matching keys, wraparound, a table with no empty slots, full-table replacement, zero capacity and all scalar keys. Compare mixed operations and all associations with an independent Python dict oracle. Include Copy/owner/file/sender cleanup, repeated reuse, peak-charge failure, exact failure-state preservation, cross-authority refunds and invalid-representation safety. Verify canonical AIR/package/hosted behavior, GC after each instruction and schedules for valid workers. Integrate normative rules in spec 16 and the API reference, register the module, measure bundle costs and report the remaining general-key gate explicitly.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
The numeric-key library adds no map-specific language concept, verifier state, syntax, diagnostic, callback, trait or runtime feature. Its separately implemented error construction prerequisite is RFC 0027. Key equality, probing and returned replacement ownership reuse existing complete-value patterns. Ten operations avoid independent entry/cursor/borrow lifetimes. Public representation invariants increase documentation needs, so full details belong on demand. This design stays outside the source/AIR bundles; RFC 0028 measures the normative API cost. No performance or Model Capability Compression result is inferred from fixtures or benchmark tasks.
|
||||
|
||||
|
||||
## General-key implementation
|
||||
|
||||
RFC 0030/spec 16 §2.14 introduces separate std.hashmap so std.map's numeric signatures remain compatible without overloads. Explicit H/E contracts support arbitrary complete owning keys and values. Dense initialized StoredEntry<K,V> slots plus Copy bucket indices permit shared key borrows, avoiding vacancy/default keys and borrowed-enum/partial-move features. Replacement returns the entire previous key/value; full returns the entire input pair. Removal exchanges the last entry into the hole and repairs its index; pop is reverse current dense order. Growth initializes new indices first, then uses failure-preserving buffer.reserve, rehashes cached hashes and frees old indices. This keeps failure exact while charging both layouts at the peak. The full library contract, rather than this historical numeric design, is normative. HashSet and BinaryHeap are later increments.
|
||||
@@ -27,7 +27,11 @@ 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 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain |
|
||||
| Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors |
|
||||
| Q-039 | resolved | STD-6d | Explicit static function parameters |
|
||||
|
||||
## Q-001 — Text AIR grammar
|
||||
|
||||
@@ -202,3 +206,85 @@ 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 Implemented):** 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.
|
||||
|
||||
**Resolved in the std bootstrap branch:** spec 15 §13 defines a closed compiler-pinned registry, fully qualified calls, deterministic name mangling and library source locations. Spec 16 defines the initial pure API. General user modules and imported types remain STD-3/P6-3; no filesystem search is invented. RFC 0016 records the proposal; the owner adopted it with the intermediate std merge (2026-10-07).
|
||||
|
||||
## Q-027 — Empty byte strings in source
|
||||
|
||||
Found while testing `std.bytes`: the frontend rejects `b""` with `E7006` (“an empty byte string has no array type”), but spec 15 §5 does not state a nonempty restriction. Zero-length byte slices work as `ref storage[0..0]` and std tests use that existing form. Resolve the source literal rule separately; the std bootstrap does not change it or format-0 array semantics.
|
||||
|
||||
## Q-028 — Recoverable endian reads need public standard result types
|
||||
|
||||
A plain integer cannot distinguish a decoded zero from a short input. A trap on malformed protocol input is not a recoverable API, and a boolean plus mutable out-parameter leaves an invalid/stale output for callers to track.
|
||||
|
||||
**Resolved in the endian work branch:** spec 16 §2.3 defines width-specific read result enums and one write result enum. Spec 15 §13 defines fully qualified standard enum type names, constructors and patterns using existing AIR enum semantics. RFC 0017 records the proposal. General modules, imported struct literals, generics and a must-use result rule remain outside this change.
|
||||
|
||||
## Q-029 — Bounded byte copy/search/split and recoverable arithmetic surface
|
||||
|
||||
Short destination capacity needs explicit failure without partial mutation. A substring search's empty needle can match the end of empty data, so the existing single-byte length sentinel cannot unambiguously encode all outcomes. A returned split pair would hold borrows inside an aggregate before that source/lifetime surface is available. Arithmetic operators currently either trap or wrap; buffer sizing needs a recoverable overflow result.
|
||||
|
||||
**Resolved in the STD-1b branch:** spec 16 §2.4 reuses `WriteResult` for copy, adds `FindResult` for substring search, and composes splitting from explicit caller-owned slices. Spec 16 §2.1.1 adds checked add/sub/mul for u64 and target-width usize with ordinary result enums. Wrapping stays with existing operators. No new borrowed aggregate, generic type, AIR instruction or arithmetic mode is introduced. RFC 0018 records this API policy; the owner adopted it with the intermediate std merge (2026-10-07).
|
||||
|
||||
## Q-030 — Strict text/encoding failures and destination state
|
||||
|
||||
UTF-8 needs a scalar-level iteration contract without an owning iterator. Hex/Base64 decoders need a choice between permissive input and one reproducible accepted encoding, plus a defined destination state when a bad byte appears after a valid prefix. Size calculations must not trap before reporting short capacity.
|
||||
|
||||
**Resolved in STD-2a:** spec 16 §2.5–§2.7 define UTF-8 next/validate with explicit offsets, lowercase hex output with case-insensitive ASCII decoding, and canonical padded standard Base64 with checked unused bits. Decoders validate all input before checking output capacity and before writing; invalid input wins over short output and both preserve the entire destination. Capacity guards avoid arithmetic overflow. RFC 0019 records the policy. No streaming state, URL-safe/permissive options, borrowed iterator or allocation is introduced. Formatting remains STD-2b.
|
||||
|
||||
## Q-031 — Minimal formatting and signed limits
|
||||
|
||||
Formatting needs a defined byte representation, insufficient-capacity state and signed-minimum behavior before a library promises arbitrary integer output. A format-string parser or growable writer would add contracts beyond the supplied-buffer milestone.
|
||||
|
||||
**Resolved in the STD-2b branch:** spec 16 §2.8 defines decimal writers for u64/i64 and target-width usize/isize with one ordinary result enum. Complete capacity is checked before mutation, successful counts include the sign, suffixes stay unchanged and no terminator is emitted. Signed minimum is supported without negating it directly. RFC 0020 records the proposal. General formatting, other widths, floats and parsing remain separate work; explicit caller offsets compose records with existing byte copy.
|
||||
|
||||
## Q-032 — Package module resolution and namespace boundaries
|
||||
|
||||
General source modules need explicit build inputs, stable ordering/provenance, local name binding and a choice of import visibility before reusable types can be published. Ambient directory/manifest discovery would make verification depend on environment state; transitive names would make one module's public surface depend on unrelated imports.
|
||||
|
||||
**Resolved on the STD-3 branch (RFC 0021 Implemented):** spec 12 §1.3 supplies an explicit `[modules]` name-to-source map, with bounded no-follow loading inside the chosen package root. Spec 15 §14 specifies an acyclic graph, direct qualified imports, module-local names, qualified struct literals, module-aware spawning, stable mangling and whole-graph verification through existing AIR. All declarations are available through import; aliases, re-exports, visibility modifiers, dependencies and generics remain separate work. File-only commands never discover manifests.
|
||||
|
||||
## Q-033 — Generic specialization and property constraints
|
||||
|
||||
The source plan names monomorphized generics but does not define application syntax, checking of unused templates, specialization bounds or precise Freeze/Local constraints.
|
||||
|
||||
**Resolved on the STD-4 branch (RFC 0022 Implemented):** spec 15 §15 defines explicit `::<...>` expression arguments, applied type names, ordered canonical specializations and concrete-body checking. Copy/Send/Share reuse existing rules; Freeze is format-0 IslandSafe content and Local is context-bound state, with explicit propagation rather than complementing Send. No trait inference or generic runtime representation is added; ordinary aggregate restrictions remain until linear_aggregates.
|
||||
|
||||
## 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 Implemented):** 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<T> 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<File>, Vec<sender<Job>> or a HashMap owning values. Partial holes, implicit destructors or host-only container magic are not an answer.
|
||||
|
||||
**Resolved on STD-6a (RFC 0024 Implemented):** spec 03 §26 uses an initialized contiguous prefix, explicit peak-charged reserve, failure returning pushed values and empty-only free returning the buffer on failure. Views reuse slice provenance and bounds. Safe Vec wrappers are spec 16 §2.10; other collections remain separate work.
|
||||
|
||||
## Q-037 — General hash-map key hashing and equality
|
||||
|
||||
HashMap<K,V> needs a stable hash/equality pair: equal keys must hash equally, while hash collisions must still compare actual keys. Current Copy/Send/Share/Freeze/Local constraints supply no user operations; type parameters cannot carry callbacks or values (spec 15 §15). Struct/byte-key equality, key ownership and effect-visible callable policies have no general source contract. A hash digest alone cannot represent original-key identity.
|
||||
|
||||
**Resolved on the STD-6d branch (RFCs 0029/0030/0031 Implemented):** spec 15 §18 supplies exact explicit static hash/equality operations; spec 16 §2.14–§2.15 specifies general owning HashMap<K,V,H,E>/HashSet<K,H,E> with dense complete entries and Copy probe indices. HashMap<Key, Own<Value>> and owning keys pass ordinary ownership/effect/borrow/task rules, independent model traces, source/AIR/profile/package checks and collection-before-every-step/scheduler stress. Numeric U64Map retains its API. No digest identity, inferred policy or map-only compiler primitive is introduced.
|
||||
|
||||
## Q-038 — Pure construction of built-in errors
|
||||
|
||||
STD-6d.2 needs to return allocation-size validation failure without allocating. Existing built-in errors were obtainable only from fallible runtime operations.
|
||||
|
||||
**Resolved (RFC 0027 Implemented):** spec 05 §14 adds feature `error_values` and pure `error.const B.variant`; source reuses `B::variant`. Every registered payload-free error variant is ordinary Copy data, never authority. Existing `enum.make` and runtime outcome rules are unchanged.
|
||||
|
||||
## Q-039 — Explicit static function parameters
|
||||
|
||||
General collections and algorithms need explicit typed hash/equality/order operations, while current generics carry only types.
|
||||
|
||||
**Resolved contract (RFC 0029 Implemented):** spec 15 §18 permits explicitly selected source functions as static parameters with exact typed/effect contracts. Selection is part of nominal specialization identity and lowers to existing named AIR calls/workers. No function pointers, capture environment, inferred effects or runtime dispatch are introduced. Q-037 is resolved by the implemented and verified generic map/set contracts (RFCs 0030/0031).
|
||||
@@ -139,6 +139,10 @@ Targets for Phase 6A, measured on dev tasks:
|
||||
| feature-header diagnostics | 0 (the frontend infers the feature closure) |
|
||||
| safety guarantees | unchanged, because the same AIR is verified | Every Phase 3+ semantic RFC re-measures the Agent Reference Bundle (`docs/agent/README.md`).
|
||||
|
||||
## Standard library track
|
||||
|
||||
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is next. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
|
||||
|
||||
## Task conventions
|
||||
|
||||
- IDs are `P<phase>-<n>` and never reused. A task split later becomes `P1-4a`, `P1-4b`.
|
||||
|
||||
@@ -132,11 +132,14 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
|---|---|---|---|---|---|
|
||||
| P6-1 | todo | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous |
|
||||
| P6-2 | todo | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics |
|
||||
| P6-3 | todo | Modules, imports, name resolution | P6-2 | `src/frontend/resolve.zig` | unresolved names produce registered diagnostics |
|
||||
| P6-4 | todo | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/types.zig` | generic code instantiates deterministically; constraint violations diagnosed |
|
||||
| P6-3 | done (RFC 0021 Implemented) | Explicit package modules, direct imports and qualified nominal types | P6-2 | `src/frontend/modules.zig`, spec 15 §14 | deterministic graph/name resolution; source/AIR and CLI tests |
|
||||
| P6-4 | done (RFC 0022 Implemented) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed |
|
||||
| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
|
||||
| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN |
|
||||
| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
|
||||
| P6-8 | todo | Formatter | P6-2 | `aji fmt` | idempotent; output parses to the same AST |
|
||||
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
|
||||
| P6-11 | todo | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics |
|
||||
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
|
||||
|
||||
The [standard-library track](standard-library.md) implements nineteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 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. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. STD-7a/RFC 0033 implements bounded std.io composition with explicit progress, resource loans and exact effects; conformance, GC/schedule, CLI and documentation checks pass. STD-7b/RFC 0034 implements safe owning buffered file adapters with explicit finish/discard and first-error/no-retry behavior; conformance, GC/schedule, CLI and documentation checks pass. STD-7c/RFC 0035 adds pure caller-buffer lexical paths and Copy component ranges; conformance, GC/schedule, CLI and documentation checks pass. The owner adopts STD-0..7 as an intermediate foundation and resumes language work (2026-10-07); remaining std system/service milestones stay in the backlog. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
|
||||
@@ -0,0 +1,196 @@
|
||||
# Standard library implementation plan
|
||||
|
||||
Non-normative. Started on `feat/std-bootstrap`, 2026-10-06, at the owner's request. Normative contracts live in spec 16 and the relevant source/runtime specifications. The owner requested an intermediate STD-0..7 merge on 2026-10-07 and a return to source-language work; remaining std work stays in the backlog. P7/P8 remain on hold for B1 analysis. B1 frozen inputs and private held-out tasks do not guide API design and MUST NOT be inspected or changed by this work.
|
||||
|
||||
## Target and design constraints
|
||||
|
||||
Without external source dependencies, Aji should support ordinary CLI tools, storage components, network services and structured concurrent programs. The mandatory semantic surface stays small.
|
||||
|
||||
- Prefer safe `.aji` over new AIR opcodes or opaque runtime implementations.
|
||||
- One canonical API for a common operation; effects, borrows, moves, failure and allocation budgets remain visible.
|
||||
- Caller-provided slices first; owning/growing buffers request `cap<mem.alloc>` and expose failure and explicit consumption.
|
||||
- Separate features (implementation support), effects (behavior) and capabilities (authority). Importing a module grants none.
|
||||
- Avoid a broad trait hierarchy. Begin with concrete adapters; add abstractions only when they reduce contracts and repair work.
|
||||
- Library functions use the existing verifier. A trusted crypto/TLS boundary is a separate audited dependency with a deterministic-profile model. Do not implement homemade cryptography.
|
||||
- Runtime capabilities and primitive coverage must be specified through every layer before a wrapper promises them. No implicit cleanup, detached tasks, reflection or ambient environment access.
|
||||
|
||||
## Current prerequisites
|
||||
|
||||
| Capability | Current state | Consequence |
|
||||
|---|---|---|
|
||||
| Scalars, structs/enums, slices/arrays, explicit borrows | implemented | pure fixed-storage algorithms can start now |
|
||||
| Heap/regions, I/O, files, TCP, clock/random, structured tasks/channels/mutex | implemented primitives | wrappers can reuse them, but their presence does not imply the complete APIs below |
|
||||
| Built-in standard imports and enum types | STD-0/1a/2a/2b implementation | compiler-pinned, closed registry; nineteen modules; qualified enum types/constructors/patterns; no package lookup |
|
||||
| General modules/imported struct literals | STD-3 implementation (P6-3; RFC Implemented) | explicit manifest mapping, direct qualified names, ordinary verifier |
|
||||
| User generics/structural constraints | STD-4 implementation (P6-4; RFC Implemented) | needed for reusable `Vec<T>`, `HashMap<K,V>`, option/result |
|
||||
| `linear_aggregates` | STD-5 implementation (RFC Implemented) | whole-value owning structs/enums/fixed arrays; initialized buffer<T>/std.vec implemented by STD-6a/b |
|
||||
| Extended filesystem, IPv6/DNS, args/env, TLS/crypto | not promised by current runtime | audit each primitive, authority, error and profile model before implementation |
|
||||
|
||||
A `Vec<u64>` prototype is not completion of `Vec<T>`. The collection gate requires valid and rejected examples for `Vec<File>`, `HashMap<Key, Own<Value>>` and `Vec<sender<Job>>`, plus cleanup and failure paths. No linked list is planned.
|
||||
|
||||
## Milestones
|
||||
|
||||
| Milestone | Deliverable | Exit criterion |
|
||||
|---|---|---|
|
||||
| Bootstrap | `std.math`, `std.bytes`, compiler-pinned import, normative API, source tests and bundle entry | all functions lower to existing AIR, verify and run; bad calls/aliases reject; import order does not affect canonical AIR; no hidden allocations or authority |
|
||||
| Intermediate foundation — STD-0..7 | nineteen pinned modules, explicit owning collections, bytes/text/formatting/encodings, bounded and buffered I/O, lexical paths | module contracts, failure/ownership, GC/schedule and source/AIR/profile/package gates pass; adopted for continuing language development |
|
||||
| Std 0.1 — system utilities | core bytes/math/mem/slice/hash, option/result, buffer and owning collections, UTF-8/fmt, hex/base64, small I/O/fs/path/time/random/log APIs | a CLI and bounded storage utility written in `.aji` use only std, explicit grants, documented failure/cleanup and deterministic fixture tests |
|
||||
| Integration gate | public, independently chosen 5–10k LOC application | ownership, cancellation, bounded memory and error cleanup work together; API/documentation costs recorded; defects become general repairs |
|
||||
| Std 0.2 — network services | TCP, IPv4/IPv6, DNS, task/channel helpers, JSON DOM, URI, bounded HTTP/1.1 | a local concurrent JSON/HTTP service passes deterministic fixtures and hosted smoke tests without external source packages |
|
||||
| Std 0.3 — internet services | audited secure random, SHA-256/SHA-512/HMAC/constant-time compare, TLS client/server, complete HTTP client/server and buffered I/O | verified caller contracts, audited trusted boundary, certificate validation, explicit network authority, bounded buffers and deterministic failure fixtures |
|
||||
|
||||
**CLI args/env move before the Std 0.1 exit**, rather than waiting for Std 0.3: they are required by the CLI target. Their capabilities and startup contracts need a vertical feature. Secure entropy is distinct from deterministic test randomness. Typed JSON schema generation waits for an independently justified compile-time facility; the DOM comes first.
|
||||
|
||||
SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protobuf, GUI, templating, regex and broad compression suites remain package-ecosystem work. TLS may initially depend on a vetted host crypto library; “no external source dependencies for callers” does not mean “no trusted native dependency.”
|
||||
|
||||
## Tasks
|
||||
|
||||
| ID | Status | Work | Depends | Done when |
|
||||
|---|---|---|---|---|
|
||||
| STD-0 | done (RFC Implemented) | bootstrap spec, source std, closed imports, conformance, documentation and complexity measurement | existing source frontend | bootstrap exit criterion above and required repository checks pass |
|
||||
| STD-1a | done (RFC Implemented) | endian u16/u32/u64 and qualified standard enum results | STD-0 | recoverable short-input/output failure, no partial mutation; all short lengths, empty/maximal values, fixtures and rejected alias examples pass |
|
||||
| STD-1b | done (RFC Implemented) | bounded copy/search, split composition and recoverable arithmetic for u64/usize | STD-1a | contracts define capacity/overflow failure, no partial mutation, empty inputs and aliasing; independent fixtures pass |
|
||||
| STD-2a | done (RFC Implemented) | UTF-8 next/validate and supplied-buffer hex/base64 | STD-1a/1b | malformed text and insufficient capacity are explicit, output unchanged on returned errors; independent vectors and boundary cases pass |
|
||||
| STD-2b | done (RFC Implemented) | 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 (RFC Implemented) | general modules and imported type names (P6-3) | STD-0 | deterministic resolution, collisions/cycles and diagnostics specified and covered |
|
||||
| STD-4 | done (RFC Implemented) | source generics (P6-4), constraints and option/result | STD-3 | deterministic specialization and rejected constraint examples; source/AIR budgets measured |
|
||||
| STD-5 | done (RFC Implemented) | 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-6a | done (RFC 0024 Implemented) | dynamic initialized buffer<T> storage/drain contract (Q-036) | STD-4/5 | vertical allocate/grow/push/pop/view/free; allocation failures preserve state, returned owners consumed; no hidden destruction |
|
||||
| STD-6b | done (RFC 0024 Implemented) | safe std.vec for Copy/owners/files/channel endpoints | STD-6a | explicit reserve, bounded push, moving pop/replace, empty-only free; deterministic and failure/cleanup tests |
|
||||
| STD-6c | done (RFC 0025 Implemented) | safe std.deque for Copy/owners/files/endpoints | STD-6a/b | bounded ring, both ends, failure-preserving explicit growth, complete resource transfer and empty-only free |
|
||||
| STD-6d | done (RFCs Implemented) | HashMap, HashSet, BinaryHeap | STD-6a/b/c | safe collection contracts, including HashMap<Key, Own<Value>>, recoverable failures and explicit draining |
|
||||
| STD-6d.1 | done (RFC 0026 Implemented) | pure std.hash: FNV-1a 64 / CRC32C, fresh/extend | STD-1b | four safe functions, exact byte/chunk conventions, independent public vectors and CLI/profile checks |
|
||||
| STD-6d.2a | done (RFC 0027 Implemented) | pure built-in error construction prerequisite | STD-6d.1 | vertical error_values feature, no authority/effect/resource changes; preflight allocation validation |
|
||||
| STD-6d.2 | done (numeric-key implementation; RFC 0028 Implemented) | U64Map<V> first; general HashMap<K,V> key policy Q-037 | STD-6d.1 | safe map with ownership/failure/collision tests and error_values prerequisite (RFC 0027); general-key gate resolved by STD-6d.4/5 |
|
||||
| STD-6d.3 | done (RFC 0029 Implemented) | explicit static hash/equality/order functions | STD-4 | exact callable contracts, ordinary AIR calls/workers and nominal operation identity; general collections remain required |
|
||||
| STD-6d.4 | done (RFC 0030 Implemented) | general owning HashMap<K,V,H,E> | STD-6d.3 | dense complete entries, Copy probe indices, exact equality and returned key/value ownership |
|
||||
| STD-6d.5 | done (RFC 0031 Implemented) | general owning HashSet<K,H,E> | STD-6d.4 | exact membership, duplicate/full input ownership, moving extraction and empty-only free |
|
||||
| STD-6d.6 | done (RFC 0032 Implemented) | owning BinaryHeap<T,B> | STD-6a/6d.3 | explicit pure order, complete resource extraction, bounded push, failure-preserving growth |
|
||||
| STD-7 | done (intermediate foundation) | 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-7a | done (RFC 0033 Implemented) | exact/bounded reads and limited file copies | STD-1b/3 | explicit progress/EOF/error, borrowed resources, caller slices and exact effects |
|
||||
| STD-7b | done (RFC 0034 Implemented) | owning buffered concrete file reader/writer | STD-6a/7a | failure ownership, refill/flush, explicit finish/discard and no hidden cleanup |
|
||||
| STD-7c | done (RFC 0035 Implemented) | caller-buffer lexical paths | STD-1b/2a | pure normalization/join/components with no 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 |
|
||||
| STD-10 | todo | IPv4/IPv6/TCP/DNS contracts and runtime gaps; task/channel helpers | STD-9 | bounded service fixtures, deterministic scheduling and schedule stress pass |
|
||||
| STD-11 | todo | JSON DOM, URI and bounded HTTP/1.1 | STD-6/10 | depth/size/header/body limits, malformed-input errors, streaming/EOF and cleanup tests |
|
||||
| STD-12 | todo | vetted crypto backend and TLS vertical RFC | STD-10/11 | explicit trusted dependency, certificate/trust/entropy inputs, audit and deterministic model |
|
||||
| STD-13 | todo | HTTP client/server integration and Std 0.3 review | STD-12 | internet-service exit criterion |
|
||||
|
||||
Each task can be split into reviewable increments; only executable exit criteria mark it done. The intermediate foundation is complete; the remaining system and service milestones are backlog work. P7 is reconsidered after B1 analysis and the integration gate; this plan does not unilaterally reopen it.
|
||||
|
||||
## API review and Model Capability Compression
|
||||
|
||||
For each increment record public signatures, conceptual additions, syntax forms, diagnostics, required verifier state, allocations/budgets and cleanup obligations. Run `zig build agent-reference` and `tools/agent_bundle_tokens.py --source`; report Quick Reference and Source Reference Bundle growth by group. Library reference pages are read on demand.
|
||||
|
||||
Use general public use cases and fixtures to measure documentation read, output size, verifier failures, repair cycles and ownership visibility. Performance and allocations also matter, but an API with five overlapping forms needs evidence. No language/API design decision is made from tasks M/C or the private corpus, and no compression benefit is claimed before measurement.
|
||||
|
||||
## Bootstrap verification
|
||||
|
||||
Required: `zig build`, `zig build test`, `zig build conformance`, `zig fmt --check build.zig build.zig.zon src tools tests/extended`, `python3 tools/source_coverage.py`, and `zig build agent-reference`. Because imported code reaches the ordinary CLI, also run `python3 tests/hosted/smoke.py`. Run tests use fuel, never wall-clock termination.
|
||||
|
||||
The bootstrap does not add ownership or concurrency semantics. Preserved invariant: shared slices only read, exclusive slices only write, no borrow escapes or resource is consumed. Existing borrow/bounds transfer functions and interpreter rules apply; valid and rejected source fixtures exercise that boundary. Existing `E7001`, `E7002`, `E7005`, `E7006`, `E2101`, `T0002` suffice. AIR format 0 remains unchanged and existing programs without imports lower identically.
|
||||
|
||||
Bootstrap result: nine APIs implemented; full conformance, unit/Quick Reference, formatting and source coverage checks pass. Hosted file/stdin/TCP smoke tests and evaluation harness self-tests pass (22 tests; one environment-dependent skip). The documented example returns 42 with no grants; invalid clamp bounds report `std/math.aji:20`. RFC 0016 remains Proposed for owner review. Token growth (cl100k): Quick Reference +4.8%; source bundle excluding AIR +6.6%; AIR unchanged.
|
||||
|
||||
## STD-1a verification
|
||||
|
||||
Twelve additional endian functions and four ordinary Copy enums lower to existing AIR. The invariant remains: no access outside the supplied slice, no escaping borrow, no hidden allocation, and no mutation on insufficient output capacity. The capacity branch precedes every access. Existing verifier/interpreter rules and diagnostics apply; valid/rejected source examples and hand-written AIR fixtures exercise payload typing and read behavior. AIR format 0 is unchanged. Qualified standard enum names implement only a closed-registry subset of STD-3; user modules, imported struct literals, dependencies and generics remain open.
|
||||
|
||||
Run the same required checks as bootstrap. Endian fixtures include independent LE/BE byte vectors, every short length, zero/maximal values, every bit, nonzero offsets, extra input/output bytes, returned enum records, compound types, name collisions, exhaustive matches and forbidden mutable aliasing. RFC 0017 records final checks and complexity measurements.
|
||||
|
||||
## STD-1b verification
|
||||
|
||||
Eight further pure functions reuse existing primitives: `std.bytes.copy` and `find_slice`, plus checked add/sub/mul for `u64` and `usize`. Copy reuses `WriteResult`; three additional ordinary Copy enums represent substring matches and arithmetic results. Wrapping remains an operator. Splitting composes a search with explicit caller-bounded slice operations; no borrowed aggregate, iterator, cursor, compiler/runtime change or hidden allocation is added.
|
||||
|
||||
The preserved invariant is shared-read/exclusive-write access only within the supplied slices, no escaping borrows and no mutation on short output. Existing verifier/call/alias/enum rules and interpreter behavior suffice. Valid/rejected source fixtures and hand-written AIR twins cover the contracts; current diagnostics and AIR format 0 are unchanged. Tests include all 81 input/output length pairs through eight, disjoint split borrows, overlapping and empty short-output aliases, 428 search cases, seven split cases and 320 independently computed arithmetic operand pairs exercised through both widths. The interpreter's numeric vectors use its default `air64`; library usize limits are computed with target-width wrapping subtraction. RFC 0018 records the final repository checks and complexity measurements. STD-2 can now start with UTF-8 and supplied-buffer encodings.
|
||||
|
||||
## STD-2a verification
|
||||
|
||||
Six functions and six ordinary result enums add UTF-8 next/validate and supplied-buffer hex/Base64 to the closed registry. UTF-8 returns a scalar plus consumed bytes; caller offsets carry iteration state. Hex accepts both ASCII letter cases and emits lowercase; Base64 accepts canonical padded standard text with zero unused bits. Decode validates all input before capacity/mutation, so malformed input wins over insufficient output and every returned error preserves the destination. Size guards avoid intermediate overflow.
|
||||
|
||||
All algorithms are safe source using existing verifier/runtime rules, fixed frame storage and explicit slice borrows. No borrow escapes, owner/resource is consumed, heap allocation is hidden, AIR meaning changes or authority is granted. Valid/rejected examples, stable existing diagnostics, deterministic interpreter tests and compatibility are specified in spec 16 §2.5–§2.7 and RFC 0019. The registry embeds three additional modules without a resolver or dependency extension. Tests cover independent Python scalar/byte vectors, UTF-8 boundaries/truncation/surrogates, all input byte values, canonical pad bits, every relevant capacity, late invalid bytes, output suffixes, disjoint same-allocation buffers, namespace collisions and hand-written AIR equivalence. Formatting remains STD-2b; this increment does not mark the original whole text/formatting task complete.
|
||||
|
||||
## STD-2b verification
|
||||
|
||||
Four safe decimal writers and one ordinary result enum complete the supplied-buffer formatting increment. No heap, retained cursor, format-string language, runtime primitive or syntax is added. Counts include a negative sign, suffixes remain unchanged and insufficient capacity preserves the complete destination. Counting precedes mutation; signed magnitude uses `-(value + 1)` then an unsigned increment, avoiding signed-minimum negation. Explicit caller offsets and `std.bytes.copy` compose a record; failure preserves the individual call's destination, not earlier successful calls.
|
||||
|
||||
Spec 16 §2.8 and RFC 0020 specify the invariant, existing verifier/runtime rules, valid/rejected examples, diagnostic impact, deterministic execution and unchanged AIR format 0. Independent Python decimal vectors exercise zero, all small values, decimal/binary transitions, seeded scalar inputs, both 64-bit limits and every capacity from zero through 22, checking all guard/suffix bytes. Target-width fixtures guard conversions against the target limits; the current interpreter executes at air64. Source/AIR result equivalence, explicit record composition, disjoint borrows, qualified types/collisions and rejection of conflicting borrows (including short output), missing imports, invalid payloads/types and incomplete matches cover the public boundary. RFC 0020 records required checks and source/AIR documentation budgets. Next semantic prerequisites for owning buffers and containers remain STD-3/4/5; a decimal writer does not complete general formatting or owning strings.
|
||||
|
||||
## STD-3 verification
|
||||
|
||||
P6-3 now links explicit package sources through the same frontend as compiler-pinned std. Manifest mappings supply source bytes; pure linking checks an acyclic graph, module identity and direct-import visibility, then emits collision-free deterministic AIR. Imported functions, structs, enums and qualified task workers use existing ownership, lifetime, effect and scheduler rules. Check/lower/report instantiate no grants; run/explore use explicit manifest grants and overrides. Package sources have portable bounded paths, no symlink traversal and a 64 MiB aggregate source budget; file-only commands never discover manifests.
|
||||
|
||||
RFC 0021 records invariants, diagnostics, compatibility, complete validation and documentation growth. General modules and imported struct literals are implemented on this branch; dependencies and external package resolution are separate work. The next semantic step is STD-4/P6-4 generics and structural constraints, followed by the independent linear-aggregate gate. Owning collections still require both gates.
|
||||
|
||||
## STD-4 verification
|
||||
|
||||
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<array<T,N>> 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.
|
||||
|
||||
## STD-6a/b/c verification
|
||||
|
||||
Initialized buffer<T> and safe Vec/Deque use existing ownership/borrow/task rules and deterministic allocation budgets. Deque is ordinary library source: Option<T> represents vacancy, both ends exchange complete elements, and explicit growth rotates a ring only after allocation succeeds. Nonempty free returns the queue, so no library action closes user resources. Slot charges include Option's enum tag. Ordinary visible representation fields have a documented invariant, with no unsafe bypass.
|
||||
|
||||
RFC 0024 records storage/Vec validation. RFC 0025 records the deque API/budget measurements and validation: independent Python deque traces, all small head/length combinations under growth, wrapped owners, files/senders/workers, failure/cleanup and borrow/constraint rejections. Maps/sets/heaps are STD-6d; this increment does not complete Std 0.1.
|
||||
|
||||
## Hash foundation and next map contract
|
||||
|
||||
STD-6d.1/RFC 0026 adds safe std.hash with four byte-only fresh/continuation operations, no new semantics or heap authority. FNV/CRC constants and public vectors are independently verified; hashes never replace key equality. [The map design](../design/hash-map.md) specifies numeric-key U64Map<V>, bounded insert, returned replacement/full ownership, tombstone lookup, moving removal/drain and explicit peak-charged rehash. STD-6d.2/RFC 0028 implements safe std.map.U64Map<V> with ten operations, using explicit error construction (RFC 0027) for preflight validation. Independent dictionary traces, collision/tombstone/wrap cases, exact peak/refund accounting, owning/files/sender/task tests and rejected leaks/aliases/Copy uses cover the contract. Q-037 is now resolved by STD-6d.4/5; general HashMap<Key, Own<Value>>/HashSet and BinaryHeap validation are recorded below.
|
||||
|
||||
|
||||
## General operation-selection prerequisite
|
||||
|
||||
STD-6d.3/RFC 0029 implements explicitly bound static functions with exact typed/effect contracts, forwarding, generic function arguments, nominal operation identity and named workers. It reuses ordinary AIR and preserves direct-import visibility, capability inputs, ownership and task loans. Source/AIR positives/rejections, recursive/cyclic contracts, GC/scheduler stress, CLI/profile/provenance checks and documentation budgets are recorded in the RFC. General HashMap/HashSet storage/API subsequently resolves Q-037, and BinaryHeap completes STD-6d; STD-7 remains required.
|
||||
|
||||
|
||||
## General owning set verification
|
||||
|
||||
STD-6d.5/RFC 0031 implements safe HashSet<K,H,E> over the general map, with nine explicit operations. Duplicate insertion preserves every stored entry/bucket and returns the exact incoming key, including its resources; full does likewise for new keys. Remove/pop transfer complete stored keys, and nonempty free returns the whole set. Allocation, failure rollback, peak/refund accounting and dense pop order follow the map. No new language syntax, verifier/runtime state, diagnostic, AIR feature or trusted boundary is added.
|
||||
|
||||
All 973 conformance cases pass, including 26 set cases. Runtime fixtures pass collection before every instruction; the shared lookup fixture passes 12 seeds under quanta 1, 2, 7 and its own quantum. Independent Python set/representative oracles cover 80 operations across Copy/owning traces and check membership after each operation. Byte-buffer/file keys, exact duplicate-table preservation, returned owners, allocation failure/refunds/peaks and rejected leaks/moves/aliases/loans/policies/non-Share contents are covered. Unit/Quick Reference, formatting, hosted smoke, 53 CLI/profile/package/source/AIR checks, 106/106 source coverage constructs and bundle generation pass. RFC 0031 records documentation growth. The separate general-map full GC/stress process subsequently completed with all 33 cases passing. BinaryHeap validation follows below; STD-7 I/O/path is next.
|
||||
|
||||
|
||||
## Owning binary heap verification
|
||||
|
||||
STD-6d.6/RFC 0032 implements eight safe std.heap operations with an exact explicit pure ordering function. Copy-index sifting preserves complete owners in dense initialized storage; moving pop repairs dense holes. Full push returns its input without callbacks, nonempty free returns the heap, and explicit reserve preserves values/layout/extraction order on every returned allocation failure. No new source/AIR semantics, diagnostics, verifier/runtime state or trusted boundary are added.
|
||||
|
||||
All 1007 conformance cases pass, including 34 heap fixtures. Heap runtime fixtures pass collection before every instruction; shared lookup, sender ownership transfer and restored task loans run 12 schedule seeds under quanta 1, 2, 7 and their own quantum. Independent heapq traces cover 160 operations over min/Copy and max/owning records, plus all 120 permutations of five values. Direct owners, owning byte buffers, files, sender endpoints, duplicates, empty/full/overflow, exact layout preservation under both reserve-failure phases, peaks/refunds/cross-authority accounting and rejected leaks/Copy/aliases/loans/policy/effects are covered. Unit/Quick Reference, formatting, hosted smoke, 70 CLI/source/AIR/package/profile/provenance checks, 109/109 source coverage constructs and bundle generation pass. RFC 0032 records documentation growth.
|
||||
|
||||
The long general-map GC/stress process also completed with 33/33; Q-037 and the collection gate STD-6d are resolved on this branch. I/O and lexical paths are STD-7; filesystem gaps, args/env and logs remain STD-8. This does not complete Std 0.1 or reopen the native backend phase.
|
||||
|
||||
|
||||
## Bounded I/O foundation verification
|
||||
|
||||
STD-7a/RFC 0033 implements six safe std.io compositions with concrete io.read/fs.read/net.read/fs.write effects, borrowed resources and caller-supplied slices. Exact reads distinguish completed data, EOF and read errors. Bounded read-to-end/copy stop at capacity/limit without consuming an extra byte to probe EOF. Copy errors distinguish confirmed reads from confirmed writes; external partial writes have no rollback promise. No heap, retained borrow, open/close, task/timeout, new syntax/AIR semantics, verifier state or diagnostic is added.
|
||||
|
||||
All 1027 conformance cases pass, including 20 I/O cases. All runtime I/O fixtures pass collection before every instruction; fragmented TCP and restored task loans run 12 schedule seeds under quanta 1, 2, 7 and their own quantum. An independent Python prefix oracle covers 162 exact/bounded reads and 250 copy/append combinations, validating bytes, guards, counts, source cursor tails, limits and empty scratch. Hosted tests produce a real read error and partial external file write: four bytes consumed, two confirmed written, three actually present. Unit/Quick Reference, formatting, hosted smoke, 55 CLI/source/AIR/package/import-order/profile/provenance checks, 111/111 source coverage constructs and bundle generation pass. RFC 0033 records documentation growth. Owning buffered adapters STD-7b and lexical paths STD-7c remain required; STD-7 and Std 0.1 are unfinished.
|
||||
|
||||
|
||||
## Owning buffered file verification
|
||||
|
||||
STD-7b/RFC 0034 implements safe std.io.reader/std.io.writer, each owning a file and a fixed-capacity initialized byte buffer. Only new allocates with explicit authority and failure returns the original file. Reads distinguish cached data/refill/EOF and finish returns unread readers. Writer errors preserve pending bytes and the first error, forbid further writes/retries, and return the whole failed writer from finish. Explicit discard reports abandoned cached/pending bytes, frees storage and returns the file. No file open/close/sync, hidden growth/cleanup or new syntax/AIR/runtime/verifier state is added.
|
||||
|
||||
All 1061 conformance cases pass, including 34 buffered adapter fixtures. Every buffered fixture passes collection before every instruction; worker transfer and restored loans run 12 seeds under quanta 1, 2, 7 and their own quantum. Independent byte oracles cover 48 read streams, 64 exact prefixes and 96 segmented writes. On Linux, 89 CLI/source/AIR/package/profile/provenance checks include a real read fault and four external partial-write cases; raising the child's file quota after failure proves the writer still performs no retry and preserves pending bytes/error. Unit/Quick Reference, formatting, hosted smoke, 115/115 source coverage constructs and reference generation pass. RFC 0034 records documentation growth. Lexical paths STD-7c, system gaps STD-8 and the Std 0.1 exit examples remain required; the full std roadmap is unfinished.
|
||||
|
||||
|
||||
## Caller-buffer lexical path verification
|
||||
|
||||
STD-7c/RFC 0035 implements six pure std.path operations: raw component queries return bounded Copy ranges; normalize/join write into caller-provided storage with no heap or authority. NUL/size/capacity errors preserve the entire output. Reverse measurement/emission retains relative unmatched parents, drops parents above root, and needs only the final normalized capacity. Filesystem operations still enforce their independent path/grant rules.
|
||||
|
||||
All 1079 conformance cases pass, including 18 path fixtures. All path runtime fixtures pass collection before every instruction; shared reads and restored output loans pass 12 seeds under quanta 1, 2, 7 and their own quantum. An independent Python forward-stack oracle covers 132 paths with raw queries/idempotence and every short/exact/extra capacity, 49 joins and four malformed pairs; separate fixtures cover all 255 non-NUL bytes, disjoint slices, one-byte canceled results, late malformed input, guards/suffixes and T0008 for reused ranges. The model uses bounded batches with separate literal frames, preserving all vectors and capacities. Linux CLI/source/AIR/package/profile/provenance/audit/authority checks pass (68); all fourteen preceding std/source CLI suites pass again. Unit/Quick Reference, formatting, hosted smoke, 117/117 source construct coverage and reference generation pass. RFC 0035 records documentation growth. STD-7 and the intermediate foundation are complete; STD-8, the full Std 0.1 exit and later service milestones remain unfinished.
|
||||
|
||||
|
||||
## Intermediate adoption (owner decision, 2026-10-07)
|
||||
|
||||
The owner requested a sufficient intermediate std stage, integration of the work branch and resumption of language development. STD-0 through STD-7 provide nineteen compiler-pinned safe source modules: math/bytes/hash, UTF-8/hex/Base64/formatting, option/result, Vec/Deque/U64Map/general HashMap/HashSet/BinaryHeap, bounded std.io, owning buffered file adapters and lexical paths. The branch also supplies explicit modules/generics, whole-value linear aggregates/initialized buffers, pure error values and exact static callable contracts, through source/AIR/verifier/interpreter and tests where applicable. RFCs 0016–0035 are adopted and implemented; their rules are integrated into spec/reference in the same merged change.
|
||||
|
||||
This intermediate gate is sufficient to resume language work. It does not mark Std 0.1 complete: filesystem gaps, args/env, time/random wrappers, structured logs and CLI/storage exit examples remain STD-8; the public 5–10k LOC integration gate and network/JSON/HTTP/TLS milestones remain in the backlog. Frozen evaluation inputs and the private held-out corpus are untouched. Next source-language work is Q-034/P6-11 (explicit borrowed-return calls/bindings); P7/P8 retain their existing gate.
|
||||
@@ -39,10 +39,12 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It
|
||||
| `channel_transfer` | reserved | — | `cancellation`, `capabilities`, `channels`, `effects`, `heap`, `ownership`, `resources`, `tasks` | endpoints inside channel elements or mutex contents; unscheduled |
|
||||
| `channels` | published | 3 | `cancellation`, `capabilities`, `effects`, `heap`, `ownership`, `resources`, `tasks` | `sender<T>`, `receiver<T>`, `channel.*`, `select` (spec 04 §38–§39) |
|
||||
| `effects` | published | 2 | — | flat effect checking of `effects [...]` for `call` and `intrinsic` (E3101, spec 05 §9) |
|
||||
| `error_values` | published | 6 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | pure construction of registered built-in errors with `error.const`; errors confer no authority (spec 05 §14) |
|
||||
| `guard_transfer` | reserved | — | `cancellation`, `effects`, `ownership`, `sync`, `tasks` | `guard<T>` as parameter, return type or aggregate member; unscheduled |
|
||||
| `heap` | published | 2 | `capabilities`, `effects`, `ownership`, `resources` | `own<T>`, `own_array<T>`, `own.*`, built-in `alloc_error`, `mem.alloc` budgets and `budget` narrowing (spec 03 §18–§19) |
|
||||
| `islands` | published | 4 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `island<T>`, `frozen<T>`, `iref<T>`, `island.*`, `frozen.*`, `iref.eq`, `IslandSafe`, `T0010` (spec 03 §22–§23) |
|
||||
| `linear_aggregates` | 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 |
|
||||
| `linear_buffers` | published | 6 | `arrays`, `capabilities`, `effects`, `heap`, `linear_aggregates`, `ownership`, `resources` | initialized prefix buffer<T>, explicit growth/push/pop/view/empty-only free; spec 03 §26 |
|
||||
| `ownership` | published | 1 | — | frame storage `local<T>`, second-class borrows `ref<T>`/`mut<T>`, `from` returns, initialization (spec 07 §8.8, spec 07a, spec 08 §11, §13) |
|
||||
| `receiver_dup` | reserved | — | `cancellation`, `capabilities`, `channels`, `effects`, `heap`, `ownership`, `resources`, `tasks` | several receivers of one channel (MPMC); unscheduled |
|
||||
| `regions` | published | 2 | `capabilities`, `effects`, `heap`, `ownership`, `resources` | `region`, `region.*`, static generations (spec 03 §20) |
|
||||
|
||||
@@ -57,6 +57,7 @@ instruction = [ local { "," local } "=" ] operation ;
|
||||
|
||||
operation = "const." int_type int_lit
|
||||
| "const.bool" ( "true" | "false" )
|
||||
| "error.const" ( "alloc_error" | "cap_error" | "io_error" ) "." ident (* feature error_values; no payload *)
|
||||
| "copy" local
|
||||
| arith_op local "," local
|
||||
| "assert" local
|
||||
@@ -65,6 +66,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
|
||||
@@ -117,6 +119,11 @@ capability_op = "cap.narrow." ident local { "," local } ok_err (* te
|
||||
|
||||
(* Feature heap (spec 03 §18–§19). *)
|
||||
heap_op = "own.new" local "," local ok_err (* terminator: value, cap<mem.alloc> *)
|
||||
| "buffer.new" type local "," local ok_err
|
||||
| ( "buffer.len" | "buffer.capacity" | "buffer.view" ) local
|
||||
| "buffer.reserve" local "," local "," local ok_err
|
||||
| "buffer.push" local "," local ok_err
|
||||
| ( "buffer.pop" | "buffer.free" ) local ok_err
|
||||
| "own.array" local "," local "," local ok_err (* terminator: count, element, cap<mem.alloc> *)
|
||||
| "own.take" local
|
||||
| "own.free" local ;
|
||||
@@ -210,6 +217,7 @@ type = int_type | "bool" | "void" | "never" | global
|
||||
| "cap" "<" path ">" (* feature capabilities; a capability kind, e.g. cap<fs.read> *)
|
||||
| "file" "<" ( "read" | "write" | "append" ) ">" (* feature resources *)
|
||||
| "listener" | "stream" (* feature resources *)
|
||||
| "buffer" "<" type ">" (* feature linear_buffers *)
|
||||
| ( "own" | "own_array" ) "<" type ">" (* feature heap *)
|
||||
| "region" (* feature regions *)
|
||||
| "scope" | "task" "<" type ">" (* feature tasks *)
|
||||
@@ -240,3 +248,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 ;
|
||||
+26
-12
@@ -12,29 +12,39 @@
|
||||
- Every construct has one canonical spelling (spec 15 §1).
|
||||
*)
|
||||
|
||||
module = "module" path { item } ;
|
||||
module = "module" path { module_import } { item } ;
|
||||
module_import = "import" path ";" ; (* contextual word, spec 15 §13/§14 *)
|
||||
item = type_decl | fn_decl ;
|
||||
path = ident { "." ident } ;
|
||||
|
||||
type_decl = struct_decl | enum_decl ;
|
||||
struct_decl = "struct" ident "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
struct_decl = "struct" ident [ type_params ] "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
field = ident ":" type ;
|
||||
enum_decl = "enum" ident "{" variant { "," variant } [ "," ] "}" ;
|
||||
enum_decl = "enum" ident [ type_params ] "{" variant { "," variant } [ "," ] "}" ;
|
||||
variant = ident [ "(" type { "," type } ")" ] ;
|
||||
|
||||
fn_decl = "fn" ident "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
|
||||
fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
|
||||
"effects" "[" [ path { "," path } ] "]"
|
||||
block ; (* `trusted` is reserved and rejected, E7006 *)
|
||||
param = ident ":" type ;
|
||||
type_params = "<" type_param { "," type_param } ">" ;
|
||||
type_param = ident [ ":" ( property { "+" property } | function_contract ) ] ;
|
||||
function_contract = "fn" "(" [ type { "," type } ] ")" "->" type
|
||||
"effects" "[" [ path { "," path } ] "]" ;
|
||||
property = "Copy" | "Send" | "Share" | "Freeze" | "Local" ;
|
||||
type_args = "<" generic_arg { "," generic_arg } ">" ;
|
||||
generic_arg = type | "fn" path [ application ] ; (* static function selection; spec 15 §18 *)
|
||||
application = "::" type_args ; (* explicit; no inference, spec 15 §15 *)
|
||||
|
||||
type = int_type | "bool" | "void" | "never" | ident
|
||||
type = int_type | "bool" | "void" | "never" | path
|
||||
| path type_args
|
||||
| "[" type ";" int_lit "]"
|
||||
| wrapper "<" type ">"
|
||||
| "cap" "<" path ">"
|
||||
| "file" "<" ( "read" | "write" | "append" ) ">" ;
|
||||
(* `>>` closes two type arguments: mut<file<write>> *)
|
||||
wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array"
|
||||
| "task" | "sender" | "receiver" | "mutex" ;
|
||||
| "task" | "sender" | "receiver" | "mutex" | "buffer" ;
|
||||
int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
|
||||
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ;
|
||||
(* `region`, `listener`, `stream`, `io_error`, `alloc_error`,
|
||||
@@ -45,12 +55,12 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
|
||||
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
|
||||
statement = "let" binding [ ":" type ] "=" expr ";"
|
||||
| "var" ident ":" type "=" ( expr | "zero" ) ";"
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] ident "=" place ";" (* borrow binding *)
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] ident "=" ( place | borrow_call ) ";" (* borrow binding; buffer.view(b) / graph access also bind child borrows, spec 15 §17 *)
|
||||
| place "=" expr ";"
|
||||
| "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";"
|
||||
| expr ";"
|
||||
| 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
|
||||
@@ -63,7 +73,7 @@ if_expr = "if" expr block [ "else" ( if_expr | block ) ] ;
|
||||
match_expr = "match" expr "{" { arm } "}" ;
|
||||
arm = pattern "=>" ( block | expr "," ) ;
|
||||
pattern = "_" | int_lit (* integer matches only; `_` is required there *)
|
||||
| ident "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *)
|
||||
| path [ application ] "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *)
|
||||
| ident [ "(" ident { "," ident } ")" ] ; (* outcome of a fallible operation: ok(n), closed *)
|
||||
|
||||
select_stmt = "select" "{" { select_arm } "cancelled" [ "(" ident { "," ident } ")" ] "=>" ( block | expr "," ) "}" ;
|
||||
@@ -83,16 +93,20 @@ unary = ( "-" | "not" | "*" ) unary
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] place
|
||||
| "move" ident
|
||||
| postfix ;
|
||||
postfix = primary { "." member | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
postfix = primary { application | "." member | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *)
|
||||
call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ;
|
||||
primary = int_lit | "true" | "false" | string
|
||||
| ident [ "{" field_init { "," field_init } [ "," ] "}" ] (* struct literal *)
|
||||
| ident "::" ident (* enum variant; applied by a call *)
|
||||
| "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 ;
|
||||
borrow_call = "buffer" "." "view" "(" ident ")"
|
||||
| ( "island" | "frozen" | "arc" ) "." "at" "(" expr "," expr ")" ;
|
||||
place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ;
|
||||
|
||||
int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ;
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
# Standard library API
|
||||
|
||||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve and std.io.reader/std.io.writer new.
|
||||
|
||||
Except std.io/std.io.reader/std.io.writer (§2.17–§2.18) and std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||||
|
||||
| Module | Function signature | Result/failure |
|
||||
|---|---|---|
|
||||
| `std.math` | `min_u64(a: u64, b: u64) -> u64` | smaller operand |
|
||||
| `std.math` | `max_u64(a: u64, b: u64) -> u64` | larger operand |
|
||||
| `std.math` | `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` | inclusive clamp; `T0002` if `lower > upper` |
|
||||
| `std.bytes` | `equal(a: slice<u8>, b: slice<u8>) -> bool` | byte equality |
|
||||
| `std.bytes` | `compare(a: slice<u8>, b: slice<u8>) -> i8` | unsigned lexicographic order: exactly -1/0/1 |
|
||||
| `std.bytes` | `find(data: slice<u8>, byte: u8) -> usize` | first index; `data.len` if absent |
|
||||
| `std.bytes` | `starts_with(data: slice<u8>, prefix: slice<u8>) -> bool` | empty prefix matches |
|
||||
| `std.bytes` | `ends_with(data: slice<u8>, suffix: slice<u8>) -> bool` | empty suffix matches |
|
||||
| `std.bytes` | `fill(dst: slice_mut<u8>, byte: u8) -> void` | fills caller-provided storage |
|
||||
|
||||
```aji
|
||||
module demo.standard
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var data: [u8; 4] = zero;
|
||||
std.bytes.fill(mut data, 65);
|
||||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||||
let index = std.bytes.find(ref data, 65);
|
||||
if index < data.len { assert(data[index] == 65); }
|
||||
return std.math.clamp_u64(42, 0, 100);
|
||||
}
|
||||
```
|
||||
|
||||
Unknown module/member or absent import: `E7002`; duplicate import: `E7006`; malformed import or type arguments: `E7001`; wrong argument type/arity: `E7005`; conflicting borrows: `E2101`. No new diagnostic code.
|
||||
|
||||
The example is `tests/conformance/source/quickref/std.aji`; library boundary and algorithm tests live under `tests/conformance/source/std/`.
|
||||
|
||||
## Endian integers
|
||||
|
||||
All functions operate at slice offset zero. Pass a sub-slice to select an offset. Extra bytes are ignored on read and preserved on write. No alignment or heap allocation is required. A short destination is unchanged; a short source yields no integer payload.
|
||||
|
||||
| Width | Read functions (`src: slice<u8>`) | Result | Write functions (`dst: slice_mut<u8>, value: uW`) | Result |
|
||||
|---|---|---|---|---|
|
||||
| 16 | `std.bytes.read_u16_le`, `std.bytes.read_u16_be` | `std.bytes.ReadU16` | `std.bytes.write_u16_le`, `std.bytes.write_u16_be` | `std.bytes.WriteResult` |
|
||||
| 32 | `std.bytes.read_u32_le`, `std.bytes.read_u32_be` | `std.bytes.ReadU32` | `std.bytes.write_u32_le`, `std.bytes.write_u32_be` | `std.bytes.WriteResult` |
|
||||
| 64 | `std.bytes.read_u64_le`, `std.bytes.read_u64_be` | `std.bytes.ReadU64` | `std.bytes.write_u64_le`, `std.bytes.write_u64_be` | `std.bytes.WriteResult` |
|
||||
|
||||
Read enums have exactly `ok(uW)` and `short_input`. `WriteResult` has exactly `ok` and `short_output`. These are ordinary Copy enums, handled with qualified enum patterns; they are not intrinsic outcome matches. They can be passed or returned through user functions. No generic must-use rule is introduced.
|
||||
|
||||
```aji
|
||||
module demo.endian
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u32
|
||||
effects []
|
||||
{
|
||||
var wire: [u8; 6] = zero;
|
||||
match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.bytes.read_u32_be(ref wire[1..5]) {
|
||||
std.bytes.ReadU32::ok(value) => { return value; }
|
||||
std.bytes.ReadU32::short_input => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Missing enum arm: `E7004`; duplicate/wildcard enum arm: `E7006`; unknown type/variant or missing import: `E7002`; wrong width/payload, immutable destination or variant from another enum: `E7005`; conflicting destination borrows: `E2101`. Existing `or trap` only applies to fallible built-in operations, so it is not used with these enums.
|
||||
|
||||
The example is checked in `source/quickref/std_endian.aji`; fixtures for every width/order and all short lengths are in `source/std/endian_u*.aji`.
|
||||
|
||||
## Non-cryptographic hashing and CRC-32C
|
||||
|
||||
Directly import `std.hash`. All four functions are ordinary safe source, `effects []`, with no heap allocation, mutation, retained borrow or capability requirement.
|
||||
|
||||
| Function | Result |
|
||||
|---|---|
|
||||
| `std.hash.fnv1a64(data: slice<u8>) -> u64` | FNV-1a 64, offset basis `0xcbf29ce484222325` |
|
||||
| `std.hash.fnv1a64_extend(state: u64, data: slice<u8>) -> u64` | continue from the supplied state |
|
||||
| `std.hash.crc32c(data: slice<u8>) -> u32` | finalized Castagnoli CRC; empty input gives zero |
|
||||
| `std.hash.crc32c_extend(checksum: u32, data: slice<u8>) -> u32` | continue from a finalized checksum, undo/reapply final XOR |
|
||||
|
||||
Extend with the previous result and the next bytes: `crc32c_extend(crc32c(prefix), suffix)` equals CRC of their concatenation. Empty input preserves any supplied continuation value. FNV wraps multiplication modulo 2^64; CRC uses reflected polynomial `0x82f63b78` and initial/final XOR `0xffffffff`. Every byte participates, including zero; there are no implicit separators or padding. Numeric results are target-independent; serialize explicitly with `std.bytes.write_u32/u64_le/be`. These are not cryptographic functions, and CRC-32C is not IEEE CRC-32. A hash collision never establishes key equality. Structured fields need explicit byte encoding and boundaries.
|
||||
|
||||
The [checked example](../../examples/std/hash.aji) computes CRC-32C of `123456789` (`0xe3069283`) in two chunks, hashes `foobar` and serializes the CRC little-endian. Empty slices use an existing array's `ref data[0..0]`; an empty byte literal has no array type. Calls cost O(bytes) work and O(1) auxiliary state; CRC initially uses eight bit steps per byte. Borrow/type/import errors keep E2101/E7005/E7002, and these monomorphic functions take no generic arguments. Definition/constants: [FNV RFC 9923](https://www.rfc-editor.org/rfc/rfc9923.html#section-2); independent published CRC vectors: [RFC 3720 B.4](https://www.rfc-editor.org/rfc/rfc3720.html#appendix-B.4). Exact recurrence is spec 16 §2.12.
|
||||
|
||||
## Copy and substring search
|
||||
|
||||
| Function | Result and contract |
|
||||
|---|---|
|
||||
| `std.bytes.copy(dst: slice_mut<u8>, src: slice<u8>) -> std.bytes.WriteResult` | `ok` copies the whole input into the output prefix, preserving the suffix; `short_output` leaves the whole output unchanged. Empty input succeeds. Overlap rejects (`E2101`), including on the error path. |
|
||||
| `std.bytes.find_slice(data: slice<u8>, needle: slice<u8>) -> std.bytes.FindResult` | `found(index)` for the first match, or `not_found`. Empty needle is `found(0)`, including empty data. Offset is relative to the passed slice; it need not be a readable element index. |
|
||||
|
||||
Search allocates no heap and uses constant auxiliary storage; the reference algorithm has O(data length × needle length) worst-case comparisons. Interpreter fuel bounds execution. For splitting at the first separator, match the search result, then take `data[0..index]` and `data[index + separator.len..data.len]`, or split at the index and borrow past the separator in the right half. An empty separator leaves the whole data in the right half; repeated splitting needs an explicit progress rule. There is no split iterator or returned pair of borrowed slices.
|
||||
|
||||
## Recoverable arithmetic
|
||||
|
||||
| Operand type | Functions | Result |
|
||||
|---|---|---|
|
||||
| `u64` | `std.math.checked_add_u64`, `std.math.checked_sub_u64`, `std.math.checked_mul_u64` | `std.math.U64Result::ok(u64)` / `overflow` |
|
||||
| `usize` | `std.math.checked_add_usize`, `std.math.checked_sub_usize`, `std.math.checked_mul_usize` | `std.math.UsizeResult::ok(usize)` / `overflow` |
|
||||
|
||||
Every function takes two operands of the indicated type. A representable mathematical result succeeds; unsigned subtraction underflow also returns `overflow`. Multiplication by zero always succeeds with zero. `usize` follows target pointer width. Normal arithmetic operators still trap on overflow; wrapping uses `+%`, `-%`, `*%`, with no library wrappers. These monomorphic APIs do not provide generic or signed arithmetic. Result enums use the same ordinary match rules as the endian results.
|
||||
|
||||
For a zero-terminated byte record, check the complete output size before copying:
|
||||
|
||||
```aji
|
||||
fn encode(dst: slice_mut<u8>, data: slice<u8>) -> usize
|
||||
effects []
|
||||
{
|
||||
match std.math.checked_add_usize(data.len, 1) {
|
||||
std.math.UsizeResult::ok(total) => {
|
||||
if total > dst.len { return 0; }
|
||||
match std.bytes.copy(mut dst, ref data) {
|
||||
std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; }
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
}
|
||||
std.math.UsizeResult::overflow => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This helper returns the encoded byte count or zero on failure, and leaves the destination unchanged on failure. Import both `std.math` and `std.bytes`. Its zero sentinel is unambiguous because a successful record includes the terminator.
|
||||
|
||||
The checked [bounded example](../../examples/std/bounded.aji) combines overflow-aware output sizing, whole-input copy and delimiter search; it returns 10. Copy/search/split and independent arithmetic fixtures are in `source/std/bounded_*.aji`. Wrong operands/payloads are `E7005`; absent imports/types are `E7002`; missing result arms are `E7004`. No new diagnostic code, syntax, verifier state or runtime primitive is introduced.
|
||||
|
||||
## UTF-8 and encodings
|
||||
|
||||
| Function | Result and contract |
|
||||
|---|---|
|
||||
| `std.utf8.next(src: slice<u8>) -> std.utf8.NextResult` | `ok(scalar: u32, consumed: usize)` for the first scalar, `end` for empty input, or `invalid_input` for a bad/truncated first sequence; trailing bytes do not affect a successful first decode. |
|
||||
| `std.utf8.validate(src: slice<u8>) -> std.utf8.ValidateResult` | `ok` for wholly valid bytes, including empty input; `invalid_input(offset)` at the beginning of the first bad/truncated sequence. |
|
||||
| `std.encoding.hex.encode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.hex.EncodeResult` | lowercase ASCII hex; `ok(count)` or `short_output`. |
|
||||
| `std.encoding.hex.decode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.hex.DecodeResult` | even-length ASCII digits, upper/lower/mixed case; `ok(count)`, `invalid_input` or `short_output`. |
|
||||
| `std.encoding.base64.encode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.base64.EncodeResult` | standard alphabet with canonical padding and zero unused bits; `ok(count)` or `short_output`. |
|
||||
| `std.encoding.base64.decode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.base64.DecodeResult` | canonical standard Base64 only; `ok(count)`, `invalid_input` or `short_output`. |
|
||||
|
||||
UTF-8 uses shortest scalar encodings, excluding surrogates and values above U+10FFFF. NUL, BOM, noncharacters and unassigned scalars are accepted; validation does not normalize or replace bytes. Iteration repeatedly calls `next(ref data[offset..data.len])` and advances offset by the returned consumed count. `next` validates its first sequence only, so validate the whole slice when that is the required contract. A malformed final prefix is `invalid_input`, not a streaming "need more" result. [UTF-8 rules: RFC 3629 §3/§4](https://www.rfc-editor.org/rfc/rfc3629.html#section-3).
|
||||
|
||||
Encoders check complete capacity before writing; decoders check the entire input first, then capacity. Invalid input takes precedence over short output. Every returned error preserves the whole destination. Success writes a prefix, preserves remaining output and appends no terminator. Empty encoding/decoding succeeds with `ok(0)`, including zero capacity. Mathematical lengths too large for usize/output are `short_output`, checked without overflowing an intermediate. Input/output cannot overlap; disjoint `split_at` siblings from the same allocation are allowed. These guarantees do not cover interpreter fuel interruption.
|
||||
|
||||
Hex decoding rejects whitespace, prefixes, separators, odd length and non-hex bytes. Base64 uses the standard `+/` alphabet; incomplete final groups require `=` padding, and complete groups omit it. Decoding rejects whitespace, URL-safe symbols, incomplete groups, misplaced/excess padding and nonzero unused bits. This is a deliberate strict policy permitted by [RFC 4648 §3.5/§4](https://www.rfc-editor.org/rfc/rfc4648.html#section-3.5); no permissive or URL-safe mode is implied.
|
||||
|
||||
```aji
|
||||
module demo.text
|
||||
import std.bytes;
|
||||
import std.encoding.hex;
|
||||
import std.encoding.base64;
|
||||
import std.utf8;
|
||||
|
||||
fn main() -> u32
|
||||
effects []
|
||||
{
|
||||
var utf8: [u8; 3] = zero;
|
||||
match std.encoding.hex.decode(mut utf8, b"E282AC") {
|
||||
std.encoding.hex.DecodeResult::ok(count) => { assert(count == 3); }
|
||||
std.encoding.hex.DecodeResult::invalid_input => { return 0; }
|
||||
std.encoding.hex.DecodeResult::short_output => { return 0; }
|
||||
}
|
||||
match std.utf8.validate(ref utf8) {
|
||||
std.utf8.ValidateResult::ok => {}
|
||||
std.utf8.ValidateResult::invalid_input(offset) => { return 0; }
|
||||
}
|
||||
var encoded: [u8; 4] = zero;
|
||||
match std.encoding.base64.encode(mut encoded, ref utf8) {
|
||||
std.encoding.base64.EncodeResult::ok(count) => { assert(count == 4); }
|
||||
std.encoding.base64.EncodeResult::short_output => { return 0; }
|
||||
}
|
||||
assert(std.bytes.equal(ref encoded, b"4oKs"));
|
||||
match std.utf8.next(ref utf8) {
|
||||
std.utf8.NextResult::ok(scalar, count) => { assert(count == 3); return scalar; }
|
||||
std.utf8.NextResult::end => { return 0; }
|
||||
std.utf8.NextResult::invalid_input => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The [text example](../../examples/std/text.aji) is checked by `source/std/text_example.aji` and returns 8364 (U+20AC). Independent byte/scalar vectors, capacities, invalid-input precedence, namespace collisions, alias rejects and disjoint buffers are under `source/std/text_*.aji`. UTF-8/encoding algorithms allocate no heap and declare `effects []`; fixed local tables are constant auxiliary storage. Wrong operands/payloads: `E7005`; missing result arms: `E7004`; unknown types/imports: `E7002`; conflicting borrows: `E2101`. Results are ordinary Copy enums with no new must-use rule.
|
||||
|
||||
## Integer formatting (`std.fmt`)
|
||||
|
||||
Import `std.fmt`. Its four functions share `std.fmt.WriteResult::ok(count: usize)` / `short_output`:
|
||||
|
||||
| Function | Value type |
|
||||
|---|---|
|
||||
| `write_u64(dst: slice_mut<u8>, value: u64)` | unsigned 64-bit |
|
||||
| `write_i64(dst: slice_mut<u8>, value: i64)` | signed 64-bit |
|
||||
| `write_usize(dst: slice_mut<u8>, value: usize)` | unsigned target pointer width |
|
||||
| `write_isize(dst: slice_mut<u8>, value: isize)` | signed target pointer width |
|
||||
|
||||
Output is decimal ASCII with no leading zeroes, plus sign, padding or terminator; negative values begin with `-` and zero is `0`. Every scalar value is supported, including signed minima. Success writes the prefix and preserves the suffix; short capacity preserves the entire output. Empty output is short even for zero. No heap allocation, cursor or format string exists. Full contracts are in spec 16 §2.8.
|
||||
|
||||
Compose byte literals and integers using explicit offsets, advancing only after a successful operation:
|
||||
|
||||
```aji
|
||||
module demo.format
|
||||
import std.bytes;
|
||||
import std.fmt;
|
||||
|
||||
fn main() -> usize
|
||||
effects []
|
||||
{
|
||||
var record: [u8; 24] = [165; 24];
|
||||
match std.bytes.copy(mut record, b"value=") {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
var offset: usize = 6;
|
||||
match std.fmt.write_i64(mut record[offset..record.len], -42) {
|
||||
std.fmt.WriteResult::ok(count) => { offset = offset + count; }
|
||||
std.fmt.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.bytes.copy(mut record[offset..record.len], b" count=") {
|
||||
std.bytes.WriteResult::ok => { offset = offset + 7; }
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.fmt.write_usize(mut record[offset..record.len], 7) {
|
||||
std.fmt.WriteResult::ok(count) => { offset = offset + count; }
|
||||
std.fmt.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
assert(std.bytes.equal(ref record[0..offset], b"value=-42 count=7"));
|
||||
for i in offset..record.len { assert(record[i] == 165); }
|
||||
return offset;
|
||||
}
|
||||
```
|
||||
|
||||
This checked program is `examples/std/format.aji` and `tests/conformance/source/std/fmt_example.aji`. It returns 17 without grants. Each operation preserves its own destination on short output; a sequence is not transactional across earlier successful calls. Existing alias checks apply even when a write would return short output. Smaller scalar widths require an explicit widening conversion to an appropriate writer; wider integers, float formatting and parsing are outside this increment.
|
||||
|
||||
## Copy option/result templates
|
||||
|
||||
Requires direct `import std.option;` / `import std.result;`; explicit generic spelling is spec 15 §15.
|
||||
|
||||
| Declaration | Contract |
|
||||
|---|---|
|
||||
| `std.option.Option<T>` | `some(T)`, `none` |
|
||||
| `std.option.is_some<T: Copy>(value: Option<T>) -> bool` | true for some; false for none; effects [] |
|
||||
| `std.result.Result<T, E>` | `ok(T)`, `err(E)` |
|
||||
| `std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool` | true for ok; false for err; effects [] |
|
||||
|
||||
All are ordinary safe source/static specialization, with no allocation or authority. Generic helper calls use `is_some::<u64>(value)` / `is_ok::<u64, u8>(value)`. Constructors and patterns use `std.option.Option::<u64>::some(value)` or `std.result.Result::<u64, u8>::err(code)`; names and variant matches remain explicit even for none. Extract values by exhaustive match; an err variant is not intrinsic outcome syntax. Owners/resources/endpoints make these enums linear under spec 03 §25 and require exhaustive `match move`. Borrows remain invalid members; Copy classification helpers reject linear arguments with E7005. No must-use or implicit unwrap/default/conversion is introduced. [Checked example](../../examples/std/generics.aji) returns 42 without grants.
|
||||
|
||||
## Owning vectors
|
||||
|
||||
Import std.vec; every function supplies explicit `::<T>`. Vec<T> contains a buffer<T> and is always linear. No implicit growth or cleanup occurs. The storage field follows ordinary aggregate visibility/borrow rules. New/reserve require cap<mem.alloc> and effects [mem.alloc]; all other functions declare effects [].
|
||||
|
||||
| Function | Parameters | Result |
|
||||
|---|---|---|
|
||||
| new<T> | capacity: usize, heap: cap<mem.alloc> | NewResult<T>: ok(Vec<T>) / err(alloc_error) |
|
||||
| len<T> / capacity<T> | value: ref<Vec<T>> | usize |
|
||||
| reserve<T> | value: mut<Vec<T>>, capacity: usize, heap: cap<mem.alloc> | ReserveResult: ok / err(alloc_error) |
|
||||
| push<T> | value: mut<Vec<T>>, item: T | PushResult<T>: ok / full(T) |
|
||||
| pop<T> | value: mut<Vec<T>> | std.option.Option<T>: some(T) / none |
|
||||
| free<T> | value: Vec<T> | FreeResult<T>: ok / not_empty(Vec<T>) |
|
||||
| get<T: Copy> | value: ref<Vec<T>>, index: usize | std.option.Option<T>: some(T) / none |
|
||||
| replace<T> | value: mut<Vec<T>>, index: usize, item: T | ReplaceResult<T>: ok(old_value: T) / out_of_bounds(original_item: T) |
|
||||
|
||||
Growth has an old+new capacity allocation peak. Failure preserves capacity/length/elements; full push and out-of-bounds replacement return the exact input. Nonempty free returns the vector; pop/consume all elements before retrying. get returns none out of bounds, replace returns the old complete element on success. Generic moves compose Copy and linear types. Qualified variants require direct imports (including std.option for pop/get). [Executable owning vector](../../examples/std/vector.aji) returns 42 with heap=mem.alloc:256. Views and nested element borrows cannot escape or overlap shape changes. Normative contracts: spec 16 §2.10 and spec 03 §26.
|
||||
|
||||
## Owning deques
|
||||
|
||||
Import std.deque; every operation supplies `::<T>`. Deque<T> is always linear and has bounded ring capacity. Pop transfers complete values. No operation grows except explicit reserve. New/reserve declare mem.alloc and take explicit authority; all others declare effects [].
|
||||
|
||||
| Function | Parameters | Result |
|
||||
|---|---|---|
|
||||
| new<T> | capacity: usize, heap: cap<mem.alloc> | NewResult<T>: ok(Deque<T>) / err(alloc_error) |
|
||||
| len<T> / capacity<T> | value: ref<Deque<T>> | usize |
|
||||
| reserve<T> | value: mut<Deque<T>>, capacity: usize, heap: cap<mem.alloc> | ReserveResult: ok / err(alloc_error) |
|
||||
| push_front<T> / push_back<T> | value: mut<Deque<T>>, item: T | PushResult<T>: ok / full(original_item: T) |
|
||||
| pop_front<T> / pop_back<T> | value: mut<Deque<T>> | std.option.Option<T>: some(T) / none |
|
||||
| free<T> | value: Deque<T> | FreeResult<T>: ok / not_empty(Deque<T>) |
|
||||
| get<T: Copy> | value: ref<Deque<T>>, index: usize | std.option.Option<T>: some(T) / none |
|
||||
| replace<T> | value: mut<Deque<T>>, index: usize, item: T | ReplaceResult<T>: ok(old_item: T) / out_of_bounds(original_item: T) |
|
||||
|
||||
Indices count from the front. Full pushes, out-of-bounds replaces and nonempty free preserve the queue and return ownership. Allocation failure also preserves physical slots/head/length. Successful growth preserves logical order, resets head and charges the old+new capacities at the peak; no shrink occurs. Every slot is an Option<T> (tag plus payload), including free slots: capacity 3 of own<u64> charges 27 bytes. Empty free explicitly drains internal none slots; it never destroys a user's T. Callers pop and consume resources before freeing; match move on linear result values and import std.option to name pop/get variants.
|
||||
|
||||
End operations and indexing use constant slot work; construction/growth/free use O(capacity) work. Interpreter representation costs remain those of buffer primitives. Deque<T> fields are ordinarily visible; direct representation writes/construction must preserve spec 16 §2.11's ring invariant. Library calls maintain it. [Executable owning deque](../../examples/std/deque.aji) returns 42 with heap=mem.alloc:1024. There is no iterator, returned borrow, trait hierarchy or implicit allocation/cleanup. Existing alias, task-loan and Copy/Send/Share checks apply.
|
||||
|
||||
## Owning numeric-key maps
|
||||
|
||||
Import `std.map`; each generic operation supplies `::<V>`. `U64Map<V>` is always linear, uses exact u64 key equality and supports Copy values, owners, files and sender endpoints. Hashes select probe positions; they never establish key equality. General keys use `std.hashmap` with explicit hash/equality (§2.14).
|
||||
|
||||
| Operation | Return / ownership |
|
||||
|---|---|
|
||||
| `new<V>(capacity: usize, heap: cap<mem.alloc>)` | `NewResult<V>::ok(U64Map<V>)` / `err(alloc_error)` |
|
||||
| `len<V>(map: ref<U64Map<V>>) -> usize` | entry count |
|
||||
| `capacity<V>(map: ref<U64Map<V>>) -> usize` | maximum live entries before a new key returns full |
|
||||
| `reserve<V>(map: mut<U64Map<V>>, capacity: usize, heap: cap<mem.alloc>)` | `ReserveResult::ok` / `err(alloc_error)`; grow explicitly, preserve every slot on returned failure |
|
||||
| `insert<V>(map: mut<U64Map<V>>, key: u64, value: V)` | `InsertResult<V>::inserted` / `replaced(V)` / `full(V)` |
|
||||
| `contains<V>(map: ref<U64Map<V>>, key: u64) -> bool` | presence without copying V |
|
||||
| `get<V: Copy>(map: ref<U64Map<V>>, key: u64)` | `std.option.Option<V>` copied lookup |
|
||||
| `remove<V>(map: mut<U64Map<V>>, key: u64)` | `std.option.Option<V>` moved removal |
|
||||
| `pop<V>(map: mut<U64Map<V>>)` | `std.option.Option<Entry<V>>`; Entry has key: u64, value: V |
|
||||
| `free<V>(map: U64Map<V>)` | `FreeResult<V>::ok` / `not_empty(U64Map<V>)` |
|
||||
|
||||
Only new/reserve declare `effects [mem.alloc]` and take allocation authority. No operation implicitly grows. Full insertion returns the exact input; replacement works even when full and returns the old value. Callers must explicitly consume owning results and drain before free. Use `ref map` for reads and `mut map` for mutation, including explicit shared reborrows from mut parameters.
|
||||
|
||||
Representation: `U64Map<V> { storage: buffer<Slot<V>>, length: usize }`, `Slot<V> { key: u64, state: SlotState, value: std.option.Option<V> }`, `SlotState { empty, deleted, occupied }`. Occupied implies some(V), vacancies imply none, keys are unique and reachable, and length equals occupied count. Direct representation writes must preserve spec 16 §2.13's invariant. Capacity N allocates and initializes 2N physical slots, with both enum tags charged. N=0 allocates no bytes. Both whole tables and user allocations count toward growth's peak quota; old storage is refunded to its original authority. Overflowing size returns budget_exceeded.
|
||||
|
||||
Lookup traverses deleted slots, compares original keys and terminates after bounded probes, even with no empty slots. Pop drains physical-index order; successful rehash may change this deterministic order. Worst-case probe work is O(N); collision-heavy growth is O(N²). Existing borrow, task-loan, Copy/Send/Share and resource diagnostics apply. The [owning example](../../examples/std/map.aji) returns 42 with heap=mem.alloc:256.
|
||||
|
||||
## Owning general-key maps
|
||||
|
||||
Import `std.hashmap` and `std.option` for lookup/extraction results. `HashMap<K,V,fn hash,fn equal>` stores complete keys and values, including owning byte buffers, structs, owners, files and channel endpoints. The two declared functions have exactly `fn(ref<K>) -> u64 effects []` / `fn(ref<K>,ref<K>) -> bool effects []`. Equality is stable equivalence and equal keys must hash equally; hash equality alone never identifies a key. Do not change a live key's hash/equality. Different bound functions produce distinct nominal map types. Operations never capture state or gain authority from selection.
|
||||
|
||||
Every call supplies `::<K,V,fn hash,fn equal>` (get additionally requires V: Copy, without requiring K: Copy):
|
||||
|
||||
| Function arguments | Result |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,V,fn hash,fn equal>: ok(HashMap), err(alloc_error) |
|
||||
| len(map: ref<HashMap>) | usize live count |
|
||||
| capacity(map: ref<HashMap>) | usize maximum live entries |
|
||||
| reserve(map: mut<HashMap>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| insert(map: mut<HashMap>, key: K, value: V) | InsertResult<K,V>: inserted, replaced(Entry<K,V>), full(Entry<K,V>) |
|
||||
| contains(map: ref<HashMap>, key: ref<K>) | bool |
|
||||
| get(map: ref<HashMap>, key: ref<K>) | std.option.Option<V> copied value |
|
||||
| remove(map: mut<HashMap>, key: ref<K>) | std.option.Option<Entry<K,V>> moving extraction |
|
||||
| pop(map: mut<HashMap>) | std.option.Option<Entry<K,V>> moving extraction |
|
||||
| free(map: HashMap) | FreeResult<K,V,fn hash,fn equal>: ok, not_empty(HashMap) |
|
||||
|
||||
Here HashMap abbreviates the fully applied type, and Entry<K,V> has key: K/value: V. Pass `ref q` when querying through mut q; ownership transfer of named linear K/V requires move. Replacement returns both old resources and retains the new equivalent key. Full insert returns both original inputs. Explicitly consume every owning result; free returns the nonempty map. get cannot copy an owned V, while contains/remove work without Copy requirements. No borrowed value/cursor escapes.
|
||||
|
||||
Only new/reserve allocate and declare mem.alloc with explicit authority. Growth has no implicit trigger and returned failure preserves every old entry/bucket and pop order. A capacity N reserves N StoredEntry slots (hash + full K/V sizes) and 2N Copy Bucket slots (hash + usize + state tag). Live entries form an initialized dense prefix, with a separate probe-index table and cached hashes. Removing a middle entry exchanges the last into its position, repairing the index. Pop drains reverse current dense order; reserve preserves it and clears tombstones. Zero capacity is valid. Peak growth includes both entry buffers, both index buffers and external user owners; refunds follow the recorded allocation capabilities. Capacity-one Key{id:u64}/own<u64> reserves 58 bytes, plus 8 for the owned payload in the [checked example](../../examples/std/hashmap.aji), which runs with heap=mem.alloc:66.
|
||||
|
||||
Representation fields are ordinary visible source; manual construction/mutation must preserve the full invariant in spec 16 §2.14. Hash/equality traps and fuel exhaustion are abnormal outcomes. Existing moves, alias/task-loan and Copy/Send/Share rules apply without unsafe or map-specific runtime semantics. Worst-case lookup/insert/remove/pop is O(N) plus callback work, rehash O(N²); no adversarial collision/native-throughput guarantee is made. `std.map.U64Map<V>` retains its existing API for numeric keys.
|
||||
|
||||
## Owning general-key sets
|
||||
|
||||
Import `std.hashset` and `std.option` for extraction results. `HashSet<K,fn hash,fn equal>` uses the map's exact pure `fn(ref<K>) -> u64 effects []` / `fn(ref<K>,ref<K>) -> bool effects []` contracts and stable equality/hash laws. Complete owning keys, including byte buffers and resource-bearing structs, need no Copy constraint. Every operation supplies `::<K,fn hash,fn equal>`:
|
||||
|
||||
| Function arguments | Result |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,fn hash,fn equal>: ok(HashSet), err(alloc_error) |
|
||||
| len(set: ref<HashSet>) | usize live count |
|
||||
| capacity(set: ref<HashSet>) | usize maximum live keys |
|
||||
| reserve(set: mut<HashSet>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| insert(set: mut<HashSet>, key: K) | InsertResult<K>: inserted, present(K), full(K) |
|
||||
| contains(set: ref<HashSet>, key: ref<K>) | bool |
|
||||
| remove(set: mut<HashSet>, key: ref<K>) | std.option.Option<K> moving extraction |
|
||||
| pop(set: mut<HashSet>) | std.option.Option<K> moving extraction |
|
||||
| free(set: HashSet) | FreeResult<K,fn hash,fn equal>: ok, not_empty(HashSet) |
|
||||
|
||||
Here HashSet abbreviates the applied type. Duplicate insertion preserves the stored representative and every entry/bucket, returning the original incoming K as present, even at capacity. Full returns the original new key. Remove/pop return stored keys; free returns a nonempty set. Explicitly consume all owning results. Use `move` for named linear inputs and `ref q` for queries through mut q; contains retains no borrow. Replacement requires explicit remove followed by insert.
|
||||
|
||||
Only new/reserve allocate with mem.alloc and explicit authority. There is no automatic growth or cleanup. The visible representation is `map: std.hashmap.HashMap<K,bool,fn hash,fn equal>` with every live value true; callers must preserve spec 16 §2.15's complete invariant. Dense extraction/pop order, failure preservation, peak accounting and refunds follow the map. Each capacity slot charges hash + K + bool and two buckets: 51 bytes for u64, or 59 for Key{id:u64,owner:own<u64>}, plus the separately allocated payload. The [owning example](../../examples/std/hashset.aji) returns 42 with heap=mem.alloc:67.
|
||||
|
||||
Policies may run for membership and again for insertion, with no runtime dispatch or gained authority. Existing moves/aliases/task loans and Copy/Send/Share checks apply. Callback traps/fuel exhaustion are abnormal outcomes. Worst-case membership/insert/remove/pop is O(N) plus callbacks; growth is O(N²) under collisions. No sorted iteration or native-throughput guarantee is made.
|
||||
|
||||
## Owning binary heaps
|
||||
|
||||
Import `std.heap` and `std.option`. `BinaryHeap<T,fn before>` stores complete T with an explicit exact `fn(ref<T>,ref<T>) -> bool effects []` operation. before(a,b) means a has higher extraction priority. It must remain a stable strict weak order: irreflexive/transitive, with transitive incomparability. Equivalent items have deterministic extraction for a fixed operation sequence, without a stable tie-order promise. Use `<` for numeric minimum first or `>` for maximum first. Distinct bound operations give distinct nominal types; selection grants no authority.
|
||||
|
||||
Every call supplies `::<T,fn before>`; peek additionally requires T: Copy:
|
||||
|
||||
| Function arguments | Result |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<T,fn before>: ok(BinaryHeap), err(alloc_error) |
|
||||
| len(value: ref<BinaryHeap>) | usize live count |
|
||||
| capacity(value: ref<BinaryHeap>) | usize maximum live count |
|
||||
| reserve(value: mut<BinaryHeap>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| push(value: mut<BinaryHeap>, item: T) | PushResult<T>: ok, full(T) |
|
||||
| peek(value: ref<BinaryHeap>) | std.option.Option<T> copied root |
|
||||
| pop(value: mut<BinaryHeap>) | std.option.Option<T> moving root extraction |
|
||||
| free(value: BinaryHeap) | FreeResult<T,fn before>: ok, not_empty(BinaryHeap) |
|
||||
|
||||
Here BinaryHeap abbreviates the applied type. Use move for named linear inputs, mut for push/pop/reserve and ref for queries (ref q through a mut parameter). Full push preserves all state, returns the original input and calls no comparator. Empty pop/peek returns none; nonempty free returns the whole heap. Explicitly consume owning full/pop/not_empty results. Peek retains no borrow and cannot copy an owner; complete owning records, files and sender endpoints use pop. Only new/reserve allocate with mem.alloc and explicit authority; growth is never automatic.
|
||||
|
||||
The visible representation is entries: buffer<Entry<T>> / indices: buffer<usize>, Entry<T>{position:usize,value:T}. Both initialized lengths/capacities agree. Indices are a permutation of dense positions; each entry points back to its index position, and no child precedes its parent. Callers must preserve spec 16 §2.16's complete invariant. Sifting swaps Copy indices and inverse positions; pop repairs the dense hole through complete exchange. No default T or implicit destruction is needed.
|
||||
|
||||
New allocates empty entries then indices, refunding entries on second-allocation failure. Reserve allocates/copies new indices before growing entries; returned failure preserves both old buffers, values/positions/indices and extraction order, and refunds temporaries. Success preserves the layout and frees old indices explicitly. Peak quota includes both entry/index buffers and all external user allocations; refunds go to recorded authorities. Zero capacity is valid; size overflow returns budget_exceeded. On air64 each capacity slot costs sizeof(T)+16 bytes. The [owning example](../../examples/std/heap.aji) needs 32 bytes for one Item slot plus 8 for its payload: heap=mem.alloc:40.
|
||||
|
||||
Existing ownership/alias/task-loan/Send/Share rules apply with no unsafe boundary or new runtime semantics. Callback/fuel traps are abnormal. Abstract push/pop need O(log L) comparisons/swaps, peek O(1), reserve O(L) copies; interpreter prefix-copy/GC costs may add host work. There is no native-throughput guarantee.
|
||||
|
||||
## Bounded I/O composition
|
||||
|
||||
Import `std.io`. Six concrete functions compose existing primitives with caller-provided slices. They never allocate, open/close resources or retain borrows. Effects and authority remain explicit even for empty/no-op paths. File/stream resources are mutably lent and remain owned by the caller on every normal return.
|
||||
|
||||
| Function | Result | Effects |
|
||||
|---|---|---|
|
||||
| read_exact_stdin(input: cap<io.read>, destination: slice_mut<u8>) | ReadExactResult | io.read |
|
||||
| read_exact_file(input: mut<file<read>>, destination: slice_mut<u8>) | ReadExactResult | fs.read |
|
||||
| read_exact_stream(input: mut<stream>, destination: slice_mut<u8>) | ReadExactResult | net.read |
|
||||
| read_to_end_file(input: mut<file<read>>, destination: slice_mut<u8>) | ReadToEndResult | fs.read |
|
||||
| copy_file(input: mut<file<read>>, output: mut<file<write>>, scratch: slice_mut<u8>, limit: usize) | CopyResult | fs.read, fs.write |
|
||||
| copy_file_append(input: mut<file<read>>, output: mut<file<append>>, scratch: slice_mut<u8>, limit: usize) | CopyResult | fs.read, fs.write |
|
||||
|
||||
ReadExactResult is ok / eof(completed:usize) / err(ReadError{completed:usize,error:io_error}). Exact reads fill the destination, looping over short reads. Empty destination is ok without I/O. EOF leaves the remaining suffix unchanged. A read error guarantees only the successful prefix; the attempted suffix follows the primitive's failure contract. Bytes outside the supplied destination remain unchanged.
|
||||
|
||||
ReadToEndResult is eof(completed:usize) / full(completed:usize) / err(ReadError). Full means the supplied buffer was filled; it does not establish whether EOF was reached or unread data remains. Empty destination is full(0), and no extra byte is read/discarded to probe EOF. Growing/owning read-to-end is separate work; fixed-capacity adapters are below.
|
||||
|
||||
CopyResult is eof(completed:usize) / limit(completed:usize) / err(CopyError{read:usize,confirmed_written:usize,error:io_error}). Copies bound every scratch chunk by remaining limit and stop without probing past it. Exact EOF at the limit reports limit. A read error has both counts equal to earlier completed chunks. A write error includes its consumed input chunk in read; confirmed_written includes only prior successful writes. The failed write may have externally written a prefix: there is no rollback promise or exact failed-output count. Resources remain borrowed for explicit caller cleanup.
|
||||
|
||||
Zero limit returns limit(0) without I/O, even with empty scratch. Empty scratch with positive limit returns invalid_input with both error counts zero without I/O. No counter exceeds the limit or overflows. Scratch contents after a call are unspecified; bytes outside its slice remain unchanged. The [copy example](../../examples/std/io.aji) uses only fs.read/fs.write entry grants and a fixed frame scratch array, handling results and closing both resources explicitly. Existing fs.write_all/net.send_all/console writes already write all bytes on success, so this increment adds no duplicate write alias.
|
||||
|
||||
Ordinary alias/task-loan, type/mode, capability and effect checks apply; imports grant nothing. Blocking/fuel/profile errors remain spec 11 behavior, with no hidden timeout, task or unsafe boundary. std.io's concrete contracts are spec 16 §2.17; owning buffered adapters and lexical paths remain forthcoming.
|
||||
|
||||
## Owning buffered files
|
||||
|
||||
Import `std.io.reader` for Reader/file<read> and `std.io.writer` for Writer/file<write>. Import `std.io` directly when spelling read_exact's result, and `std.option` when matching the writer failure state; dependency imports do not expose names to callers. Each adapter owns a fixed initialized buffer and its file. Only new allocates, with an explicit mem.alloc capability, charging N bytes. Zero capacity delegates directly to primitive I/O. Files are never implicitly closed or synced. All file/adapter-bearing results are linear: consume every normal branch explicitly.
|
||||
|
||||
| Function arguments | Result | Effects |
|
||||
|---|---|---|
|
||||
| std.io.reader.new(input: file<read>, capacity: usize, heap: cap<mem.alloc>) | NewResult: ok(Reader), err(NewError{file:file<read>,error:alloc_error}) | mem.alloc |
|
||||
| std.io.reader.read(input: mut<Reader>, destination: slice_mut<u8>) | ReadResult: ok(usize), err(io_error) | fs.read |
|
||||
| std.io.reader.read_exact(input: mut<Reader>, destination: slice_mut<u8>) | std.io.ReadExactResult | fs.read |
|
||||
| std.io.reader.finish(input: Reader) | FinishResult: ok(file<read>), unread(Reader) | none |
|
||||
| std.io.reader.discard(input: Reader) | Discarded{file:file<read>,unread:usize} | none |
|
||||
| std.io.writer.new(output: file<write>, capacity: usize, heap: cap<mem.alloc>) | NewResult: ok(Writer), err(NewError{file:file<write>,error:alloc_error}) | mem.alloc |
|
||||
| std.io.writer.write(output: mut<Writer>, bytes: slice<u8>) | WriteResult: ok, err(WriteError{accepted:usize,error:io_error}) | fs.write |
|
||||
| std.io.writer.flush(output: mut<Writer>) | FlushResult: ok, err(io_error) | fs.write |
|
||||
| std.io.writer.finish(output: Writer) | FinishResult: ok(file<write>), err(FinishError{writer:Writer,error:io_error}) | fs.write |
|
||||
| std.io.writer.discard(output: Writer) | Discarded{file:file<write>,pending:usize,failed:std.option.Option<io_error>} | none |
|
||||
|
||||
Move named files into new and named adapters into finish/discard. Constructor failure returns the exact original file before I/O; it can be closed or reused. Successful finish/discard drains/frees storage and refunds its recorded authority, returning the file for explicit use/close. No implicit growth, cleanup, retained caller borrow or extra authority is introduced.
|
||||
|
||||
Reader.read copies one cached prefix without refilling; when empty it refills the storage once, then returns a prefix. Thus read can return short even with more data available. Empty destination returns ok(0) without consuming/refilling and does not establish EOF. read_exact loops to fill the destination, using the std.io prefix/EOF/error contract. Reader.finish returns the complete unchanged Reader if cached unread bytes remain. Empty cache permits finish without probing EOF. Discard explicitly abandons unread prefetched bytes and returns their count: the file cursor remains advanced through prefetch, with no rewind. A read error retains ownership/offsets but promises no external cursor rollback or untouched attempted destination suffix.
|
||||
|
||||
Writer.write fills available storage and flushes a full buffer only when more input needs room. Ending with a full buffer keeps it pending. Empty input on a healthy writer does nothing. A write error reports bytes accepted from that call; accepted includes buffered data and is not an externally written/durable count. Pending data may include earlier calls. At capacity zero a direct failed write reports accepted=0 even if an external prefix was written. Healthy flush of empty storage performs no I/O; successful flush resets used to zero.
|
||||
|
||||
Any failed external write preserves pending bytes/used and records its first io_error. Every subsequent write, including empty, returns that error with accepted=0; every flush returns it, with no I/O or mutation. Finish returns the complete failed Writer plus error. There is no retry/reset because the failed operation may already have externally written an unknown prefix. Discard returns the file, pending count and failure state; pending can overlap that prefix and is not an exact loss count. Callers can explicitly handle the returned file according to their application protocol.
|
||||
|
||||
The visible representations are Reader{file,storage,begin,end}, 0≤begin≤end≤N, and Writer{file,storage,used,failed}, 0≤used≤N. Both buffers have initialized length=capacity=N. Caller field access/construction must preserve spec 16 §2.18's complete data/cursor/first-error invariant and must not independently consume/use the internal file/storage. Existing ownership, alias/task-loan, effects and Send/Share checks apply. Adapters can transfer to workers but cannot be shared immutably across tasks because files are non-Share. No unsafe/trusted boundary or new runtime/verifier state is needed.
|
||||
|
||||
The [copy example](../../examples/std/buffered_io.aji) uses two three-byte buffers (heap=mem.alloc:6), explicitly handles constructor/finish failure and returns the copied byte count, or zero after normal error cleanup. Conformance fixtures include capacities zero/full, unread finish/discard, exact EOF, allocation failure/refunds, worker transfer and rejected ownership/effect/alias cases. Hosted tests exercise read errors and real partial external writes; Linux raises the child file quota after failure to detect forbidden retry.
|
||||
|
||||
## Lexical paths
|
||||
|
||||
Import `std.path`. Six pure operations use byte `/` separators in every profile. They never allocate heap, retain/return a borrow, inspect the filesystem/current directory or grant authority. Backslash, colon and non-UTF-8 bytes are ordinary component bytes; there is no drive/UNC or symlink resolution. Range{start:usize,end:usize} is Copy; callers explicitly borrow ref path[range.start..range.end]. A range is data, and bounds are still checked if it is reused for a different path.
|
||||
|
||||
| Function arguments | Result |
|
||||
|---|---|
|
||||
| is_absolute(path: slice<u8>) | bool: first byte is `/` |
|
||||
| basename(path: slice<u8>) | Range of final nonempty raw component, ignoring trailing separators; 0..0 for empty/root-only |
|
||||
| parent(path: slice<u8>) | Range of raw prefix before basename, trimming the separator run before it; rooted input retains first `/`; 0..0 for empty/relative leaf |
|
||||
| extension(path: slice<u8>) | Range after basename's last dot, excluding dot; empty at basename.end for absent/leading-only/trailing dot or `.`/`..` |
|
||||
| normalize(destination: slice_mut<u8>, path: slice<u8>) | WriteResult: ok(usize), invalid_input, size_overflow, short_output |
|
||||
| join(destination: slice_mut<u8>, base: slice<u8>, child: slice<u8>) | WriteResult |
|
||||
|
||||
Queries accept arbitrary bytes, including NUL, and return offsets into the original input, without normalizing it. For a//b///, basename selects b and parent selects a; parent(a/../b) selects `a/..`. Root-only parent selects the first slash; root-only basename is empty. Extension(.profile) is empty, extension(.profile.json) selects json, extension(a..b) selects b, extension(a.) is empty. Empty extension deliberately makes no distinction between no dot and empty suffix.
|
||||
|
||||
Normalize collapses separator runs and leading slashes, removes `.` and trailing slashes, and cancels each ordinary component followed by `..`. Relative unmatched parents remain leading `..`; parents above root are dropped. Empty/reduced-empty relative input becomes `.`; empty rooted output becomes `/`. Examples: a//b/../c/ → a/c; a/../../b → ../b; /../../a → /a; a/.. → . . Normalization is idempotent. Exactly two leading slashes have no special meaning.
|
||||
|
||||
Join normalizes absolute child alone, replacing base. Otherwise it normalizes base followed by child as components separated by a slash; an empty base does not introduce a root. Empty child normalizes base, both empty become `.`, and child parents can cancel base components. Examples: /data/a + ../b → /data/b; a + /b → /b; empty + a → a. These transformations give no capability-containment proof. Filesystem primitives still reject normalized relative paths and enforce their granted scopes on absolute ones.
|
||||
|
||||
Both writers first validate all input bytes: NUL yields invalid_input, including in base when an absolute child replaces it. Invalid input precedes size_overflow, which precedes short_output. Every returned error leaves the entire destination unchanged. Success writes exactly the reported prefix, preserves the suffix and writes no NUL terminator. Only final normalized size must fit: a long component followed by `..` can normalize into one byte of output. Reverse measurement/emission needs fixed frame state and no intermediate buffer or allocation. Work is linear in supplied input/output bytes.
|
||||
|
||||
Input borrows can overlap each other; destination must be disjoint. Explicit split_at permits source/output in one allocation. Existing type/borrow/task-loan/Send/Share checks apply, including no-op/short-output paths. No unsafe boundary, new language/AIR semantics or hidden effects are needed. Borrow-return source support (Q-034) remains separate. The [pure example](../../examples/std/path.aji) joins into a caller buffer and borrows basename/parent/extension from the returned prefix. The independent Python forward-stack oracle covers normalization/join/query/capacity/idempotence; hosted fixtures confirm filesystem authority remains independent.
|
||||
@@ -49,3 +49,11 @@ Because of it, a graph never holds outside authority or a mutable ownership edge
|
||||
|
||||
An `ArcSafe` value may be held by an `arc` (spec 03 §24): the last release destroys it by freeing memory only, with no user or resource action. In format 0 it is exactly `IslandSafe`. `Share` alone is not enough; for example, a `mutex<T>` is `Share` but not `ArcSafe`.
|
||||
|
||||
|
||||
## 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/buffer/mutex wrappers and arrays/aggregates containing Local content. It is not the complement of Send. These properties add no methods, effects, unsafe declarations or implicit resource actions.
|
||||
|
||||
Under linear_aggregates (spec 03 §25), structs/enums/fixed arrays containing any linear member are linear as whole values. Every variant contributes, regardless of the active tag. Borrow/storage/function-bound members remain forbidden; whole-value unpack/take/exchange preserve exactly-once consumption.
|
||||
|
||||
Under linear_buffers (spec 03 §26), buffer<T> is always linear; Send/Share follow T, and Local propagates. Borrow/storage/task-bound content is forbidden. It is neither IslandSafe nor ArcSafe: its nested linear values require explicit draining.
|
||||
@@ -0,0 +1,122 @@
|
||||
# RFC 0016: Standard library bootstrap and built-in source imports
|
||||
|
||||
Status: Implemented
|
||||
Scope: `.aji` source composition and safe pure standard modules; AIR format 0 unchanged
|
||||
Language version: 0.1
|
||||
Supersedes: —
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
This branch contains the proposed spec text, reference implementation and tests for review. Only the owner changes the RFC to Accepted; implementation on a work branch does not constitute acceptance.
|
||||
|
||||
## Motivation
|
||||
|
||||
Reusable byte operations reduce repeated loop/borrow code and the reasoning burden of basic system software. The current frontend has no modules/import resolution or user generics, while linear aggregates are reserved. Beginning with safe non-owning byte functions makes progress without pretending that resource-owning collections already work.
|
||||
|
||||
The proposal improves implementation simplicity, deterministic behavior, auditability and machine repairability. Its value for Model Capability Compression is a hypothesis to measure, not a result inferred from smoke tasks. The full roadmap is `docs/plan/standard-library.md`.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
Imported standard source is ordinary code under the same verifier: immutable slices only read, exclusive slices only write, no borrow escapes, no resource is consumed, no authority is created, no hidden heap allocation occurs. Every source call lowers to a normal AIR call with a collision-free identifier.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
The complete proposed text is integrated into spec 15 §2/§13, spec 16 and `reference/grammar.ebnf`/`reference/std.md` in this branch. It defines a closed compiler-pinned module registry, contextual `import std.bytes;`, fully qualified calls, lexicographic composition, collision-free name mangling, library source provenance and nine pure API contracts.
|
||||
|
||||
This proposal covers only `std.bytes` and `std.math`. It does not make general package imports, aliases, imported types or generic collections available. The whole imported module is lowered, so unused declarations also contribute to the feature closure. Dependency pruning is deferred until there is evidence that the simple strategy becomes costly.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new state, transfer functions, diagnostics or trusted exemptions. Calls, slices, alias checks, frame lifetime, bounds and initialization use the existing rules. Module/function limits apply to the combined module, including all standard declarations. Imported source cannot bypass verification.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
No new runtime rule. Ordinary function calls execute pure operations under fuel. `fill` writes only caller-provided storage. No initialization on import, hidden cleanup, allocation or task creation. Invalid clamp bounds trap `T0002` at the assertion in `std/math.aji`; valid byte slices do not trap due to library arithmetic or bounds.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None. There is no new feature registry entry or opcode: the source import is composition, not an AIR construct. Dots are not allowed in format-0 global identifiers; standard functions therefore use deterministic collision-free `__aji_std_bytes_equal`-style names, with numeric suffixes when needed. The compiler emits the existing feature closure. Existing AIR constructs, types and effects retain their frozen semantics.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 4] = zero;
|
||||
std.bytes.fill(mut buf, 65);
|
||||
assert(std.bytes.equal(ref buf, b"AAAA"));
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Rejected example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 4] = zero;
|
||||
ref saved = buf;
|
||||
std.bytes.fill(mut buf, 65);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
The exclusive borrow conflicts with `saved`: `E2101`. Current verification reports it at both the borrowed argument and the call, as captured by the conformance test; no new rule or code is introduced. A wrong slice type/arity is `E7005`, an unknown import/member or absent import is `E7002`, a duplicate import is `E7006`, malformed import/type-argument syntax is `E7001`.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new code. Library diagnostics and traps use the stable bundled source path and original positions; AIR locations remain available. User diagnostics retain their existing file and source mapping. Source-mapping deduplication compares the file as well as code/line/column, so separate files cannot silently suppress one another.
|
||||
|
||||
## Spec integration
|
||||
|
||||
- Spec 15 §2/§13: imports, resolution, lowering and source provenance.
|
||||
- Spec 16: standard library contract and bootstrap modules.
|
||||
- Reference grammar: import syntax; API reference: signatures/failure table.
|
||||
- Source Reference Bundle: import rules in `language/syntax.md`, APIs in the on-demand `library/std.md`, navigation and a checked Quick Reference example.
|
||||
|
||||
The AIR bundle is unchanged; the functions need only existing AIR contracts. The spec remains authoritative after owner acceptance.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
AIR format 0 is unchanged, with no new instruction, type, verifier/runtime rule or interpretation. Programs without imports keep identical canonical AIR; the contextual word `import` still works as an ordinary local/function name. User functions/types with generated-name collisions are preserved and standard symbols get suffixes. A local binding named `std` does not change fully qualified standard resolution. No migration required.
|
||||
|
||||
General user imports, public types and generics need their own source specifications. Resource-owning collections require the independent vertical `linear_aggregates` RFC; this proposal cannot be used as permission to weaken ownership.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: compiler-bundled module import and fully qualified library call; nine named pure operations.
|
||||
- New verifier state: none.
|
||||
- New syntax forms: one import statement; qualified calls reuse existing dotted call expressions. No new AIR instruction.
|
||||
- Interactions: existing call typing, frame/slice borrows, bounds, function naming, feature closure and source spans. No capability or effect is inferred away.
|
||||
- Repairability: reuse checked functions instead of rewriting loops; absent import/type/alias mistakes reuse stable diagnostics. `find` uses a length sentinel that callers must check. No benefit is claimed until measured.
|
||||
- Existing primitives suffice for every algorithm; source composition removes the need for manual source concatenation.
|
||||
- Public generics are not invented; the three integer functions explicitly say `u64`. The source-side budget includes this temporary monomorphic surface.
|
||||
- New source diagnostics: none; existing codes gain import/member cases.
|
||||
|
||||
Measured with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source` on the bootstrap branch:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference (`QUICK.md`, includes navigation) | 5,511 → 5,777 (+4.8%) | 5,529 → 5,797 (+4.8%) | 5,664 → 5,948 (+5.0%) |
|
||||
| Other source docs | 28,470 → 30,461 (+7.0%) | 28,552 → 30,546 (+7.0%) | 29,238 → 31,307 (+7.1%) |
|
||||
| Full source docs without AIR | 33,981 → 36,238 (+6.6%) | 34,081 → 36,343 (+6.6%) | 34,902 → 37,255 (+6.7%) |
|
||||
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
The new on-demand API page costs 1,346/1,347/1,406 tokens. Standalone AIR bundle size stays 160,797 bytes, 48 sections, 19 files. Growth is below the 10% warning threshold. Nine APIs replace repeated user loops without adding verifier state; later additions must remeasure rather than assuming this budget scales.
|
||||
|
||||
Branch checks: build, unit tests, Quick Reference extraction, full conformance (456 passed, zero failed/pending), formatting and source coverage (69/69) pass. Hosted file/stdin/TCP smoke tests pass. Evaluation harness self-tests pass (22 tests; one environment-dependent skip). The source run tests execute twice for determinism, and one std test compares against hand-written AIR. Boundary tests cover empty slices, embedded zero/high bytes, length ordering, repeated/absent search results, every u8 fill value, sub-slice mutation, u64 extremes and inverted clamp bounds. Collision tests exercise both user type/function names and the local `std` name; mapping and CLI record tests preserve library provenance.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Manual copying/concatenation makes library source and diagnostics hard to track. Hidden std intrinsics enlarge the trusted surface for ordinary algorithms. Implementing general packages and generics first delays pure reusable code; the closed two-module registry provides a bounded first increment while keeping those prerequisites explicit. Implicit prelude and aliases increase name-resolution choices and are omitted.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-026 records the import/distribution decision. Q-027 records the existing discrepancy between the spec and frontend for empty byte literals; tests pass zero-length slices with the existing `ref storage[0..0]` form. Typed schemas, crypto backend choice, TLS trust configuration, cancellation-safe container cleanup and extended runtime capabilities are separate roadmap gates.
|
||||
@@ -0,0 +1,128 @@
|
||||
# RFC 0017: Recoverable endian operations and qualified standard enums
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-1a, safe `std.bytes` algorithms and closed-registry enum names; AIR format 0 unchanged
|
||||
Language version: 0.1
|
||||
Supersedes: —
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
This branch integrates the proposed specification, implementation and tests for review. Only the owner changes the RFC to Accepted; branch implementation is not acceptance. RFC 0016 remains the historical bootstrap record.
|
||||
|
||||
## Motivation
|
||||
|
||||
Byte protocols and storage formats need bounded integer decoding and encoding. Short input/output is normal recoverable failure and cannot be represented by a numeric sentinel: every u16/u32/u64 value is valid. A trap would force every caller to duplicate capacity prechecks. A borrowed scalar output argument adds mutation and alias reasoning to an otherwise pure read.
|
||||
|
||||
This increment improves semantic explicitness, deterministic behavior, memory safety and repairability by returning existing typed enums and checking capacity before access. Model Capability Compression remains a hypothesis requiring empirical evidence, not a conclusion from passing fixtures.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
Read operations access only the first N bytes of a sufficiently long shared slice. Write operations mutate only the first N bytes of a sufficiently long exclusive slice. A short write leaves every byte unchanged. No borrow escapes, allocation occurs, resource is consumed, authority is created or task is started. A successful zero integer is distinct from short input.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
The complete rules are integrated into spec 16 §2.3 and spec 15 §13 in this branch:
|
||||
|
||||
- Width and byte order MUST appear in the function name: `read_u16_le`/`be`, `read_u32_le`/`be`, `read_u64_le`/`be` and corresponding writes. There is no native-endian default, offset parameter or cursor state; offsets use explicit sub-slices.
|
||||
- Reads MUST return the corresponding `std.bytes.ReadU16`, `ReadU32` or `ReadU64`: `ok(value)` or `short_input`. Extra input bytes MUST NOT affect the value. Short input MUST cause no element reads.
|
||||
- Writes MUST return `std.bytes.WriteResult`: `ok` or `short_output`. Short output MUST leave the entire destination unchanged; success MUST leave bytes after the encoded integer unchanged.
|
||||
- Qualified standard enum types, constructors and patterns MUST resolve only through explicitly imported modules in the closed compiler-pinned registry. They introduce no unqualified names or aliases. Source type diagnostics MUST use public qualified names, including inside compound types.
|
||||
- Standard types and functions MUST receive deterministic collision-free AIR identifiers. Composition includes all imported declarations and uses the existing verifier with no exemption.
|
||||
|
||||
These results are ordinary Copy values. This increment does not add must-use checking: callers can ignore a result under the same rules as any existing Copy-returning function. Applications that require successful writes should exhaustively match the result. General user modules, imported struct literals and generic result types remain separate work.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new abstract state, transfer function or diagnostic code. The existing enum payload, exhaustive `enum.switch`, call typing, alias, lifetime, initialization and bounds rules apply. Imported enum values can appear in signatures, user fields, arrays and wrapper types under the same existing type-property rules. Shared inputs remain read-only; destinations require an exclusive slice. Module limits include all imported declarations.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
No new runtime primitive. Ordinary branches, integer widening, bounded shifts, bitwise operations, truncating byte casts, borrows and enum construction implement the APIs. Each capacity check precedes every access. Short results and successful values are identical in deterministic and hosted profiles. There are no library bounds, arithmetic, cast or shift traps for valid slices and scalar values; ordinary interpreter fuel limits still apply. Imports have no runtime initialization or heap allocation.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None. Public enums lower to existing named Copy enums, constructors to `enum.make`, matches to `enum.switch` and functions to ordinary calls. Their full contracts remain those of spec 07/08. Generated names keep dots out of format-0 identifiers. No feature registration is needed because no AIR construct is introduced; the existing feature closure is emitted.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u32
|
||||
effects []
|
||||
{
|
||||
var wire: [u8; 6] = zero;
|
||||
match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.bytes.read_u32_be(ref wire[1..5]) {
|
||||
std.bytes.ReadU32::ok(value) => { return value; }
|
||||
std.bytes.ReadU32::short_input => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is checked by `source/quickref/std_endian.aji` and returns 305419896. `examples/std/endian.aji` is a runnable copy.
|
||||
|
||||
## Rejected example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u16
|
||||
effects []
|
||||
{
|
||||
return std.bytes.read_u16_le(b"\x34\x12");
|
||||
}
|
||||
```
|
||||
|
||||
`E7005`: expected `u16`, found `std.bytes.ReadU16`. The caller must distinguish success from short input. Holding a shared borrow of the destination while passing an exclusive write argument is rejected with `E2101`; `endian_alias.aji` records the existing two alias diagnostics. Incorrect payload types are rejected in both source and AIR.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new codes or registry entries. Existing `E7002` covers unknown/missing imports, types and variants; `E7005` wrong types/payloads or another enum; `E7004` missing arms; `E7006` duplicate/wildcard enum arms; `E2101` borrow conflicts. Malformed syntax remains `E7001`. Standard type fields display public source paths instead of generated identifiers. Unit tests check both direct and compound type fields.
|
||||
|
||||
## Spec integration
|
||||
|
||||
- Spec 15 §13: standard enum names, constructors/patterns, diagnostics and deterministic type/function mangling.
|
||||
- Spec 16 §2.3: twelve signatures, four enums, byte order, capacity, mutation, failure and profile contracts.
|
||||
- Reference grammar: qualified paths in type annotations, enum constructors and patterns.
|
||||
- API reference and checked Quick Reference: ordinary enum result handling, explicit sub-slices and error repair.
|
||||
- Source Reference Bundle: syntax rules and on-demand `library/std.md`. AIR bundle unchanged.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
AIR format 0 and every existing AIR meaning remain unchanged. Programs without imports retain canonical lowering; the previous nine standard APIs keep their contracts. Importing `std.bytes` now composes twelve more functions and four enums. Public names do not collide with user short names; generated-name collisions use suffixes. A local `std` binding does not affect qualified standard resolution. Library path/source-span mapping remains intact. No migration is needed.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: explicit width/order APIs and width-specific ordinary enum results; closed-registry qualified type names. Four enums and twelve function names are added to the public API, read on demand.
|
||||
- New verifier state/instructions: none. No new ownership, allocation, lifetime, concurrency or capability obligation.
|
||||
- New syntax forms: dotted paths in type positions and before the existing `::` constructor/pattern operator. No keyword or result-handling shorthand. Existing exhaustive enum matches suffice.
|
||||
- Interactions: enum payload typing, Copy/type properties, signatures, field/array/wrapper types, canonical composition, feature closure, collision avoidance and source diagnostics.
|
||||
- Repairability: stable names identify the required width, order and failure arm. Short writes cannot leave partially encoded records. Diagnostics expose source types instead of mangled AIR identifiers. Ignored Copy results remain a caller obligation; no compression benefit is claimed yet.
|
||||
- Existing primitives suffice for every algorithm and result. The frontend only composes source declarations and resolves qualified names; no opaque intrinsic is needed.
|
||||
- New source diagnostic codes: zero; existing codes cover the additional name/type/match cases.
|
||||
|
||||
Measured against RFC 0016's bootstrap commit with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference (`QUICK.md`, includes navigation) | 5,777 → 6,000 (+3.9%) | 5,797 → 6,019 (+3.8%) | 5,948 → 6,189 (+4.1%) |
|
||||
| Other source docs | 30,461 → 31,918 (+4.8%) | 30,546 → 32,001 (+4.8%) | 31,307 → 32,838 (+4.9%) |
|
||||
| Full source docs without AIR | 36,238 → 37,918 (+4.6%) | 36,343 → 38,020 (+4.6%) | 37,255 → 39,027 (+4.8%) |
|
||||
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
The on-demand library page grows from 1,346/1,347/1,406 to 2,533/2,532/2,654 tokens. Standalone AIR stays 160,797 bytes, 48 sections and 19 files. Incremental source growth is below the 10% warning threshold. The Quick Reference reaches its approximate 6k target; its new example spends 223 cl100k tokens on correct typed failure handling, while the signatures and detailed contracts remain on demand. Future API increments should avoid repeating full catalogs in the front door.
|
||||
|
||||
Branch verification: `zig build`, `zig build test` (including checked Quick Reference excerpts and source diagnostic fields), full conformance (482 passed, zero failed/pending), formatting, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke tests pass. The executable example returns 305419896 without grants. All run fixtures execute twice for determinism. Twenty-six new tests cover each width/order, every short length, empty slices, maximal integers, every bit position, independently fixed byte vectors, offset/extra-byte preservation, compound type composition, symbol collisions and rejected payloads/matches/borrows. A source run returning the enum record matches hand-written AIR; an AIR wrong-payload fixture rejects with `E1001`.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Capacity traps make recoverable protocol errors caller assertions. Boolean plus borrowed output requires an extra variable, mutable alias reasoning and a separate guarantee about unchanged output. A numeric sentinel cannot represent failure. A generic `Result<T,E>` would be preferable once independently specified source generics exist; adding those now would enlarge this increment substantially. Three monomorphic read results keep success payloads width-correct with existing mechanisms. Runtime intrinsics would expand the trusted boundary for algorithms safe source already expresses.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-028 records the short-buffer/result decision as resolved in this branch. Must-use results, general modules, imported structs and generics are separate design questions, not implicitly implemented. Q-027's existing empty byte-literal discrepancy is unchanged; empty input/output fixtures use zero-length sub-slices.
|
||||
@@ -0,0 +1,135 @@
|
||||
# RFC 0018: Bounded copy/search and recoverable unsigned arithmetic
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-1b, safe standard library APIs; existing source and AIR format 0 unchanged
|
||||
Language version: 0.1
|
||||
Supersedes: —
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
The proposed spec, reference implementation and tests are integrated on the work branch for review. Only the owner changes an RFC to Accepted. RFCs 0016/0017 remain the historical records for imports and endian operations.
|
||||
|
||||
## Motivation
|
||||
|
||||
Storage and protocol code needs whole-input byte copy with capacity failure, substring lookup with an unambiguous empty-input result, and overflow-aware buffer sizing. Existing primitive copy and arithmetic trap on invalid capacity/overflow; manually repeating guards adds repair work. Standard functions can express these operations using existing verified source.
|
||||
|
||||
This increment improves semantic explicitness, deterministic behavior, memory safety and implementation simplicity. It adds eight functions and three ordinary result enums, with no new language feature or verifier state. A reduction in model capability requirements remains an empirical hypothesis.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
Copy accesses only supplied initialized slices and mutates exactly the source-length prefix of sufficient exclusive output. A short-output result leaves the entire destination unchanged and reads no source elements. Search only reads shared input. No borrowed value escapes, heap allocation occurs, resource is consumed, authority is created or task starts. Arithmetic returns a payload exactly when the mathematical result fits the operand type; neither overflow nor a zero multiplier traps.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
Integrated text is spec 16 §2.1.1/§2.4, with the primitive-versus-recoverable copy distinction clarified in spec 15 §6:
|
||||
|
||||
- `std.bytes.copy(dst, src)` MUST return `WriteResult::short_output` before any element access when output is short. Success MUST copy the whole input into the output prefix and preserve the remainder. Empty input succeeds. Existing alias rules reject overlapping shared/exclusive borrows regardless of runtime capacity; this is not `memmove`.
|
||||
- `find_slice(data, needle)` MUST return `FindResult::found(index)` at the first match or `not_found`. Empty needle MUST return `found(0)`, including empty data. A found offset may equal the data length and is not necessarily a readable index. No borrow is returned or retained.
|
||||
- Splitting at the first separator composes that search with existing explicit slices or `split_at`. There is no split function returning an aggregate of borrows or implicit cursor. Empty separator gives an empty left part and the whole right part; repeated splitting requires a caller-chosen progress rule.
|
||||
- `checked_add_u64`, `checked_sub_u64`, `checked_mul_u64` return `std.math.U64Result`; the `_usize` forms return `std.math.UsizeResult`. Both enums have `ok(value)` and `overflow`. Representability determines success; unsigned underflow is overflow. `usize` follows target width.
|
||||
- Normal arithmetic still traps on overflow. Wrapping stays with `+%`, `-%`, `*%`; no synonymous library wrappers are added. Generalized widths, signed/saturating arithmetic and generics are outside this increment.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new abstract state, transfer function, diagnostic or privilege. Existing slice initialization/lifetime, shared/exclusive alias, call typing and Copy enum payload/match rules apply. Capacity guards do not grant an alias exception. A disjoint `split_at` pair from one allocation can be copied; two sub-slices of the same parent retain the existing conservative overlap rule. Results are ordinary Copy values with no must-use checking.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
No runtime change. Copy checks capacity, then calls the existing primitive `slice.copy`. Search checks empty/oversize needles, bounds a scan by `data.len - needle.len`, and uses existing equality and sub-slices. It checks the final start before incrementing, avoiding an overflowing end-plus-one loop bound. Search has constant auxiliary storage and O(data length × needle length) worst-case byte comparisons.
|
||||
|
||||
Unsigned arithmetic uses prechecks before checked operations: add checks available headroom, subtract compares operands, and multiply short-circuits the divisor check when its second operand is zero. The unsigned maximum is computed as `0 -% 1` in the operand type, without host constants or assumptions about pointer width. No implicit widening occurs.
|
||||
|
||||
All APIs are safe `.aji` with `effects []`, no heap/authority/concurrency effect and identical deterministic/hosted behavior. Valid slices and scalar operands do not produce bounds, arithmetic, cast or shift traps. Interpreter fuel remains an environment limit and is not a returned library error; the unchanged-output guarantee applies to `short_output`, not interruption mid-execution.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None. Functions lower to ordinary calls, branches, arithmetic, borrows, `slice.copy`, `enum.make` and `enum.switch`, under the existing published feature closure. There is no new instruction, type kind, feature entry or interpretation. AIR format 0 remains frozen.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn encode(dst: slice_mut<u8>, data: slice<u8>) -> usize
|
||||
effects []
|
||||
{
|
||||
match std.math.checked_add_usize(data.len, 1) {
|
||||
std.math.UsizeResult::ok(total) => {
|
||||
if total > dst.len { return 0; }
|
||||
match std.bytes.copy(mut dst, ref data) {
|
||||
std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; }
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
}
|
||||
std.math.UsizeResult::overflow => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`examples/std/bounded.aji` adds a main that encodes a zero-terminated byte record, searches its delimiter and verifies untouched output bytes. The conformance copy returns 10 without grants. `bounded_split.aji` checks first-separator composition, including empty inputs and separators.
|
||||
|
||||
## Rejected example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 4] = zero;
|
||||
let result = std.bytes.copy(mut buf, ref buf);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Existing `E2101` reports the conflicting shared borrow and the call's argument conflict. `bounded_copy_alias.aji` captures both diagnostics. Holding a shared borrow of the array and copying into its empty prefix is also rejected; runtime capacity checks do not weaken verification.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new codes. Wrong operands/result payloads use `E7005` (AIR payload typing `E1001`); unknown/absent imports use `E7002`; incomplete matches use `E7004`; conflicting copy borrows use `E2101`. Existing diagnostic counts and source mapping remain unchanged. Capacity and overflow are result variants, not diagnostics or traps.
|
||||
|
||||
## Spec integration
|
||||
|
||||
- Spec 16 §2.1.1: six recoverable arithmetic functions, two result enums, exact representability and operator policy.
|
||||
- Spec 16 §2.4: copy, search result enum, first-separator composition, capacity/empty/alias/profile contracts.
|
||||
- Spec 15 §6: distinguishes primitive trapping copy from recoverable byte copy; no new grammar or lowering rule.
|
||||
- API reference and Quick Reference: signatures, ordinary result handling, source example and on-demand contracts.
|
||||
- Plan and Q-029: bounded split/arithmetic decisions and remaining general-module/generic work.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
No source/AIR syntax, ownership, alias, effect, capability, runtime or existing API meaning changes. Existing `find` retains its single-byte length sentinel, including absence on empty data. Substring search uses an enum because an empty needle can successfully match empty data at offset zero. The distinct operations are intentionally documented together, without silently changing `find`'s result type. Import composition now includes eight additional functions and three enums; existing whole-module composition and collision-free names still apply. No migration required.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: bounded whole-input copy; first substring offset including empty needles; recoverable scalar overflow. Results reuse ordinary enum handling.
|
||||
- New verifier state: none. No new borrow return/lifetime or cleanup obligation.
|
||||
- New syntax/instructions: none. Eight monomorphic function names and three ordinary result enum names are added, on demand.
|
||||
- Interactions: slice aliases, disjoint split borrows, sub-slice bounds, Copy results, qualified standard type names, target-sized integers, short-circuit evaluation and interpreter fuel.
|
||||
- Repairability: short copies cannot partially overwrite records; arithmetic sizing errors become typed results; search distinguishes absence from an empty match. Explicit splitting keeps borrow scopes visible. Callers can still ignore Copy results under existing rules; no measured compression claim is made.
|
||||
- Existing primitives express all algorithms. No compiler change or trusted intrinsic is needed. Wrapping operators already suffice, so wrappers are omitted.
|
||||
- New source diagnostic codes: zero. General width/signed APIs wait for a separate contract rather than proliferating wrappers.
|
||||
- Quick Reference adds only a short routing paragraph; the signature catalog and full contracts remain in on-demand `library/std.md`.
|
||||
|
||||
Measured against the endian increment (`a2ca293`) with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference (`QUICK.md`, includes navigation) | 6,000 → 6,082 (+1.4%) | 6,019 → 6,102 (+1.4%) | 6,189 → 6,272 (+1.3%) |
|
||||
| Other source docs | 31,918 → 33,628 (+5.4%) | 32,001 → 33,718 (+5.4%) | 32,838 → 34,572 (+5.3%) |
|
||||
| Full source docs without AIR | 37,918 → 39,710 (+4.7%) | 38,020 → 39,820 (+4.7%) | 39,027 → 40,844 (+4.7%) |
|
||||
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
Standalone AIR remains 160,797 bytes, 48 sections and 19 files. Incremental source bundle growth stays below the 10% warning threshold. The library page grows from 2,533/2,532/2,654 to 4,223/4,229/4,367 tokens: eight APIs need capacity, empty-match, split progress, target-width and overflow contracts, plus one checked sizing/copy example. This is on-demand documentation; the Quick Reference only gains an 82-token routing paragraph (cl100k) instead of a repeated arithmetic catalog. Its approximately 6k target remains a front-door constraint for future increments.
|
||||
|
||||
Branch checks: build, unit tests/Quick Reference extraction, full conformance (505 passed, zero failed/pending), formatting, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke all pass. The bounded example returns 10 without grants. Twenty-three new conformance tests exercise all 81 length/capacity pairs through eight, disjoint same-allocation copy, overlapping/empty short-output aliases, 428 substring cases, seven split cases and 320 independently computed arithmetic pairs through both u64 and usize APIs. Arithmetic fixtures include zero multipliers, underflow, addition headroom and multiplication near limits, plus seeded fixed random inputs. They use the interpreter's default `air64`; no 32-bit runtime test is claimed. Copy and arithmetic source runs match hand-written AIR; an AIR wrong-payload fixture rejects with `E1001`. All run tests execute twice for determinism, and accepted source lowers canonically and deterministically.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
An ambiguous length sentinel for substring search needs an extra empty-needle convention from the caller. A numeric result enum directly distinguishes absence. A split iterator or returned slice aggregate adds lifetime state and cursor semantics before imported structs/borrowed aggregates are specified; explicit existing slicing suffices. A silent partial copy makes output validity caller-dependent. A memmove wrapper cannot bypass the existing alias rule. Duplicating wrapping operators expands the API without changing the contract. Adding generics or a generic Result to this increment would substantially enlarge its semantic surface.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-029 records these API decisions as resolved on the branch. General generics, imported structs, borrowed aggregates and must-use values remain separate work. The reference interpreter currently executes `air64`; arithmetic fixtures use that target, while the usize implementation computes its limit in target width. Q-027's empty byte-literal gap is unchanged; empty tests use existing zero-length slices.
|
||||
@@ -0,0 +1,133 @@
|
||||
# RFC 0019: UTF-8 and supplied-buffer hex/Base64
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-2a, safe standard modules; existing source syntax and AIR format 0 unchanged
|
||||
Language version: 0.1
|
||||
Supersedes: —
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
This work branch contains the proposed specification, implementation and tests for review. Only the owner changes the RFC to Accepted. Formatting is a separate STD-2b increment.
|
||||
|
||||
## Motivation
|
||||
|
||||
CLI, protocol and storage code needs to validate text and transform arbitrary bytes without hidden allocation. UTF-8 iteration can use existing scalar/offset values, while caller-provided encoding buffers make capacity and mutation explicit. A bad trailing byte must not leave a partially decoded record that the caller needs to reason about.
|
||||
|
||||
The increment improves semantic explicitness, deterministic behavior, memory safety and implementation simplicity. Its Model Capability Compression benefit is a hypothesis, not inferred from fixtures. Three modules add six functions and six ordinary Copy enums; no runtime codec or new language mechanism is needed.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
UTF-8 only reads shared input and returns scalar/count or validation offset values. Encoding operations only access initialized supplied slices; successful writes modify exactly an output prefix. Returned invalid-input/short-output errors leave the entire destination unchanged. No borrow escapes, heap allocation occurs, owner/resource is consumed, authority is created or task starts. Fixed local tables are frame storage. Ordinary shared/exclusive alias rules apply on every path.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
Complete proposed contracts are integrated in spec 16 §2.5–§2.7; the closed registry/source-path table in §2 now lists five modules. Spec 15 §13 references that table without changing resolution rules.
|
||||
|
||||
- `std.utf8.next(src)` MUST return `ok(scalar, consumed)`, `end` for empty input or `invalid_input` for a malformed/truncated first sequence. It checks only that sequence; caller offsets/sub-slices express iteration.
|
||||
- `validate(src)` MUST validate all input and return `invalid_input(offset)` at the leading byte of the first bad/truncated sequence, or `ok`. Empty input succeeds. The scalar domain excludes surrogates and values above U+10FFFF; no normalization or replacement is performed.
|
||||
- Hex encode MUST emit lowercase ASCII digits; decode MUST accept even-length ASCII hex in either letter case, with no prefixes, separators or whitespace.
|
||||
- Base64 encode/decode MUST use canonical padded standard encoding. Decode rejects incomplete groups, nonalphabet bytes, misplaced/extra padding and nonzero unused bits. URL-safe/permissive modes are not part of the contract.
|
||||
- Encoding MUST precheck the full output size without intermediate overflow. Decode MUST validate all input before checking capacity or writing. Invalid input MUST win over short output; both returned errors MUST preserve the entire destination.
|
||||
- `ok(count)` identifies the written prefix; remaining output stays unchanged, no terminator is appended, and empty input succeeds with count zero even with empty output. A mathematical encoded size exceeding usize/capacity is `short_output`.
|
||||
|
||||
Unicode scalar/byte rules were checked against [RFC 3629 §3/§4](https://www.rfc-editor.org/rfc/rfc3629.html#section-3). Base64 alphabet/padding and the deliberate strict unused-bit policy follow [RFC 4648 §3.5/§4](https://www.rfc-editor.org/rfc/rfc4648.html#section-3.5). Hex lowercase output is an explicit Aji choice; decode also accepts uppercase public vectors.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new abstract state, transfer function, diagnostic code or trusted exemption. Existing call, slice initialization/lifetime, bounds, shared/exclusive alias and enum payload/match rules apply. Size guards do not discharge alias checks. Overlap rejects; proven disjoint `split_at` siblings from one allocation work. All results are ordinary Copy values, with existing qualified type/constructor/pattern syntax and no must-use rule.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
No runtime primitive or profile change. Ordinary source branches, shifts/masks, fixed frame arrays, slice accesses and enums implement the algorithms. UTF-8 checks remaining capacity before continuation accesses and restricted second-byte ranges before scalar assembly. Validation advances only by a successful 1..4-byte count bounded by the remaining slice.
|
||||
|
||||
Hex encode checks `src.len <= dst.len / 2` before multiplying. Base64 encode checks whole groups against `dst.len / 4`, then tail capacity before summing. This avoids overflow in `src.len + 2`, group multiplication or output offsets. Decode first validates digits/groups/padding/unused bits, computes the bounded decoded count, then checks capacity before writing. Padding is never interpreted as a data symbol.
|
||||
|
||||
Reference work is O(input length), with constant auxiliary storage: a 16- or 64-byte alphabet and/or 256-byte inverse map. Frame storage is explicit source; no heap or hidden cursor exists. All functions declare `effects []`, are deterministic in both profiles and do not produce bounds/arithmetic/cast/shift traps for valid slices. Malformed/truncated input and capacity failure are ordinary results. Fuel exhaustion remains an environment outcome; destination preservation covers returned errors, not interruption mid-operation.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None. Algorithms use existing calls, arithmetic, arrays, ownership/borrows and `enum.make`/`enum.switch`; the normal combined feature closure is emitted. There is no opcode, type kind, instruction contract, feature registry entry or altered format-0 meaning. Three new registry entries embed safe source through the existing frontend and verifier.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.utf8;
|
||||
|
||||
fn first(src: slice<u8>) -> u32
|
||||
effects []
|
||||
{
|
||||
match std.utf8.next(ref src) {
|
||||
std.utf8.NextResult::ok(scalar, count) => { return scalar; }
|
||||
std.utf8.NextResult::end => { return 0; }
|
||||
std.utf8.NextResult::invalid_input => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`examples/std/text.aji` combines hex decoding, UTF-8 validation, Base64 encoding and scalar decoding, returning 8364 (U+20AC). Its conformance copy is `text_example.aji`, and the API reference includes that checked program. `text_utf8_iteration.aji` demonstrates explicit offsets and four scalar widths. `text_disjoint.aji` encodes/decodes between disjoint halves of one allocation.
|
||||
|
||||
## Rejected example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.encoding.hex;
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 4] = zero;
|
||||
let result = std.encoding.hex.decode(mut buf, ref buf);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Existing `E2101` reports the conflicting borrow and call argument conflict; `text_hex_alias.aji` captures both. Base64 encode has the same negative test. Wrong result payloads and passing the hex result as a Base64 result reject with `E7005`; imported modules keep distinct enum identities.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new codes. Wrong operands/payloads use `E7005` (AIR payload test `E1001`); missing/unknown imports use `E7002`; incomplete result matches use `E7004`; conflicting input/output borrows use `E2101`. Source diagnostic types and provenance retain public paths. Invalid byte sequences are returned variants, not compiler diagnostics or traps. Existing enum wildcard/duplicate rules continue unchanged.
|
||||
|
||||
## Spec integration
|
||||
|
||||
- Spec 16 §2: five-module registry and stable bundled source paths.
|
||||
- Spec 16 §2.5–§2.7: UTF-8 scalar/offset rules, codec signatures, capacity/validation/mutation, complexity, safety and compatibility.
|
||||
- Spec 15 §13: provenance refers to the registry table; no new syntax/lowering rule.
|
||||
- Reference/Quick Reference/bundle navigation: on-demand API contracts and checked example, with existing result handling.
|
||||
- Plan STD-2a/2b and Q-030: this scope is complete only after checks; supplied-buffer formatting remains pending.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
AIR format 0, source syntax, existing APIs, verifier/runtime rules and capability/effect contracts retain their meanings. Unknown imports now recognize three additional compiler-pinned modules; no filesystem/network/package resolution or dependencies are introduced. Each module is self-contained and uses full standard type paths. Lexicographic composition, collision suffixes and stable diagnostics work at four-component paths; unit tests cover all five imports in different orders and directory names. No migration is required. Q-027's empty byte literal gap remains; empty fixtures use zero-length slices.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: scalar-level UTF-8 with explicit consumed count/validation offset; caller-output codec operations; strict canonical Base64 acceptance. No owning string/iterator or borrowed aggregate.
|
||||
- New verifier state: none. No additional lifetime, alias, allocation, capability, cleanup or concurrency obligation.
|
||||
- New syntax/instructions: none. Six function names and six ordinary Copy enum names are read on demand; nested standard paths use the existing parser/linker.
|
||||
- Interactions: existing enum payloads/exhaustiveness, slices/sub-slices/disjoint splits, frame arrays, checked arithmetic/short-circuit guards, compiler-pinned imports and fuel.
|
||||
- Repairability: a returned decode failure has no partial output state; empty input and valid zero-length output are explicit; UTF-8 error offsets identify a sequence start. Callers must still handle/check Copy results under existing rules. No measured model capability reduction is claimed.
|
||||
- Existing primitives suffice; pure source avoids a runtime codec trusted boundary. Scalar/offset iteration and fixed tables avoid adding iterator machinery, generics or allocation contracts.
|
||||
- New source diagnostics: zero. Quick Reference adds a routing paragraph; complete signatures, malformed-input/capacity policy and a checked example stay in on-demand `library/std.md`.
|
||||
|
||||
Measured against STD-1b (`6397a31`) with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference (`QUICK.md`, includes navigation) | 6,082 → 6,163 (+1.3%) | 6,102 → 6,184 (+1.3%) | 6,272 → 6,356 (+1.3%) |
|
||||
| Other source docs | 33,628 → 36,042 (+7.2%) | 33,718 → 36,159 (+7.2%) | 34,572 → 37,048 (+7.2%) |
|
||||
| Full source docs without AIR | 39,710 → 42,205 (+6.3%) | 39,820 → 42,343 (+6.3%) | 40,844 → 43,404 (+6.3%) |
|
||||
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
Standalone AIR stays 160,797 bytes, 48 sections and 19 files. Incremental source growth is below the 10% warning threshold. The on-demand library page grows from 4,223/4,229/4,367 to 6,644/6,677/6,849 tokens: six APIs require scalar validity, first-sequence versus whole-input handling, exact error offsets, canonical byte acceptance, capacity priority and unchanged-output contracts, plus one checked composition example. Quick Reference only adds a routing paragraph and changes the navigation row; catalogs remain on demand.
|
||||
|
||||
Cumulatively since the pre-stdlib source baseline in RFC 0016, source docs excluding AIR grow from 33,981 to 42,205 cl100k tokens (+24.2%), crossing the 20% review line. This growth is explicit for owner review: the five-module library has 35 functions and 13 result enums, all algorithm contracts live on demand, and there is no new verifier state, syntax or AIR documentation. The Quick Reference grows from 5,511 to 6,163 (+11.8%); future increments should split/selectively expose library references instead of extending its catalog. Documentation growth is not evidence of model capability compression; API/read/repair costs still need empirical review.
|
||||
|
||||
Branch checks: build, unit/Quick Reference checks, full conformance (529 passed, zero failed/pending), formatting, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke pass. The executable text example returns 8364 without grants. Twenty-four new tests cover all 256 single bytes for UTF-8, 139 fixed valid and 608 malformed/prefixed scalar-sequence cases, four-width explicit iteration, 276 independent valid vectors per encoding (including empty and every single byte), 242 malformed hex and 296 malformed Base64 vectors, every relevant capacity, untouched suffixes, invalid-input precedence, noncanonical pad bits, proven disjoint same-allocation operations, alias rejection and module/type collision rules. Source runs compare with hand-written AIR scalar/encoded-byte fixtures; AIR payload typing rejects with `E1001`. All run tests execute twice for determinism. Unit checks compare canonical lowering for all five imports in different orders/directories and preserve all bundled source paths without heap/capability/intrinsic instructions.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Replacement decoding hides malformed input; streaming recovery needs a separate explicit state contract. Silent partial output makes post-failure byte validity caller-dependent. Permissive Base64, URL-safe switches and optional padding multiply accepted forms; they can be separate independently justified APIs later. Hidden growing strings/iterators need allocation and lifetime features beyond this step. Returning a borrow or aggregate iterator is unnecessary when a scalar and consumed count suffice. Runtime intrinsics add trusted code for operations safe source can already express.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-030 records the codec policy as resolved on this branch. Streaming UTF-8/codecs, URL-safe Base64, Unicode normalization/properties, owning strings, generic results and must-use values remain separate work. STD-2b still needs a minimal formatting contract; this RFC does not claim formatting is implemented.
|
||||
@@ -0,0 +1,83 @@
|
||||
# RFC 0020: Supplied-buffer integer formatting
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-2b, safe standard source; language 0.1 and AIR format 0 unchanged
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
This branch contains the proposed spec, implementation and tests. Owner acceptance remains separate from branch implementation.
|
||||
|
||||
## Motivation and contract
|
||||
|
||||
Bounded CLI/storage records need decimal integer text without allocating or parsing format strings. Four monomorphic `std.fmt.write_u64/i64/usize/isize` functions and one Copy `WriteResult { ok(usize), short_output }` suffice. Full contracts are integrated in spec 16 §2.8; the registry adds `std.fmt` at `std/fmt.aji`.
|
||||
|
||||
Output is exact decimal ASCII, with a sign only for negative values, no leading zeroes except zero itself, and no terminator. A successful count includes the sign; only the output prefix changes. Insufficient capacity, including an empty destination, returns `short_output` before writing and preserves the whole destination. All values are supported, including signed minima. Existing byte copy and explicit caller offsets compose records. Each call's failure guarantee does not roll back earlier successful calls.
|
||||
|
||||
The increment improves deterministic behavior, explicit failure and implementation simplicity. Model Capability Compression remains an empirical hypothesis. General format strings, radix switches, floats, wider integers, text parsing, owning strings and writer protocols are outside this step.
|
||||
|
||||
## Memory and verifier invariant
|
||||
|
||||
Only the provided exclusive initialized slice is written, within its bounds. No borrow escapes, owner/resource is consumed, heap is allocated or authority/task is created. Existing initialization, call, shared/exclusive alias, lifetime, bounds and enum rules enforce this invariant. Live conflicting borrows reject even for a call that would return short output. No new verifier state, transfer function or privilege exists.
|
||||
|
||||
## Runtime and deterministic behavior
|
||||
|
||||
Safe source counts decimal digits by unsigned division before checking capacity. Signed magnitude is computed as unsigned `-(value + 1) + 1` on the negative path, avoiding direct negation of the signed minimum; nonnegative signed values convert directly. The sign is counted before capacity checking. Successful writes fill the digits from right to left, preserving the suffix. No temporary digit buffer, table or heap is needed; auxiliary scalar storage is constant and work is O(decimal digit count).
|
||||
|
||||
All functions declare `effects []` and use ordinary integer operations, slices, branches and enums. No AIR instruction/feature, trusted implementation, runtime rule or profile distinction is added. Bounds, arithmetic and checked conversions are valid for every input value and supplied slice. Interpreter fuel exhaustion remains an environment outcome, outside the returned-error preservation guarantee.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.fmt;
|
||||
fn main() -> std.fmt.WriteResult effects [] {
|
||||
var text: [u8; 3] = zero;
|
||||
return std.fmt.write_i64(mut text, -42);
|
||||
}
|
||||
```
|
||||
|
||||
This produces bytes `-42` and `ok(3)`. `examples/std/format.aji` and its conformance copy compose `value=-42 count=7` with explicit offsets and return 17. Independent scalar fixtures check all capacities, untouched guard/suffix bytes, zero, signed minima, unsigned maxima and decimal/binary boundaries. A disjoint split with a live borrow of the other half is valid.
|
||||
|
||||
## Rejected example and diagnostics
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.fmt;
|
||||
fn main() -> u8 effects [] {
|
||||
var text: [u8; 4] = zero;
|
||||
ref held = text;
|
||||
let result = std.fmt.write_i64(mut text[0..0], -1);
|
||||
return held[0];
|
||||
}
|
||||
```
|
||||
|
||||
The conflicting exclusive borrow rejects with existing `E2101`, despite short capacity. Wrong destination/value/enum payload types use `E7005`; unknown/missing imports use `E7002`; incomplete matches use `E7004`. No new code or diagnostic envelope is needed. The result is Copy and introduces no must-use rule. A hand-written AIR result fixture checks the ordinary enum payload/count independently of source lowering.
|
||||
|
||||
## Compatibility and spec integration
|
||||
|
||||
Spec 16 §2 and §2.8 add the sixth closed-registry module and complete formatting contract. Spec 15 §13 resolution stays unchanged; Q-031 records the decision. Reference, Quick Reference navigation, examples and plan STD-2b expose the API through the existing source bundle. Existing source/AIR and library APIs preserve their meanings; importing grants no authority. Canonical ordering, collision handling and source provenance use existing linking; unit checks cover all six modules in different orders/directories. No migration is required.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: a supplied-buffer decimal writer and its byte count; the existing explicit capacity/result convention is reused.
|
||||
- New verifier state, syntax, AIR instructions, effects, capabilities and diagnostics: zero.
|
||||
- API additions: four scalar function names and one ordinary Copy enum, documented on demand. Smaller widths explicitly convert to an appropriate writer. There is no generic specialization, retained offset or cleanup obligation.
|
||||
- Interactions: target-width integers, checked conversion, signed limits, slice offsets, exclusive borrows, exhaustive enum matches and interpreter fuel.
|
||||
- Repairability: a short write preserves every destination byte, all numeric inputs are valid, and exact byte count exposes the next caller offset. Whole-record transactionality is not implied.
|
||||
- Existing primitives suffice; a runtime formatter or format-string language would add complexity without improving this contract.
|
||||
|
||||
Measured against the completed STD-2a worktree with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 6,163 → 6,220 (+0.9%) | 6,184 → 6,241 (+0.9%) | 6,356 → 6,415 (+0.9%) |
|
||||
| Other source docs | 36,042 → 37,128 (+3.0%) | 36,159 → 37,248 (+3.0%) | 37,048 → 38,154 (+3.0%) |
|
||||
| Full source docs without AIR | 42,205 → 43,348 (+2.7%) | 42,343 → 43,489 (+2.7%) | 43,404 → 44,569 (+2.7%) |
|
||||
| AIR docs in source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
Standalone AIR remains 160,797 bytes, 48 sections and 19 files. The on-demand library page grows from 6,644/6,677/6,849 to 7,730/7,766/7,955 tokens: the decimal grammar, signed/target limits, capacity/failure and append composition are explicit, with one checked complete example. Quick Reference grows by only a routing sentence. Cumulative source growth from the pre-stdlib 33,981 cl100k baseline is +27.6% (43,348); Quick Reference grows from 5,511 to 6,220 (+12.9%). The existing 20% review crossing stays explicit for owner review, without claiming model capability compression. Future library-reference splitting/selective reading remains the plan; this change adds no source grammar or AIR documentation.
|
||||
|
||||
Branch checks: `zig build`, `zig build test`, full conformance (544 passed, zero failed/pending), `zig fmt --check build.zig build.zig.zon src tools tests/extended`, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke pass. The executable formatting example returns 17 without grants. Fifteen new conformance files (seven source runs, seven source rejections, one AIR run) cover 523 unsigned and 984 signed independent decimal vectors, each through both fixed/target-width APIs and all capacities 0..22. All source runs execute twice for deterministic outcomes. Target-width vectors guard conversions against the target limits; the reference interpreter currently runs air64. Zero/min/max, powers of ten/two and neighbors, every small magnitude, seeded inputs, untouched guard/suffix bytes, short-output alias rejection, names/types/payloads, exhaustive matches, disjoint live borrows and source/AIR result equivalence pass. Canonical import order/provenance checks cover all six modules without heap/capability/intrinsic instructions.
|
||||
|
||||
## Alternatives and remaining work
|
||||
|
||||
An unchecked signed negation fails at the minimum value. Writing before discovering short capacity creates partial record state. Returning only a count/sentinel hides failure, and returning an output borrow adds unnecessary lifetime state. A format-string parser, radix/configuration object, public sizing helpers or synonymous append variants multiply APIs. Decimal writers plus existing copy and explicit offsets suffice for this step. Owning collections still depend on general modules, generics and `linear_aggregates`; completing STD-2b does not remove those gates.
|
||||
@@ -0,0 +1,118 @@
|
||||
# RFC 0021: Explicit package source modules
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-3 / P6-3; source language 0.1, AIR format 0 unchanged
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
The branch contains the proposed normative text, implementation and tests. Only the language owner changes RFC acceptance status.
|
||||
|
||||
## Motivation and decision
|
||||
|
||||
Reusable library types need module identity, local name binding and explicit compiler inputs before generics or owning collections can have stable contracts. Extend the existing compiler-pinned standard import mechanism to an explicit source provider. The CLI obtains this provider solely from a selected manifest's `[modules]` map; the frontend accepts source bytes and diagnostic paths, without filesystem access. General package dependency resolution is separate work.
|
||||
|
||||
Spec 12 §1.3 defines the manifest and loading contract; spec 15 §14 defines the graph and namespace rules. The standard registry remains compiler-pinned and cannot be shadowed. Every declaration and field is available through a direct import. All reachable declarations, including unused helpers, lower and verify. There are no aliases, re-exports, visibility modifiers or executable module initialization.
|
||||
|
||||
Imports form an acyclic graph. Header mismatch, duplicate imports/mappings and cycles reject; unreachable mapped files must be readable explicit inputs but are not parsed. Fixed limits are 1,024 mapped modules, graph depth 256, 1 MiB manifest and 64 MiB aggregate source snapshot. Cached graph heights count shared tails toward the depth limit. Modules append in lexicographic order, declarations in source order, using existing collision-free AIR mangling. Entry AIR names remain unchanged; only its unqualified `main` is the entry.
|
||||
|
||||
Each module sees its own short names and directly imported full names. Linked transitive declarations do not become name-visible. A function can return a type inferred by its caller without the caller importing that type's module, but explicitly naming/constructing it requires a direct import. Qualified names resolve independently of local values with the same prefix. Module identity is carried separately from diagnostic filenames, so identical file labels cannot alter binding. Imported function `main` is an ordinary qualified function.
|
||||
|
||||
Qualified struct literals use `app.model.Pair { left: 20, right: 22 }`, retaining the existing uppercase-final-component and condition-brace grammar rules. `task.spawn(s, app.work.run, args)` resolves a static function and emits the existing `task.spawn` instruction with its actual mangled AIR name. Built-in namespaces remain reserved for provider bindings; legacy entry names and built-in precedence stay compatible.
|
||||
|
||||
## Memory, ownership and concurrency invariant
|
||||
|
||||
Importing does not create authority, allocate program heap, retain borrows, share mutable storage, change resource consumption or introduce implicit cleanup. Every cross-module call has the same explicit signature and ownership/effect obligations as a local call. Named linear arguments still require `move`; mutable borrows remain exclusive and within lifetime; task lends remain unavailable until join; all linear values/resources are consumed on every path.
|
||||
|
||||
## Verifier rule
|
||||
|
||||
The frontend binds nominal types and static functions, then submits one combined ordinary AIR module. The existing type, call, initialization, alias, lifetime, resource, effect, Send/Share and task transfer functions apply unchanged. Imported code is never trusted simply because it is imported. Every reachable function is checked even if unused. No new verifier state, transfer function, AIR instruction or feature is introduced; the combined module declares existing feature dependency closure. Format-0 meaning is unchanged.
|
||||
|
||||
## Runtime rule and deterministic behavior
|
||||
|
||||
No runtime module loader, dispatch, initialization or new primitive exists. The interpreter executes ordinary mangled function calls, struct/enum operations and structured tasks. The same explicit source bytes and bindings produce identical canonical AIR across mapping/import orders, directories, diagnostic filenames and execution profiles. First graph errors follow source import order. Imported diagnostics and traps name the supplied source file. Existing interpreter fuel, deterministic scheduler and hosted profiles remain unchanged.
|
||||
|
||||
The CLI snapshots explicit package input files relative to the selected manifest directory. Portable `.aji` paths reject absolute paths, empty/dot/parent components, backslashes, colons and NUL. Descent keeps directory handles open and uses no-follow opens; source leaves must be regular files, checked before open and again on their handles. Symlinks, directories and static pipes reject rather than execute or block on input. These checks do not promise an atomic filesystem snapshot under concurrent writes; compilation is deterministic from the bytes actually read. Legacy manifests without `[modules]` retain their loading contract.
|
||||
|
||||
Check/lower/report select source inputs without instantiating grants. Run/explore merge only explicitly selected manifest grants and command-line overrides. A file-only command never discovers a manifest. `lower --stats` compares entry source bytes against the combined AIR; it is explicitly not a whole-package compression metric.
|
||||
|
||||
## Valid examples
|
||||
|
||||
`examples/modules/aji.toml` maps `app.model` to `model.aji`. The model defines a plain Copy struct and an ordinary function:
|
||||
|
||||
```aji
|
||||
module app.model
|
||||
struct Pair { left: u64, right: u64 }
|
||||
fn total(pair: Pair) -> u64 effects [] { return pair.left + pair.right; }
|
||||
```
|
||||
|
||||
```aji
|
||||
module app.entry
|
||||
import app.model;
|
||||
fn main() -> u64 effects [] {
|
||||
let pair = app.model.Pair { left: 20, right: 22 };
|
||||
return app.model.total(pair);
|
||||
}
|
||||
```
|
||||
|
||||
`aji run --fuel 1000000 --manifest examples/modules/aji.toml` returns 42 without grants. Source conformance also passes an owner with explicit `move` to an imported disposal function and lends disjoint slices to two qualified task workers. The latter has a hand-written AIR twin and deterministic/stress schedule coverage.
|
||||
|
||||
## Rejected examples and diagnostics
|
||||
|
||||
With the same mapping, constructing `app.model.Pair` without a direct `import app.model;` is `E7002`; linking it through another module does not grant name visibility. Repeatedly lending one mutable buffer to qualified workers rejects with the existing race code:
|
||||
|
||||
```aji
|
||||
module app.entry
|
||||
import app.workers;
|
||||
fn main() -> u64 effects [task.spawn] {
|
||||
var buf: [u64; 2] = zero;
|
||||
{
|
||||
mut s = buf;
|
||||
scope sc {
|
||||
let a = task.spawn(sc, app.workers.bump, s);
|
||||
let b = task.spawn(sc, app.workers.bump, s);
|
||||
task.join(move a);
|
||||
task.join(move b);
|
||||
}
|
||||
}
|
||||
return buf[0];
|
||||
}
|
||||
```
|
||||
|
||||
The independently checked fixture rejects `E4101`. Borrow conflicts reject `E2101`; omitted owner moves use `E7003`; absent declared effects use `E3101`. Names/imports use `E7002`; graph/header/duplicate/input-depth errors use `E7006`; source syntax uses `E7001` with expected/found fields at the imported source. Type mismatch remains `E7005`/`E1001`. CLI manifest/path/I/O/budget errors use stderr and exit 2 before verification; source rejection uses JSON Lines and exit 1. No new diagnostic code or envelope is added.
|
||||
|
||||
## Compatibility and integration
|
||||
|
||||
Spec 15 §2, §5, §7, §11, §13–§14 and spec 12 §1 integrate the rules. Reference grammar, Quick Reference, source bundle, Q-032 and both implementation plans track the increment. The six standard modules still expose 39 functions and 14 ordinary enums, with no API change. Existing file-only, AIR-only, standard-only and legacy-manifest programs preserve meaning and lowering. Previously unknown package names become valid only with explicit inputs. Short names remain local; distinct module types are nominally different. No migration or semantics-changing flag is needed.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: explicit module-to-file inputs, module-local short names, direct qualified visibility and an acyclic source graph. All declarations are available; there is no separate export list or privacy state.
|
||||
- Source forms: existing `import path;`, qualified calls/types/enum variants extend to package modules; qualified struct literals and a qualified static worker are supported. Manifest adds one `[modules]` map. No new source keyword, lifetime/ownership syntax, AIR syntax, effect, capability or diagnostic code.
|
||||
- Frontend state: module identity on spans, direct-import scope table, graph visit/cache/depth state and existing nominal type/static signature binding. Verifier/runtime state: none.
|
||||
- Interactions: structs/enums/arrays, local functions, std imports, collision handling, borrow projections, owner moves, effectful calls, task return types and lent buffers. Imported files remain explicit untrusted source inputs through the ordinary verifier.
|
||||
- Repairability: missing imports, cycles, header mismatch and inaccessible members have stable diagnostics; imported source locations point to the actual repair file. No ambient resolution, transitive namespace effects, initialization order or privileged library magic must be reasoned about.
|
||||
- Existing AIR primitives suffice. Textual source concatenation would lose scope and nominal identity; a runtime loader or a new AIR module instruction would add trusted complexity without improving this contract. Generics and linear aggregates remain independent prerequisites for owning containers.
|
||||
|
||||
The source bundle adds an on-demand `language/modules.md` containing the two normative contracts; Quick Reference gives the manifest, one checked source example and navigation. No additional AIR documentation is needed. Measurements and final checks are recorded below.
|
||||
|
||||
## Alternatives and remaining work
|
||||
|
||||
Convention-based file lookup, parent manifest search and environment paths hide compiler inputs. Transitive visibility or import aliases add ambiguous bindings; private/public modifiers and re-exports add concepts before the minimal library need demands them. Lazy runtime loading adds authority and initialization ordering. Dependency fetching and lockfiles require their own package tooling contract. STD-4/P6-4 next addresses deterministic generics and structural constraints; owning collections also require a separate vertical linear-aggregates feature.
|
||||
|
||||
## Documentation measurements
|
||||
|
||||
Measured against STD-2b with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 6,220 → 6,501 (+4.5%) | 6,241 → 6,522 (+4.5%) | 6,415 → 6,704 (+4.5%) |
|
||||
| Other source docs | 37,128 → 38,822 (+4.6%) | 37,248 → 38,940 (+4.5%) | 38,154 → 39,889 (+4.5%) |
|
||||
| Full source docs without AIR | 43,348 → 45,323 (+4.6%) | 43,489 → 45,462 (+4.5%) | 44,569 → 46,593 (+4.5%) |
|
||||
| AIR docs in source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
Standalone AIR remains 160,797 bytes, 48 sections and 19 files. The new module page is 1,566/1,567/1,599 tokens; library/std.md remains 7,730/7,766/7,955. Front-door growth is 281/281/289 tokens. The precise graph, type binding, input bounds and package loading contracts live on demand. Cumulative cl100k growth since pre-stdlib is 33,981 → 45,323 (+33.4%) for full source docs and 5,511 → 6,501 (+18.0%) for Quick Reference. The existing 20% source-doc review crossing remains explicit for owner review. The additional cost buys deterministic modules and nominal types for reusable libraries; it does not establish empirical Model Capability Compression. API-reference splitting and selective reading remain necessary as std grows.
|
||||
|
||||
## Branch validation
|
||||
|
||||
`zig build`, `zig build test`, full conformance (579 passed, zero failed/pending), `zig fmt --check build.zig build.zig.zon src tools tests/extended`, source coverage (76/76), agent-reference, hosted file/stdin/TCP smoke and package CLI integration (36 checks) pass. The module example returns 42. The 35 added conformance cases include source runs/rejections, two hand-written AIR tests and the checked Quick Reference example. All source runs check canonical repeat lowering and deterministic repeat execution. Qualified workers additionally pass 32 schedule-stress seeds across quanta 1, 2 and 7; mutable lends, explicit joins and repeated-lend rejection use existing rules.
|
||||
|
||||
Unit checks cover provider/import-order independence, nominal types when diagnostic file labels coincide, imported syntax/unused-function verifier provenance, bounded shared-tail graphs and names longer than the built-in path buffer. Conformance covers local binding collisions, imported `main`, qualified types/struct fields/enums, lack of short/transitive names, effect/owner/alias/race rejection, header mismatch, duplicate maps/imports/members, cycles, syntax, absent inputs and unreachable malformed sources. CLI checks cover all five commands, grants and overrides, hosted result/output behavior, source trap locations, no ambient manifest discovery, forbidden path components, leaf/ancestor/entry symlinks, nonregular files and aggregate source limits. The integration script is included in CI. No private held-out evaluation material was consulted or changed.
|
||||
@@ -0,0 +1,103 @@
|
||||
# RFC 0022: Explicit source generics and Copy option/result
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-4 / P6-4; source language 0.1, AIR format 0 unchanged
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
This branch contains proposed normative text, implementation and tests. Owner acceptance remains separate from branch implementation.
|
||||
|
||||
## Motivation and contract
|
||||
|
||||
General modules supply reusable nominal types; generic functions/types now remove monomorphic duplication without adding runtime dispatch or inferred authority. Spec 15 §15 defines explicit specialization of functions, structs and enums. Spec 16 §2.9 adds std.option/std.result. Q-033 records the previously unspecified syntax/checking/constraint decisions. Source grammar and Quick Reference are updated in the same change.
|
||||
|
||||
Declarations use `<T>` or `<T: Copy + Send>`; function/worker/constructor/pattern applications use `::<...>`, while type annotations use `Name<...>`. Arguments are always explicit, ordered and complete. There are no traits, defaults, overloads, const/lifetime/effect parameters or argument inference. Qualified applications preserve direct-import visibility and module-local binding. Generic main is forbidden. Existing channel.make<T> spelling is unchanged.
|
||||
|
||||
Headers, signature names/arity, structural constraints, duplicate declarations/parameters/fields/variants, effects and trusted restrictions are checked even on unused templates. Bodies are checked as concrete required specializations; accepting an unused body does not prove it works for arbitrary types. All ordinary non-generic reachable declarations still verify even if unused. The frontend does not guess missing moves, effects, authority or cleanup.
|
||||
|
||||
Copy, Send and Share reuse ordinary type rules. Format-0 Freeze means IslandSafe plain graph content; Local describes context-bound task/scope/shield/guard/storage and explicitly specified wrapper/aggregate propagation, not the complement of Send. These queries provide no operations: Copy does not promise arithmetic, ordering or equality for every concrete type. Unknown/duplicate constraints reject E7006; an unsatisfied property is E7005 at the application with parameter/constraint/found fields. Generic arguments, including phantom arguments, must be well formed by ordinary type rules.
|
||||
|
||||
## Preserved memory and concurrency invariant
|
||||
|
||||
Every emitted specialization obeys existing ownership, initialization, bounds, alias, lifetime, resource, Send/Share, task and effect rules. No borrow escapes, resource duplicates, cleanup disappears or mutable sharing becomes implicit because its type came from a parameter. Named owners/resources still require explicit move and consumption on every path. Task lends remain unavailable until join and disjoint mutable slices remain independent. No implicit heap allocation, refcount, destructor or detached task is introduced.
|
||||
|
||||
Generic functions can transfer individual owners with explicit move; generic aggregate fields still cannot hold them. Copy-only Option/Result reject owners/resources/endpoints/borrows. A generic Cell<own<u64>> still hits the reserved linear_aggregates gate (E0006). Owning option/result and containers remain STD-5/6 work.
|
||||
|
||||
## Verifier and AIR rule
|
||||
|
||||
An AST specialization pass substitutes concrete types before existing lowering. Every required specialization becomes an ordinary named struct/enum or static function. No generic opcode, AIR type constructor, AIR feature or new verifier transfer state is introduced. The ordinary combined AIR verifier remains authoritative for memory/effects/tasks; source constraints use its structural property queries and type well-formedness rules. Concrete headers, parameter types and public effects are preserved. The AIR feature header is the existing dependency closure of emitted code, without fictitious runtime features for phantom type arguments.
|
||||
|
||||
The finite-layout check is repaired to follow array elements, as well as direct nominal members. Arrays cannot hide a by-value recursive aggregate under the existing E1003 contract (spec 07 §8.3). Positive and rejected AIR/source fixtures cover this. Before lowering concrete generic bodies, the same layout query rejects cycles, avoiding recursive lowering of zero-initialized cyclic types. This closes an implementation gap without extending format-0 semantics.
|
||||
|
||||
## Runtime and deterministic behavior
|
||||
|
||||
There is no generic representation, runtime loader, dynamic dispatch or new interpreter primitive. Concrete calls, enum payloads, struct fields, owned values, borrows and workers run under the existing deterministic interpreter and scheduler. Compiler memory used to specialize templates does not allocate program heap or grant authority.
|
||||
|
||||
A key consists of declaration kind, defining module/name and ordered structural concrete argument identities, independent of import/provider order, diagnostic file labels and short/qualified spelling. Nominal module types remain distinct. Same-key recursion reuses a pending instance; expanding recursion is bounded. Instances append in sorted key order after ordinary declarations, with types before functions. AIR names use lowercase SHA-256 key bytes with smallest unused numeric suffixes, assigned in sorted key order against original/generated names. Full keys determine identity; hashes do not. This handles collisions without order-dependent naming. Source diagnostics preserve template provenance, and display names show readable concrete source types/functions rather than internal encoded identifiers.
|
||||
|
||||
Fixed compiler limits are 8 parameters per declaration, 4,096 generated declarations, active expansion depth 64, structural type traversal depth 64 and canonical key length 16,384 bytes. Limits reject E7006; they are not runtime fuel or semantics-changing flags. Recursively spelled applied type keys avoid repeated hex expansion; output AIR names remain compact. Existing monomorphic input preserves canonical AIR. Source from-returns retain the existing unimplemented outcome; Q-034 tracks their missing lifetime/binding implementation rather than inventing a contract here.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module demo.generic
|
||||
import std.option;
|
||||
fn identity<T: Copy>(value: T) -> T effects [] { return value; }
|
||||
fn main() -> u64 effects [] {
|
||||
let value = std.option.Option::<u64>::some(identity::<u64>(42));
|
||||
match value {
|
||||
std.option.Option::<u64>::some(n) => { return n; }
|
||||
std.option.Option::<u64>::none => { return 0; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The checked examples/std/generics.aji returns 42 without grants. The registry includes Option<T: Copy> { some(T), none } and Result<T: Copy, E: Copy> { ok(T), err(E) }, with is_some<T>/is_ok<T,E> classification helpers declaring effects []. Matching is ordinary exhaustive enum matching, not intrinsic outcome shorthand. No implicit unwrap, default, conversion or must-use rule is added.
|
||||
|
||||
Additional runnable source fixtures swap two exclusive scalar borrows, read through a generic shared parameter, transfer an owner to a generic identity with explicit move and take it exactly once, invoke generic effectful code with an entry capability, specialize a qualified package template with a caller's nominal type, recurse with one cached instance, and lend disjoint buffers to specialized workers.
|
||||
|
||||
## Rejected examples and diagnostic impact
|
||||
|
||||
```aji
|
||||
module demo.generic
|
||||
fn marker<T: Copy>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<own<u64>>(); }
|
||||
```
|
||||
|
||||
This rejects E7005 at the argument application, identifying T, Copy and own<u64>. Missing arguments, arity, generic entry, duplicate/unknown properties, shadowed parameters and expansion limits use E7006. Missing/inaccessible templates/types use E7002; malformed syntax uses E7001. Existing E7003, E2101, E3101 and E4101 reject missing moves, alias conflicts, omitted effects and duplicate task lends. Incomplete option/result matches remain E7004. Unsupported linear aggregate members still use E0006; recursive layout uses E1003. There is no new diagnostic code or envelope. Errors and traps in imported generic bodies retain the template file/line.
|
||||
|
||||
For example, passing mut a twice to swap::<u64> rejects E2101, and passing the same slice to two live specialized workers rejects E4101. Send<task<u64>>, Share<region>, Freeze<cap<io.write>> and Local<u64> reject rather than silently changing behavior. Unknown signature types or trusted clauses in unused templates reject, while unused body operations are deliberately not concretely checked until instantiated.
|
||||
|
||||
## Compatibility and integration
|
||||
|
||||
Spec 15 §13/§14 distinguish complete ordinary declarations from templates under §15; source grammar, type property reference and spec 01 overview point to the explicit forms. The source bundle includes an on-demand language/generics.md; std signatures/constraints are in library/std.md. Two safe embedded modules add two enum templates and two helper templates; the existing six modules, 39 monomorphic functions and 14 enums retain contracts. No package discovery, ambient authority or dependency fetch is added.
|
||||
|
||||
Previously invalid explicit source generic syntax becomes valid; monomorphic source/AIR and legacy channel.make<T> remain compatible. Fixing array layout recursion rejects previously misaccepted but normatively invalid AIR. Existing unsupported from-return behavior remains visible and separately tracked. STD-4 completes the generic/structural-specialization task on this branch; full Phase 6 and owning containers remain incomplete. The owner adopted this implemented contract with the intermediate std merge (2026-10-07).
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: ordered explicit type parameters/arguments, concrete specialization versus unused-body checking, structural property requirements and bounded compile-time expansion.
|
||||
- New source forms: declaration parameter lists, optional property lists, applied type names and explicit expression/pattern specialization. Existing qualified names, fields, variants, casts and static worker operands compose with them. No new keyword, trait search, lifetime syntax, runtime instruction, effect, capability or diagnostic code.
|
||||
- Frontend state: template environment, canonical instance cache/pending markers, argument obligations, depth/key/count budgets, stable names and resolved internal references. Verifier transfer state/runtime state: unchanged. Structural queries and finite layout traversal reuse ordinary types.
|
||||
- Interactions: nominal modules, nested structs/enums/arrays, casts, builtin channel type arguments, Copy aggregates, individual linear arguments, exclusive/shared borrows, effectful calls and structured tasks. No argument inference hides ownership or contract choices.
|
||||
- Repairability: explicit parameter/property/found fields and template source locations support direct repairs. Missing moves/effects and forbidden payloads keep existing codes. Readable display names accompany compact generated AIR names. Successful unused-template checking is explicitly limited, avoiding a false universal guarantee.
|
||||
- Existing AIR primitives suffice. Manual per-type duplication makes API contracts drift; runtime dictionaries/trait dispatch add trusted semantics; inference and overload search add ambiguity; arbitrary user properties need a separate contract. Generic source templates address this step without expanding those mechanisms.
|
||||
|
||||
Measurements and final branch validation are recorded below. Documentation growth is a cost, not evidence of Model Capability Compression; public general conformance/integration fixtures do not decide benchmark semantics and private held-out tasks were not inspected.
|
||||
|
||||
Measured with `tools/agent_bundle_tokens.py --source`, relative to STD-3 (`c96199e`):
|
||||
|
||||
| Group | cl100k | o200k | Qwen2.5 |
|
||||
|---|---:|---:|---:|
|
||||
| Quick Reference | 6,501 → 6,948 (+6.9%) | 6,522 → 6,972 (+6.9%) | 6,704 → 7,172 (+7.0%) |
|
||||
| Other source docs | 38,822 → 41,086 (+5.8%) | 38,940 → 41,212 (+5.8%) | 39,889 → 42,228 (+5.9%) |
|
||||
| Full source docs excluding AIR | 45,323 → 48,034 (+6.0%) | 45,462 → 48,184 (+6.0%) | 46,593 → 49,400 (+6.0%) |
|
||||
| On-demand library/std.md | 7,730 → 8,380 (+8.4%) | 7,766 → 8,417 (+8.4%) | 7,955 → 8,621 (+8.4%) |
|
||||
| AIR reference | 42,454 → 42,454 (+0.0%) | 42,602 → 42,602 (+0.0%) | 43,827 → 43,827 (+0.0%) |
|
||||
|
||||
The new on-demand language/generics.md is 1,324 / 1,329 / 1,371 tokens. AIR stays 160,797 bytes (48 sections from 19 files). Cumulative cl100k source growth from the pre-stdlib baseline is 33,981 → 48,034 (+41.3%); Quick Reference is 5,511 → 6,948 (+26.1%). The existing >20% owner-review requirement still applies. This RFC explains the cost: explicit instantiation/header/body rules, five structural queries and bounded deterministic specialization must be visible to an agent. Quick Reference exceeds the 4–6k target; future catalogs should remain on demand and the front door needs a separate consolidation review. No measured compression benefit is asserted.
|
||||
|
||||
## Branch validation
|
||||
|
||||
`zig build`, `zig build test`, `zig build conformance`, `zig build agent-reference`, the repository-wide `zig fmt --check` and `git diff --check` pass. Full conformance: 640 passed, 0 failed, 0 pending (61 added cases). Source coverage: 82/82 constructs, including six generic forms, with 155 run/accept and 225 rejected source fixtures. Generic worker/lend tests also pass 32 schedule seeds with stress quanta 1, 2 and 7 plus their default quantum 1,000.
|
||||
|
||||
`tests/hosted/source_generics.py` passes 20 CLI checks, `source_modules.py` passes 36 existing package checks, and hosted smoke passes file, stdin, scoped-access and real TCP checks. The generic CLI checks include canonical lower/reverify/run equivalence, explicit package loading with caller-defined nominal types, readable errors and imported-template error/trap provenance. Scheduler/conformance runs use explicit fuel rather than wall-clock cutoffs.
|
||||
@@ -0,0 +1,68 @@
|
||||
# RFC 0023: Whole-value linear aggregates
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-5, vertical source/AIR/verifier/interpreter phase; AIR format 0
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## 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<u64> }
|
||||
fn main(heap: cap<mem.alloc>) -> 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<array<T,N>> 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<File> 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.
|
||||
@@ -0,0 +1,63 @@
|
||||
# RFC 0024: Initialized linear buffers and safe vectors
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6a storage / STD-6b Vec; vertical Phase 6, additive AIR format 0
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation and invariant
|
||||
|
||||
Resolve Q-036 before promising Vec<File> or Vec<sender<Job>>. A uniquely owned buffer exposes exactly its contiguous initialized prefix. Every nested linear element is owned once; unused capacity holds no observable value. No holes, implicit destructor or hidden growth is introduced. Whole-value aggregates and Copy-only own.array cannot represent dynamic initialized storage and moving extraction.
|
||||
|
||||
## Decision
|
||||
|
||||
Spec 03 §26, spec 07a buffer contracts and source §17 define buffer<T>, exact-capacity allocation, explicit reserve, bounded push, LIFO pop, child prefix view and empty-only recoverable free. Growth charges the new allocation before releasing the old authority; failure preserves state. Full push returns the supplied value, nonempty free returns the original buffer. Ordinary linearity forces cleanup on every normal path without verifier length facts. Safe std.vec wrappers provide new/len/capacity/reserve/push/pop/free/get/replace. More collections remain separate work.
|
||||
|
||||
## Verifier and runtime rules
|
||||
|
||||
Whole availability and existing child-borrow/task-loan provenance suffice. buffer content must be complete, owning type graphs acyclic and Send/Share structural. Metadata-changing operations require exclusive access even on a dynamic no-op. Views expose only initialized values and use existing slice bounds/Copy access/exchange. The deterministic interpreter transfers complete values, preserves identity across tracing collection and accounts old/new allocation peaks. No new effect/capability/trap/diagnostic or synchronization policy is added.
|
||||
|
||||
## Generic transfer
|
||||
|
||||
A complete Copy binding inside a specialized generic body may be spelled move, retaining ordinary Copy availability. Linear specializations transfer once. Ordinary monomorphic move of Copy still rejects. This narrowly specified source rule lets one safe container implementation serve Copy and linear elements without overloads/type-case metaprogramming. It adds no AIR instruction or verifier ownership state.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
A valid program explicitly allocates Vec<own<u64>>, pushes with a mutable borrow, pops, own.takes the returned owner and frees the empty vector. Rejected examples leak a returned value, free/discard a nonempty vector, mutate/reserve while a view/task loan is live, duplicate an owner, copy a linear element or store borrowed/task-bound content. Checked AIR/source fixtures and a runnable example accompany implementation.
|
||||
|
||||
## Compatibility and scope
|
||||
|
||||
New type/opcodes belong to linear_buffers; baseline own/own_array/region operations retain semantics. New source cases extend previously rejected forms. Existing generic Copy code without move lowers identically; non-generic invalid Copy moves keep E7006. Q-034 from-returns, channel_transfer, guard/task gates and recursive ownership remain restricted. The owner adopted this implemented contract with the intermediate std merge (2026-10-07). Deque/maps/heaps are not completed by this increment.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
New concepts: a contiguous initialized prefix, explicit capacity/peak-growth charge, ownership returned on full/nonempty and generic complete-value transfer. New verifier semantic state: none; primitive prefix state is runtime internal, with existing borrows/availability. New source syntax forms: none; buffer wrapper/typed allocator/builtin borrow binding compose existing forms. New diagnostics/effects/capabilities/traps: none. Eight operation names and eight AIR opcodes (len/capacity share a metadata-read contract), safe Vec wrapper signatures and their failure payloads replace opaque container behavior. Existing Copy storage cannot express resource extraction or cleanup obligations. Measured bundle costs and validation are recorded below; no MCC benefit is claimed without measurement.
|
||||
|
||||
The initial interpreter stores only the initialized prefix in its traced host representation; user-visible capacity is charged independently. Its push copies the prefix internally (O(length)); this increment makes no native Vec performance claim. A future backend may reserve physical backing while preserving the exact authority/failure contract.
|
||||
|
||||
The checked source example in Quick Reference §14 is a complete valid allocate/push/pop/drain/free program. The following rejects E2101 even when capacity does not grow:
|
||||
|
||||
```aji
|
||||
fn bad(b: mut<buffer<u64>>, heap: cap<mem.alloc>) -> void effects [mem.alloc] {
|
||||
ref values = buffer.view(b);
|
||||
buffer.reserve(b, 0usize, heap) or trap;
|
||||
}
|
||||
```
|
||||
|
||||
Missing move rejects E7003; duplicated owners reject E2002; omitted failure payload cleanup rejects E3002; a get specialization with an owner rejects E7005. Every instruction's operand/result/continuation types, ownership and memory transfer, capability/effect and runtime behavior are normative in spec 07a. AIR/source fixtures also cover empty/full, nested buffers, allocation overflow, failure preservation, old/new authority release, file closing and sender cleanup, task loans, borrowed content and recursive owning types.
|
||||
|
||||
### Measured reference costs
|
||||
|
||||
Relative to STD-5/RFC 0023, measured with the repository tool (offline tokenizers):
|
||||
|
||||
| Bundle | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---:|---:|---:|
|
||||
| Quick Reference | 7,225 → 7,667 | 7,251 → 7,697 | 7,455 → 7,902 |
|
||||
| Other source docs | 42,364 → 44,717 | 42,496 → 44,850 | 43,548 → 45,932 |
|
||||
| Full source excluding AIR | 49,589 → 52,384 | 49,747 → 52,547 | 51,003 → 53,834 |
|
||||
| AIR reference in source bundle | 43,966 → 45,520 | 44,114 → 45,667 | 45,403 → 46,981 |
|
||||
|
||||
New on-demand language/buffers.md: 1,175 cl100k tokens. library/std.md: 9,432. AIR standalone: 168,336 → 175,736 bytes (+4.4%), 19 files / 50 sections. Source output has 15 source files plus the AIR file. Full source cl100k growth is +5.6% relative to STD-5 and +54.2% since the 33,981-token pre-stdlib baseline. Quick Reference remains above the 4–6k target; the new prefix/returned-ownership contracts are necessary for one verified generic resource container and cannot be expressed by existing Copy-only dynamic storage. This cumulative cost is explicitly presented for owner review, not claimed as compression. Front-door consolidation and empirical MCC evaluation remain separate work.
|
||||
|
||||
### Validation
|
||||
|
||||
The implementation checks unit and parser/serializer round-trip tests, full AIR/source conformance, forced collection and schedule stress, extended interpreter memory tests, hosted OS smoke, package/generic/linear/buffer CLI integration, formatting, source construct coverage and generated reference bundles. Dedicated buffer fixtures cover 56 cases including the Quick Reference example; exact final check counts are recorded in the commit description. No held-out corpus or former smoke-task semantic tuning is involved.
|
||||
@@ -0,0 +1,51 @@
|
||||
# RFC 0025: Safe owning deque
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6c deque increment, ordinary safe library source
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Decision and invariant
|
||||
|
||||
Spec 16 §2.11 defines one deque API using the existing initialized buffer and Option<T>. A ring has capacity initialized option slots, a head and a logical length. Exactly the occupied ring range contains some; all other slots contain none. This represents vacancy with complete values, preserving whole-value ownership without holes or new primitives. Representation fields remain ordinarily visible; manual construction/mutation must preserve the documented invariant.
|
||||
|
||||
Eleven functions cover construction, metadata, explicit reserve, both ends, moving pop, empty-only free, Copy get and complete replace. Push never grows. Full push/out-of-bounds replace return the input; nonempty free returns the whole queue. Allocation failure preserves physical slots and metadata. Successful growth charges old+new capacity, fills new none slots, rotates old slots using complete exchanges and resets head without changing order. Index calculations avoid head+offset overflow. No destructor closes user resources.
|
||||
|
||||
## Verifier and runtime rules
|
||||
|
||||
Existing complete aggregate/enum moves and value.swap preserve exactly one owner per element. Borrow scopes, task loans, Send/Share and Copy constraints apply without special cases. The library never returns a borrow. Only new/reserve require explicit mem.alloc effect/capability; vacancy slots include the Option tag in their charge. The deterministic interpreter executes ordinary AIR with existing budgets/fuel; no opcode/runtime/feature or synchronization change is needed. Existing E7003/E2002/E3002/E2101/E4101/E7005 diagnostics cover bad moves, leaks, aliases, task loans and constraints. Valid calls are trap-free except execution limits; malformed manually modified representations have no weakened verifier or safety rules. Existing source/AIR/API semantics remain compatible.
|
||||
|
||||
## Examples and validation
|
||||
|
||||
The runnable deque example pushes a front/back owner, pops in FIFO order, explicitly consumes each owner and frees the empty queue. Rejected examples omit a move/cleanup, duplicate ownership, call Copy get with an owner or retain a borrow/task loan across mutation. Fixtures independently model ring order, wrapped growth, full/empty/zero capacity, repeated reuse, success/error budget release, files and channel endpoints. New/reserve charge Option<T> slots; tests must not assume Vec's T-only accounting. Ordinary unit/conformance, collection/schedule stress for deque cases, CLI canonical lowering/manifest/hosted checks and reference bundle checks accompany the implementation.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
New language concepts, syntax, instructions, verifier state and diagnostics: none. Library concepts: two ends and the documented ring invariant. The API reuses Vec's returned-ownership naming, effects and explicit specialization; no overload/trait/reflection or implicit allocation/destruction is introduced. Existing primitives suffice. Full API/contracts live in the on-demand library page rather than another long Quick Reference tutorial. Measured Quick/Source/AIR bundle costs and final validation follow; no empirical MCC benefit is claimed. This increment completes STD-6c deque; maps/sets/heaps remain STD-6d and Std 0.1 is not complete.
|
||||
|
||||
The checked [owning example](../../examples/std/deque.aji) uses only safe ordinary source. This call rejects E7003 because a named owner must move:
|
||||
|
||||
```aji
|
||||
fn bad(q: mut<std.deque.Deque<own<u64>>>, item: own<u64>) -> void effects [] {
|
||||
let result = std.deque.push_back::<own<u64>>(q, item);
|
||||
trap;
|
||||
}
|
||||
```
|
||||
|
||||
### Reference bundle measurement
|
||||
|
||||
Relative to STD-6a/b, with the repository's three tokenizers:
|
||||
|
||||
| Bundle | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---:|---:|---:|
|
||||
| Quick Reference | 7,667 → 7,747 | 7,697 → 7,778 | 7,902 → 7,982 |
|
||||
| Other source docs | 44,717 → 46,246 | 44,850 → 46,376 | 45,932 → 47,467 |
|
||||
| Full source excluding AIR | 52,384 → 53,993 | 52,547 → 54,154 | 53,834 → 55,449 |
|
||||
| AIR reference in source bundle | 45,520 → 45,520 | 45,667 → 45,667 | 46,981 → 46,981 |
|
||||
|
||||
The library page is 10,961 cl100k tokens; standalone AIR remains 175,736 bytes / 19 files / 50 sections. Full source growth is +3.1% relative to buffer/Vec, +58.9% since the 33,981-token pre-stdlib baseline. Quick Reference adds one short paragraph (+1.0%) rather than a new tutorial; the full ring invariant/API/accounting lives on demand. Cumulative growth and the existing front-door target overrun remain for owner review. This cost is justified by a resource-safe reusable ring using existing verifier-visible operations; documentation growth itself proves no compression benefit. No held-out corpus or task-specific semantic change was used.
|
||||
|
||||
### Checked implementation
|
||||
|
||||
Eleven generic functions and five result enums use only existing safe source/AIR. The interpreter/backend/verifier are unchanged; the compiler embeds one extra source module. Independent Python deque vectors exercise 128 operations over four seeds with every logical element checked; growth covers all 71 small capacity/head/length combinations including empty/full/wrapped queues. Owners, files, senders, shared workers, failure ownership, cross-authority refunds and tag-inclusive quota checks pass. Invalid caller metadata cannot make free normally discard a nested owner. Borrow/task/Copy/move/leak rejections have stable existing codes.
|
||||
|
||||
Validation passed full unit/conformance, focused per-instruction collection and 12-seed schedule stress (four quanta), canonical source/AIR and package/hosted CLI checks, source coverage, independent oracle checks, Zig formatting and reference bundle generation. Final counts are recorded in the commit. No native performance claim is made; construction/growth retains the interpreter's prefix-copy overhead.
|
||||
@@ -0,0 +1,40 @@
|
||||
# RFC 0026: Non-cryptographic hash foundation
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6d.1 pure library; next map contract remains a design proposal
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Decision
|
||||
|
||||
Spec 16 §2.12 registers std.hash and four monomorphic safe functions: fresh and extend for FNV-1a 64 and Castagnoli CRC-32C. Integer state is explicit; CRC continuation takes the finalized checksum, not an internal inverted register. This avoids a state/context/finalize API while supporting chunked I/O. Every input byte participates. Empty chunks are identities, arbitrary numeric continuation states are valid, and serialized integer order is explicit. Constants and public vectors are checked against [RFC 9923](https://www.rfc-editor.org/rfc/rfc9923.html#section-2) and [RFC 3720 B.4](https://www.rfc-editor.org/rfc/rfc3720.html#appendix-B.4). Neither algorithm provides authentication or adversarial collision resistance.
|
||||
|
||||
FNV implements XOR plus explicit wrapping multiplication. CRC uses eight reflected bit steps per byte, deliberately avoiding table storage/runtime magic in this initial implementation. Both cost O(bytes) work and O(1) state; no native throughput claim. Larger/specialized hashes or accelerated CRC would require separate evidence while retaining this recurrence.
|
||||
|
||||
## Borrow and compatibility checklist
|
||||
|
||||
Invariant: input remains unchanged, no ownership transfers and no borrow escapes. Existing immutable slice bounds/exclusion verify the source; no verifier state, runtime/GC rule, effect, capability, diagnostic, opcode or feature is added. Safe source lowers to existing AIR and deterministic/hosted results agree. Only interpreter fuel/environment limits can interrupt valid calls. [Valid example](../../examples/std/hash.aji) hashes chunks and explicitly serializes the CRC. Holding a mutable element while hashing its parent rejects E2101; wrong argument types/imports/monomorphic specialization use existing E7005/E7002/E7006. Existing source/AIR/API meanings remain unchanged.
|
||||
|
||||
## Map follow-through
|
||||
|
||||
The [owning map proposal](../design/hash-map.md) fixes returned-value ownership, capacity, tombstones, exact collision handling and failure-preserving explicit rehash. No map API is registered in this increment. It proposes U64Map<V> first, since current source type parameters cannot provide user hashing/equality operations. A checked storage prerequisite demonstrates that a struct with Copy key/state fields and Option<V> supports observational metadata access for owning V; a linear key/value enum would not. Both tags are explicitly charged. General HashMap<K,V> remains Q-037 and the STD-6d collection gate stays open. A byte hash must not be substituted for original key equality; no map-specific trait/compiler magic is introduced.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
New language/verifier/runtime/syntax/diagnostic concepts: none. Four functions and one numeric continuation convention; no context lifetime, implicit seed, method, overload, trait or reflection. Ordinary source operations suffice. Full recurrence and usage stay on demand; Quick Reference adds only discovery guidance. The future map draft stays outside normative source/AIR bundles. Bundle growth is measured below; no empirical Model Capability Compression benefit or task-specific semantic change is claimed. No private held-out corpus was accessed.
|
||||
|
||||
## Validation
|
||||
|
||||
Conformance covers empty/high-bit/all single-byte inputs, boundary lengths, published numeric vectors, every split of representative inputs, byte-at-a-time continuation and arbitrary state. An independent Python oracle uses arbitrary-precision FNV and forward-polynomial CRC with reflected input/output, structurally distinct from the library's right-shift CRC. It validates 286 inputs / 1,144 fresh/continuation results. Immutable sub-slice bounds/reborrow, shared workers, alias/type/import rejections, canonical AIR, local-name/import-order independence, explicit packages and hosted/isolated execution are checked. Unit tests and full conformance pass; the final suite includes the checked owning storage prerequisite. All eleven hash fixtures pass with collection before every instruction and 12 schedule seeds over four quanta; the owning slot prerequisite also passes per-instruction collection. Source/package/hosted CLI checks pass (84), source coverage is 95/95, and formatting/reference generation pass. Final conformance count is recorded in the commit. These checks add no new verifier or runtime rule.
|
||||
|
||||
## Reference bundle measurement
|
||||
|
||||
Relative to RFC 0025 Deque, using the three repository tokenizers:
|
||||
|
||||
| Bundle | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---:|---:|---:|
|
||||
| Quick Reference | 7,747 → 7,806 | 7,778 → 7,837 | 7,982 → 8,043 |
|
||||
| Other source docs | 46,246 → 47,475 | 46,376 → 47,616 | 47,467 → 48,802 |
|
||||
| Full source excluding AIR | 53,993 → 55,281 | 54,154 → 55,453 | 55,449 → 56,845 |
|
||||
| AIR reference in source bundle | 45,520 → 45,520 | 45,667 → 45,667 | 46,981 → 46,981 |
|
||||
|
||||
Full source growth is +2.4% relative to Deque and +62.7% since the 33,981-token pre-stdlib baseline. Quick Reference adds discovery guidance (+0.8%); library/std.md is 12,190 cl100k tokens. Standalone AIR stays 175,736 bytes / 19 files / 50 sections. The map draft is excluded from both bundles. Cumulative growth and the existing Quick Reference target overrun remain for owner review; the cost is justified by reusable exact byte/checksum contracts with no language/verifier-state expansion. Documentation size is not evidence of compression benefit.
|
||||
@@ -0,0 +1,83 @@
|
||||
# RFC 0027: Explicit built-in error values
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6d.2 prerequisite; vertical Phase 6, additive AIR format 0
|
||||
Language version: 0.1
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation
|
||||
|
||||
A library must reject overflowing allocation sizes before allocation. Built-in errors could previously only arrive from runtime operations. Artificially allocating to obtain an error would obscure authority and failure behavior. Explicit construction makes pure validation implementable and preserves a single error vocabulary.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
An error value is Copy data. Creating, copying, returning or matching it never confers authority, consumes a resource or proves that an operation happened. Runtime operations keep their existing outcome contracts.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
Spec 05 §14 specifies pure construction of every frozen registered variant of alloc_error, cap_error and io_error. Spec 07a and the AIR grammar add `error.const B.variant`. Spec 15 §6 extends the existing source variant expression to those built-in families. The registry adds `error_values`, depending on the full feature closure defining all three families.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
Validate static family/tag and result uses; define one available Copy value. No new abstract state, ownership, alias, resource or concurrency rule. Validation is constant time over the fixed variant registry.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
Bind a built-in family/tag deterministically, consuming ordinary fuel, without program allocation, I/O or capability acquisition. Error data already has a runtime representation. Real allocation failure remains separately specified.
|
||||
|
||||
## AIR changes
|
||||
|
||||
`error.const` takes a registered error family and variant as static operands, no SSA inputs or payloads, and has one result of that family's type. It has no ownership, borrow, memory or concurrency effects, requires no effects/capabilities and has no instruction-specific traps. The feature declaration is mandatory. This is not syntax sugar: no existing pure instruction constructs a built-in error. `enum.make` retains its declared-enum contract.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
fn overflow() -> alloc_error effects [] {
|
||||
return alloc_error::budget_exceeded;
|
||||
}
|
||||
```
|
||||
|
||||
## Rejected example
|
||||
|
||||
```aji
|
||||
fn forge() -> cap<mem.alloc> effects [] {
|
||||
return alloc_error::budget_exceeded;
|
||||
}
|
||||
```
|
||||
|
||||
Expected diagnostic: E7005; equivalent AIR is E1001. Missing feature is E0006, unknown AIR family/tag E0004, payload syntax E0001. Unknown source variant is E7002, payload arity E7005. No new diagnostic codes.
|
||||
|
||||
## Spec integration
|
||||
|
||||
Spec 05 §14, 07 §8.9, 07a Values, 08 §3, 15 §6; reference AIR grammar and feature registry; both agent bundle manifests and Quick Reference. Q-038 is resolved by these contracts.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
Additive feature in format 0. Existing type/variant meanings, enum.make, fallible operations and authority rules remain frozen. Older implementations reject modules declaring error_values through normal feature negotiation. No migration for existing source or AIR.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
One coherent semantic block: constructing ordinary error data. One feature and AIR instruction, no new source syntax form, diagnostics, verifier state or ownership concepts. Existing Enum::variant syntax and exhaustive matching suffice. Explicit preflight failures reduce the need for ad hoc error enums or artificial runtime calls. No empirical MCC benefit is claimed. Dependencies define the error data vocabulary, not ambient authority. Measured Quick Reference, source and AIR bundle growth and validation are recorded below when checks finish.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Changing enum.make would alter frozen baseline semantics. A new library-specific overflow enum would force different allocation error handling. Harvesting runtime errors through fake allocations changes failure/authority behavior. A payload-free constant is the smallest explicit primitive covering existing error families.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
None for this feature. General map key hashing/equality remains Q-037.
|
||||
|
||||
## Validation and measured documentation budget
|
||||
|
||||
`zig build`, `zig build test` and formatting pass. All 32 error-value conformance cases pass normally and with collection before every instruction; all 17 registered tags are exercised directly in AIR and through exhaustive source matches. `tests/hosted/source_errors.py` passes 26 CLI checks, including canonical lowering, matching source/AIR run records, hosted execution and zero-allocation/zero-entry-authority audit reports. Source coverage is 96/96. The full working-tree regression also includes the developing map consumer.
|
||||
|
||||
Relative to RFC 0026, excluding the uncommitted map library contract from the generated source library page:
|
||||
|
||||
| Group | cl100k | o200k | Qwen2.5 |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 7,806 → 7,863 | 7,837 → 7,894 | 8,043 → 8,102 |
|
||||
| Other source docs | 47,475 → 48,061 | 47,616 → 48,204 | 48,802 → 49,419 |
|
||||
| Full source excluding AIR | 55,281 → 55,924 | 55,453 → 56,098 | 56,845 → 57,521 |
|
||||
| AIR inside source bundle | 45,520 → 46,300 | 45,667 → 46,451 | 46,981 → 47,800 |
|
||||
|
||||
Standalone AIR grows from 175,736 to 179,282 bytes, 19 files / 51 sections. Incremental full source growth is 1.2%; cumulative growth since the pre-stdlib cl100k baseline 33,981 is 64.6%, above the existing review line. The cost is justified by a necessary pure validation primitive with no new source form, authority or ownership concepts. Detailed contracts remain on demand; documentation growth is not evidence of MCC improvement.
|
||||
@@ -0,0 +1,73 @@
|
||||
# RFC 0028: Safe owning numeric-key map
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6d.2, safe standard source; general-key gate remains Q-037
|
||||
Language version: 0.1
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation
|
||||
|
||||
Numeric identifiers need bounded lookup and storage without rebuilding ownership, quota and collision handling. std.hash supplies pure hashing; initialized buffers and whole-value exchange supply safe storage. Pure error construction (RFC 0027) permits size validation before allocation. No map-specific language feature or trusted runtime is needed.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
U64Map<V> has 2N initialized slots for logical capacity N. Copy key/state fields permit observation with owning V. Each occupied slot holds exactly one some(V); vacancies hold none. Keys are unique and reachable through the probe chain, occupied count equals length≤N. Linear owners/resources are always transferred or explicitly consumed. Both state and option tags are charged; the owning-handle slot is 18 bytes under air64.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
Spec 16 §2.13 registers std.map and its ten functions. It defines exact u64 equality, FNV-1a over eight little-endian key bytes, bounded linear probing, tombstones, ownership of inserted/replaced/full/removed/popped/not_empty results, complete failure preservation and explicit growth/cleanup. Reference/std.md publishes the API. General keys remain Q-037; this specialization does not satisfy HashMap<Key, Own<Value>>.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new verifier state or privileges. Ordinary generic constraints, field borrows, whole Option/Slot exchange, move/unpack, task loans and Copy/Send/Share apply. Only get requires V: Copy; contains needs no value copy. Library functions maintain the invariant; direct representation mutation is governed by spec 16. Existing diagnostic codes cover leaks, invalid copies/moves/aliases, task loans and missing effects.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
Existing buffer/allocation semantics and deterministic fuel apply. New/reserve explicitly require mem.alloc authority/effect; insert never grows. Growth allocates and initializes the whole new table before mutation. Returned failure preserves all old slots, metadata, key/value contents and pop order. Peak quota includes both tables and user-owned allocations. Refund uses the original table's authority, even when another funds growth. Successful transfer uses old physical-index order and clears tombstones. Pop uses first occupied physical slot. No hidden resource close or destructor exists; corrupted empty metadata cannot cause normal destruction of an owner.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None. Lowered safe library source uses existing instructions, including error.const from the separately registered error_values prerequisite. Source integer-pattern canonicalization was repaired separately; no existing instruction semantics change.
|
||||
|
||||
## Valid example
|
||||
|
||||
`examples/std/map.aji` creates a map of own<u64>, inserts a moved owner under key 7, removes and consumes it, and frees the drained map, returning 42. Tests also transfer files, sender endpoints and exclusive task loans.
|
||||
|
||||
## Rejected example
|
||||
|
||||
`tests/conformance/source/map/get_owner.aji` attempts copying lookup for own<u64> (E7005). Other tests reject missing moves, discarded replaced/full/pop/not_empty owners, mutation during borrows/task loans, shared file-valued maps and growth without its allocation effect.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new codes. E7003/E7005, E2002/E3002, E2101, E4101, E4002 and E3101 retain their existing meaning. Broken caller representation may trap; valid library operations do not trap except execution limits. Recoverable failures are explicit returned data.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
New compiler-pinned source module only, no map-specific AIR feature. Existing std and AIR API meanings remain unchanged. Maps do not implicitly allocate, compact, iterate or expose escaping borrows. General HashMap/HashSet, BinaryHeap and the remaining Std 0.1 gates remain open.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
Library concepts: bounded exact-key map and returned-value ownership, reusing Vec/Deque result names and cleanup. Ten canonical operations, no aliases, overloads, traits, reflection, callbacks or new source syntax. The slot's metadata stays Copy while values may be linear; there is no new verifier state or repair diagnostic. Existing primitives suffice after the separately measured error_values prerequisite. Full contracts remain in the on-demand library page; no long Quick Reference tutorial is added. Measurements and final checks follow below; no MCC improvement is inferred from fixtures or documentation size.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
A linear entry enum prevents read-only metadata observation with owning V. Digest equality would conflate colliding original keys. Automatic growth hides allocation/authority. Compacting on deletion changes pop order and increases mutation. Generic key hashing/equality needs a separate source contract, rather than map-specific compiler magic.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-037: general key hashing and equality. Numeric U64Map is explicitly a specialization.
|
||||
|
||||
## Validation and measured documentation budget
|
||||
|
||||
`zig build`, `zig build test`, formatting and source coverage pass (98/98). All 30 map conformance cases pass with collection before every instruction; concurrent fixtures additionally use 12 schedule seeds under quanta 1, 2, 7 and their declared quantum. The independent Python dictionary oracle verifies 128 mixed operations across Copy and owning traces without modelling the hash/probe implementation. Source/package/hosted CLI checks pass (76), including exact source/AIR records, canonical lowering, import order and absence of trusted operations. Full conformance passes: 863 cases, 0 failed, 0 pending.
|
||||
|
||||
Relative to the error_values prerequisite (the source-doc difference also includes the separate integer-pattern clarification):
|
||||
|
||||
| Group | cl100k | o200k | Qwen2.5 |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 7,863 → 7,863 | 7,894 → 7,894 | 8,102 → 8,102 |
|
||||
| Other source docs | 48,061 → 50,079 | 48,204 → 50,223 | 49,419 → 51,509 |
|
||||
| Full source excluding AIR | 55,924 → 57,942 | 56,098 → 58,117 | 57,521 → 59,611 |
|
||||
| Library page | 12,190 → 14,167 | 12,239 → 14,216 | 12,559 → 14,604 |
|
||||
|
||||
AIR remains 179,282 bytes / 19 files / 51 sections (source-bundle copy 46,300 / 46,451 / 47,800 tokens). Full source grows 3.6% incrementally and 70.5% cumulatively from the pre-stdlib cl100k baseline 33,981. The cumulative cost is above the existing review line: explicit ownership, failure preservation and peak accounting require a reviewable contract. No Quick Reference catalog, new source form or map-specific language semantics is added; the API remains on demand. This cost is documented for owner review and is not evidence of MCC improvement.
|
||||
@@ -0,0 +1,74 @@
|
||||
# RFC 0029: Explicit static function parameters
|
||||
|
||||
Status: Implemented
|
||||
Scope: vertical Phase 6 source specialization prerequisite for general collections
|
||||
Language version: 0.1
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation
|
||||
|
||||
General maps/sets, ordered heaps and algorithms need user operations without map-specific compiler logic. Copy/Send/Share properties supply no hash/equality/order. Static named functions are the smallest general facility reusing existing AIR calls and verification. They preserve explicit authority, effects and ownership.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
A selected source function has exactly the declared parameter/return types and effect set. Selection grants no authority. It is part of nominal instance identity and has no runtime representation or captured state. All linear transfers and borrows are checked by ordinary AIR verification.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
Spec 15 §18 and the source grammar define callable contracts in generic declarations and explicit `fn path` arguments. Existing type-only generic syntax/meaning remains unchanged. Declaration, signature, storage, expression and worker rules are integrated in the same phase. Q-039 records the contract; general collections remain Q-037 until implemented.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new AIR verifier state or transfer function. Specialization checks exact callable signatures/effect sets and emits ordinary named call/worker operands. Existing ownership, loan, effects, Send/Share, capability and bounded layout verification decides whether the resulting program is valid.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
No new runtime state, instruction, allocation, capability, dispatch or destructor. Existing deterministic call/task semantics and fuel apply. Selected operation bodies remain visible AIR.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None; ordinary static call/task operands suffice. Positive AIR equivalents and negative ordinary effect/ownership examples demonstrate the existing boundary. No existing opcode meaning changes and no new instruction is introduced as sugar.
|
||||
|
||||
## Valid example
|
||||
|
||||
`apply<T, F: fn(T) -> T effects []>` can call F with complete transfer; `apply::<u64, fn identity>` selects a named pure function. Borrowed comparators, owning transforms, explicit effectful capability operations and task workers compose with the same mechanism.
|
||||
|
||||
## Rejected example
|
||||
|
||||
A `fn(ref<T>) -> u64 effects []` parameter rejects a mem.alloc function, wrong return type or mut<T> parameter with E7005. Selected functions cannot be stored/returned as values (E7006), forged from capabilities or resolved through unimported modules (E7002). Ordinary missing effects, invalid moves/loans and resource leaks remain rejected after substitution.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new codes. E7001 syntax, E7002 inaccessible names, E7005 argument/signature/effect mismatch, E7006 forbidden use/limits; existing AIR codes apply after lowering. Diagnostics retain caller argument and template body provenance. Callable mismatch records include the parameter, selected function and expected/found contracts.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
Additive explicit source syntax. AIR format 0 and all registered feature meanings remain unchanged. Existing type-only generics, instance identities, capabilities and effect contracts retain meaning. No borrowed returns, methods, traits, overload search, captures or argument inference are added.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
One concept: a compile-time named function with an exact contract. Two composed source forms: callable generic declaration and explicit fn argument. No runtime or verifier state, diagnostic code or AIR feature. Frontend state adds callable contracts to the existing bounded environment/cache, with selected function identity in type/function keys. Exact effects avoid variance and effect shims; normal explicit arguments/moves make ownership repairable. Existing AIR primitives suffice, while manual per-key algorithm duplication cannot express a reusable general source container. The facility also serves ordering and transforms, beyond maps. The measured source growth is recorded below; the AIR bundle is unchanged. No empirical MCC benefit is claimed.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Numeric-only wrappers do not meet the general collection gate. Hash-only identity is incorrect under collisions. Runtime function pointers/closures, trait dictionaries, reflection and type-name conventions require more semantics or hide operation selection. Implicit structural hashing fixes one policy and leaves user ordering/equality unresolved. Exact static contracts use existing calls and public effect declarations.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-037 remains open for the complete generic map/set library contract. A dense initialized entry buffer plus Copy probe-index metadata permits borrowed arbitrary owning keys without default keys or borrowed enum payloads; that storage design will be specified separately.
|
||||
|
||||
## Branch validation
|
||||
|
||||
The complete regression corpus passes 912 tests; the two subsequently added recursive/cyclic-contract cases pass in the focused 51-case corpus. All 51 static-function/source/AIR/Quick Reference cases also pass with collection before every instruction and 12 schedule seeds under stress quanta 1, 2, 7 and the test quantum. Unit tests, Quick Reference checking, formatting, reference-bundle generation and source coverage pass. CLI integration covers 25 source/AIR/package/hosted/report/explore/diagnostic checks; existing generic (20) and numeric-map (76) CLI checks pass. Type-argument traversal for built-in allocation/channel calls remains covered by the existing container corpus. No wall-clock run limit is used.
|
||||
|
||||
## Documentation budget
|
||||
|
||||
Relative to RFC 0028 (all counts exclude generated AIR from the full source group):
|
||||
|
||||
| Bundle group | cl100k_base before → after | o200k_base before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 7,863 → 8,051 | 7,894 → 8,082 | 8,102 → 8,300 |
|
||||
| Other source docs | 50,079 → 51,002 | 50,223 → 51,150 | 51,509 → 52,468 |
|
||||
| Full source | 57,942 → 59,053 | 58,117 → 59,232 | 59,611 → 60,768 |
|
||||
|
||||
cl100k growth is +2.4% / +1.8% / +1.9%, respectively. The on-demand generics page is 2,194 cl100k tokens. AIR remains 179,282 bytes / 19 files / 51 sections and 46,300 cl100k tokens in the source bundle. No AIR normative material is added to bundle.txt because ordinary instructions retain their contracts. Cumulative source growth from the pre-stdlib 33,981-token baseline is +73.8%; the rationale is a general operation-selection mechanism needed for arbitrary collection keys and ordering, rather than per-container compiler rules. The Quick Reference remains above its 4–6k target; consolidation/selective reading is separate work. Documentation/fixtures alone are not evidence of an empirical MCC improvement.
|
||||
@@ -0,0 +1,57 @@
|
||||
# RFC 0030: Safe owning general-key hash map
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6d.4, ordinary safe library source after RFC 0029
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation
|
||||
|
||||
Arbitrary keys need exact equality and explicit hash policy. Numeric-key U64Map cannot represent bytes/structs/owners by digest alone. Static functions supply reusable typed operations without container-specific language rules.
|
||||
|
||||
## Invariant and normative changes
|
||||
|
||||
Spec 16 §2.14 defines std.hashmap.HashMap<K,V,H,E>, dense initialized complete entries and Copy probe metadata. Every live entry has one reachable occupied bucket; cached hashes and equality agree. Keys and values may both own resources, with no vacancy key/default allocation. The registry/reference/API changes land together.
|
||||
|
||||
## Verifier rule
|
||||
|
||||
No new transfer function. Complete buffer transfer/pop/exchange, borrowed fields, exact callable contracts, normal effects/capabilities, Copy/Send/Share and ownership verification apply. Representation/hash-law preconditions are explicit, as for existing containers. No manual unsafe implementation is allowed.
|
||||
|
||||
## Runtime and deterministic behavior
|
||||
|
||||
Ordinary AIR. Probes are bounded; replacement/full/removal/free return complete owners. Allocation failure rolls back temporary empty storage, preserving old buffers/metadata/pop order. Explicit peak charges include both layouts and separately owned payloads. Removal swaps the last dense entry into a hole and repairs Copy indices. Rehash uses cached hashes after allocation succeeds; no recoverable failure follows the first old-buffer mutation. Normal profiles agree; fuel/callback traps are abnormal outcomes.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
A struct key containing an owner and a Copy identity field supplies pure ref-key hash/equality functions; insert transfers it with an owned value, removal/pop returns both for explicit consumption. Copy-value lookup does not need Copy keys. Missing moves, leaked full/replacement/pop/nonempty-free results, illegal aliases/loans, Copy lookup of owning V and sharing non-Share contents reject through existing codes. Mismatched static policy identities reject E7005.
|
||||
|
||||
## Diagnostics / compatibility / AIR
|
||||
|
||||
No new diagnostic, opcode, AIR feature or runtime boundary. Existing E7003/E2002/E3002/E2101/E4101/E7005/E4002 and ordinary call/effect checks apply. The new module is additive; std.map.U64Map and every existing API retain meaning. No implicit growth, destructor, retained borrow or authority is introduced. Spec 15 §17 clarifies the existing distinction between a Copy value bound in frame storage and internal storage/scope/guard/shield handles; ordinary Copy loading is unchanged.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
No new language concept, syntax or verifier/runtime state beyond already specified static operations. Ten functions match the numeric-map operation set; four explicit arguments name type/hash/equality policies, and linear replacement returns both old resources. Algebraic hash/equality and visible dense/index invariants add documentation obligations, which are kept on demand and measured below. Existing safe primitives suffice without borrowing enum payloads or partial moves. No MCC or throughput benefit is claimed from fixtures.
|
||||
|
||||
## Alternatives
|
||||
|
||||
Digest identity loses collisions. Per-key duplication loses general reuse. A vacant Option<Entry> table cannot observe owning keys through existing Copy enum switching. Two dense/probe buffers need no default key, borrowed enum feature, private representation privilege or unsafe pointer.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Independent dictionary/model traces, exact collisions, tombstones/wrap, full replacement, moving-hole repair, zero capacity, complete owners/files/senders, allocation rollback/peak/refunds, immutable/exclusive/task loans, nominal policies, invalid representation safety, source/AIR/profile/package consistency and GC/schedule stress are required before completion. HashSet and BinaryHeap remain separate increments.
|
||||
|
||||
## Documentation budget
|
||||
|
||||
Relative to the static-operation prerequisite (RFC 0029), all full-source counts exclude AIR:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 8,051 → 8,124 | 8,082 → 8,156 | 8,300 → 8,374 |
|
||||
| Other source | 51,002 → 53,363 | 51,150 → 53,537 | 52,468 → 54,845 |
|
||||
| Full source | 59,053 → 61,487 | 59,232 → 61,693 | 60,768 → 63,219 |
|
||||
|
||||
cl100k growth is +0.9% / +4.6% / +4.1%. library/std.md is 16,504 cl100k tokens. AIR remains 179,282 bytes / 19 files / 51 sections (46,300 cl100k in the source bundle). No normative AIR material is needed. Full source growth from the pre-stdlib 33,981-token baseline is +80.9%; the justification is a general owning-key map meeting the original HashMap<Key, Own<Value>> gate, exact failure/resource contracts and a separate numeric API retained for compatibility. The Quick Reference has one compact paragraph; policies/invariants/accounting stay on demand. Selective reference reading/consolidation remains separate work; no empirical MCC benefit is claimed.
|
||||
|
||||
## Validation result
|
||||
|
||||
The complete conformance corpus passes 947 cases, including 33 general-map cases. Unit tests, Quick Reference checking, formatting, reference-bundle generation, source coverage (104/104 constructs) and 55 CLI/source/AIR/profile/package/provenance checks pass. Independent Python dict/dense-order oracles cover 192 public operations across Copy and owning-value traces, checking every key and complete returned owners. Tests cover owning byte-buffer keys, owning key/value replacement/full returns, files, sender task transfer, shared lookups, exact allocation peaks, both reserve-failure phases, new-allocation rollback, cross-authority refunds and invalid-metadata nonempty free. The focused collection-before-every-step/scheduler-stress process has completed: all 33 general-map cases pass, including both independent owning/Copy model traces; scheduled fixtures run 12 seeds under quanta 1, 2, 7 and their own quantum. The process used no wall-clock termination. Subsequent set/heap regression passes the full 1007-case corpus. General key-policy/storage validation is complete on this branch (Q-037); The owner adopted this implemented contract with the intermediate std merge (2026-10-07).
|
||||
@@ -0,0 +1,48 @@
|
||||
# RFC 0031: Safe owning general-key hash set
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6d.5, safe library source after RFCs 0029/0030
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation and normative changes
|
||||
|
||||
General maps provide exact explicit hash/equality and complete owning keys. Spec 16 §2.15 adds std.hashset without set-specific language machinery. Duplicate insertion returns the original input and retains the existing representative, exposing resource ownership without hidden destructors.
|
||||
|
||||
## Preserved invariant
|
||||
|
||||
The underlying general map's dense/probe invariant holds with bool values true. Every live K has one owned occurrence; equal keys are unique. Keys/hash/equality remain stable. Duplicate/full/failing-growth paths preserve stored entries/buckets and return input ownership as specified.
|
||||
|
||||
## Verifier rule
|
||||
|
||||
No new transfer function: complete struct/enum/buffer moves, exact static callable contracts, borrow/task-loan exclusion, bounds, effects, Copy/Send/Share and explicit consumption apply. All code is ordinary safe Aji.
|
||||
|
||||
## Runtime and deterministic behavior
|
||||
|
||||
Nine wrappers use existing map AIR calls, without runtime dispatch, allocation beyond explicit new/reserve or cleanup. Normal failure preserves all old state; peak charges/refunds and deterministic pop order follow the map. User callback traps/fuel are abnormal outcomes.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
An owning byte/struct key is moved into insert. Duplicate/full returns the original key for explicit consumption. A successful remove/pop returns the stored key; nonempty free returns the set. Missing moves, ignored owning results, bad aliases/task loans, invalid effect/policy bindings and sharing non-Share keys reject through existing diagnostics.
|
||||
|
||||
The [owning example](../../examples/std/hashset.aji) allocates one slot and one payload with a 67-byte grant, inserts the complete key, pops/unpacks/takes it and frees the empty set. [Owning duplicates](../../tests/conformance/source/hashset/owner.aji) return the incoming payload and retain the original. [A leaked duplicate](../../tests/conformance/source/hashset/present_leak.aji) rejects with E3002; [missing move](../../tests/conformance/source/hashset/missing_move.aji) rejects with E7003; [a file key shared with a worker](../../tests/conformance/source/hashset/not_share.aji) rejects with E4002.
|
||||
|
||||
## Diagnostics / compatibility / AIR
|
||||
|
||||
No new code, opcode, AIR feature, source syntax or verifier/runtime state. Existing source/type/availability/alias/effect/Send/Share diagnostics apply. Registry addition is additive and imports grant no authority; old APIs retain meaning.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
No additional language concept beyond explicit static policy arguments. Nine operations omit value lookup and replacement alternatives; duplicate handling clearly distinguishes stored and returned owner. An extra membership check reuses the map and its stable callback laws, avoiding a new primitive or overwrite/destructor rule. Full API/representation/accounting stays on demand; measured bundle growth and executable validation are recorded below. No empirical MCC result is claimed.
|
||||
|
||||
No new syntax form, diagnostic or verifier state. Relative to RFC 0030, cl100k Quick Reference grows 8,124 → 8,201 (+0.9%); other source documentation 53,363 → 54,798 (+2.7%); full source excluding AIR 61,487 → 62,999 (+2.5%). The on-demand std reference is 17,939 tokens. Corresponding o200k counts are 8,234 / 54,977 / 63,211; qwen2.5 counts are 8,451 / 56,295 / 64,746. AIR remains 179,282 bytes, 19 files and 51 sections; its source-bundle copy remains 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k source growth from the 33,981-token pre-std baseline is +85.4%. The increase buys explicit duplicate ownership, nine signatures and representation/failure/quota laws; mandatory Quick Reference stays at one short paragraph. No language expansion or measured compression benefit is claimed.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Copy/owning/byte keys, duplicate/full preservation, collisions, pop/remove order, zero capacity, growth failure/refunds/peak, rejected leaks/moves/loans/policy/effects, independent Python set traces, source/AIR/package/profile checks, GC/scheduler stress and documentation budgets are required. BinaryHeap and I/O/path remain following increments.
|
||||
|
||||
|
||||
## Validation result
|
||||
|
||||
Full conformance passes 973/973, including 26 set fixtures. All runtime set fixtures pass collection before every instruction, including both independent model traces; shared lookup runs 12 schedule seeds under quanta 1, 2, 7 and its own quantum. Existing compilation checks reject owner leaks, missing moves, bad borrows/task loans, wrong nominal policies, missing effects and non-Share file keys. Copy and owning key traces use independent Python set/representative/dense-order oracles for 80 operations, checking every domain key after every operation. Duplicate input/stored representative and complete probe metadata, owning byte keys, files, full/remove/pop/nonempty-free ownership, zero/overflow, both failure phases, rollback, exact peaks and cross-authority refunds are covered.
|
||||
|
||||
Unit/Quick Reference checks, formatting, hosted smoke, agent-reference generation, source coverage (106/106 constructs) and 53 CLI checks pass. CLI checks compare source/AIR results, hosted execution, explicit package policies, reordered imports, report/audit and callback provenance. AIR and source syntax remain unchanged. The separate general-map full GC/stress process subsequently completed with all 33 cases passing, without wall-clock termination. BinaryHeap and I/O/path remain subsequent work.
|
||||
@@ -0,0 +1,48 @@
|
||||
# RFC 0032: Safe owning binary heap
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-6d.6, safe library source after RFCs 0024/0029
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation and normative changes
|
||||
|
||||
Spec 16 §2.16 supplies a bounded priority queue for arbitrary complete T with one explicit pure ref-value ordering operation. Copy and owning values share the same API and safe implementation. Ownership, allocation/failure and ordering contracts are visible to the verifier and caller.
|
||||
|
||||
## Preserved invariant
|
||||
|
||||
Dense entries own each live T exactly once. A Copy index permutation and inverse positions describe the heap; no child precedes its parent. Unused capacity owns no T. Callback laws are a stable strict weak order. Full push and every returned allocation failure preserve all state, and returned resources are explicitly consumed.
|
||||
|
||||
## Verifier / runtime rules
|
||||
|
||||
No new transfer function or runtime rule. Existing complete buffer/aggregate moves, exchange, ref/mut exclusion, task loans, exact static callable contracts, bounds, effects, Copy/Send/Share and consumption apply. Indices sift while owners remain in initialized storage; complete pop/exchange repairs a dense hole. All code is safe Aji lowering to ordinary AIR. Callback/fuel traps are abnormal; normal failures preserve layout/extraction order and refund recorded allocation authorities.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
An owning record orders by a Copy priority field. Push consumes the record; full returns it; pop moves it out for complete unpack and explicit resource consumption; nonempty free returns the whole heap. A Copy heap may peek; attempting peek of an owning T, ignoring full/pop/nonempty-free owners, missing move, borrowing across mutation/task loans, mismatched ordering policies/effects or sharing non-Share resources MUST reject through existing diagnostics. Executable examples and validation results are recorded below.
|
||||
|
||||
The [checked owning example](../../examples/std/heap.aji) moves a priority/owner record into one slot, pops/unpacks/takes the payload and frees the empty heap with a 40-byte grant. [Owning peek](../../tests/conformance/source/heap/peek_owner.aji) rejects E7005; [a leaked full return](../../tests/conformance/source/heap/full_leak.aji) rejects E3002; [a live task loan](../../tests/conformance/source/heap/loan.aji) rejects E4101. [Corrupt indices](../../tests/conformance/source/heap/invalid_indices.aji) trap T0008 through ordinary bounds checks, preserving safe-code memory safety.
|
||||
|
||||
## Diagnostics / compatibility / AIR
|
||||
|
||||
No new diagnostic, instruction, AIR feature, source syntax or verifier/runtime state. E7003/E7005, E3002, E2101/E4101, E3101 and E4001/E4002 remain ordinary checks. Addition of std.heap is compatible with existing modules and AIR format 0; imports grant no authority. No implicit allocation/destructor or unsafe/trusted boundary is introduced.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
One strict-weak-order precondition, already expressible with static operation selection, plus an explicit priority-queue invariant. Eight operations mirror existing bounded containers; no inferred comparator, convenience auto-growth, borrowed-return facility or stable-sort concept. The Copy-only peek restriction follows existing lookup contracts. Dense/Copy-index storage avoids a new owner-swapping primitive, borrowed enum payloads or holes. Verifier state and syntax are unchanged; Quick Reference and full source documentation growth are measured below. No empirical MCC benefit is claimed.
|
||||
|
||||
Measured cl100k growth from RFC 0031: Quick Reference 8,201 → 8,284 (+1.0%); other source documentation 54,798 → 56,770 (+3.6%); full source excluding AIR 62,999 → 65,054 (+3.3%). library/std.md is 19,911 tokens. o200k groups are 8,317 / 56,955 / 65,272; qwen2.5 groups 8,534 / 58,278 / 66,812. AIR stays 179,282 bytes / 19 files / 51 sections; its source-bundle copy stays 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k growth over the 33,981 pre-std baseline is +91.4%, justified by the owning priority queue and explicit ordering/representation/failure/budget contracts. No new language form, verifier state or diagnostic; the Quick Reference has one short paragraph and full contracts stay on demand. Existing primitives suffice without changing AIR.
|
||||
|
||||
## Alternatives
|
||||
|
||||
Copy-only array heaps fail the owning resource gate. A vacancy/default T loses generality. Direct swapping owners could use extra scratch rotations, but adds transient value movement and proof complexity. Two initialized buffers make permutation swaps and complete extraction explicit with a documented 16-byte per-capacity metadata cost on air64. Opaque runtime collection magic enlarges the trusted boundary unnecessarily.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Independent Python priority-queue traces; ascending/descending order, duplicate priorities, complete owning/files/endpoint values, dense-hole repair, empty/zero/full, capacity overflow, both allocation failure phases, exact peak/refunds/cross-authority accounting, rejected leaks/aliases/loans/Copy/effect/policies; source/AIR/package/profile consistency; GC and scheduler stress; unit/Quick Reference, formatting, full conformance, source coverage and reference budgets. I/O/path remain subsequent increments.
|
||||
|
||||
|
||||
## Validation result
|
||||
|
||||
All 1007 conformance cases pass, including 34 heap fixtures. All runtime heap fixtures pass collection before every instruction; shared read-only lookup, sender heap transfer and task-loan restoration run 12 seeds under quanta 1, 2, 7 and their own quantum. Independent Python heapq oracles cover 160 min/Copy and max/owning operations; sorted oracles check all 120 permutations of five elements. Tests cover duplicate priorities, dense-hole repair, direct own<u64>, owning byte buffers, files/endpoints, returned full/pop/nonempty-free ownership, empty/zero/overflow, both growth failure phases, complete layout preservation, exact peak/refund and cross-authority accounting, absence of full-push callbacks and bounds traps for invalid representation. Existing diagnostics reject leaks/missing move/Copy/aliases/loans/effects/policies/non-Share sharing.
|
||||
|
||||
Unit/Quick Reference, formatting, hosted smoke, bundle generation, 109/109 source coverage constructs and 70 CLI checks pass. CLI checks compare source/AIR/profile/package behavior, reordered imports, audit output, selected-comparator provenance and std bounds-trap locations. The separate general-map GC/stress process also completed with 33/33, closing Q-037. Collections STD-6d are implemented and validated on this branch; Std 0.1, I/O/path and system adapters remain unfinished.
|
||||
@@ -0,0 +1,46 @@
|
||||
# RFC 0033: Explicit bounded I/O composition
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-7a, safe std.io foundation before buffered adapters and paths
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation and normative changes
|
||||
|
||||
Spec 16 §2.17 adds six concrete functions composing existing console/file/TCP reads and file writes. Runtime writes already have all-or-error success contracts, so this increment adds no write alias or broad protocol hierarchy. Exact reads and bounded copies need reusable loops with explicit partial progress and no implicit allocation/authority.
|
||||
|
||||
## Preserved invariant
|
||||
|
||||
Only caller-supplied destination/scratch slices are accessed within their bounds. Mutable resources remain borrowed and owned by their caller on every normal return. No buffer, file or stream is allocated, opened, closed or retained. Confirmed counts never exceed supplied capacities/limits. Errors do not imply rollback of prior reads/writes or atomic failure of external I/O.
|
||||
|
||||
## Verifier and runtime rules
|
||||
|
||||
No new transfer function or runtime rule: ordinary ref/mut, disjoint slices, resource borrowing, task loans, exact typed/effect calls and checked arithmetic/bounds suffice. The underlying intrinsic supplies authority through cap<io.read>, mut<file<read/write/append>> or mut<stream>. Spec 11 still defines deterministic/hosted outcomes, blocking, fuel and errors. There is no timer, background task, ambient grant or new error variant.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
The caller opens read/write files with explicit capabilities, lends both and a fixed scratch slice to copy_file with a limit, handles eof/limit/err, and explicitly closes both on every path. Exact readers report completed prefix length on EOF/error. Aliased buffers, wrong resource modes/capability kinds, missing public effects, active task loans and closing a lent resource reject through existing diagnostics. Executable fixtures and validation results are recorded below.
|
||||
|
||||
The [copy example](../../examples/std/io.aji) lends two files and a fixed three-byte frame buffer, handles all results and explicitly closes resources. [Exact file reading](../../tests/conformance/source/io/file.aji) validates prefix/suffix/guard preservation. [Wrong mode](../../tests/conformance/source/io/wrong_mode.aji) rejects E7005; [missing effect](../../tests/conformance/source/io/missing_effect.aji) rejects E3101; [a live task loan](../../tests/conformance/source/io/loan.aji) rejects E4101. No callback or hidden resource cleanup is needed.
|
||||
|
||||
## Diagnostics / compatibility / AIR
|
||||
|
||||
No new instruction, AIR feature, syntax, verifier/runtime state or diagnostic. Existing type/capability, effect, alias/task-loan and resource-consumption checks apply. Built-in io_error.invalid_input represents unusable nonempty copy with zero scratch capacity, without performing an intrinsic. Imports grant no authority and all existing APIs/AIR meaning are unchanged.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
Six concrete signatures carry exact io.read/fs.read/net.read/fs.write effects; no effect inference, unions of unrelated effects, callbacks, type erasure or reader trait is needed. EOF and filled-buffer/limit are distinct because no extra byte is consumed to discover EOF. Read and copy error records distinguish confirmed progress from external I/O that may have partially failed. This is a library contract, not a new language concept. Existing safe primitives suffice. Quick Reference/source budgets are measured below; no empirical MCC benefit is claimed.
|
||||
|
||||
Measured cl100k growth from RFC 0032: Quick Reference 8,284 → 8,350 (+0.8%); other source documentation 56,770 → 58,473 (+3.0%); full source excluding AIR 65,054 → 66,823 (+2.7%). library/std.md is 21,614 tokens. Corresponding o200k groups are 8,384 / 58,664 / 67,048; qwen2.5 groups are 8,600 / 59,988 / 68,588. AIR remains 179,282 bytes / 19 files / 51 sections; its source-bundle copy remains 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k growth over the pre-std 33,981-token baseline is +96.6%, justified by explicit partial-progress, authority, EOF/limit and cleanup contracts. No new syntax, diagnostic or verifier/runtime state is introduced; detailed contracts stay on demand. No empirical compression benefit is claimed.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Empty/exact/short input, preserved guard/suffix bytes, limits at/below/above EOF, small scratch chunks, append mode, zero scratch/limit, supplied destination counts, fragmented TCP and task loan restoration; rejected effects/modes/kinds/aliases/loans/close; independent public byte-vector oracle, source/AIR/package/profile/provenance and hosted read/write errors; GC/schedule stress and required repository/bundle checks. Buffered owning reader/writer and lexical paths remain required by STD-7.
|
||||
|
||||
|
||||
## Validation result
|
||||
|
||||
All 1027 conformance cases pass, including 20 I/O fixtures. Runtime fixtures pass collection before every instruction; fragmented TCP and restored task loans run 12 seeds under quanta 1, 2, 7 and their own quantum. Independent Python byte-prefix/count oracles cover 162 exact/bounded reads and 250 copy/append combinations with empty/exact/short inputs, guard/suffix bytes, limits, cursor tails and scratch capacities. Tests reject wrong modes/kinds, missing effects, active aliases/task loans and closing a borrowed resource with existing codes. Maximum usize limit and exact EOF at limit are covered without overflow or probing past the bound.
|
||||
|
||||
Hosted tests exercise an actual stdin read error (directory → invalid_input) and a child-only file-size quota causing a partial second write: read=4, confirmed_written=2, actual output length=3. Source code explicitly consumes both files and checks the input cursor tail; no wall-clock timeout, global host configuration change or result-file write under that quota is used. The result confirms why failed writes cannot promise rollback/exact output counts.
|
||||
|
||||
Unit/Quick Reference, formatting, hosted smoke, reference generation, 111/111 source coverage constructs and 55 CLI checks pass. CLI checks compare source/AIR/profile/package results, reordered imports, audit output and caller diagnostic provenance. AIR semantics and source syntax remain unchanged. The foundation is complete on this branch; buffered owning reader/writer, lexical paths and Std 0.1 remain required future work.
|
||||
@@ -0,0 +1,48 @@
|
||||
# RFC 0034: Owning bounded file reader and writer
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-7b, safe std.io.reader / std.io.writer after RFCs 0024/0033
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation and normative integration
|
||||
|
||||
Spec 16 §2.18 adds concrete file adapters with fixed-capacity initialized byte buffers. They reduce repeated refill/flush code while keeping file ownership, allocation, effects, failure and cleanup explicit. Existing linear aggregates/buffers suffice without a reader trait, hidden destructor or new instruction.
|
||||
|
||||
## Preserved invariant
|
||||
|
||||
The adapter owns exactly one file and one initialized buffer. Reader offsets delimit its unread prefix; writer used count delimits pending bytes. A failed writer retains its first I/O error and prevents further writes/flush retries because failed external writes may have written an unknown prefix. All normal outcomes transfer complete resources or retain them in the adapter; no resource is implicitly closed.
|
||||
|
||||
## Verifier rule
|
||||
|
||||
No new abstract state/transfer function. Ordinary whole-value struct/enum moves, resource borrowing, buffer views, disjoint slices, effects/capabilities, alias/task loans, Copy/Send/Share and consumption checks apply. Fields remain visible with a documented caller invariant, as for existing safe collections. Invalid representation may trap through checked bounds/arithmetic but cannot bypass memory safety.
|
||||
|
||||
## Runtime / deterministic behavior
|
||||
|
||||
Only new allocates, with explicit mem.alloc authority, charging capacity bytes. A failed new returns the original unchanged file with alloc_error. Existing spec 11 I/O/blocking/fuel/profile behavior applies. Reader refill/cached copies and writer room-making flushes are ordinary safe source. Finish frees Copy storage and returns the file; unread/failed finish returns the complete adapter. Discard explicitly abandons buffered bytes, frees storage and returns the file plus counts/error state. No sync/close is hidden.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
The caller moves a file into new, explicitly consumes constructor failure, lends the adapter for reads/writes, handles finish returning the file or complete adapter, and closes the returned file. Discard reports unread/pending byte counts. Ignoring owning new/finish/discard outcomes, missing moves, invalid modes/effects, alias/task loans and sharing file-bearing adapters reject through existing diagnostics. The [copy example](../../examples/std/buffered_io.aji) consumes every constructor/finish result and closes returned files. [Unread finish](../../tests/conformance/source/buffered_io/unread_finish.aji) returns/reuses the complete reader; [explicit discard](../../tests/conformance/source/buffered_io/writer_discard.aji) reports abandoned pending bytes and refunds storage. [Ignoring a constructor failure](../../tests/conformance/source/buffered_io/new_error_leak.aji) and [ignoring failed finish](../../tests/conformance/source/buffered_io/finish_error_leak.aji) reject E3002. [Aliasing the cached bytes](../../tests/conformance/source/buffered_io/writer_alias.aji) rejects E2101; [sharing a file-bearing adapter](../../tests/conformance/source/buffered_io/not_share.aji) rejects E4002.
|
||||
|
||||
## Diagnostics / compatibility / AIR
|
||||
|
||||
No new diagnostic, syntax, AIR opcode/feature or verifier/runtime rule. Existing E7003/E7005/E3002/E2101/E4101/E3101/E4002 and resource availability checks apply. Two pinned modules are additive; old std.io APIs and AIR meanings retain their contracts. No implicit allocation, cleanup, authority, timeout, task or unsafe/trusted boundary.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
Five operations per concrete adapter: reader new/read/read_exact/finish/discard; writer new/write/flush/finish/discard. Known file modes keep exact fs.read/fs.write effects. Writer failure state distinguishes acceptance into an owned buffer from confirmation of external output and prohibits an unsound automatic retry. No language/verifier state is added. Full representation/failure contracts stay on demand; measured Quick Reference/source budgets follow. Existing primitives suffice, and no empirical MCC improvement is claimed.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Independent read/segmented-write byte oracles, capacities including zero, refill/flush/exact EOF, preserved guards, empty/full pending storage, constructor failure ownership/refunds, unread/failed finish, explicit discard, files transferred to tasks and restored loans, rejected ownership/type/effect/alias/Share cases. Hosted read error, externally partial write, no retry after error, source/AIR/package/import-order/profile/provenance checks, GC/scheduler stress and required repository/bundle checks. Paths and other system modules remain subsequent work.
|
||||
|
||||
|
||||
Measured cl100k growth from RFC 0033: Quick Reference 8,350 → 8,445 (+1.1%); other source documentation 58,473 → 61,223 (+4.7%); full source excluding AIR 66,823 → 69,668 (+4.3%). library/std.md is 24,364 tokens. Corresponding o200k groups are 8,478 / 61,408 / 69,886; qwen2.5 groups are 8,695 / 62,738 / 71,433. AIR remains 179,282 bytes / 19 files / 51 sections; its source-bundle copy remains 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k growth over the pre-std 33,981-token baseline is +105.0%, justified for owner review by visible prefetch/cursor, acceptance/partial-write, first-error and explicit resource cleanup contracts. Quick Reference remains beyond the 4–6k target; front-door consolidation/selective reading remains separate work. This increment adds no language syntax, diagnostic or verifier/runtime state and claims no empirical MCC improvement.
|
||||
|
||||
## Validation result
|
||||
|
||||
All 34 buffered adapter conformance cases pass, including collection before every instruction. Owning reader/writer transfers and restored reader loans run 12 schedule seeds under quanta 1, 2, 7 and their own quantum. Independent Python byte oracles cover 48 complete read streams, 64 exact prefixes and 96 segmented writes over empty/exact/short inputs, zero and nonzero storage, multiple refills/flushes and preserved destination guards. Fixtures cover unread finish/discard cursor behavior, no EOF probe at finish, lazy full-cache flush, explicit discard, maximum capacity, constructor failure ownership and allocation refunds to narrowed authorities. Existing diagnostics reject missing moves, resource/result leaks, wrong mode/kind/effects, aliases, active task loans and non-Share references.
|
||||
|
||||
On Linux, 89 CLI checks pass: source/AIR/package/profile parity, reordered imports, pure audit and caller diagnostic provenance, a real file read fault (/proc/self/mem at unreadable offset zero), and four partial external write traces. A child-only three-byte file quota causes room-making, previous-call pending, explicit flush and capacity-zero direct write errors. The parent then raises the child's quota before the program attempts another write/empty write/flush/finish; the file remains exactly abc and the first error/pending bytes are preserved. This detects forbidden retry even when a later external write would succeed. Constructor/finish/discard failures retain complete owners, and the program explicitly closes returned files and verifies quota refunds. Tests use fuel and pipe handshakes, no wall-clock timeout or global host configuration change. macOS runs the portable checks/partial quota cases; read-fault and raised-quota retry probes are Linux-specific.
|
||||
|
||||
Unit/Quick Reference, formatting, hosted smoke, 115/115 source coverage constructs and reference generation pass. Full repository conformance passes with 1061 cases, zero failures and zero pending. The buffered file adapter gate is complete on this branch. Lexical paths and Std 0.1 remain required subsequent work.
|
||||
@@ -0,0 +1,46 @@
|
||||
# RFC 0035: Caller-buffer lexical paths
|
||||
|
||||
Status: Implemented
|
||||
Scope: STD-7c, std.path after owning buffered files
|
||||
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
|
||||
|
||||
## Motivation and spec integration
|
||||
|
||||
Spec 16 §2.19 adds six pure path operations on bytes with one portable slash syntax. Paths are frequent CLI/storage data; normalization/join/component loops should be reusable without hidden allocations, host state or a larger authority surface. Spec 16 and reference/std.md contain the normative contracts; this record explains them.
|
||||
|
||||
## Preserved invariant and verifier rule
|
||||
|
||||
Output writes remain within the supplied exclusive slice, successful output preserves its suffix, and every returned input/size/capacity error preserves the entire destination. Input borrows only read; no borrow escapes, file/resource is consumed or capability is gained. Component queries return bounded Copy index ranges, keeping lifetime/bounds decisions visible in the caller. Ordinary borrow, bounds, Copy/Send/Share, task loans and effect checks apply without new verifier state.
|
||||
|
||||
## Runtime / deterministic behavior
|
||||
|
||||
Only safe source algorithms: validation and final-size measurement precede emission. Reverse scanning cancels components with pending parents; a second reverse pass writes retained components into the exact final prefix. Capacity is measured after cancellation, so a short destination can hold a result whose raw input was long. No heap/scratch allocation, platform branch, filesystem access, symlink interpretation or current directory. `/` is the separator in every profile. NUL rejects in writers; non-UTF-8/backslash bytes remain ordinary data. Primitive filesystem capability/path checks are unchanged and still mandatory.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
Join /data/a with ../b into a caller array, handle WriteResult, then use the resulting slice with an explicit fs capability. Normalization alone cannot authorize the path. Disjoint slices within one allocation are valid; overlapping source/output, task-loaned output and wrong scalar/slice types reject through existing diagnostics. The [pure example](../../examples/std/path.aji) joins into caller storage and borrows its component ranges. [A one-byte canceled result](../../tests/conformance/source/path/canceled_capacity.aji) and [disjoint slices](../../tests/conformance/source/path/disjoint.aji) are valid. [Overlapping slices](../../tests/conformance/source/path/overlap.aji) reject E2101; [a live task loan](../../tests/conformance/source/path/loan.aji) rejects E4101. [Authority](../../tests/conformance/source/path/authority.aji) remains independently enforced, and [reusing a range on a shorter input](../../tests/conformance/source/path/range_bounds.aji) traps T0008 through ordinary bounds checking.
|
||||
|
||||
## Diagnostics / AIR / compatibility
|
||||
|
||||
No new diagnostic, source syntax, AIR instruction/feature/meaning, verifier/runtime state or trusted boundary. Existing E7002/E7005/E2101/E4101 apply. WriteResult variants are ordinary Copy data; insufficient output and malformed input do not trap or mutate output. All existing paths/fs grants/source/AIR contracts retain their meaning. Q-034 is neither expanded nor silently inferred: callers explicitly borrow a returned Range from their own path.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
Six supported operations: is_absolute/basename/parent/extension/normalize/join. One separator syntax and one destination-first writing result. Queries report raw bounded offsets without borrowed returns; writing reports final prefix size and has an unchanged-output error contract. No agent needs platform-specific normalization, hidden allocation or lifetime inference. Existing primitives suffice; no language concepts, verifier state, syntax forms or diagnostics are added. Full edge rules stay on demand. Measured Quick Reference/source bundle budgets follow; no empirical MCC benefit is claimed.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Host-dependent paths would make deterministic fixtures/platform reasoning harder and disagree with the existing runtime slash syntax. Borrowed query returns would require a separate vertical lifetime feature before safe source can use them. Requiring raw-input-sized output would fail ordinary cancellation cases unnecessarily. In-place mutation would need explicit overlap semantics and would violate the current exclusive-output/shared-input contract. Adding an opaque path opcode is unnecessary.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Independent forward-stack byte oracle; empty/root/relative/absolute, repeated separators, dot/parent cancellation, root saturation, hidden/multiple/trailing extensions, non-UTF-8/backslash/NUL, exact/short capacities, late malformed input, suffix preservation, disjoint same-allocation slices and small canceled-result output. Rejected aliases/types/imports/task loans; valid task transfer/restored loans; source/AIR/package/profile/provenance/audit and authority checks; GC/scheduler stress, full conformance, unit/Quick Reference, formatting, source coverage and documentation budget. STD-7 completes only after this gate; STD-8 and the broader roadmap remain required.
|
||||
|
||||
|
||||
Measured cl100k growth from RFC 0034: Quick Reference 8,445 → 8,518 (+0.9%); other source documentation 61,223 → 63,296 (+3.4%); full source excluding AIR 69,668 → 71,814 (+3.1%). library/std.md is 26,437 tokens. Corresponding o200k groups are 8,552 / 63,497 / 72,049; qwen2.5 groups are 8,768 / 64,821 / 73,589. AIR remains 179,282 bytes / 19 files / 51 sections; its source-bundle copy remains 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k growth over pre-std 33,981 is +111.3%, justified for owner review by visible byte syntax, cancellation/root, range/capacity and authority contracts. Quick Reference is beyond its 4–6k target; front-door consolidation/selective reading remains separate work. No new syntax, diagnostic or verifier/runtime state is added, and no empirical MCC improvement is claimed.
|
||||
|
||||
## Validation result
|
||||
|
||||
All 1079 repository conformance cases pass, including 18 path fixtures. The independent Python forward-stack oracle covers 132 paths with queries/idempotence and every short/exact/extra output capacity, 49 joins and four malformed pairs. All 255 non-NUL bytes are additionally tested. Fixtures cover one-byte canceled outputs, late malformed input winning over short capacity (including ignored base), suffix/guard preservation, raw ranges, no borrowed-return inference, disjoint same-allocation slices, aliases, task loans, wrong types/imports and independent filesystem authority. Reused ranges retain normal runtime bounds checks, with T0008 on a shorter unrelated path.
|
||||
|
||||
68 CLI/source/AIR/package/profile/provenance/audit checks pass. Pure APIs use no entry grants, heap allocation or unsafe sites. Lowered AIR and source agree; reordered imports/package loading/name collisions are deterministic. Hosted cases cover arbitrary byte components and actual denied-file authority independently of normalization. Unit/Quick Reference, formatting, 117/117 source coverage constructs and reference generation pass. All 18 path fixtures pass the collection-before-every-step gate; scheduled fixtures pass 12 seeds under quanta 1, 2, 7 and their own quantum. The oracle batches preserve every vector/capacity while ending literal frames between batches, bounding collector roots. STD-7c and the intermediate STD-0..7 foundation are complete. STD-8 and Std 0.1 remain unfinished.
|
||||
@@ -94,10 +94,10 @@ Every trap has a stable code in the `T0xxx` range of [`../reference/error-codes.
|
||||
|
||||
## 7. Generics
|
||||
|
||||
Aji supports monomorphized generics.
|
||||
Aji supports explicit monomorphized generics (source contract: spec 15 §15). Calls use `swap::<u64>(mut a, mut b)`; type annotations use `Pair<u64>`.
|
||||
|
||||
```aji
|
||||
fn swap<T>(a: mut<T>, b: mut<T>) { ... }
|
||||
fn swap<T: Copy>(a: mut<T>, b: mut<T>) -> void effects [] { ... }
|
||||
```
|
||||
|
||||
Version 0.1 does not require user-defined traits/typeclasses. Generic constraints use compiler-known structural properties such as `Copy`, `Send`, `Share`, `Freeze` and `Local`.
|
||||
|
||||
@@ -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<T>`, `own_array<T>` 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<T>` 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> → T`); an `own_array<T>` has no `take`, since a runtime-sized array is not an SSA value.
|
||||
|
||||
`T` in `own<T>` and `own_array<T>` must be a value type; a linear `T` (for example `own<file<read>>` or `own<own<u64>>`) 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<T>` and in `own_array<T>` must be Copy. Linear `T` in individual `own<T>` 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<T>`: a graph owner; linear; `Send`, not `Share`.
|
||||
- `iref<T>`: 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,28 @@ 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<T>` may hold linear aggregate content in this phase; channels and mutexes retain their existing complete-value transfer rules. `own.pack` explicitly moves a value into an individually owned allocation: on failure, the error continuation receives both alloc_error and the original complete value. `own.take` consumes the owner, frees the allocation and returns its complete content, including all nested owners/resources. `own.free` MUST reject E1001 when content is linear. Repeated heap arrays, region allocations and frame locals MUST remain Copy-only; bulk freeing cannot destroy resources. Dynamic linear buffers require a separate feature/API with an explicit drain contract. Existing heap/region operations on Copy values retain their semantics.
|
||||
|
||||
Verifier state is whole-value availability, existing borrow provenance and initialization, with no per-field moved state. Structural Send/Share still apply, so transfer to workers/channels/mutexes requires their ordinary rules. The deterministic interpreter moves existing handles, performs swaps as one instruction and uses existing allocation budgets/fuel; it performs no user cleanup on normal paths or traps. AIR format 0 remains compatible: previously unsupported feature/type/opcode cases gain meanings; previously accepted Copy modules keep identical behavior.
|
||||
|
||||
|
||||
## 26. Dynamic initialized buffers
|
||||
|
||||
Feature `linear_buffers` adds the linear complete value `buffer<T>`, accounted handle size 24 bytes. T MUST be a complete value with ordinary linear_aggregates member rules: no borrow/storage/function-bound content. Ownership type graphs through buffer wrappers MUST be acyclic (E1003). `buffer<T>` is Send exactly when T is Send and Share exactly when T is Share, like own_array. Local propagates through T; no guard/task/channel-transfer gate is weakened.
|
||||
|
||||
A buffer uniquely owns capacity C and a contiguous initialized prefix of length L, 0 ≤ L ≤ C. Only [0,L) is observable. Every live linear element is owned exactly once inside that prefix. There are no observable holes, default values, implicit destructors or partially moved fields. Constructors start with L=0. Push/pop change the prefix by one complete value; pop is LIFO. Views borrow precisely the prefix. Metadata changes, growth and consumption obey ordinary exclusive alias and task-loan rules; a live view excludes those operations, even when a dynamic branch would perform no change.
|
||||
|
||||
Allocation charges C × accounted_size(T), using checked arithmetic and the named mem.alloc authority. Overflows/authority exhaustion return alloc_error::budget_exceeded. Zero capacity is valid and charged zero. Capacity is a target usize, not a format-0 fixed-array type length. Growth to C' > C allocates explicitly from the supplied authority: it MUST charge the complete new capacity before releasing the old charge to its original authority. Thus peak live charges include both allocations. Success transfers all initialized values and changes capacity/authority; failure preserves length, capacity, contents and old authority exactly. A request ≤ C succeeds without mutation/allocation, but public effects/capability requirements remain explicit. Unused capacity contains no user value and cannot be borrowed.
|
||||
|
||||
Push requires no allocation effect or capability: if L<C, it transfers one value and increments L; otherwise it returns that original value without mutation. Pop returns the last complete value and decrements L, or reports empty with no change. `buffer.free` consumes the whole handle: it frees storage only when L=0, otherwise returns that same complete buffer. This applies uniformly to Copy and linear T. Every normal path MUST explicitly transfer/drain nested resources; a caller MAY trap under the existing abnormal-path contract but no cleanup is inserted. Existing own.array, own.free and region/frame rules retain their meanings.
|
||||
|
||||
The verifier tracks whole buffer ownership and existing borrow provenance, not a symbolic length or per-slot initialization state. Prefix validity is enforced by the trusted primitive semantics. Views use existing slice borrow/end, load/store bounds and explicit value.swap rules. Copy loads/copies require Copy T; ordinary overwrite of linear T remains forbidden. The deterministic interpreter preserves buffer identity and initialized prefix across tracing collection, tasks and swaps; metadata accesses participate in race checks, and allocation uses existing deterministic budgets and fuel. No synchronization, ambient authority, implicit allocation or new trap is added. The feature is additive in AIR format 0.
|
||||
@@ -368,7 +368,7 @@ Any other `T` is `E1001`: 128-bit integers, aggregates, references, owners and h
|
||||
`atomic<T>` 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<T> 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`.
|
||||
|
||||
@@ -556,7 +556,7 @@ Example: two workers square the two halves of one buffer in parallel; both loans
|
||||
| integers, `bool`, built-in enums | yes | yes |
|
||||
| `cap<K>` (every kind) | yes | yes — the authority object is shared and its host side is synchronized |
|
||||
| `file<…>`, `listener`, `stream` | yes | no |
|
||||
| `own<T>`, `own_array<T>` | if `T` is | if `T` is |
|
||||
| `own<T>`, `own_array<T>`, `buffer<T>` | if `T` is | if `T` is |
|
||||
| `region` | yes | no — allocation through a shared borrow mutates the region |
|
||||
| `ref<T>` | if `T` is `Share` | if `T` is `Share` |
|
||||
| `mut<T>` | if `T` is `Send` | no |
|
||||
@@ -718,7 +718,7 @@ Decision record: RFC 0012. Depends on `cancellation`, `heap`.
|
||||
| `sender<T>` | a sending endpoint | linear |
|
||||
| `receiver<T>` | 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<T> 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<T>`, §40):
|
||||
|
||||
@@ -857,4 +857,3 @@ Common properties:
|
||||
- *Exact coverage, normative litmus corpus only.* For every test of `reference/concurrency-litmus.md`, the outcomes observed under exhaustive exploration equal the oracle's allowed set: `observed_exhaustive = allowed` (§20.5).
|
||||
- *Weak reads.* A read whose ordering is not `seq_cst` may read any write the model allows. The choice is a draw from the schedule generator (§36.2) and counts in `schedule.choices`.
|
||||
- *No weak access.* A run with no non-`seq_cst` access makes no extra draw, and every read reads the latest write.
|
||||
|
||||
@@ -289,3 +289,15 @@ atomic.new, atomic.take → no effect
|
||||
For compare-exchange, the operation is non-`seq_cst` if either ordering is. A missing atom is `E3101`.
|
||||
|
||||
If `atomic.weak` is not among the transitive effects of `@main`, every atomic access is `seq_cst`, and every execution of the safe program is explainable as an SC interleaving (spec 04 §22).
|
||||
|
||||
## 14. Explicit error values (feature `error_values`)
|
||||
|
||||
An error is Copy data, not authority or proof that an operation occurred. Safe code MAY create any registered payload-free variant of `alloc_error` (spec 03 §18), `cap_error` (§10) or `io_error` (spec 06 §7). Creating an error MUST NOT allocate, perform I/O, narrow a capability, change resource state or grant authority. Actual fallible operations retain their specified outcome rules.
|
||||
|
||||
In AIR, `%e = error.const B.variant` has two static operands: a built-in error family `B` and one of its registered variant names. It takes no SSA operands or payloads and produces exactly one Copy value of type `B`. The module MUST declare `error_values` and its full dependency closure (`capabilities`, `effects`, `heap`, `ownership`, `resources`). These dependencies make all three existing error families available; they grant no capabilities.
|
||||
|
||||
The verifier MUST validate the family and variant (`E0004` for an unknown name in text), result uses (`E1001` for a type mismatch) and feature declaration (`E0006`). Its transfer function introduces one available Copy value; it changes no ownership, borrow, memory, concurrency or authority state. Effects and capabilities required: none. Instruction-specific traps: none. The interpreter deterministically binds the selected family/tag as ordinary built-in error data; the instruction consumes normal fuel. The payload syntax is not permitted (`E0001`).
|
||||
|
||||
Source uses the existing variant expression `alloc_error::budget_exceeded`, `cap_error::not_subset` or `io_error::invalid_input`, lowering to `error.const`; the frontend MUST include the feature closure. Every registered variant is constructible; errors cannot be converted into capabilities. Source rejects unknown variants with `E7002`, payloads with `E7005`, and wrong result types with `E7005`.
|
||||
|
||||
Valid: a pure function returning `alloc_error::budget_exceeded` before overflowing an allocation size. Rejected: returning that value from a function returning `cap<mem.alloc>` (`E7005` / AIR `E1001`). Existing `enum.make` remains restricted to declared enums. This is an additive format-0 feature; no existing instruction, error tag, fallible outcome or authority rule changes.
|
||||
@@ -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
|
||||
|
||||
|
||||
+4
-2
@@ -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<T>` 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
|
||||
@@ -258,6 +258,8 @@ Any other change to format 0 — a different meaning, typing rule, trap behavior
|
||||
|
||||
`cap<K>` (feature `capabilities`) is an opaque, copyable, authority-bearing value type; `K` is a registered capability kind ([`../reference/capabilities.md`](../reference/capabilities.md)). Built-in enums such as `cap_error` and `io_error` are spelled without `@`, have registered variants and are used with `enum.switch <builtin> %v, …` like declared enums. Rules: spec 05 §9–§12.
|
||||
|
||||
Feature `error_values`: `%e = error.const alloc_error.budget_exceeded` creates ordinary Copy error data without authority or effects (spec 05 §14); `enum.make` remains a declared-enum instruction.
|
||||
|
||||
Feature `resources`: `file<read>`, `file<write>`, `file<append>`, `listener`, `stream` are linear, authority-bearing resource types (spec 06 §6).
|
||||
|
||||
Feature `heap`: `own<T>` and `own_array<T>` (linear owners, `T` a value type) and the built-in enum `alloc_error`. Feature `regions`: `region` (linear). Rules: spec 03 §18–§21. Linear values — resources, owners and regions — follow the consumption rules of spec 06 §6.2–§6.3.
|
||||
@@ -289,6 +291,6 @@ Feature membership: `local<T>`, `ref<T>`, `mut<T>` 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).
|
||||
@@ -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 |
|
||||
|---|---|
|
||||
@@ -22,6 +22,15 @@ Notation: `T` is the type suffix of the opcode; `I` ranges over integer types; `
|
||||
|
||||
## Values
|
||||
|
||||
### `error.const B.variant` (feature `error_values`)
|
||||
|
||||
- Static operands: built-in error family `B` and its registered payload-free variant; no SSA operands.
|
||||
- Result: one Copy value of type `B`.
|
||||
- Ownership/borrow/memory/concurrency transitions: none; effects and capabilities required: none; traps: none.
|
||||
- Verifier transfer: define one available Copy value. Unknown family/variant: `E0004`; undeclared feature: `E0006`; incompatible result use: `E1001`. Payload syntax: `E0001`.
|
||||
- Interpreter: bind the built-in family/tag deterministically, using normal fuel; no program allocation or authority acquisition.
|
||||
- Complete contract and source syntax: spec 05 §14. `enum.make` is unchanged.
|
||||
|
||||
### `const.T lit`
|
||||
|
||||
- Operands: an integer literal (`T` ∈ `I`) or `true`/`false` (`T` = `bool`).
|
||||
@@ -309,3 +318,46 @@ 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<T, N>(%v0, …, %vN-1)`
|
||||
|
||||
Operands MUST be exactly N complete values of T (E1001). Result is array<T,N>. 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<T,N> %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<T> 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<mem.alloc> (E1001/E3201); T may be Copy or linear. No SSA result; success receives own<T>, failure receives (alloc_error,T) (E5002/E1001). Linear input is consumed on both edges; success owns it inside the allocation, failure owns the same original value. Memory: new allocation initialized with the complete value on success; none on failure. Effects: mem.alloc. Capability: explicit bounded mem.alloc. Synchronization/traps: none; ordinary alloc_error failure reasons/budget rules apply. Interpreter transfers handles without duplicating ownership and charges/frees the same accounted bytes as own.new/own.take.
|
||||
|
||||
|
||||
## Dynamic buffers (`linear_buffers`)
|
||||
|
||||
These instructions add no concurrency effects. Metadata access uses existing shared/exclusive race and task-loan checks; views carry child provenance. Valid buffer states MUST NOT trap; allocation failure is an outcome, while execution limits retain spec 11 behavior.
|
||||
|
||||
All operations require linear_buffers and its full dependency closure (arrays, capabilities, effects, heap, linear_aggregates, ownership, resources). buffer<T> content and lifetime rules are spec 03 §26. T MUST be a complete value. Counts/indices are usize. All continuations receive exactly the listed parameters (E5002 count, E1001 types), with no SSA result for terminators. New operations add no traps, except existing borrowed-index bounds checks applied to a view. No synchronization is performed.
|
||||
|
||||
| Instruction | Operands/result or continuations | Ownership/memory/transfer | Effects/capabilities |
|
||||
|---|---|---|---|
|
||||
| `buffer.new T %capacity, %cap, ok -> @ok, err -> @err` | usize, cap<mem.alloc>; ok(buffer<T>), err(alloc_error) | new initialized empty prefix; no consumed input; successful result owned | mem.alloc, explicit mem.alloc cap |
|
||||
| `%n = buffer.len %borrow` / `%n = buffer.capacity %borrow` | ref<buffer<T>> or mut<buffer<T>> → usize | shared metadata read through live borrow, no consumption | — |
|
||||
| `buffer.reserve %borrow, %capacity, %cap, ok -> @ok, err -> @err` | mut<buffer<T>>, usize, cap<mem.alloc>; ok(), err(alloc_error) | exclusive metadata/storage access; charge new backing before releasing old; failure preserves buffer; borrow remains live on both edges | mem.alloc, explicit mem.alloc cap |
|
||||
| `buffer.push %borrow, %value, ok -> @ok, err -> @err` | mut<buffer<T>>, T; ok(), err(T) | exclusive access; linear input consumed on both edges; success appends, failure returns original value; borrow remains live | — |
|
||||
| `buffer.pop %borrow, ok -> @ok, err -> @err` | mut<buffer<T>>; ok(T), err() | exclusive access; success removes/owns last value; empty preserves prefix; borrow remains live | — |
|
||||
| `%view = buffer.view %borrow` | ref<buffer<T>> → slice<T>; mut<buffer<T>> → slice_mut<T> | child borrow of initialized prefix, same shared/exclusive mode and provenance; MUST explicitly end; no ownership transferred | — |
|
||||
| `buffer.free %buffer, ok -> @ok, err -> @err` | buffer<T>; ok(), err(buffer<T>) | linear handle consumed on both edges; empty frees/releases charge, nonempty returns same complete buffer; live descendant borrows/task loans reject | — |
|
||||
|
||||
Verifier transfer uses existing whole-value availability for new/free and returned linear block parameters, and useThrough/child provenance for borrowed operations. Length/capacity/view are shared/exclusive access as declared above; all modifying operations require exclusive access even for an empty/full/no-op dynamic case (E2101/E4101). Runtime observes L/C, updates the initialized prefix atomically per instruction and selects the corresponding continuation deterministically. Allocation overflow/exhaustion selects err(alloc_error); no user value is destroyed by a failing operation. Local/borrow/task-bound element types, mismatches and copy/overwrite of linear contents reject E1001; cyclic ownership rejects E1003. Existing resource-leak/repeated-consumption errors apply. No new diagnostic/effect/capability/trap is introduced.
|
||||
@@ -47,6 +47,8 @@ resource state
|
||||
|
||||
## 4. Ownership state machine
|
||||
|
||||
For `error.const` (feature `error_values`, spec 05 §14), verification introduces one available Copy value of the selected built-in error type. It MUST NOT alter authority, resource, memory, borrow or concurrency state. The static family/tag and ordinary result-use typing MUST be checked.
|
||||
|
||||
Representative states:
|
||||
|
||||
```text
|
||||
@@ -120,6 +122,7 @@ The **accounted size** of a type is a normative, platform-independent metric of
|
||||
| enum | `tag + ` the largest sum over one variant's payload, where `tag` is the smallest of 1, 2, 4, 8 bytes that can hold the index of every variant |
|
||||
| `ref<T>`, `mut<T>` | 8 |
|
||||
| `slice<T>`, `slice_mut<T>` | 16 |
|
||||
| `buffer<T>` (linear_buffers) | 24 |
|
||||
|
||||
`void`, `never` and storage types (`local<T>`) are not materializable values and have no accounted size; the `T` inside a storage type does.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
A package contains an `aji.toml` manifest. Decision record for capability grants: RFC 0010.
|
||||
|
||||
1. **A manifest requests; the operator grants.** The author of a package writes `[capabilities]`. Authority is granted only when someone explicitly runs the program with that manifest (`aji run --manifest`). Building, verifying or installing never grants anything (spec 05 §6).
|
||||
1. **A manifest requests; the operator grants.** The author of a package writes `[capabilities]`. Authority is granted only when someone explicitly runs the program with that manifest (`aji run --manifest` or `aji explore --manifest`). Building, verifying or installing never grants anything (spec 05 §6).
|
||||
2. **Same model as `--grant`.** One entry per `@main` capability parameter: `parameter = "kind[:scope]"`. All instantiation rules apply unchanged (missing, mismatched, unknown, invalid scope; mandatory `mem.alloc` budget in the deterministic profile).
|
||||
3. **The operator has the last word.** A command-line `--grant P=…` replaces the manifest entry for `P`, for example to point a scope at another directory. It never silently adds parameters: an unknown parameter is still `unknown_parameter`.
|
||||
4. **Strict parsing.** Unknown sections, unknown keys and duplicate keys are errors, so a typo cannot silently drop or misplace authority.
|
||||
@@ -42,10 +42,31 @@ aji run --manifest aji.toml [--grant P=KIND[:SCOPE]]... [other run options]
|
||||
|
||||
- The module is the manifest's `entry`; a file argument is not allowed together with `--manifest`.
|
||||
- Grants are the manifest's `[capabilities]` entries, each replaced by a `--grant` for the same parameter if given.
|
||||
- `aji check` and `aji report` do not read manifests.
|
||||
- `aji check`, `aji lower` and `aji report` read a manifest only with explicit `--manifest PATH`, selecting its entry and module inputs without granting program authority. `aji explore --manifest PATH` uses its entry/module inputs and grants with the same override rules as run.
|
||||
|
||||
Manifest errors (unreadable file, syntax, unknown section or key, duplicate key, missing `name`/`version`/`entry`, malformed grant string) are reported before verification as a usage error (exit code 2) with a message naming the line. Structured manifest diagnostics belong to the package tooling of Phase 8.
|
||||
|
||||
### 1.3 Package source mapping
|
||||
|
||||
An optional `[modules]` table maps dotted source module names to manifest-relative `.aji` file paths:
|
||||
|
||||
```toml
|
||||
[package]
|
||||
name = "record-tool"
|
||||
version = "0.1.0"
|
||||
entry = "src/main.aji"
|
||||
|
||||
[modules]
|
||||
app.model = "src/model.aji"
|
||||
app.work = "src/work.aji"
|
||||
```
|
||||
|
||||
Mapping keys MUST be ASCII identifier components separated by dots and MUST NOT occupy standard/built-in namespaces (spec 15 §14). Duplicate keys remain manifest errors. With this section present, `entry` is required and MUST name `.aji` source; entry/mapped paths MUST be nonempty portable relative paths with `/` separators and no empty, `.` or `..` component, backslash, colon or NUL. They MUST end in `.aji`. Every directory component and source file MUST be opened without following symlinks, relative to the selected manifest directory; that directory is the operator-selected root. Directory/file handles stay open while descending/reading to avoid substituting an ancestor with a symlink. Nonregular sources MUST be rejected. Unsupported safe no-follow behavior MUST fail rather than silently read outside the package.
|
||||
|
||||
The loader MUST read entry first, then mapped files in lexicographic module-name order into fixed compilation inputs. All mapped files are explicit build inputs and MUST be readable even if unreachable; only the reachable graph is parsed/linked (spec 15 §14). No source is executed during loading. The manifest is limited to 1 MiB, at most 1,024 mapped modules and the total source snapshot to 64 MiB. Invalid bindings/paths, unavailable files, symlinks, input limits and other I/O errors use the existing usage/I/O error contract (exit 2 before verification); source graph/name/type errors are verification rejection (exit 1, JSON diagnostics). Manifests without `[modules]` retain their entry-loading contract.
|
||||
|
||||
Commands accept one file or `--manifest PATH`, never both. Check/lower/report never grant program authority; run/explore instantiate only with explicitly selected manifest grants and command-line overrides. No implicit manifest discovery is allowed.
|
||||
|
||||
## 2. Reproducibility
|
||||
|
||||
Given the same:
|
||||
|
||||
@@ -29,7 +29,7 @@ It MUST NOT hide:
|
||||
|
||||
Rules:
|
||||
|
||||
1. Lowering is a pure function of the source: the same module gives byte-identical canonical AIR (spec 07 §8.5).
|
||||
1. Lowering is a pure function of its explicit source inputs: the same module graph gives byte-identical canonical AIR (spec 07 §8.5).
|
||||
2. No source construct admits a program whose AIR the verifier rejects. Errors the verifier would find are reported with the verifier's code (§9).
|
||||
3. `.aji` 0.1 covers the published features of Phases 0–3 and nothing else.
|
||||
4. Every construct has **one canonical spelling**. There are no alternative forms of the same operation.
|
||||
@@ -58,6 +58,7 @@ effects [io.read, io.write]
|
||||
```
|
||||
|
||||
- A file holds one module: `module <dotted.path>`, then type and function declarations in any order.
|
||||
- Between the module header and declarations, `import <dotted.path>;` imports a standard (§13) or explicitly supplied package module (§14). `import` is contextual at this position; it remains an ordinary identifier elsewhere.
|
||||
- `//` starts a line comment.
|
||||
- Function `f` lowers to `@f`; type `T` to `@T`.
|
||||
- **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then the body block.
|
||||
@@ -75,7 +76,7 @@ The AIR spellings are used (spec 07 §8):
|
||||
- integers `u8`…`u128`, `usize`, `i8`…`i128`, `isize`; `bool`, `void`, `never`;
|
||||
- named types;
|
||||
- `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`;
|
||||
- `own<T>`, `own_array<T>`, `region`;
|
||||
- `own<T>`, `own_array<T>`, `buffer<T>` (§17), `region`;
|
||||
- `cap<K>`;
|
||||
- `file<read|write|append>`, `listener`, `stream`;
|
||||
- `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>`;
|
||||
@@ -158,7 +159,7 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
|
||||
|
||||
6A has no destructuring: no `let Point { x, y } = p`, no nested patterns, guards or or-patterns.
|
||||
|
||||
**Calls.** `f(args)` calls a function of the module. Built-in operations are called by their AIR names (§7, §8). Arguments are evaluated left to right.
|
||||
**Calls.** `f(args)` calls a local function; a directly imported function uses its full path (§13–§14). Built-in operations are called by their AIR names (§7, §8). Arguments are evaluated left to right.
|
||||
|
||||
**Borrows and places.** A place is:
|
||||
|
||||
@@ -178,7 +179,7 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
|
||||
| `s.len` | `slice.len`, or the static length of an array |
|
||||
| `s[a..b]` | a sub-slice (`slice.sub` with start `a`, length `b - a`); a borrow, so it is bound or passed, never a value |
|
||||
| `let (left, right) = s.split_at(k);` | `slice.split`: two disjoint borrows of `s`. Besides `atomic.compare_exchange` (§12), the only multi-result binding. There is no general tuple destructuring. |
|
||||
| `slice.copy(mut dst, ref src)` | `slice.copy`, the only copy form |
|
||||
| `slice.copy(mut dst, ref src)` | primitive `slice.copy`; insufficient capacity traps. Recoverable byte copy is `std.bytes.copy` (spec 16 §2.4). |
|
||||
|
||||
**Writes.**
|
||||
|
||||
@@ -198,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<u8>` is expected, it is borrowed for the operation.
|
||||
|
||||
@@ -234,10 +235,11 @@ match io.stdin_read(input, mut buf) {
|
||||
|
||||
- **Match kinds.** The parser decides the kind of a `match` from its arms: `Enum::Variant` arms make an enum match, integer literals and `_` an integer match, and bare outcome names (`ok`, `err`, `closed`, `cancelled`, `pending`) an outcome match. Outcome names are not enum patterns. In an outcome match the scrutinee MUST be a fallible operation (`E7006` otherwise). Each outcome is matched exactly once: a repeated one is `E7006`, an unknown one `E7002`, a wrong number of bound names `E7005`. A fallible operation outside an outcome match or `or trap` is `E7006`.
|
||||
- **Outcome values.** `err(e)` binds the real error value (`alloc_error`, `cap_error`, `io_error`). These built-in enums are matched like declared ones: `alloc_error::out_of_memory`, exhaustive, no `_`. A borrow bound by an outcome (the `ok(item)` of `region.new`) ends at the end of its arm. A borrow bound by `let item = region.new(arena, v) or trap;` ends at the end of the enclosing block.
|
||||
- **Error construction.** Every registered built-in error variant is also a payload-free expression, e.g. `let e = alloc_error::budget_exceeded;`. It lowers to `error.const` with feature `error_values` and its dependency closure (spec 05 §14), requires no effects or capabilities and changes no resource state. Unknown variants are `E7002`, payload arguments `E7005`; errors are Copy data and cannot confer authority.
|
||||
- **Rebinding.** A value that comes back on an edge is rebound by the name in its arm: `closed(v)`, `pending(rx)`, `cancelled(t)`. If that name is a variable (`var`) of the value's type, the value becomes the variable's new value. A receiver kept in `var r` is closed with `match channel.close_receiver(move r) { ok => …, pending(r) => … }` and received from again.
|
||||
- **`or trap`.** `op(args) or trap` is the expression of the `ok` value, or of `void`. Every other outcome traps (`T0001`). It is the only shorthand.
|
||||
- **Enums.** A `match` over a value of an enum type has exactly one arm per variant, each written `Enum::Variant(names…)` (`Enum::Variant` without payload). It must be exhaustive (`E7004` lists the missing variants), and `_` is not allowed (`E7006`), so a new variant cannot slip through silently. Payload names are bound only inside their arm (they are the arm block's parameters in AIR). It lowers to `enum.switch`.
|
||||
- **Integers.** A `match` over an integer has literal arms and exactly one `_` arm, which is required (`E7004`). It lowers to `switch`.
|
||||
- **Integers.** A `match` over an integer has literal arms and exactly one `_` arm, which is required (`E7004`). Pattern values MUST fit the scrutinee type (`E7005`); different spellings of the same value are duplicate arms (`E7006`). It lowers to `switch` with canonical decimal literals, without source suffixes or separators.
|
||||
- **Booleans** use `if`.
|
||||
- **As expressions.** `match` and `if` are expressions when their arms yield values (§4). Every arm must have the type of the others, or diverge.
|
||||
- **Source map.** The switch maps to the `match`; each arm's code and its branch to the join map to that arm.
|
||||
@@ -253,7 +255,7 @@ scope s {
|
||||
|
||||
**`scope s { … }`** is `task.scope.begin` and `task.scope.end`, at every normal exit of the block. Inside it:
|
||||
|
||||
- `task.spawn(s, f, args)` spawns `f` (a function of the module) into the scope `s`. Arguments are passed like call arguments: a named linear value is `move`d (`E7003`). A borrow argument is lent until the join (spec 04 §34), so it is a borrow binding passed by name (`mut part = buf;` … `task.spawn(s, f, part)`). A borrow or byte string written inline is `E7006`, because a temporary would have to end right after the spawn. The first operand must be the scope (`E7005`);
|
||||
- `task.spawn(s, f, args)` spawns `f` (a local or directly imported qualified function, §14) into the scope `s`. Arguments are passed like call arguments: a named linear value is `move`d (`E7003`). A borrow argument is lent until the join (spec 04 §34), so it is a borrow binding passed by name (`mut part = buf;` … `task.spawn(s, f, part)`). A borrow or byte string written inline is `E7006`, because a temporary would have to end right after the spawn. The first operand must be the scope (`E7005`);
|
||||
- `task.join(move t)` joins; its value is the task's result (`task<T>` gives `T`);
|
||||
- a task that is not joined at an exit is `E4301`.
|
||||
|
||||
@@ -361,7 +363,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<T>`, `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<u8>` is expected is materialized in frame storage and borrowed for the operation.
|
||||
|
||||
@@ -425,10 +427,13 @@ Its diagnostics keep their AIR codes, reported at the source location.
|
||||
| `aji lower --stats file.aji` | source and AIR size, expansion ratios and the two `mechanical_air_eliminated` metrics below |
|
||||
| `aji lower --annotate file.aji` | the same with `; line:col-line:col` source spans before each instruction (not canonical; for debugging) |
|
||||
|
||||
Lowering is deterministic: the same source and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test.
|
||||
`check`, `lower`, `report`, `run` and `explore` also accept `--manifest PATH` for explicit package inputs (§14, spec 12 §1.3). Check/lower/report do not instantiate grants.
|
||||
|
||||
Lowering is deterministic: the same source inputs and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test.
|
||||
|
||||
**Size metrics** (`--stats`, non-normative tooling with a fixed definition):
|
||||
|
||||
- With `--manifest`, source sizes count the entry file only; AIR sizes count the combined module. These ratios MUST NOT be interpreted as whole-package compression.
|
||||
- Sizes count code only: non-empty lines that are not comments (`//` in source, `;` in AIR), each with its newline.
|
||||
- `mechanical_air_eliminated_raw` = 1 − `source_bytes` / `air_bytes`: how much of the AIR text the author did not write. This is the main engineering metric.
|
||||
- `mechanical_air_eliminated_normalized` = 1 − `source_bytes` / `air_bytes_normalized`: the same against AIR in which every byte-string materialization counts as one logical constant operation. Such a materialization is the instructions from the string's `local.zero` to its final `borrow.end`, a store per non-zero byte, because format 0 has no byte-array constant. It is replaced by the single notional line ` const.bytes %<storage>, <literal>`, where `<literal>` is the canonical spelling: printable ASCII as is, otherwise the escapes `\n \r \t \0 \\ \" \xNN`. The storage's `local.alloc` is real frame storage and stays. No other instruction is normalized. The rule is the same for every program, and `byte_string_constants` reports how many were replaced.
|
||||
@@ -466,3 +471,116 @@ Other rules:
|
||||
|
||||
- `*c` and any other ordinary read of a cell is `E4202`.
|
||||
- Effects are declared by the programmer (spec 05 §13).
|
||||
|
||||
## 13. Built-in standard modules
|
||||
|
||||
The compiler MUST provide the standard modules listed in spec 16 §2, pinned to its own version. An import of `std` or a `std.*` path MUST resolve only against that closed registry: no file-system search, environment variable, network fetch, package manifest, or build extension participates. Unknown modules are `E7002`; duplicate imports are `E7006`. Imports MUST precede declarations; a misplaced import or missing semicolon is `E7001`.
|
||||
|
||||
An imported standard function is called by its full path, for example `std.bytes.equal(ref a, ref b)`. An unknown member or a call without the corresponding import is `E7002`. Importing a module MUST NOT introduce unqualified names or aliases. Qualified standard calls MUST NOT resolve through a local binding named `std`. User functions with the same short name remain independent. Standard functions are ordinary function calls: their argument types, borrows, moves, effects and failure contracts follow the existing rules. Type arguments on these monomorphic functions are rejected (`E7006`, §15).
|
||||
|
||||
Lowering MUST append the complete non-generic type and function declarations of the imported modules after the program's declarations, in lexicographic module order and source declaration order within each module. For a type or function `f` in module `m`, the AIR name starts as `__aji_` plus `m` with dots replaced by underscores, then `_f`. If that name collides with a program type/function or a previously linked standard declaration, the compiler MUST append the smallest positive decimal suffix `_1`, `_2`, … that is unused. Qualified source calls MUST use the resulting AIR name. This is name mangling, not an extension to the format-0 identifier grammar. Generic templates follow §15. The imported source is parsed and lowered as ordinary safe `.aji` and the combined AIR MUST pass the same verifier. No runtime dispatch or new AIR instruction is introduced. The feature header is the dependency closure of the combined module, including unused imported functions.
|
||||
|
||||
Imports grant no authority, perform no runtime initialization and allocate no program heap memory. Merely importing a module does not add effects to the caller's contract; calling an effectful function would require its declared effects under the usual call rule.
|
||||
|
||||
Canonical AIR MUST be independent of import order, working directory and execution profile for a fixed compiler and program. Source diagnostics and traps inside a standard function MUST identify its stable repository-relative source path (spec 16 §2) and its original line/column, rather than the program's path. `aji lower --annotate` MUST include that path on annotations for imported instructions. AIR locations remain available as in §10.
|
||||
|
||||
Standard enum types are named by their full path, for example `std.bytes.ReadU32`. In type annotations, constructors and match patterns, that path MUST resolve only to a type from an explicitly imported standard module. An unknown module/type or missing import is `E7002`. Importing a module MUST NOT introduce short type names. Standard declarations with the same short names as user types remain distinct.
|
||||
|
||||
A constructor or pattern is written `std.bytes.ReadU32::ok(value)` or `std.bytes.ReadU32::short_input`. Constructors, payload typing and exhaustive enum matches obey §5/§6 without a library-specific exception. A wrong payload or variant from another enum is `E7005`, an unknown variant `E7002`, a missing arm `E7004`, and duplicate/wildcard enum arms `E7006`. These are ordinary Copy enum values; this increment does not add a must-use or linear-result rule. Source type diagnostics MUST name standard types by their public qualified source path, including inside compound types; AIR output still uses the generated identifiers. Library source uses the same full type paths in signatures, constructors and matches. Standard types lower with the collision-free naming rule above; their declarations precede function declarations as in §2.
|
||||
|
||||
The standard registry exports ordinary structs/enums and their generic templates (§15). Qualified named types and enum variants introduce no member methods, reflection, dependency resolution or aliases. Generic standard forms use §15. Package modules and qualified struct literals are specified in §14.
|
||||
|
||||
## 14. Package source modules
|
||||
|
||||
### 14.1 Explicit inputs and graph
|
||||
|
||||
The frontend MUST take an entry source and an explicit mapping of module names to source bytes and diagnostic file paths. Its compilation MUST be a pure function of those inputs and compiler version. The CLI supplies the mapping only from an explicitly selected manifest's `[modules]` (spec 12 §1.3); a file-only invocation has no package mapping and MUST NOT discover a manifest. No parent search, directory scan, environment search path, network access, dependency fetch or build script participates. Standard imports continue to use §13's compiler-pinned registry and MUST NOT be shadowed by the package mapping.
|
||||
|
||||
Each mapped source MUST declare exactly its mapped module name. An imported source need not define `main`; only the entry's unqualified `main` is the program entry. A module's own function named `main` is an ordinary qualified function. All top-level declarations and fields are available through explicit import; no visibility modifier or re-export is introduced. Modules have no executable top-level initialization.
|
||||
|
||||
Imports form an acyclic directed graph. The linker MUST parse each reachable module once, reject self-import/cycles, duplicate imports, duplicate mappings and mismatched headers with `E7006`, and unknown imports with `E7002`. Source syntax errors in a package module use `E7001` at that module's file/line/column. Imports are visited in source order for first-error selection; all complete non-generic declarations of reachable modules, including unused functions, enter verification; templates follow §15. Unreachable mapped source is not parsed or linked. Compiler input limits are 1,024 mapped modules and import depth 256; exceeding them is `E7006`. These are fixed implementation input limits, not runtime fuel or semantics-changing flags.
|
||||
|
||||
Module names use source paths. The first component of a package mapping MUST NOT be `std` or a namespace of a built-in operation (`slice`, `own`, `buffer`, `region`, `cap`, `task`, `channel`, `mutex`, `island`, `frozen`, `arc`, `atomic`, or the first component of a registered intrinsic). Such a mapping is `E7006` (a manifest error at the CLI). Root source names retain their existing grammar; duplicate entry/module identity is rejected when imported.
|
||||
|
||||
### 14.2 Names and types
|
||||
|
||||
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<app.model.Pair>` 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.
|
||||
|
||||
### 14.3 AIR, safety and compatibility
|
||||
|
||||
Entry declarations retain their existing AIR names. Imported declarations use §13's collision-free mangling, with all reachable standard/package modules appended in lexicographic module order and source order within each module. Type declarations still precede functions. Valid canonical AIR MUST be independent of import order, mapping order, directory/profile and source file paths for identical source bytes and module bindings. Whole-graph AIR feature closure is explicit as before. Source provenance MUST use each imported source's supplied file path; the CLI supplies its manifest-relative path. AST module identity is distinct from a diagnostic path, so coinciding file labels cannot change name resolution.
|
||||
|
||||
The combined AIR MUST pass the ordinary verifier and runs as a single format-0 module. There is no new opcode, AIR feature, verifier state, runtime primitive, initialization, implicit heap allocation or authority. Existing enum/struct layout, alias, initialization, borrow, ownership, resource, task and effect transfer functions apply across module calls unchanged. All return/cleanup paths remain explicit; imported code is not trusted by virtue of its module. Existing file-only and standard-only programs retain their lowering and behavior. Package imports require the new explicit mapping; previous unknown import paths become valid only when supplied.
|
||||
|
||||
## 15. Explicit source generics
|
||||
|
||||
### 15.1 Declarations and applications
|
||||
|
||||
Functions, structs and enums MAY declare 1–8 type parameters immediately after their name, e.g. `fn identity<T>(value: T) -> T effects [] { return value; }`, `struct Pair<T: Copy> { left: T, right: T }`, `enum Option<T: Copy> { some(T), none }`. Parameters MUST be distinct uppercase identifiers, MUST NOT shadow a visible type/builtin type, and have no default. Constraints are optional compiler-known `Copy`, `Send`, `Share`, `Freeze` or `Local`, joined by `+`; repeated/unknown constraints are `E7006`. Generic `main` is forbidden (`E7006`). No user traits, overloads, type inference, const/lifetime/effect parameters or specialization overrides are introduced.
|
||||
|
||||
Every generic use MUST supply exactly its ordered arguments (type arguments here; static function arguments in §18). Type annotations use `Pair<u64>`; expression applications use `identity::<u64>(42)`, `Pair::<u64> { left: 20, right: 22 }` and `Option::<u64>::some(42)`. Enum patterns use `Option::<u64>::some(value)` and `Option::<u64>::none`. The `::<...>` spelling separates generic application from comparisons; bare `f<T>(...)` is outside the expression grammar. Qualified forms obey §14's direct-import rules. `task.spawn(s, worker::<u64>, ...)` statically specializes the worker; this creates no function value. Existing `channel.make<T>(...)` 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; type parameters are types, not values or operations; static function parameters are separately defined in §18. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT bypass the member restrictions; linear members require §16, and borrowed aggregate members remain forbidden.
|
||||
|
||||
Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity, effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source.
|
||||
|
||||
### 15.2 Structural constraints
|
||||
|
||||
Constraints are requirements on concrete types, not compiler authority to infer effects or repair ownership. `Copy` follows existing value duplication: scalars, built-in enums, capabilities, `iref` and aggregates of Copy values; borrows and linear values are not Copy. `Send` and `Share` use exactly spec 04 §35. In format 0, `Freeze` is exactly `IslandSafe` (spec 03 §22): plain content accepted by deep graph conversion, including `iref`; it does not promise conversion of owners/resources/wrappers. `Local` identifies context-bound `task`, `scope`, `shield` and `guard` (and internal local storage); it propagates through borrows, own/own_array/buffer/mutex wrappers and arrays/aggregates containing Local content. Scalars, authority, resources, regions, endpoints and graph owners/handles are not Local. Local is not the complement of Send. No unsafe/manual property declarations are added.
|
||||
|
||||
A type can satisfy several constraints; each requirement MUST be checked. Constraints add no operations or trait dispatch: a body using arithmetic with `T: Copy` still requires an arithmetic-compatible concrete specialization. Effects, `from`, `move`, lends and cleanup remain explicit in every specialization.
|
||||
|
||||
### 15.3 Deterministic monomorphization and safety
|
||||
|
||||
A specialization is keyed by template module identity, declaration kind/name and the ordered structural identity of concrete arguments. Named arguments use nominal defining-module identity, independent of source filename, short/qualified spelling or import/provider order. Each key MUST emit at most one concrete declaration; repeated same-key recursion reuses it. Type-specialization cycles still obey ordinary finite-layout rules. Expanding specialization is bounded by 4,096 generated declarations and active expansion depth 64 (`E7006`), with structural type traversal bounded at depth 64. These are fixed compiler input limits, not runtime fuel or semantic flags.
|
||||
|
||||
Non-generic declarations retain their AIR names and order. Generated types and functions append in lexicographic specialization-key order within their categories. Their AIR identifier starts with `__aji_g_` followed by lowercase SHA-256 of the canonical key bytes; collisions with original names or earlier keys in sorted order receive the smallest unused `_1`, `_2`, … suffix. The canonical key is `type:` or `fn:`, full defining-module/declaration path, and ordered `<...>` arguments. Named arguments use full nominal paths, applied arguments recursively spell their template/arguments, arrays spell `[T;N]` with decimal N, wrappers/cap/file spell `name<T>`; argument separators are commas without whitespace. Full keys, not hashes, determine identity and reuse. Keys are limited to 16,384 bytes (`E7006`). Every required body lowers to existing format-0 constructs, and the combined module MUST pass the ordinary verifier. There is no new AIR instruction/feature, verifier transfer state, runtime dispatch, implicit allocation/refcount/destructor, effect inference or authority. Source provenance retains template locations and the locations of supplied argument types. Generic borrow/owner/task contracts use the existing runtime/interpreter rules unchanged. Existing monomorphic source and AIR retain meaning and canonical lowering. The finite-layout verifier now visits array elements as well as direct nominal members, closing a prior E1003 implementation gap without changing the normative no-recursive-value rule. Existing unimplemented source `from`-returns remain unimplemented; specialization retains their contract rather than inventing borrow lifetimes.
|
||||
|
||||
## 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.
|
||||
|
||||
|
||||
## 17. Source dynamic buffers
|
||||
|
||||
`buffer<T>` is the linear initialized-prefix owner of spec 03 §26. Built-ins use ordinary explicit borrows, moves and outcome matches: `buffer.new<T>(capacity, heap)`, `buffer.len(b)`, `buffer.capacity(b)`, `buffer.reserve(b, capacity, heap)`, `buffer.push(b, move value)`, `buffer.pop(b)` and `buffer.free(move owner)`. Except new/free, b MUST be a named ref/mut<buffer<T>> binding, borrowed first from an owner or aggregate field. Mutating operations require mut. len/capacity accept ref or mut. new/reserve declare mem.alloc explicitly. push requires no heap capability and never grows implicitly.
|
||||
|
||||
Outcomes: new has ok(buffer)/err(alloc_error); reserve has ok()/err(alloc_error); push has ok()/err(original_value); pop has ok(value)/err(); free has ok()/err(original_buffer). Ordinary exhaustive outcome matching/or trap applies. A returned linear value MUST be explicitly consumed. `ref values = buffer.view(b);` binds a shared slice from ref or mut b; `mut values = buffer.view(b);` requires mut b and binds an exclusive slice. The child borrow lasts for its explicit lexical scope and never escapes through an aggregate. This is a primitive borrow binding like graph access, not a general function returning a borrow (Q-034 remains open). Existing indexing/value.swap provides Copy reading and complete linear element exchange. Views expose only the initialized prefix; mutation/growth/free while a view or task loan is live MUST reject even on a dynamically full/empty/no-op branch.
|
||||
|
||||
A specialized generic body MAY use `move name` to express complete value transfer for a type parameter. If its concrete binding is Copy, lowering passes the existing Copy value and it remains available; if linear, ordinary transfer/availability applies. This rule applies to complete Copy bindings inside a specialized generic body, not borrows or internal storage/scope/guard/shield handles. A Copy value bound in frame storage remains a Copy value and is loaded normally when transferred. Outside a specialized generic body, move of a Copy value remains E7006. No AIR ownership rule changes and no implicit destructor/allocation is added. This makes one generic container body correct for both Copy and linear contents; ordinary borrow/effect/type constraints still apply to every specialization.
|
||||
|
||||
The frontend MUST emit linear_buffers and its full dependencies for buffer types/operations. Existing syntax suffices apart from admitting the buffer wrapper and the typed built-in allocator with the existing channel.make<T> type-argument form. General methods, borrowed aggregate storage, recursive ownership and from-return calls are not added.
|
||||
|
||||
## 18. Static function parameters
|
||||
|
||||
Generic structs, enums and functions MAY declare a static function parameter alongside type parameters: `F: fn(ref<T>) -> u64 effects []`. This is a compile-time contract, not a value type. Its ordered parameter types, return type and complete flat effect set MUST be explicit. Static function parameter names MUST be uppercase, distinct, and MUST NOT shadow a visible type or function. All types are checked/substituted like ordinary function signatures; all effect atoms MUST be registered and unique. Borrow returns and `from` contracts are outside this increment (Q-034). A callable parameter MUST NOT carry structural property constraints or be used as a type. The existing maximum of eight generic parameters counts both kinds.
|
||||
|
||||
An explicit argument is `fn path`, or `fn path::<arguments>` for a generic function. The path MUST resolve to a directly accessible declared source function. Built-in operation names, runtime values and captures are not function arguments. `fn F` forwards an already bound static parameter; it cannot be specialized again. A type argument in a function position or a function argument in a type position is `E7005`. Wrong generic arity remains `E7006`; unknown/inaccessible functions remain `E7002`. Signature/effect mismatch diagnostics include `parameter`, `function`, `expected` and `found` contracts.
|
||||
|
||||
After substitution, the selected function MUST have exactly the declared ordered parameter/return types and effect set (`E7005`). Effect order is irrelevant; widening/narrowing of effects or borrow types is not implicit. Exact effect contracts avoid effect shims and ensure that specialization cannot infer effects away from a public contract. Capabilities are ordinary explicit arguments; selecting a function grants no authority. A borrowed input retains ordinary read/exclusive access rules, and linear arguments retain explicit moves and consumption obligations.
|
||||
|
||||
The bound name MAY occur only as a direct call target or named `task.spawn` worker; normal arguments and explicit moves/borrows still apply. It MUST NOT escape into storage, aggregates, returns or runtime expressions (`E7006`). It MUST NOT be shadowed by a runtime binding in a specialized body or its signature (`E7006`). Static parameters have no runtime representation, capture environment, destructor, heap allocation or indirect dispatch. They are not inferred. Templates remain subject to the header/body distinction of §15.
|
||||
|
||||
Function identity, including explicit specialization arguments and defining module, MUST participate in the instance identity of both functions and types. In canonical keys a static argument spells `fn ` followed by the full defining-module/function path, including canonical `<...>` arguments when specialized. Thus two container types with different bound hash/equality functions are nominally distinct, even when their storage layouts agree. Linking retains direct-import restrictions and caller-site provenance for explicit arguments. Limits remain depth 64, 4,096 specializations and 16,384-byte instance keys, including argument/contract resolution; unresolved cyclic contracts MUST reject with `E7006`, never recurse without a bound.
|
||||
|
||||
Lowering MUST replace each bound call/worker with an ordinary named AIR function operand. No new AIR instruction, type, effect, capability, feature or verifier state is added: ordinary `call`, task checking, effects, borrows and ownership validate every resulting specialization. Existing AIR format-0 semantics and type-only source generics are unchanged. AIR equivalence and source rejection tests MUST cover static selection, nominal policy identity, authority, ownership, effects, imports and workers.
|
||||
|
||||
```aji
|
||||
fn identity(value: u64) -> u64 effects [] { return value; }
|
||||
fn apply<T, F: fn(T) -> T effects []>(value: T) -> T effects [] {
|
||||
return F(move value);
|
||||
}
|
||||
// In main: apply::<u64, fn identity>(42u64)
|
||||
```
|
||||
|
||||
General collections MAY use these explicit contracts for hash/equality/order operations. Their algebraic laws remain library preconditions; no compiler magic infers hashing or equality. This facility alone does not complete HashMap/HashSet or resolve their storage/API invariants.
|
||||
@@ -0,0 +1,399 @@
|
||||
# 16. Standard Library
|
||||
|
||||
## 1. Contract
|
||||
|
||||
The standard library SHOULD make CLI programs, storage components, network services and structured concurrent programs possible without external source dependencies. Scope and sequencing are tracked in `docs/plan/standard-library.md`; that roadmap does not imply that unimplemented APIs are available.
|
||||
|
||||
Standard APIs MUST expose allocation, authority, effects, ownership transfer and recoverable failure in their public contracts. Safe library source MUST pass the ordinary verifier. Unsafe or foreign implementations MUST use an explicit audited trusted boundary under spec 13; they MUST NOT masquerade as verified source. The library MUST NOT obtain ambient host authority.
|
||||
|
||||
APIs SHOULD offer one canonical operation for a common need, small documentation requirements, bounded memory behavior and stable repair guidance (spec 14 §8). Resource cleanup remains explicit. Pure byte/path transformations do not grant authority over files or sockets.
|
||||
|
||||
## 2. Bootstrap module registry
|
||||
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.hash`, `std.hashmap`, `std.hashset`, `std.heap`, `std.io`, `std.io.reader`, `std.io.writer`, `std.map`, `std.math`, `std.option`, `std.path`, `std.result`, `std.utf8`, `std.vec` and `std.deque`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/hash.aji`, `std/hashmap.aji`, `std/hashset.aji`, `std/heap.aji`, `std/io.aji`, `std/io/reader.aji`, `std/io/writer.aji`, `std/map.aji`, `std/math.aji`, `std/option.aji`, `std/path.aji`, `std/result.aji`, `std/utf8.aji`, `std/vec.aji` and `std/deque.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. Modules other than std.io/std.io.reader/std.io.writer implement deterministic algorithms in every profile and have no concurrency effects; std.io/std.io.reader/std.io.writer follow the profile I/O/blocking rules in §2.17–§2.18 and spec 11. Modules other than std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap and std.io/std.io.reader/std.io.writer declare effects [] and allocate no heap memory. std.io declares only the concrete I/O effects in §2.17 and allocates no heap storage. std.io.reader/std.io.writer declare mem.alloc only on new and the concrete file effects in §2.18 on read/write/flush/finish; their other operations allocate no heap. std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11, §2.13–§2.16); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
|
||||
|
||||
### 2.1 `std.math`
|
||||
|
||||
- `min_u64(a: u64, b: u64) -> u64` returns the smaller operand.
|
||||
- `max_u64(a: u64, b: u64) -> u64` returns the larger operand.
|
||||
- `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` returns `lower` below the range, `upper` above it, or `value` inside it. The inclusive range MUST satisfy `lower <= upper`; violation traps `T0002` before returning a value.
|
||||
|
||||
These are monomorphic functions, not a generic arithmetic facility. Checked/wrapping operators retain their existing semantics (spec 02); importing this module does not alter them.
|
||||
|
||||
#### 2.1.1 Recoverable unsigned arithmetic
|
||||
|
||||
For `T` equal to `u64` or `usize`, `checked_add_T(a: T, b: T)`, `checked_sub_T(a: T, b: T)` and `checked_mul_T(a: T, b: T)` return `std.math.U64Result` or `std.math.UsizeResult`, respectively:
|
||||
|
||||
```aji
|
||||
enum U64Result { ok(u64), overflow }
|
||||
enum UsizeResult { ok(usize), overflow }
|
||||
```
|
||||
|
||||
Each operation MUST return `ok(value)` exactly when its mathematical result is representable in T, and `overflow` otherwise. Unsigned subtraction underflow is `overflow`. A successful zero is distinct from overflow. `usize` uses the target pointer width (spec 02); no fixed-width maximum or implicit cast is allowed. These functions MUST NOT trap for any scalar operands, apart from the execution environment's fuel limit, including multiplication by zero. They allocate no heap and declare `effects []`.
|
||||
|
||||
The functions use ordinary Copy enums and the existing integer and enum rules, with no new verifier/runtime primitive. Failure is handled by an exhaustive qualified enum match; no must-use rule or intrinsic outcome shorthand is added. Normal `+`, `-`, `*` still trap on overflow; wrapping uses `+%`, `-%`, `*%`. The library MUST NOT add synonymous wrapping wrappers for these operators. Signed arithmetic and other widths are outside this monomorphic increment; general numeric APIs require separate contracts.
|
||||
|
||||
### 2.2 `std.bytes`
|
||||
|
||||
Inputs are byte slices, not encoded text. No UTF-8 validation or locale interpretation occurs. Read-only parameters are `slice<u8>`.
|
||||
|
||||
- `equal(a, b) -> bool`: true exactly when lengths and all bytes agree.
|
||||
- `compare(a, b) -> i8`: unsigned-byte lexicographic comparison; returns exactly `-1`, `0` or `1`. The shorter of two matching prefixes sorts first.
|
||||
- `find(data, byte: u8) -> usize`: index of the first occurrence; `data.len` when absent. A found index is valid only for the searched slice and exactly when the result is less than its length. Indexing retains the ordinary bounds-check rules (`T0008` for an absent result used as an index).
|
||||
- `starts_with(data, prefix) -> bool`, `ends_with(data, suffix) -> bool`: true for matching prefixes/suffixes, including empty ones; false when the candidate is longer than `data`.
|
||||
- `fill(dst: slice_mut<u8>, byte: u8) -> void`: writes every byte of `dst`, including zero writes for an empty slice.
|
||||
|
||||
The library MUST NOT read or write outside a passed slice and MUST NOT retain or return any borrow. The verifier enforces existing shared/exclusive borrowing, lifetime and bounds rules; there is no library privilege or new transfer function. Read-only functions only read their slices; `fill` writes only its exclusive slice. None consumes an owner or resource. These operations MUST NOT trap for valid byte slices and scalar operands, apart from the execution environment's fuel limit.
|
||||
|
||||
### 2.3 Endian reads and writes in `std.bytes`
|
||||
|
||||
The library provides `read_u16_le`, `read_u16_be`, `read_u32_le`, `read_u32_be`, `read_u64_le`, `read_u64_be`, and the corresponding `write_` functions. Width/order are part of the function name; no native-endian default exists. `le` is least-significant byte first; `be` is most-significant byte first. These functions operate on the beginning of the passed slice. To use an offset, pass an explicit sub-slice. There is no cursor state or alignment requirement.
|
||||
|
||||
Public result enums:
|
||||
|
||||
```aji
|
||||
enum ReadU16 { ok(u16), short_input }
|
||||
enum ReadU32 { ok(u32), short_input }
|
||||
enum ReadU64 { ok(u64), short_input }
|
||||
enum WriteResult { ok, short_output }
|
||||
```
|
||||
|
||||
These declarations belong to `std.bytes` and are named with that prefix (spec 15 §13). For width `W` and byte count `N = W / 8`:
|
||||
|
||||
- `read_uW_ORDER(src: slice<u8>) -> std.bytes.ReadUW` MUST return `short_input` when `src.len < N`, without reading elements. Otherwise it MUST return `ok(value)` decoded from exactly the first N bytes. Extra bytes MUST NOT affect the result. `value = Σ src[i] × 2^(8i)` for LE and `Σ src[i] × 2^(8(N-1-i))` for BE, for `0 <= i < N`.
|
||||
- `write_uW_ORDER(dst: slice_mut<u8>, value: uW) -> std.bytes.WriteResult` MUST return `short_output` when `dst.len < N` and leave every destination byte unchanged. Otherwise it MUST write exactly the first N bytes in the selected order, leave the remaining bytes unchanged and return `ok`.
|
||||
|
||||
Short slices are recoverable enum results, not traps. A successful zero value is distinct from a short input. These APIs declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. They have no concurrency or authority requirements beyond the ordinary slice borrow contract. All capacity checks precede all accesses/mutations. Valid slices and values MUST NOT produce bounds, arithmetic, cast or shift traps; interpreter fuel exhaustion remains an environment outcome.
|
||||
|
||||
The verifier uses the existing enum payload, call, shared/exclusive borrow, lifetime and bounds rules. There is no new transfer function, runtime primitive or AIR feature. Ordinary enum construction and exhaustive `enum.switch` lower the result handling. Existing `E7002`, `E7004`, `E7005`, `E7006`, `E2101` cover invalid names/matches/calls and aliasing. The behavior is identical in deterministic and hosted profiles. Existing AIR and the existing nine library operations retain their semantics; imported source receives additional declarations pinned to the compiler version.
|
||||
|
||||
### 2.4 Bounded copy, substring search and splitting
|
||||
|
||||
`std.bytes.copy(dst: slice_mut<u8>, src: slice<u8>) -> std.bytes.WriteResult` MUST return `short_output` when `dst.len < src.len`, leaving every destination byte unchanged and reading no source elements. Otherwise it MUST copy exactly `src.len` bytes into the beginning of `dst`, preserve remaining destination bytes and return `ok`. Empty input succeeds, including with an empty output. Capacity is checked before any copy. Source/destination overlap MUST be rejected by the existing shared/exclusive alias rules (`E2101`), even if the output is short or the slices are empty. This operation is not an overlap-safe move.
|
||||
|
||||
`std.bytes.find_slice(data: slice<u8>, needle: slice<u8>) -> std.bytes.FindResult` returns an ordinary Copy enum:
|
||||
|
||||
```aji
|
||||
enum FindResult { found(usize), not_found }
|
||||
```
|
||||
|
||||
It MUST return `found(index)` for the least index at which all needle bytes match, or `not_found` if there is no match. A found index satisfies `index <= data.len` and `needle.len <= data.len - index`. An empty needle MUST return `found(0)` for any data, including empty data, without reading elements. A needle longer than the data MUST return `not_found` without reading elements. Offsets are relative to the passed slice; a found index is an offset, not necessarily an index of a readable element. Search only reads shared slices, retains no borrow and never mutates its input. The reference implementation uses constant auxiliary storage and at most O(data.len × needle.len) byte comparisons; interpreter fuel still bounds execution.
|
||||
|
||||
Splitting at the first byte-string separator uses `find_slice`, then the existing explicit sub-slice or `split_at` forms (spec 15 §6). On `found(index)`, the left part is `data[0..index]`, the separator `data[index..index + separator.len]` and the right part `data[index + separator.len..data.len]`. On `not_found` the caller chooses how to handle an absent separator. An empty separator yields an empty left part and the whole data as the right part; repeated splitting with an empty separator needs a caller-defined progress rule. There is no standard split iterator, returned aggregate of borrows or hidden cursor. Single-byte splitting MAY use the existing `find` length sentinel, checked before slicing.
|
||||
|
||||
Both functions declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. Valid slices MUST NOT produce bounds or integer traps; fuel exhaustion remains an environment outcome. The invariant is existing shared-read/exclusive-write access within the supplied slices, with no partial mutation on a short-output result. Existing call, alias, lifetime, initialization, capacity/bounds and enum transfer functions apply, with no new privilege, diagnostic code, AIR feature or runtime rule. Deterministic and hosted profiles behave identically. Existing APIs and AIR format 0 retain their contracts.
|
||||
|
||||
### 2.5 UTF-8
|
||||
|
||||
`std.utf8` interprets UTF-8 as the shortest encoding of Unicode scalar values 0..0x10FFFF excluding 0xD800..0xDFFF, following RFC 3629 §3/§4. Unassigned scalar values, noncharacters, NUL and U+FEFF are valid. No normalization, replacement decoding, locale handling or BOM removal occurs.
|
||||
|
||||
```aji
|
||||
enum NextResult { ok(u32, usize), end, invalid_input }
|
||||
enum ValidateResult { ok, invalid_input(usize) }
|
||||
```
|
||||
|
||||
- `next(src: slice<u8>) -> std.utf8.NextResult` MUST return `end` exactly when src is empty. Otherwise it MUST decode only the first scalar: `ok(value, byte_count)` with 1..4 consumed bytes, or `invalid_input` if the first sequence is malformed or truncated. Trailing bytes after a successful first sequence MUST NOT affect that result. Iteration uses an explicit caller offset and a sub-slice, without retained cursor state or borrows.
|
||||
- `validate(src: slice<u8>) -> std.utf8.ValidateResult` MUST return `ok` for a wholly valid sequence, including empty input. Otherwise it MUST return `invalid_input(offset)` at the beginning of the first malformed or truncated sequence, relative to src, after the maximal valid prefix. The offset identifies the sequence's leading byte, not necessarily the bad continuation byte.
|
||||
|
||||
ASCII bytes 00..7F are single-byte scalars. Multi-byte leading bytes are C2..DF, E0..EF and F0..F4 with two, three or four total bytes, respectively. Continuations MUST be 80..BF; the second byte MUST be A0..BF after E0, 80..9F after ED, 90..BF after F0 and 80..8F after F4. These conditions reject overlong forms, surrogates and out-of-range scalars. Invalid input is a result, never replacement text or a trap. Validation and explicit iteration use O(src.len) work and constant auxiliary storage.
|
||||
|
||||
### 2.6 Supplied-buffer encodings
|
||||
|
||||
Both `std.encoding.hex` and `std.encoding.base64` export these ordinary Copy enums, distinct between modules:
|
||||
|
||||
```aji
|
||||
enum EncodeResult { ok(usize), short_output }
|
||||
enum DecodeResult { ok(usize), invalid_input, short_output }
|
||||
```
|
||||
|
||||
Each module provides `encode(dst: slice_mut<u8>, src: slice<u8>) -> EncodeResult` and `decode(dst: slice_mut<u8>, src: slice<u8>) -> DecodeResult`, with fully qualified result types. `ok(count)` MUST report the number of output bytes. Successful operations MUST write exactly the output prefix and leave remaining destination bytes unchanged; no terminator is appended. Empty input MUST succeed with `ok(0)` for any capacity, including zero.
|
||||
|
||||
Encoding MUST check full output capacity before writing. If the mathematical encoded length exceeds either usize or output capacity, it MUST return `short_output`, leaving the entire destination unchanged; guards MUST avoid intermediate overflow. Decoding MUST validate the entire input before any destination write. Malformed input MUST return `invalid_input`, even with insufficient output capacity. Valid input with insufficient capacity MUST return `short_output`. Both error results MUST leave the entire destination unchanged. Ordinary shared/exclusive alias rules (`E2101`) apply even on failure paths; overlapping input/output is not allowed. Guarantees about unchanged output apply to returned errors, not interpreter fuel exhaustion mid-operation.
|
||||
|
||||
#### 2.6.1 Hex
|
||||
|
||||
`std.encoding.hex.encode` MUST produce two lowercase ASCII hexadecimal digits per byte, most-significant nibble first, with mathematical length 2 × src.len. `decode` MUST accept exactly even-length sequences of ASCII digits 0..9, a..f or A..F, interpreting each pair as one byte. Mixed case is accepted. Odd lengths, separators, prefixes, whitespace and other bytes are `invalid_input`. There is no padding.
|
||||
|
||||
#### 2.6.2 Base64
|
||||
|
||||
`std.encoding.base64` uses RFC 4648 §4's standard alphabet `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`, with `=` padding, no line breaks and zero unused bits. Encoded length is 4 × ceil(src.len / 3). Implementations MUST check that this length fits without overflowing an intermediate such as an unconditional `src.len + 2`.
|
||||
|
||||
Decoding MUST accept only canonical standard Base64: input length divisible by four; alphabet symbols in every unpadded position; zero, one or two padding symbols only at the end; and zero unused low bits (four low bits in the second symbol for `==`, two low bits in the third for `=`). Padding is required for incomplete final groups, and omitted for complete groups. Whitespace, URL-safe `-`/`_`, extra/misplaced padding, incomplete groups and nonzero unused bits are `invalid_input`. Empty input is canonical. Invalid-input precedence and unchanged-output guarantees are those of §2.6.
|
||||
|
||||
### 2.7 Text/encoding safety and compatibility
|
||||
|
||||
Sections 2.5/2.6 use safe source, ordinary calls, integer operations, slices, local fixed-size tables and enums. They declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. Work is O(input length) with constant auxiliary storage. The preserved invariant is shared-read/exclusive-write access within supplied initialized slices, no escaping borrow and no mutation on returned encoding errors. Existing verifier call/alias/lifetime/bounds/initialization/enum rules and deterministic interpreter behavior apply without a privilege, new transfer function, diagnostic, AIR feature or runtime primitive. Valid slices MUST NOT produce bounds, arithmetic, cast or shift traps; malformed bytes and capacity failure are results. Deterministic and hosted profiles behave identically. Existing APIs, source syntax and AIR format 0 retain their contracts.
|
||||
|
||||
### 2.8 Supplied-buffer integer formatting
|
||||
|
||||
`std.fmt` provides `write_u64`, `write_i64`, `write_usize` and `write_isize`. Each takes `(dst: slice_mut<u8>, value: T)` with the named integer type T, and returns `std.fmt.WriteResult`, an ordinary Copy enum:
|
||||
|
||||
```aji
|
||||
enum WriteResult { ok(usize), short_output }
|
||||
```
|
||||
|
||||
The functions MUST produce the exact ASCII decimal representation of value: `0` for zero, no leading zeroes otherwise, and a leading `-` exactly for negative signed values. No plus sign, whitespace, padding, locale transformation or terminator is written. `usize`/`isize` use the target pointer width (spec 09 §9); all values, including signed minima and unsigned maxima, MUST be supported.
|
||||
|
||||
When dst can hold the complete representation, the function MUST write exactly that prefix, preserve every remaining byte and return `ok(count)` with its length, including any sign. Otherwise it MUST return `short_output` and leave the entire destination unchanged. Empty output always fails, including for zero. Capacity MUST be checked before any write. To append, the caller passes a sub-slice at an explicit offset and advances it only after success; no implicit cursor, returned borrow, growable string or format-string language is introduced. Text copying uses `std.bytes.copy`; byte-to-hex encoding remains `std.encoding.hex`.
|
||||
|
||||
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 Option and result
|
||||
|
||||
The compiler registry MUST also include `std.option` and `std.result`. They declare ordinary generic enums:
|
||||
|
||||
```aji
|
||||
enum Option<T> { some(T), none }
|
||||
enum Result<T, E> { ok(T), err(E) }
|
||||
```
|
||||
|
||||
`std.option.is_some<T: Copy>(value: Option<T>) -> bool` and `std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool` declare `effects []`, allocate no heap and classify the active variant. They neither extract nor implicitly consume any payload. Call them using spec 15 §15's explicit expression arguments, e.g. `std.option.is_some::<u64>(value)`. Types/constructors/patterns are fully qualified and require a direct import; exhaustive matches extract payloads through ordinary enum rules. `none` still requires a type argument. `err(E)` is an ordinary enum variant, not the intrinsic outcome shorthand.
|
||||
|
||||
Option/Result accept ordinary complete value payloads, including owners/resources/endpoints under linear_aggregates (spec 03 §25, source §16). Their class is structural: an owning specialization is linear even when the active variant is none or a Copy error. It MUST be explicitly moved and exhaustively consumed; unused linear payloads reject E3002. Borrow/storage/function-bound payloads remain forbidden by ordinary member/type rules. is_some/is_ok retain Copy constraints and MUST reject E7005 for linear arguments; they do not consume a resource merely to classify it. Match an owning value explicitly instead. Existing Copy specializations retain behavior. No implicit unwrap/default/conversion or cleanup is added.
|
||||
|
||||
|
||||
### 2.10 Explicit owning vectors
|
||||
|
||||
Compiler-pinned `std.vec` MUST provide `Vec<T> { storage: buffer<T> }` and ordinary result enums: NewResult<T> { ok(Vec<T>), err(alloc_error) }, PushResult<T> { ok, full(T) }, ReserveResult { ok, err(alloc_error) }, FreeResult<T> { ok, not_empty(Vec<T>) }, ReplaceResult<T> { ok(T), out_of_bounds(T) }. All payloads follow ordinary complete-value/linearity rules; no implicit destruction occurs. Fields are ordinary visible source fields, not an opaque trusted container.
|
||||
|
||||
Public functions use explicit `::<T>` specialization: new<T>(capacity:usize,heap:cap<mem.alloc>)→NewResult<T>; len<T>(value:ref<Vec<T>>)→usize; capacity<T>(value:ref<Vec<T>>)→usize; reserve<T>(value:mut<Vec<T>>,capacity:usize,heap:cap<mem.alloc>)→ReserveResult; push<T>(value:mut<Vec<T>>,item:T)→PushResult<T>; pop<T>(value:mut<Vec<T>>)→std.option.Option<T>; free<T>(value:Vec<T>)→FreeResult<T>; get<T:Copy>(value:ref<Vec<T>>,index:usize)→std.option.Option<T>; replace<T>(value:mut<Vec<T>>,index:usize,item:T)→ReplaceResult<T>. Only new/reserve declare effects [mem.alloc]; all other functions declare effects [].
|
||||
|
||||
These are safe `.aji` wrappers over spec 03 §26. new chooses exact initial capacity, reserve chooses a minimum capacity without shrinking, and push never grows implicitly. len/capacity observe initialized length/backing capacity. pop removes the last complete value, returning none for empty. A full push returns the original item. get copies an in-bounds Copy item or returns none. replace exchanges an in-bounds initialized element and returns the previous item; out_of_bounds returns the original supplied item and preserves the vector. free releases only an empty vector; otherwise it returns the same vector. Returned owning result specializations need exhaustive match move; Copy results use ordinary matching. Callers drain and explicitly consume resource payloads before freeing.
|
||||
|
||||
Capacity/allocation failure, alias/task exclusion, deterministic profiles and diagnostics are those of buffer primitives and ordinary enum/call rules. Valid complete values include owners/files/endpoints; no collection bypasses Send/Share or channel_transfer gates. Imports grant no authority. HashMap/HashSet/BinaryHeap, owning strings and general borrowed function returns remain separate increments of STD-6.
|
||||
|
||||
### 2.11 Explicit owning deques
|
||||
|
||||
The compiler-pinned registry MUST include safe `std.deque` (`std/deque.aji`). Its ordinary type is `Deque<T> { storage: buffer<std.option.Option<T>>, head: usize, length: usize }`, always linear. It exports `NewResult<T> { ok(Deque<T>), err(alloc_error) }`, `PushResult<T> { ok, full(T) }`, `ReserveResult { ok, err(alloc_error) }`, `FreeResult<T> { ok, not_empty(Deque<T>) }` and `ReplaceResult<T> { ok(T), out_of_bounds(T) }`.
|
||||
|
||||
For a valid deque of capacity C, the backing buffer MUST have C initialized Option<T> slots. For C=0, head=length=0; otherwise head<C and length≤C, with head=0 when empty. Logical element i (0≤i<length) occupies `(head+i) mod C`; precisely those slots contain some(T), every other slot contains none. Each linear element is owned exactly once. Algorithms MUST compute indices without intermediate usize overflow. Fields follow ordinary source visibility: callers constructing or modifying the representation MUST preserve this invariant. Library operations preserve it; ordinary traps/bounds/ownership checks still apply to invalid caller representations, with no unsafe exemption or promise to validate the entire invariant on every call.
|
||||
|
||||
Every function supplies explicit `::<T>` specialization:
|
||||
|
||||
| Function | Parameters | Result / contract |
|
||||
|---|---|---|
|
||||
| new<T> | capacity: usize, heap: cap<mem.alloc> | NewResult<T>; exact capacity, empty queue |
|
||||
| len<T> / capacity<T> | value: ref<Deque<T>> | usize; logical length / capacity |
|
||||
| reserve<T> | value: mut<Deque<T>>, capacity: usize, heap: cap<mem.alloc> | ReserveResult; no shrink; successful growth preserves logical order and sets head=0 |
|
||||
| push_front<T> / push_back<T> | value: mut<Deque<T>>, item: T | PushResult<T>; insert at selected end, or full(original_item) with entire deque unchanged |
|
||||
| pop_front<T> / pop_back<T> | value: mut<Deque<T>> | std.option.Option<T>; remove/move selected end, or none with empty deque unchanged |
|
||||
| free<T> | value: Deque<T> | FreeResult<T>; empty frees all backing storage; nonempty returns same deque unchanged |
|
||||
| get<T: Copy> | value: ref<Deque<T>>, index: usize | std.option.Option<T>; copy logical element, or none out of bounds |
|
||||
| replace<T> | value: mut<Deque<T>>, index: usize, item: T | ReplaceResult<T>; return old logical element after complete exchange, or out_of_bounds(original_item) without mutation |
|
||||
|
||||
Only new/reserve declare effects [mem.alloc] and require cap<mem.alloc>. Each slot charges accounted_size(Option<T>) (the enum tag plus its largest payload), including free none slots. Growth uses buffer.reserve's old+new allocation peak; an allocation error MUST preserve head, length, capacity, every slot and ownership. After successful allocation the library initializes new slots to none and rotates the old ring using complete value.swap operations, with no second allocation. Requests≤C succeed without mutation. New/growth perform O(capacity) slot work; end operations, get/replace and metadata use constant slot work; freeing an empty deque drains its none slots in O(capacity). These are library slot-operation counts; the reference interpreter currently copies the initialized prefix in buffer.push, so construction/growth can have higher host cost. No native backend performance guarantee is added. Fuel exhaustion/traps are abnormal execution outcomes, outside returned-error preservation guarantees.
|
||||
|
||||
A full push and out-of-bounds replace return the exact original item. Callers MUST consume returned linear payloads. A nonempty free MUST NOT pop, close or destroy user elements; callers pop/consume all elements first. Empty free explicitly consumes only internal none slots before freeing its buffer. Ownership never escapes through a borrowed result. Valid calls add no program trap beyond the environment's execution limits. Existing linear availability, borrow/task-loan, bounds, generic Copy/Send/Share, effects and allocation rules verify the library as ordinary source; no new verifier state, AIR feature/opcode, runtime primitive, diagnostic, effect or authority is added. AIR format 0 and existing APIs retain meaning. Owners, files and channel endpoints follow the same rules as Vec; map/set/heap collections remain separate work.
|
||||
|
||||
### 2.12 `std.hash`: non-cryptographic bytes and checksums
|
||||
|
||||
The compiler registry MUST include `std.hash`, implemented in ordinary safe source. It exports exactly four monomorphic functions, all `effects []`:
|
||||
|
||||
| Function | Contract |
|
||||
|---|---|
|
||||
| `fnv1a64(data: slice<u8>) -> u64` | FNV-1a 64, initial state `0xcbf29ce484222325` |
|
||||
| `fnv1a64_extend(state: u64, data: slice<u8>) -> u64` | continue from the supplied FNV state |
|
||||
| `crc32c(data: slice<u8>) -> u32` | reflected CRC-32C (Castagnoli), initial/final XOR `0xffffffff` |
|
||||
| `crc32c_extend(checksum: u32, data: slice<u8>) -> u32` | continue from a finalized checksum, undoing and reapplying the final XOR |
|
||||
|
||||
FNV MUST process each byte in slice order by XOR with its zero-extended value, then multiplication by `0x100000001b3` modulo 2^64. CRC results MUST equal this recurrence: start with `checksum XOR 0xffffffff`, XOR each zero-extended byte into the low bits, and perform eight steps: shift right once, XOR `0x82f63b78` exactly when the previous low bit was one. Return the state XOR `0xffffffff`. `crc32c(data)` is `crc32c_extend(0, data)`. These numeric results do not depend on target byte order or pointer width; serialization uses explicit std.bytes endian operations. CRC-32C is distinct from IEEE CRC-32. FNV and CRC definitions follow [RFC 9923 §§2,5](https://www.rfc-editor.org/rfc/rfc9923.html#section-2) and [RFC 3720 Appendix B.4](https://www.rfc-editor.org/rfc/rfc3720.html#appendix-B.4), respectively; the rules above specify the API's numeric convention.
|
||||
|
||||
Empty input returns the supplied state/checksum; a fresh empty hash is the FNV offset basis or zero CRC. For any bytes A/B, extending hash(A) with B MUST equal hashing their concatenation. Any u64/u32 continuation value is valid; it need not come from a previous call. Input bytes including zero MUST all participate. No UTF-8 validation, terminator, implicit padding or field separator is introduced. The caller MUST encode field boundaries and scalar byte order when hashing structured data.
|
||||
|
||||
These operations MUST NOT allocate heap memory, mutate input, retain a borrow, obtain authority or consume an owner. They use ordinary slice bounds, immutable borrows and explicit wrapping arithmetic; no new verifier/runtime rule, diagnostic, AIR feature or unsafe boundary is introduced. Conflicting mutable access rejects under existing E2101; argument type errors use E7005 and missing imports/members E7002. Valid calls do not trap except ordinary execution limits. Time is O(data.len), auxiliary state O(1); the initial CRC implementation MAY use eight bit steps per byte rather than a lookup table. Deterministic and hosted profiles MUST return the same values, and existing APIs/AIR retain meaning. Hashes/checksums provide neither cryptographic authentication nor adversarial collision resistance and MUST NOT be used as key equality in a map.
|
||||
|
||||
### 2.13 `std.map`: bounded owning numeric-key map
|
||||
|
||||
The registry MUST include std.map, ordinary safe source. U64Map<V> stores exact u64 keys and complete V values; V MAY be Copy, an owner, file or endpoint subject to existing member/Send/Share rules. It does not implement general HashMap<K,V> hashing/equality (Q-037). Entry<V> has key: u64 and value: V. Ten operations use explicit `::<V>` specialization:
|
||||
|
||||
| Function | Result |
|
||||
|---|---|
|
||||
| `new<V>(capacity: usize, heap: cap<mem.alloc>)` | NewResult<V>: ok(U64Map<V>), err(alloc_error) |
|
||||
| `len<V>(map: ref<U64Map<V>>) -> usize` | live entries |
|
||||
| `capacity<V>(map: ref<U64Map<V>>) -> usize` | maximum live entries |
|
||||
| `reserve<V>(map: mut<U64Map<V>>, capacity: usize, heap: cap<mem.alloc>)` | ReserveResult: ok, err(alloc_error) |
|
||||
| `insert<V>(map: mut<U64Map<V>>, key: u64, value: V)` | InsertResult<V>: inserted, replaced(V), full(V) |
|
||||
| `contains<V>(map: ref<U64Map<V>>, key: u64) -> bool` | exact presence |
|
||||
| `get<V: Copy>(map: ref<U64Map<V>>, key: u64) -> std.option.Option<V>` | copy of value, or none |
|
||||
| `remove<V>(map: mut<U64Map<V>>, key: u64) -> std.option.Option<V>` | moving extraction, or none |
|
||||
| `pop<V>(map: mut<U64Map<V>>) -> std.option.Option<Entry<V>>` | first occupied physical slot, or none |
|
||||
| `free<V>(map: U64Map<V>)` | FreeResult<V>: ok, not_empty(U64Map<V>) |
|
||||
|
||||
Representation: U64Map<V> has storage: buffer<Slot<V>> and length: usize. Slot<V> has key: u64, state: SlotState and value: std.option.Option<V>; SlotState is the Copy enum empty/deleted/occupied. A logical capacity N uses exactly 2N initialized physical slots. buffer.len(storage) equals buffer.capacity(storage); length≤N equals occupied count; occupied slots contain some(V), other slots none; occupied keys are unique and reachable by the probing rule. Copy key/state fields are observable through ref without copying V. Ordinary visible fields have no special access protection; manual construction/mutation MUST preserve this invariant. Invalid representations retain ordinary ownership/bounds safety but need not preserve map behavior.
|
||||
|
||||
New creates all-empty slots. Only new/reserve declare effects [mem.alloc] and require cap<mem.alloc>; every other operation is effects [] and allocates no heap. Multiplication/charge overflow MUST return alloc_error.budget_exceeded before mutation. Each slot charges the key, SlotState tag and Option<V> tag plus maximum payload, including vacancies/tombstones; separately allocated V owners retain their own charges. Zero capacity succeeds with zero slots, no modulo; new-key insertion returns full(value). A key's hash is FNV-1a of exactly eight little-endian key bytes; the starting slot is that u64 hash modulo physical count. Probing visits at most the physical count and wraps without overflowing. Lookup passes deleted and stops at empty/end. Hash equality MUST NOT substitute for exact u64 equality; 0 and maximum u64 are valid keys.
|
||||
|
||||
Insert searches for an existing key before choosing its first deleted/empty slot. Existing-key replacement MUST succeed even at full logical capacity, returning the old complete V. A new key when full MUST return the exact input V without mutation. Deletion/pop exchange a complete Option<V> for none, mark deleted and return ownership; missing removal preserves all state. Tombstones need no implicit compaction. Tables with no empty slots MUST still terminate probes and reuse deleted slots without duplicate keys. pop order is physical-index order, deterministic for the complete history; successful rehash MAY change that order. No borrowed value or cursor escapes.
|
||||
|
||||
Reserve≤N is an unchanged no-op, retaining its explicit effect/capability/mut contract. Growth MUST allocate/initialize the entire new table before changing the original. Returned failure MUST preserve every old slot, metadata, key/value association and pop order. Peak quota includes both whole tables and existing user-owned allocations; old storage is refunded to its recorded authority even if a different capability funds growth. After successful allocation, transfer complete entries in old physical-index order, clear tombstones and explicitly free old internal vacant storage. No subsequent recoverable error is permitted; fuel/traps are abnormal outcomes outside returned-error preservation. Nonempty free MUST return the entire map; empty free MUST consume all internal none values and free the storage, never normally discarding an occupied/owning payload, including with corrupted caller metadata. Callers MUST consume returned linear replacements/full/remove/pop/not_empty results; no hidden destructor closes user resources.
|
||||
|
||||
Existing aggregate/enum moves, value.swap, slice bounds, borrow/task-loan exclusion, Copy/Send/Share, effects and allocation accounting verify this library without map-specific rules, diagnostics, AIR instructions/features or runtime behavior. Preflight size failures construct alloc_error values through error_values (spec 05 §14); map adds no further semantic feature. Bad moves/leaks/aliases/tasks/Copy uses retain E7003/E2002/E3002/E2101/E4101/E7005 and Share restrictions E4002. Valid operations do not trap except execution limits. Deterministic/hosted profiles agree; existing source/AIR/API meanings remain unchanged. Lookup/insert/remove are O(N) worst-case slot work, pop/free O(N), growth O(N²) worst-case collision work. Initialized-prefix copying may increase interpreter host cost; no native throughput guarantee or adversarial collision bound is added.
|
||||
|
||||
### 2.14 `std.hashmap`: bounded owning general-key map
|
||||
|
||||
The registry MUST include std.hashmap at std/hashmap.aji, ordinary safe source. `HashMap<K,V,H,E>` binds explicit static `H: fn(ref<K>) -> u64 effects []` and `E: fn(ref<K>,ref<K>) -> bool effects []` (spec 15 §18). K/V MAY be Copy, owners, files or endpoints under ordinary member/Send/Share rules. An applied type uses `HashMap<K,V,fn hash,fn equal>`; functions use `::<K,V,fn hash,fn equal>`. Distinct operation identities are distinct nominal map types. Entry<K,V> has key: K and value: V; both are returned/transferred completely, never implicitly destroyed.
|
||||
|
||||
The caller MUST supply deterministic, stable hashing and equality for live keys: E is an equivalence relation, and E(a,b) implies H(a)=H(b). Equality decides identity even when hashes collide. A stored key MUST NOT be modified in a way that changes its hash/equality; normal exclusive access rules still apply. These algebraic laws are explicit library preconditions, not compiler-proved properties. Hash/equality receive only shared key borrows, no capability or hidden state. User callback traps and fuel exhaustion are abnormal outcomes, outside returned-error preservation.
|
||||
|
||||
Ten operations are specialized by the four ordered arguments above (get additionally requires V: Copy):
|
||||
|
||||
| Operation | Result / transfer |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,V,H,E>: ok(HashMap<K,V,H,E>), err(alloc_error) |
|
||||
| len(map: ref<HashMap<K,V,H,E>>) -> usize | live entry count |
|
||||
| capacity(map: ref<HashMap<K,V,H,E>>) -> usize | maximum live entries |
|
||||
| reserve(map: mut<HashMap<K,V,H,E>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| insert(map: mut<HashMap<K,V,H,E>>, key: K, value: V) | InsertResult<K,V>: inserted, replaced(Entry<K,V>), full(Entry<K,V>) |
|
||||
| contains(map: ref<HashMap<K,V,H,E>>, key: ref<K>) -> bool | presence by actual key equality |
|
||||
| get(map: ref<HashMap<K,V,H,E>>, key: ref<K>) -> std.option.Option<V> | copied value; no K: Copy requirement |
|
||||
| remove(map: mut<HashMap<K,V,H,E>>, key: ref<K>) -> std.option.Option<Entry<K,V>> | moves complete stored key/value out |
|
||||
| pop(map: mut<HashMap<K,V,H,E>>) -> std.option.Option<Entry<K,V>> | moves the last dense entry out |
|
||||
| free(map: HashMap<K,V,H,E>) | FreeResult<K,V,H,E>: ok, not_empty(HashMap<K,V,H,E>) |
|
||||
|
||||
Only new/reserve declare effects [mem.alloc] and require explicit heap authority; all other functions declare effects [] and perform no heap allocation. Insert is bounded, never grows. Replacement succeeds at full capacity and returns the previous complete key/value; the supplied equivalent key becomes the stored key. A new key when full returns the exact supplied key/value with all storage unchanged. Missing removal leaves storage unchanged. Callers MUST consume owning replaced/full/remove/pop/not_empty payloads explicitly. No borrowed value/cursor escapes.
|
||||
|
||||
Representation: HashMap has entries: buffer<StoredEntry<K,V>>, buckets: buffer<Bucket>. StoredEntry has hash: u64, key: K, value: V. Bucket has hash: u64, index: usize, state: BucketState (empty/deleted/occupied). For capacity N, entries.capacity=N, entries.len=L≤N; buckets.capacity=buckets.len=2N. Every dense entry [0,L) has one occupied bucket whose hash/index agree; no other bucket owns or refers to a live entry. Cached hash equals H(key); live keys are pairwise unequal by E. Each occupied bucket is reachable by the probing rule. Keys/values have no vacancy sentinel or default value. Manual representation construction/mutation MUST preserve this invariant; invalid representations retain ordinary memory/ownership safety but may trap or violate map behavior.
|
||||
|
||||
Probe start is the unsigned u64 hash modulo the bucket count. Advance wraps without overflow, and at most bucket count probes occur. Lookup skips deleted and stops at empty/end; occupied hash equality is only a filter before E. Insert remembers the first deleted/empty slot but searches for an existing equal key before choosing it, including when full. Zero capacity never performs modulo and returns full on insert. Deleted-only tables remain bounded and reusable.
|
||||
|
||||
Removal exchanges the last dense entry into the removed entry's position when needed and repairs that moved entry's occupied bucket by its cached hash/index. Thus the initialized prefix always contains complete values; no uninitialized hole or partial move is introduced. pop consumes the last dense entry and marks its bucket deleted without invoking H/E. Pop order is reverse current dense order (insertion appends; replacement retains position; removal may exchange the last entry into a hole). This is deterministic for the history, not sorted order. Successful reserve preserves dense/pop order and clears tombstones. Nonempty free returns the entire map unchanged, based on actual entries.len, not forgeable length metadata. Empty free explicitly drains only Copy bucket metadata and frees both buffers; it cannot normally discard a key/value, even with invalid bucket metadata.
|
||||
|
||||
New checks 2N overflow, allocates the empty entry buffer, then the fully initialized bucket buffer. A returned second-allocation failure MUST free the temporary empty entry buffer and refund its recorded authority. Reserve≤N is an unchanged no-op with its declared mut/effect/capability requirements. Growth MUST allocate/initialize a new bucket buffer before calling ownership-preserving buffer.reserve on the dense entries. Any returned failure MUST free temporary metadata, preserve both original buffers, every key/value/hash/index/state and pop order, and refund all temporary charges. After entries reserve succeeds, only cached hashes are used to rebuild the new buckets; no further recoverable allocation or callback occurs. Swap in the new buckets and explicitly free the old Copy metadata buffer. Peak quota includes old/new entry buffers, old/new bucket buffers and separately charged user owners. All old storage refunds go to their recorded authorities, even when growth uses another capability. Arithmetic/allocation-size overflow returns alloc_error.budget_exceeded; no shrink occurs.
|
||||
|
||||
Each StoredEntry slot charges hash plus full K/V slot sizes, including uninitialized capacity; each Bucket charges hash, usize and state tag. Unused capacity reserves bytes but contains no live K/V. There is no tag/default key allocation and no implicit destruction. Existing initialized buffers, aggregate transfer/exchange, borrows/task loans, bounds, effects, Copy/Send/Share and quota verification suffice; no new AIR instruction/feature, source form, verifier/runtime state or diagnostic is added. Generic callback contracts are RFC 0029. Valid bookkeeping does not trap with a valid representation and successful callbacks. Existing API/AIR meanings remain unchanged, including std.map.U64Map. Deterministic/hosted behavior agrees. Probe operations are O(N) worst-case plus callback work, pop/removal repair O(N), reserve O(N²) worst-case collision work; buffer-prefix interpreter copying may add host cost. No adversarial collision or native throughput promise is made.
|
||||
|
||||
### 2.15 `std.hashset`: bounded owning general-key set
|
||||
|
||||
The registry MUST include std.hashset at std/hashset.aji, ordinary safe source. HashSet<K,H,E> binds the same exact pure ref-key hash/equality contracts and stable algebraic laws as std.hashmap (§2.14), with explicit type/application arguments `K,fn hash,fn equal`. It owns complete arbitrary K, including owning byte buffers, structs, resources and endpoints subject to existing member/Send/Share rules. Its representation is one field map: std.hashmap.HashMap<K,bool,H,E>, with every live value true; all underlying dense/probe invariants apply. No default key, implicit destruction or library access privilege is added.
|
||||
|
||||
Nine operations use the three ordered arguments above:
|
||||
|
||||
| Operation | Result / transfer |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,H,E>: ok(HashSet<K,H,E>), err(alloc_error) |
|
||||
| len(set: ref<HashSet<K,H,E>>) -> usize | live count |
|
||||
| capacity(set: ref<HashSet<K,H,E>>) -> usize | maximum live keys |
|
||||
| reserve(set: mut<HashSet<K,H,E>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| insert(set: mut<HashSet<K,H,E>>, key: K) | InsertResult<K>: inserted, present(original_input_K), full(original_input_K) |
|
||||
| contains(set: ref<HashSet<K,H,E>>, key: ref<K>) -> bool | exact membership |
|
||||
| remove(set: mut<HashSet<K,H,E>>, key: ref<K>) -> std.option.Option<K> | moving extraction of the stored key |
|
||||
| pop(set: mut<HashSet<K,H,E>>) -> std.option.Option<K> | moving extraction of last dense key |
|
||||
| free(set: HashSet<K,H,E>) | FreeResult<K,H,E>: ok, not_empty(HashSet<K,H,E>) |
|
||||
|
||||
Only new/reserve declare mem.alloc and take explicit heap authority. Insert checks membership before transferring to the underlying map: duplicate insertion MUST preserve the existing stored key and every entry/bucket, returning the exact input key as present, even when full. New-key full also preserves the set and returns its exact input. This gives one canonical insert contract; replacement requires explicit remove/insert by the caller. No automatic growth occurs. Owning present/full/remove/pop/not_empty results MUST be consumed. contains returns no borrow. Missing remove and nonempty free preserve all state. Pop order is the underlying reverse current dense order; removal may move the last key to a hole, and reserve preserves the order.
|
||||
|
||||
New/reserve failure, peak quota/refund, zero capacity, probing, collision equality, callback/fuel traps and visible representation invariants are exactly §2.14's rules. Each capacity slot charges hash plus complete K plus bool, and two buckets: for K=u64, N charges 51N bytes; separately owned K allocations remain separately charged. insert MAY evaluate H/E for membership and again for bounded map insertion; these pure stable operations grant no authority and cannot be inferred away. Once membership says absent, map replacement is unreachable under the valid representation/hash/equality laws; invalid laws may trap under ordinary abnormal-path semantics.
|
||||
|
||||
Existing buffers/aggregates/borrows, static callable identity, effects, Copy/Send/Share and ownership verification suffice. No new syntax, diagnostic, feature/opcode, verifier/runtime state, implicit allocation/destructor or trusted boundary is added. Deterministic/hosted behavior agrees and existing APIs/AIR meanings remain unchanged. Worst-case insertion/membership/removal/pop is O(N) plus callback work; growth is O(N²) worst-case collision work with existing interpreter prefix-copy costs. No sorted output, adversarial collision bound or native throughput promise is added.
|
||||
|
||||
### 2.16 `std.heap`: bounded owning binary heap
|
||||
|
||||
The registry MUST include std.heap at std/heap.aji, ordinary safe source. `BinaryHeap<T,B>` binds an explicit static `B: fn(ref<T>,ref<T>) -> bool effects []` (spec 15 §18), applied as `BinaryHeap<T,fn before>` and `::<T,fn before>`. T MAY contain owners, files or endpoints under ordinary member/Send/Share rules. Distinct bound operations give distinct nominal heap types. No default T, captured environment, runtime dispatch or implicit cleanup is added.
|
||||
|
||||
B(a,b) means a MUST precede b. B MUST be a stable strict weak order on live values: irreflexive and transitive, with transitive incomparability. Equivalent values have neither B(a,b) nor B(b,a); their extraction order is deterministic for a fixed operation sequence but MUST NOT be assumed stable. Changing a live value's relative order violates the representation precondition. Pure callbacks grant no authority; callback traps/fuel exhaustion are abnormal outcomes, with no returned-state preservation promise.
|
||||
|
||||
Eight operations use the two ordered arguments above; peek additionally requires T: Copy:
|
||||
|
||||
| Operation | Result / transfer |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<T,B>: ok(BinaryHeap<T,B>), err(alloc_error) |
|
||||
| len(value: ref<BinaryHeap<T,B>>) -> usize | live count |
|
||||
| capacity(value: ref<BinaryHeap<T,B>>) -> usize | maximum live count |
|
||||
| reserve(value: mut<BinaryHeap<T,B>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| push(value: mut<BinaryHeap<T,B>>, item: T) | PushResult<T>: ok, full(original_input_T) |
|
||||
| peek(value: ref<BinaryHeap<T,B>>) -> std.option.Option<T> | Copy root value, or none |
|
||||
| pop(value: mut<BinaryHeap<T,B>>) -> std.option.Option<T> | moving extraction of root, or none |
|
||||
| free(value: BinaryHeap<T,B>) | FreeResult<T,B>: ok, not_empty(BinaryHeap<T,B>) |
|
||||
|
||||
Only new/reserve declare mem.alloc and take explicit allocation authority. Push is bounded: full MUST preserve all state, return the exact input and evaluate no ordering callback; it never grows. Successful push/pop MUST restore the heap invariant; pop returns the root that preceded the operation, or none without mutation when empty. Peek copies only Copy T and retains no borrow. Nonempty free MUST return the complete unchanged heap. Every owning full/pop/not_empty result MUST be explicitly consumed.
|
||||
|
||||
The visible representation is `BinaryHeap<T,B> { entries: buffer<Entry<T>>, indices: buffer<usize> }`, `Entry<T> { position: usize, value: T }`. Both initialized lengths are L and capacities N, with L≤N. Indices form a permutation of 0..L; entries[indices[p]].position MUST equal p. For every nonroot p, B(value_at(p),value_at((p-1)/2)) MUST be false. Values are owned exactly once in the initialized dense prefix; unused capacity contains no live T. Copy indices permit sifting without copying owners, holes, temporary default values or borrowed enum payloads. Caller construction/mutation MUST preserve the complete invariant.
|
||||
|
||||
Push appends a complete entry and its Copy index, then sifts upward by swapping Copy indices and repairing positions. Pop removes the final Copy index, installs it at the root when nonempty, then sifts downward: compare the children, choose right only when it strictly precedes left, and swap only when the chosen child strictly precedes its parent. After ordering, pop the last dense entry; if it is not the removed root, exchange it into that dense hole and repair its Copy heap index using its recorded position. Return the complete removed T. Bounds and parent/child arithmetic MUST be checked before accesses; the nonleaf condition p<L/2 permits 2p+1 without overflow. No retained view escapes.
|
||||
|
||||
New allocates empty entries then empty indices; a returned second-allocation failure MUST free the temporary empty entries and refund its recorded authority. Zero capacity is valid. Reserve≤N is an unchanged no-op with its declared mut/effect/capability requirements. Growth MUST allocate a new index buffer and copy the old live indices before ownership-preserving buffer.reserve on entries. Any returned failure MUST drain/free temporary Copy indices, preserve both original buffers, all values/positions/indices and extraction order, and refund temporary charges. After entries reserve succeeds, exchange the new indices into place and explicitly drain/free the old Copy indices; no callback or further recoverable allocation occurs. Growth preserves the heap layout and never shrinks.
|
||||
|
||||
Each capacity slot charges usize + complete T for Entry and usize for the index. On air64, T=u64 or own<u64> reserves 24N bytes, with separately owned payloads charged independently. Peak growth includes old/new entries, old/new indices and all user-owned allocations. Refunds follow each buffer's recorded authority, including growth through a different capability. Arithmetic/allocation-size overflow returns alloc_error.budget_exceeded.
|
||||
|
||||
Existing buffer/aggregate transfer/exchange, static contracts, borrow/task-loan exclusion, bounds, effects, Copy/Send/Share and resource verification suffice. Valid representations/successful callbacks do not trap during bookkeeping. Existing source/AIR meanings are unchanged; no new syntax, diagnostic, AIR feature/instruction, verifier/runtime state or trusted boundary is added. Deterministic/hosted behavior agrees. Abstract push/pop perform O(log L) comparisons and index swaps, peek is O(1), reserve copies O(L); interpreter prefix-copy/GC costs may add host work. No native-throughput or stable tie-order promise is made.
|
||||
|
||||
### 2.17 `std.io`: bounded I/O foundation
|
||||
|
||||
The registry MUST include std.io at std/io.aji, ordinary safe source. Six concrete functions compose existing borrowed-resource/capability I/O with caller-supplied slices. They MUST NOT allocate heap storage, open/close resources, retain borrows, infer effects or gain authority through import. Existing primitive writes already report all bytes written on success; no redundant write alias is added.
|
||||
|
||||
ReadError has completed: usize / error: io_error. ReadExactResult has ok, eof(usize), err(ReadError). ReadToEndResult has eof(usize), full(usize), err(ReadError). CopyError has read: usize / confirmed_written: usize / error: io_error; CopyResult has eof(usize), limit(usize), err(CopyError). All are ordinary Copy data, never authority.
|
||||
|
||||
| Function arguments | Result | Effects |
|
||||
|---|---|---|
|
||||
| read_exact_stdin(input: cap<io.read>, destination: slice_mut<u8>) | ReadExactResult | io.read |
|
||||
| read_exact_file(input: mut<file<read>>, destination: slice_mut<u8>) | ReadExactResult | fs.read |
|
||||
| read_exact_stream(input: mut<stream>, destination: slice_mut<u8>) | ReadExactResult | net.read |
|
||||
| read_to_end_file(input: mut<file<read>>, destination: slice_mut<u8>) | ReadToEndResult | fs.read |
|
||||
| copy_file(input: mut<file<read>>, output: mut<file<write>>, scratch: slice_mut<u8>, limit: usize) | CopyResult | fs.read, fs.write |
|
||||
| copy_file_append(input: mut<file<read>>, output: mut<file<append>>, scratch: slice_mut<u8>, limit: usize) | CopyResult | fs.read, fs.write |
|
||||
|
||||
Exact reads loop over the unfilled suffix until destination.len successful bytes have been read (ok), an intrinsic reports zero (eof(completed)), or a read errors (err with the previous successful byte count and unchanged error). Empty exact destination returns ok without an intrinsic. EOF leaves the remaining destination unchanged. On a returned read error, only the completed successful prefix is guaranteed; contents of the attempted suffix follow the primitive and are not additionally promised by this wrapper. Bytes outside the destination MUST remain unchanged. Every count increment MUST be bounded by the remaining capacity.
|
||||
|
||||
read_to_end_file loops until zero (eof(completed)), destination capacity is reached (full(destination.len)), or a read errors (same prefix/error contract). Empty destination returns full(0) without I/O. Full does not establish that unread bytes remain or that EOF was reached: the function MUST NOT read/discard an extra byte to distinguish those states. Neither reader changes or retains caller resource ownership.
|
||||
|
||||
Copies use scratch chunks bounded by min(scratch.len, limit-completed). Successful reads are followed by fs.write_all; reaching zero returns eof(completed), reaching limit returns limit(completed) without probing EOF. Thus exact EOF at limit returns limit, not eof. A read error returns both counts equal to the previously confirmed completed chunks. A write error returns read including the just-read chunk and confirmed_written counting only earlier successful writes. The failed write MAY have externally written a prefix; confirmed_written is a lower bound, not an exact failed-output count or rollback promise. The input has advanced through confirmed successful reads. Counts MUST NOT exceed limit or overflow. EOF/error retain both borrowed resources for explicit caller cleanup.
|
||||
|
||||
limit=0 MUST return limit(0) without I/O, including with empty scratch. Empty scratch with positive limit MUST return err(CopyError{read:0,confirmed_written:0,error:io_error.invalid_input}) without I/O. Scratch contents after the call are unspecified; bytes outside its slice MUST remain unchanged. Functions do not allocate, grow, sync or close; the caller explicitly supplies all grants, slices, limits and final resource consumption. Effects/mut/task-loan requirements apply even to no-op paths. Append copies use the existing append resource semantics.
|
||||
|
||||
Existing type, effect/capability, borrow/task-loan, resource availability, bounds and outcome checks apply without new diagnostics or verifier/runtime state. Operations use ordinary AIR and spec 11 profile behavior; no unsafe/trusted boundary, syntax/opcode/feature, implicit cleanup, timeout or existing semantic change is introduced. Blocking/fuel remain environment outcomes. Returned failures are explicit ordinary enums, never exceptions. Successful work is linear in read bytes plus intrinsic calls; caller capacities/limits and fuel bound work. Buffered adapters are specified in §2.18; lexical paths remain a subsequent STD-7 increment.
|
||||
|
||||
### 2.18 `std.io.reader` / `std.io.writer`: owning bounded file adapters
|
||||
|
||||
The registry MUST include std.io.reader at std/io/reader.aji and std.io.writer at std/io/writer.aji, ordinary safe source with concrete file modes. They MUST NOT open/close files, sync, retain caller borrows, grow implicitly, infer effects or acquire authority through import. Each owns one file and one fixed-capacity initialized buffer<u8>. Only new declares mem.alloc and accepts explicit allocation authority; byte storage charges capacity bytes, including unused capacity. Capacity zero is valid and uses direct primitive reads/writes. Constructor failure MUST return the exact original file with alloc_error, without I/O or resource consumption.
|
||||
|
||||
Reader is `{ file: file<read>, storage: buffer<u8>, begin: usize, end: usize }`, with fully initialized length=capacity=N and 0≤begin≤end≤N. Bytes begin..end are unread prefetched data; the underlying file cursor has advanced through those bytes. Writer is `{ file: file<write>, storage: buffer<u8>, used: usize, failed: std.option.Option<io_error> }`, with fully initialized length=capacity=N and 0≤used≤N. Bytes 0..used are pending accepted data; failed is none or the first failed external-write error. Neither adapter's file/storage may be independently used, consumed or mutated in a way that violates these logical invariants. Ordinary visible fields grant no representation privilege.
|
||||
|
||||
Reader types: NewError{file:file<read>,error:alloc_error}; NewResult{ok(Reader),err(NewError)}; ReadResult{ok(usize),err(io_error)}; FinishResult{ok(file<read>),unread(Reader)}; Discarded{file:file<read>,unread:usize}. Writer types: NewError{file:file<write>,error:alloc_error}; NewResult{ok(Writer),err(NewError)}; WriteError{accepted:usize,error:io_error}; WriteResult{ok,err(WriteError)}; FlushResult{ok,err(io_error)}; FinishError{writer:Writer,error:io_error}; FinishResult{ok(file<write>),err(FinishError)}; Discarded{file:file<write>,pending:usize,failed:std.option.Option<io_error>}. Every file/adapter-bearing result is linear and MUST be explicitly consumed.
|
||||
|
||||
| Module operation | Result | Effects |
|
||||
|---|---|---|
|
||||
| reader.new(input: file<read>, capacity: usize, heap: cap<mem.alloc>) | NewResult | mem.alloc |
|
||||
| reader.read(input: mut<Reader>, destination: slice_mut<u8>) | ReadResult | fs.read |
|
||||
| reader.read_exact(input: mut<Reader>, destination: slice_mut<u8>) | std.io.ReadExactResult | fs.read |
|
||||
| reader.finish(input: Reader) | FinishResult | none |
|
||||
| reader.discard(input: Reader) | Discarded | none |
|
||||
| writer.new(output: file<write>, capacity: usize, heap: cap<mem.alloc>) | NewResult | mem.alloc |
|
||||
| writer.write(output: mut<Writer>, bytes: slice<u8>) | WriteResult | fs.write |
|
||||
| writer.flush(output: mut<Writer>) | FlushResult | fs.write |
|
||||
| writer.finish(output: Writer) | FinishResult | fs.write |
|
||||
| writer.discard(output: Writer) | Discarded | none |
|
||||
|
||||
Reader.read returns at most destination.len bytes. Empty destination returns ok(0) without I/O or consuming cached data; it does not establish EOF. If cached bytes exist, copy min(unread,destination.len) and advance begin, without refilling during that call. Otherwise, for N>0, refill the whole storage using fs.read, then return one cached prefix; a successful zero refill returns ok(0) as EOF. With N=0 delegate one primitive read directly to the destination. Refill errors retain the file/storage and existing offsets, returning the original io_error with no guessed external cursor rollback. Bytes outside the destination remain unchanged. read_exact composes read over destination suffixes and uses §2.17's completed-prefix/EOF/error contract, with no borrow escaping.
|
||||
|
||||
Reader.finish MUST return unread(the complete unchanged Reader) when begin<end. Otherwise drain/free Copy storage and return the original file at its current cursor. It does not require a confirmed EOF and does not read or close. Reader.discard explicitly abandons end-begin prefetched bytes, drains/frees storage and returns the file plus unread count. No rewind is promised; the underlying cursor remains advanced through prefetch. Storage refunds follow its recorded allocation authority.
|
||||
|
||||
Writer.write accepts the complete input into buffered storage or successful writes, returning ok; accepted is not a durability/external-write count. With N>0, copy as much as fits, flushing a full buffer only to make room for further input. If a call ends with a full buffer, retain it until a later write/flush/finish. On a room-making flush error, return WriteError with the number of this call's input bytes already accepted and the original error; the unaccepted suffix remains caller-owned. Buffered pending bytes remain in Writer, including accepted bytes from earlier calls. With N=0, delegate fs.write_all directly: failure has accepted=0, though an external prefix MAY have been written. No count exceeds input.len or overflows.
|
||||
|
||||
Writer.flush on a healthy empty buffer returns ok without I/O. On a successful external write, used becomes zero. On any external write failure, used/data remain unchanged and failed becomes some(the first error); no automatic retry/reset is allowed. Once failed is some(error), every write (including empty) MUST return err with accepted=0 and that error, and every flush MUST return err(error), without I/O or buffer mutation. Unknown partial external writes make retrying pending data unsound. Writer.finish first flushes: success drains/frees storage and returns the file; error returns FinishError with the complete unchanged failed Writer and original error. Finish does not sync or close. Writer.discard explicitly abandons buffered pending bytes, drains/frees storage and returns the file, used count and failure state; pending on failure MAY overlap an already externally written prefix and is not an exact loss count.
|
||||
|
||||
Effects, moves and mut/task-loan requirements apply on no-op/cached/failure paths. Existing aggregate/buffer moves, resource borrowing, alias exclusion, bounds/arithmetic, effect/capability and Copy/Send/Share rules verify all safe code; files make adapters non-Share and ordinary Send checks govern task transfer. Deterministic/hosted behavior follows existing profile primitives. No new AIR meaning, instruction/feature, syntax, diagnostic, verifier/runtime state, unsafe boundary, implicit destructor or cancellation policy is introduced. Invalid representation may trap through existing checked operations, preserving memory safety. Valid bookkeeping does not trap for a valid invariant/conforming primitives. Work is linear in initialized/copy/drained bytes plus I/O calls, with existing interpreter prefix-copy/GC costs. Std 0.1 remains unfinished.
|
||||
|
||||
### 2.19 `std.path`: caller-buffer lexical paths
|
||||
|
||||
The registry MUST include std.path at std/path.aji as ordinary safe source. All six supported operations declare effects [], allocate no heap, retain/return no borrow and grant no filesystem authority. Paths use the same byte separator `/` in every profile, independent of host platform. Backslash, colon and non-UTF-8 bytes are ordinary component bytes; there is no drive/UNC, symlink, filesystem lookup or current-directory interpretation. Lexical normalization MUST NOT be used as a capability-containment or symlink-resolution check; every filesystem operation still validates its path and granted scope independently.
|
||||
|
||||
Range is Copy `{ start: usize, end: usize }`. For a query on path, 0≤start≤end≤path.len; the caller takes ref path[start..end] under ordinary bounds/borrow rules. Empty ranges are valid. Query functions accept every byte slice, including NUL, and perform no normalization or validity claim. WriteResult is Copy `{ ok(usize), invalid_input, size_overflow, short_output }`. Both writing functions MUST reject NUL anywhere in either input with invalid_input, including an ignored base when child is absolute. Invalid input takes precedence over output-size overflow, which takes precedence over short output. Every returned error MUST leave the complete destination unchanged. Success writes exactly the reported canonical prefix and preserves the destination suffix. No NUL terminator is written. Aliased inputs/output MUST reject under existing borrowing rules; explicitly disjoint slices of the same allocation are permitted.
|
||||
|
||||
| Function arguments | Result |
|
||||
|---|---|
|
||||
| is_absolute(path: slice<u8>) | bool: nonempty and first byte `/` |
|
||||
| basename(path: slice<u8>) | Range of the last nonempty component, ignoring trailing separators; empty/root-only input returns 0..0 |
|
||||
| parent(path: slice<u8>) | Range of the raw prefix before basename, trimming the separator run before it; rooted input retains at least its first `/`; empty/relative single component returns 0..0 |
|
||||
| extension(path: slice<u8>) | Range after the final dot in basename, excluding the dot; absent/leading-only/trailing dot and `.`/`..` return the empty range at basename.end |
|
||||
| normalize(destination: slice_mut<u8>, path: slice<u8>) | WriteResult |
|
||||
| join(destination: slice_mut<u8>, base: slice<u8>, child: slice<u8>) | WriteResult |
|
||||
|
||||
Component queries preserve original byte offsets and do not collapse interior separator runs or dot components. For example basename(b"a//b///") is 3..4 and parent is 0..1; basename(b"///") is 0..0 and parent is 0..1; parent(b"a/../b") is 0..4. Extension(b".profile") is 8..8, extension(b".profile.json") selects json, and extension(b"a..b") selects b. Empty extension makes no distinction between no dot and an empty suffix after a trailing dot. A returned Range is ordinary data, not a proof that it applies to some different/mutated path.
|
||||
|
||||
Normalize MUST collapse separator runs, remove `.` components and trailing separators, and cancel each ordinary component followed by `..`. Relative unmatched `..` components MUST be preserved at the beginning. Rooted `..` above `/` MUST be ignored. Empty or reduced-empty relative input becomes `.`; root-only/reduced-empty rooted input becomes `/`. All leading separators collapse to one root; there is no special meaning for exactly two. Dot bytes embedded in other names are ordinary bytes. Examples: a//b/../c/ → a/c; a/../../b → ../b; /../../a → /a; ../a/.. → ..; a/.. → . . Normalization is idempotent.
|
||||
|
||||
Join MUST normalize child alone when child is absolute; otherwise normalize the component sequence of base followed by child, as if separated by one `/`, without making an empty base into an artificial root. An empty child normalizes base; both empty become `.`. Relative child `..` may cancel base components; an absolute child replaces base. Examples: /data/a joined with ../b → /data/b; a joined with /b → /b; empty base joined with a → a. These are byte algorithms only: a successfully normalized relative path is still invalid for current filesystem primitives, and a normalized absolute result may still lie outside the caller's authority.
|
||||
|
||||
Writing operations MUST validate input and determine final normalized length before mutation. Capacity need only accommodate the final prefix, not canceled components or raw concatenation; joining/normalization MUST NOT demand hidden scratch/heap storage. The safe reference algorithm scans components backward, tracking pending parent components, measures retained bytes/separators with checked arithmetic, then emits the retained components backward into the already-validated prefix. Pending relative parents become the leading `..` components; rooted excess parents are dropped. No combined raw input length is required. Input-size/length/cursor arithmetic MUST avoid overflow; size_overflow is ordinary data, not a trap. For conforming slices, returned errors/success do not trap except ordinary fuel exhaustion.
|
||||
|
||||
Existing slices, Copy structs/enums, checked bounds/arithmetic, exclusive-output/shared-input loans, effects and task Send/Share rules suffice. No owner/resource is consumed and no loan escapes. Valid/rejected calls use existing E7002/E7005/E2101/E4101; malformed bytes and insufficient capacity are ordinary WriteResult variants, not verifier diagnostics. No new syntax, AIR meaning/instruction/feature, verifier/runtime state or unsafe/trusted boundary is introduced. Query work is O(path.len); writing work is O(base.len+child.len+output.len) with fixed frame state and existing interpreter costs. Current source borrow-return limitations (Q-034) remain unchanged. Filesystem/system gaps and the Std 0.1 exit examples remain subsequent work.
|
||||
@@ -25,6 +25,7 @@ The specification is split by semantic domain. Rationale for major decisions liv
|
||||
| [13-contracts-and-unsafe.md](13-contracts-and-unsafe.md) | Normative draft | Contracts, proof status and unsafe boundaries |
|
||||
| [14-agent-efficiency.md](14-agent-efficiency.md) | Normative draft (design objectives) | Agent efficiency, Model Capability Compression, design review requirement |
|
||||
| [15-source-language.md](15-source-language.md) | Normative draft | The agent-facing source language `.aji` 0.1 (Phase 6A), lowering to AIR |
|
||||
| [16-standard-library.md](16-standard-library.md) | Normative draft | Standard library contracts and built-in pure modules |
|
||||
|
||||
## Reading order
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "module-example"
|
||||
version = "0.1.0"
|
||||
entry = "main.aji"
|
||||
|
||||
[modules]
|
||||
app.model = "model.aji"
|
||||
@@ -0,0 +1,9 @@
|
||||
module app.entry
|
||||
import app.model;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
let pair = app.model.Pair { left: 20, right: 22 };
|
||||
return app.model.total(pair);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
module app.model
|
||||
|
||||
struct Pair { left: u64, right: u64 }
|
||||
|
||||
fn total(pair: Pair) -> u64
|
||||
effects []
|
||||
{ return pair.left + pair.right; }
|
||||
@@ -0,0 +1,35 @@
|
||||
module demo.bounded
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn encode(dst: slice_mut<u8>, data: slice<u8>) -> usize
|
||||
effects []
|
||||
{
|
||||
match std.math.checked_add_usize(data.len, 1) {
|
||||
std.math.UsizeResult::ok(total) => {
|
||||
if total > dst.len { return 0; }
|
||||
match std.bytes.copy(mut dst, ref data) {
|
||||
std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; }
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
}
|
||||
std.math.UsizeResult::overflow => { return 0; }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> usize
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 16] = [165; 16];
|
||||
let size = encode(mut buf, b"key=value");
|
||||
assert(size == 10);
|
||||
assert(buf[9] == 0 and buf[10] == 165);
|
||||
match std.bytes.find_slice(ref buf[0..size - 1], b"=") {
|
||||
std.bytes.FindResult::found(index) => {
|
||||
assert(std.bytes.equal(ref buf[0..index], b"key"));
|
||||
assert(std.bytes.equal(ref buf[index + 1..size - 1], b"value"));
|
||||
}
|
||||
std.bytes.FindResult::not_found => { trap; }
|
||||
}
|
||||
return size;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
module demo.buffered_io
|
||||
import std.io.reader;
|
||||
import std.io.writer;
|
||||
|
||||
fn main(src: cap<fs.read>,dst: cap<fs.write>,heap: cap<mem.alloc>) -> u64 effects [fs.read,fs.write,mem.alloc] {
|
||||
let input = fs.open_read(src,b"/in/data") or trap;
|
||||
let output = fs.create(dst,b"/out/data") or trap;
|
||||
let reader = match std.io.reader.new(move input,3usize,heap) {
|
||||
std.io.reader.NewResult::ok(value) => { move value },
|
||||
std.io.reader.NewResult::err(error) => {
|
||||
let (file,error) = struct.unpack(move error);
|
||||
fs.close(move file) or trap; fs.close(move output) or trap; return 0;
|
||||
}
|
||||
};
|
||||
let writer = match std.io.writer.new(move output,3usize,heap) {
|
||||
std.io.writer.NewResult::ok(value) => { move value },
|
||||
std.io.writer.NewResult::err(error) => {
|
||||
let (file,error) = struct.unpack(move error);
|
||||
fs.close(move file) or trap;
|
||||
let (file,unread) = struct.unpack(std.io.reader.discard(move reader)); fs.close(move file) or trap; return 0;
|
||||
}
|
||||
};
|
||||
var failed: bool = false; var count: usize = 0; var bytes: [u8;2] = [0u8;2];
|
||||
{ mut input = reader; mut output = writer; loop {
|
||||
match std.io.reader.read(input,mut bytes) {
|
||||
std.io.reader.ReadResult::err(error) => { failed = true; break; },
|
||||
std.io.reader.ReadResult::ok(n) => {
|
||||
if n == 0usize { break; }
|
||||
match std.io.writer.write(output,ref bytes[0usize..n]) {
|
||||
std.io.writer.WriteResult::ok => { count = count + n; },
|
||||
std.io.writer.WriteResult::err(error) => { failed = true; break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
} }
|
||||
let (file,unread) = struct.unpack(std.io.reader.discard(move reader)); fs.close(move file) or trap;
|
||||
match std.io.writer.finish(move writer) {
|
||||
std.io.writer.FinishResult::ok(file) => { fs.close(move file) or trap; },
|
||||
std.io.writer.FinishResult::err(error) => {
|
||||
let (writer,error) = struct.unpack(move error);
|
||||
let (file,pending,error) = struct.unpack(std.io.writer.discard(move writer));
|
||||
fs.close(move file) or trap; return 0;
|
||||
}
|
||||
}
|
||||
if failed { return 0; } return count as! u64;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
module demo.standard
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var data: [u8; 4] = zero;
|
||||
std.bytes.fill(mut data, 65);
|
||||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||||
let index = std.bytes.find(ref data, 65);
|
||||
if index < data.len { assert(data[index] == 65); }
|
||||
return std.math.clamp_u64(42, 0, 100);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
module example.deque
|
||||
import std.deque;
|
||||
import std.option;
|
||||
fn opened<T>(capacity: usize, heap: cap<mem.alloc>) -> std.deque.Deque<T> effects [mem.alloc] {
|
||||
match std.deque.new::<T>(capacity, heap) {
|
||||
std.deque.NewResult::<T>::ok(value) => { return move value; }
|
||||
std.deque.NewResult::<T>::err(error) => { trap; }
|
||||
}
|
||||
}
|
||||
fn pushed<T>(result: std.deque.PushResult<T>) -> void effects [] {
|
||||
match move result {
|
||||
std.deque.PushResult::<T>::ok => {}
|
||||
std.deque.PushResult::<T>::full(item) => { trap; }
|
||||
}
|
||||
}
|
||||
fn front<T>(value: mut<std.deque.Deque<T>>) -> T effects [] {
|
||||
match std.deque.pop_front::<T>(value) {
|
||||
std.option.Option::<T>::some(item) => { return move item; }
|
||||
std.option.Option::<T>::none => { trap; }
|
||||
}
|
||||
}
|
||||
fn back<T>(value: mut<std.deque.Deque<T>>) -> T effects [] {
|
||||
match std.deque.pop_back::<T>(value) {
|
||||
std.option.Option::<T>::some(item) => { return move item; }
|
||||
std.option.Option::<T>::none => { trap; }
|
||||
}
|
||||
}
|
||||
fn released<T>(value: std.deque.Deque<T>) -> void effects [] {
|
||||
match std.deque.free::<T>(move value) {
|
||||
std.deque.FreeResult::<T>::ok => {}
|
||||
std.deque.FreeResult::<T>::not_empty(returned) => { trap; }
|
||||
}
|
||||
}
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let value = opened::<own<u64>>(2, heap);
|
||||
let first = own.new(7u64, heap) or trap;
|
||||
let last = own.new(42u64, heap) or trap;
|
||||
var answer: u64 = 0;
|
||||
{
|
||||
mut q = value;
|
||||
pushed::<own<u64>>(std.deque.push_front::<own<u64>>(q, move first));
|
||||
pushed::<own<u64>>(std.deque.push_back::<own<u64>>(q, move last));
|
||||
let a = front::<own<u64>>(q);
|
||||
assert(own.take(move a) == 7u64);
|
||||
let b = back::<own<u64>>(q);
|
||||
answer = own.take(move b);
|
||||
}
|
||||
released::<own<u64>>(move value);
|
||||
return answer;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
module demo.endian
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u32
|
||||
effects []
|
||||
{
|
||||
var wire: [u8; 6] = zero;
|
||||
match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.bytes.read_u32_be(ref wire[1..5]) {
|
||||
std.bytes.ReadU32::ok(value) => { return value; }
|
||||
std.bytes.ReadU32::short_input => { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
module demo.format
|
||||
import std.bytes;
|
||||
import std.fmt;
|
||||
|
||||
fn main() -> usize
|
||||
effects []
|
||||
{
|
||||
var record: [u8; 24] = [165; 24];
|
||||
match std.bytes.copy(mut record, b"value=") {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
var offset: usize = 6;
|
||||
match std.fmt.write_i64(mut record[offset..record.len], -42) {
|
||||
std.fmt.WriteResult::ok(count) => { offset = offset + count; }
|
||||
std.fmt.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.bytes.copy(mut record[offset..record.len], b" count=") {
|
||||
std.bytes.WriteResult::ok => { offset = offset + 7; }
|
||||
std.bytes.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
match std.fmt.write_usize(mut record[offset..record.len], 7) {
|
||||
std.fmt.WriteResult::ok(count) => { offset = offset + count; }
|
||||
std.fmt.WriteResult::short_output => { return 0; }
|
||||
}
|
||||
assert(std.bytes.equal(ref record[0..offset], b"value=-42 count=7"));
|
||||
for i in offset..record.len { assert(record[i] == 165); }
|
||||
return offset;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
module demo.generic
|
||||
import std.option;
|
||||
|
||||
fn identity<T: Copy>(value: T) -> T effects [] { return value; }
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
let value = std.option.Option::<u64>::some(identity::<u64>(42));
|
||||
match value {
|
||||
std.option.Option::<u64>::some(n) => { return n; }
|
||||
std.option.Option::<u64>::none => { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
module example.hash
|
||||
import std.hash;
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
let prefix = std.hash.crc32c(b"1234");
|
||||
let checksum = std.hash.crc32c_extend(prefix, b"56789");
|
||||
assert(checksum == 0xe3069283u32);
|
||||
assert(checksum == std.hash.crc32c(b"123456789"));
|
||||
let first = std.hash.fnv1a64(b"foo");
|
||||
assert(std.hash.fnv1a64_extend(first, b"bar") == 0x85944171f73967e8u64);
|
||||
var wire: [u8; 4] = zero;
|
||||
match std.bytes.write_u32_le(mut wire, checksum) {
|
||||
std.bytes.WriteResult::ok => {}
|
||||
std.bytes.WriteResult::short_output => { trap; }
|
||||
}
|
||||
assert(std.bytes.equal(ref wire, b"\x83\x92\x06\xe3"));
|
||||
return 42;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
module demo.hashmap
|
||||
import std.hashmap;
|
||||
import std.option;
|
||||
|
||||
struct Key { id: u64 }
|
||||
fn hash(key: ref<Key>) -> u64 effects [] { return key.id; }
|
||||
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
|
||||
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let map = match std.hashmap.new::<Key,own<u64>,fn hash,fn equal>(1,heap) {
|
||||
std.hashmap.NewResult::<Key,own<u64>,fn hash,fn equal>::ok(value) => { move value },
|
||||
std.hashmap.NewResult::<Key,own<u64>,fn hash,fn equal>::err(error) => { trap; }
|
||||
};
|
||||
let value = own.new(42u64,heap) or trap;
|
||||
{ mut q = map;
|
||||
match std.hashmap.insert::<Key,own<u64>,fn hash,fn equal>(q,Key { id: 7 },move value) {
|
||||
std.hashmap.InsertResult::<Key,own<u64>>::inserted => {}
|
||||
std.hashmap.InsertResult::<Key,own<u64>>::replaced(old) => { trap; }
|
||||
std.hashmap.InsertResult::<Key,own<u64>>::full(returned) => { trap; }
|
||||
}
|
||||
let key = Key { id: 7 };
|
||||
match std.hashmap.remove::<Key,own<u64>,fn hash,fn equal>(q,ref key) {
|
||||
std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::some(entry) => {
|
||||
let (stored_key,owner) = struct.unpack(move entry);
|
||||
assert(stored_key.id == 7u64); assert(own.take(move owner) == 42u64);
|
||||
}
|
||||
std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::none => { trap; }
|
||||
}
|
||||
}
|
||||
match std.hashmap.free::<Key,own<u64>,fn hash,fn equal>(move map) {
|
||||
std.hashmap.FreeResult::<Key,own<u64>,fn hash,fn equal>::ok => {}
|
||||
std.hashmap.FreeResult::<Key,own<u64>,fn hash,fn equal>::not_empty(returned) => { trap; }
|
||||
}
|
||||
return 42;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
module demo.hashset
|
||||
import std.hashset;
|
||||
import std.option;
|
||||
|
||||
struct Key { id: u64, owner: own<u64> }
|
||||
fn hash(key: ref<Key>) -> u64 effects [] { return key.id; }
|
||||
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
|
||||
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let set = match std.hashset.new::<Key,fn hash,fn equal>(1,heap) {
|
||||
std.hashset.NewResult::<Key,fn hash,fn equal>::ok(value) => { move value },
|
||||
std.hashset.NewResult::<Key,fn hash,fn equal>::err(error) => { trap; }
|
||||
};
|
||||
let key = Key { id: 7, owner: own.new(42u64,heap) or trap };
|
||||
{ mut q = set;
|
||||
match std.hashset.insert::<Key,fn hash,fn equal>(q,move key) {
|
||||
std.hashset.InsertResult::<Key>::inserted => {}
|
||||
std.hashset.InsertResult::<Key>::present(returned) => { trap; }
|
||||
std.hashset.InsertResult::<Key>::full(returned) => { trap; }
|
||||
}
|
||||
match std.hashset.pop::<Key,fn hash,fn equal>(q) {
|
||||
std.option.Option::<Key>::some(key) => {
|
||||
let (id,owner) = struct.unpack(move key);
|
||||
assert(id == 7u64); assert(own.take(move owner) == 42u64);
|
||||
}
|
||||
std.option.Option::<Key>::none => { trap; }
|
||||
}
|
||||
}
|
||||
match std.hashset.free::<Key,fn hash,fn equal>(move set) {
|
||||
std.hashset.FreeResult::<Key,fn hash,fn equal>::ok => {}
|
||||
std.hashset.FreeResult::<Key,fn hash,fn equal>::not_empty(returned) => { trap; }
|
||||
}
|
||||
return 42;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
module demo.heap
|
||||
import std.heap;
|
||||
import std.option;
|
||||
|
||||
struct Item { priority: u64, owner: own<u64> }
|
||||
fn before(a: ref<Item>, b: ref<Item>) -> bool effects [] { return a.priority < b.priority; }
|
||||
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let value = match std.heap.new::<Item,fn before>(1,heap) {
|
||||
std.heap.NewResult::<Item,fn before>::ok(value) => { move value },
|
||||
std.heap.NewResult::<Item,fn before>::err(error) => { trap; }
|
||||
};
|
||||
let item = Item { priority: 7, owner: own.new(42u64,heap) or trap };
|
||||
{ mut q = value;
|
||||
match std.heap.push::<Item,fn before>(q,move item) {
|
||||
std.heap.PushResult::<Item>::ok => {}
|
||||
std.heap.PushResult::<Item>::full(returned) => { trap; }
|
||||
}
|
||||
match std.heap.pop::<Item,fn before>(q) {
|
||||
std.option.Option::<Item>::some(item) => {
|
||||
let (priority,owner) = struct.unpack(move item);
|
||||
assert(priority == 7u64); assert(own.take(move owner) == 42u64);
|
||||
}
|
||||
std.option.Option::<Item>::none => { trap; }
|
||||
}
|
||||
}
|
||||
match std.heap.free::<Item,fn before>(move value) {
|
||||
std.heap.FreeResult::<Item,fn before>::ok => {}
|
||||
std.heap.FreeResult::<Item,fn before>::not_empty(returned) => { trap; }
|
||||
}
|
||||
return 42;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
module demo.io
|
||||
import std.io;
|
||||
|
||||
fn main(src: cap<fs.read>,dst: cap<fs.write>) -> u64 effects [fs.read,fs.write] {
|
||||
let input = fs.open_read(src,b"/in/data") or trap;
|
||||
let output = fs.create(dst,b"/out/data") or trap;
|
||||
var scratch: [u8;3] = [0u8;3];
|
||||
let count = match std.io.copy_file(mut input,mut output,mut scratch,42usize) {
|
||||
std.io.CopyResult::eof(count) => { count },
|
||||
std.io.CopyResult::limit(count) => { count },
|
||||
std.io.CopyResult::err(error) => {
|
||||
fs.close(move input) or trap; fs.close(move output) or trap;
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
fs.close(move input) or trap; fs.close(move output) or trap;
|
||||
return count as! u64;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
module example.map
|
||||
import std.map;
|
||||
import std.option;
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
match std.map.new::<own<u64>>(1, heap) {
|
||||
std.map.NewResult::<own<u64>>::err(error) => { trap; }
|
||||
std.map.NewResult::<own<u64>>::ok(map) => {
|
||||
let owner = own.new(42u64, heap) or trap;
|
||||
{ mut q = map;
|
||||
match std.map.insert::<own<u64>>(q, 7, move owner) {
|
||||
std.map.InsertResult::<own<u64>>::inserted => {}
|
||||
std.map.InsertResult::<own<u64>>::replaced(old) => { trap; }
|
||||
std.map.InsertResult::<own<u64>>::full(returned) => { trap; }
|
||||
}
|
||||
}
|
||||
var answer: u64 = 0;
|
||||
{ mut q = map;
|
||||
match std.map.remove::<own<u64>>(q, 7) {
|
||||
std.option.Option::<own<u64>>::none => { trap; }
|
||||
std.option.Option::<own<u64>>::some(value) => { answer = own.take(move value); }
|
||||
}
|
||||
}
|
||||
match std.map.free::<own<u64>>(move map) {
|
||||
std.map.FreeResult::<own<u64>>::ok => {}
|
||||
std.map.FreeResult::<own<u64>>::not_empty(returned) => { trap; }
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
module test.linear
|
||||
import std.option;
|
||||
fn replace(value: mut<std.option.Option<own<u64>>>) -> std.option.Option<own<u64>> effects [] {
|
||||
return value.swap(mut value, std.option.Option::<own<u64>>::none);
|
||||
}
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let owner = own.new(42u64, heap) or trap;
|
||||
var value: std.option.Option<own<u64>> = std.option.Option::<own<u64>>::some(move owner);
|
||||
let old = replace(mut value);
|
||||
match move value { std.option.Option::<own<u64>>::none => {}, std.option.Option::<own<u64>>::some(extra) => { own.free(move extra); } }
|
||||
match move old { std.option.Option::<own<u64>>::some(part) => { return own.take(move part); } std.option.Option::<own<u64>>::none => { return 0; } }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
module demo.path
|
||||
import std.path;
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u64 effects [] {
|
||||
var bytes: [u8;32] = [255u8;32];
|
||||
let count = match std.path.join(mut bytes,b"/data/sub",b"../file.tar") {
|
||||
std.path.WriteResult::ok(count) => { count },
|
||||
std.path.WriteResult::invalid_input => { return 0; },
|
||||
std.path.WriteResult::size_overflow => { return 0; },
|
||||
std.path.WriteResult::short_output => { return 0; }
|
||||
};
|
||||
{ ref path = bytes[0usize..count];
|
||||
assert(std.bytes.equal(path,b"/data/file.tar"));
|
||||
let base = std.path.basename(path); let parent = std.path.parent(path); let extension = std.path.extension(path);
|
||||
assert(std.bytes.equal(ref path[base.start..base.end],b"file.tar"));
|
||||
assert(std.bytes.equal(ref path[parent.start..parent.end],b"/data"));
|
||||
assert(std.bytes.equal(ref path[extension.start..extension.end],b"tar"));
|
||||
}
|
||||
return 42;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
module demo.static_functions
|
||||
fn identity(value: u64) -> u64 effects [] { return value; }
|
||||
fn apply<T, F: fn(T) -> T effects []>(value: T) -> T effects [] {
|
||||
return F(move value);
|
||||
}
|
||||
fn main() -> u64 effects [] { return apply::<u64, fn identity>(42u64); }
|
||||
@@ -0,0 +1,31 @@
|
||||
module demo.text
|
||||
import std.bytes;
|
||||
import std.encoding.hex;
|
||||
import std.encoding.base64;
|
||||
import std.utf8;
|
||||
|
||||
fn main() -> u32
|
||||
effects []
|
||||
{
|
||||
var utf8: [u8; 3] = zero;
|
||||
match std.encoding.hex.decode(mut utf8, b"E282AC") {
|
||||
std.encoding.hex.DecodeResult::ok(count) => { assert(count == 3); }
|
||||
std.encoding.hex.DecodeResult::invalid_input => { return 0; }
|
||||
std.encoding.hex.DecodeResult::short_output => { return 0; }
|
||||
}
|
||||
match std.utf8.validate(ref utf8) {
|
||||
std.utf8.ValidateResult::ok => {}
|
||||
std.utf8.ValidateResult::invalid_input(offset) => { return 0; }
|
||||
}
|
||||
var encoded: [u8; 4] = zero;
|
||||
match std.encoding.base64.encode(mut encoded, ref utf8) {
|
||||
std.encoding.base64.EncodeResult::ok(count) => { assert(count == 4); }
|
||||
std.encoding.base64.EncodeResult::short_output => { return 0; }
|
||||
}
|
||||
assert(std.bytes.equal(ref encoded, b"4oKs"));
|
||||
match std.utf8.next(ref utf8) {
|
||||
std.utf8.NextResult::ok(scalar, count) => { assert(count == 3); return scalar; }
|
||||
std.utf8.NextResult::end => { return 0; }
|
||||
std.utf8.NextResult::invalid_input => { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
module example.vector
|
||||
import std.vec;
|
||||
import std.option;
|
||||
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
match std.vec.new::<own<u64>>(1, heap) {
|
||||
std.vec.NewResult::<own<u64>>::ok(value) => {
|
||||
let owner = own.new(42u64, heap) or trap;
|
||||
{
|
||||
mut v = value;
|
||||
match std.vec.push::<own<u64>>(v, move owner) {
|
||||
std.vec.PushResult::<own<u64>>::ok => {}
|
||||
std.vec.PushResult::<own<u64>>::full(returned) => {
|
||||
own.free(move returned);
|
||||
trap;
|
||||
}
|
||||
}
|
||||
}
|
||||
var answer: u64 = 0;
|
||||
{
|
||||
mut v = value;
|
||||
match std.vec.pop::<own<u64>>(v) {
|
||||
std.option.Option::<own<u64>>::some(item) => {
|
||||
answer = own.take(move item);
|
||||
}
|
||||
std.option.Option::<own<u64>>::none => { trap; }
|
||||
}
|
||||
}
|
||||
match std.vec.free::<own<u64>>(move value) {
|
||||
std.vec.FreeResult::<own<u64>>::ok => {}
|
||||
std.vec.FreeResult::<own<u64>>::not_empty(returned) => { trap; }
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
std.vec.NewResult::<own<u64>>::err(e) => { trap; }
|
||||
}
|
||||
}
|
||||
@@ -31,10 +31,12 @@ pub const registry = [_]Feature{
|
||||
.{ .name = "channel_transfer", .depends = &.{ "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "resources", "tasks" }, .status = .reserved, .phase = null },
|
||||
.{ .name = "channels", .depends = &.{ "cancellation", "capabilities", "effects", "heap", "ownership", "resources", "tasks" }, .status = .published, .phase = 3 },
|
||||
.{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 },
|
||||
.{ .name = "error_values", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 6 },
|
||||
.{ .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 = "linear_buffers", .depends = &.{ "arrays", "capabilities", "effects", "heap", "linear_aggregates", "ownership", "resources" }, .status = .published, .phase = 6 },
|
||||
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
|
||||
.{ .name = "receiver_dup", .depends = &.{ "cancellation", "capabilities", "channels", "effects", "heap", "ownership", "resources", "tasks" }, .status = .reserved, .phase = null },
|
||||
.{ .name = "regions", .depends = &.{ "capabilities", "effects", "heap", "ownership", "resources" }, .status = .published, .phase = 2 },
|
||||
@@ -49,7 +51,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", "error_values", "heap", "islands", "linear_aggregates", "linear_buffers", "ownership", "regions", "resources", "sync", "tasks", "unsafe" };
|
||||
|
||||
pub const Reason = enum {
|
||||
unknown_feature,
|
||||
|
||||
+83
-13
@@ -82,6 +82,7 @@ pub const Type = union(enum) {
|
||||
// Features `heap` and `regions` (spec 03 §18–§20).
|
||||
own: *const Type,
|
||||
own_array: *const Type,
|
||||
buffer: *const Type,
|
||||
region,
|
||||
// Feature `tasks` (spec 04 §33).
|
||||
scope,
|
||||
@@ -109,7 +110,7 @@ pub const Type = union(enum) {
|
||||
return switch (a) {
|
||||
.int => |x| b.int == x,
|
||||
.named => |x| b.named == x,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(b.inner().?),
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.eql(b.inner().?),
|
||||
.region, .scope, .shield => true,
|
||||
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
|
||||
.cap => |k| b.cap == k,
|
||||
@@ -122,7 +123,7 @@ pub const Type = union(enum) {
|
||||
/// Element or pointee type of storage, borrow and slice types.
|
||||
pub fn inner(t: Type) ?Type {
|
||||
return switch (t) {
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||||
.local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| x.*,
|
||||
.array => |a| a.elem,
|
||||
else => null,
|
||||
};
|
||||
@@ -139,7 +140,7 @@ pub const Type = union(enum) {
|
||||
/// Linear values: consumed exactly once (spec 06 §6.2–§6.3).
|
||||
pub fn isLinear(t: Type) bool {
|
||||
return switch (t) {
|
||||
.resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => true,
|
||||
.resource, .own, .own_array, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
@@ -173,7 +174,7 @@ pub const Type = union(enum) {
|
||||
/// Linear resources are neither values nor borrows: they are moved.
|
||||
pub fn isValue(t: Type) bool {
|
||||
return switch (t) {
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => false,
|
||||
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .atomic => false,
|
||||
else => true,
|
||||
};
|
||||
}
|
||||
@@ -290,6 +291,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,
|
||||
@@ -302,6 +306,8 @@ pub const Op = union(enum) {
|
||||
assume: ValueId,
|
||||
|
||||
@"const": struct { ty: Type, bits: u128 },
|
||||
/// Pure built-in error data (feature error_values, spec 05 §14).
|
||||
error_const: struct { which: authority.Builtin, variant: u32 },
|
||||
copy: ValueId,
|
||||
arith: struct { op: ArithOp, mode: ArithMode, ty: IntType, a: ValueId, b: ValueId },
|
||||
bit: struct { op: BitOp, ty: Type, a: ValueId, b: ValueId },
|
||||
@@ -318,6 +324,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 +334,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,
|
||||
@@ -335,6 +343,15 @@ pub const Op = union(enum) {
|
||||
region_array: struct { region: ValueId, n: ValueId, value: ValueId, ok: u32, err: u32 },
|
||||
region_reset: ValueId,
|
||||
region_destroy: ValueId,
|
||||
// Feature linear_buffers (spec 03 §26).
|
||||
buffer_new: struct { ty: Type, n: ValueId, cap: ValueId, ok: u32, err: u32 },
|
||||
buffer_len: ValueId,
|
||||
buffer_capacity: ValueId,
|
||||
buffer_view: ValueId,
|
||||
buffer_reserve: struct { borrow: ValueId, n: ValueId, cap: ValueId, ok: u32, err: u32 },
|
||||
buffer_push: struct { borrow: ValueId, value: ValueId, ok: u32, err: u32 },
|
||||
buffer_pop: struct { value: ValueId, ok: u32, err: u32 },
|
||||
buffer_free: struct { value: ValueId, ok: u32, err: u32 },
|
||||
// Feature `tasks` (spec 04 §33).
|
||||
task_scope_begin,
|
||||
task_spawn: struct { scope: ValueId, callee: u32, args: []const ValueId },
|
||||
@@ -408,10 +425,18 @@ pub const Op = union(enum) {
|
||||
return buf[0..n];
|
||||
}
|
||||
|
||||
pub fn isTerminator(op: Op) bool {
|
||||
pub fn bufferTargets(op: Op) ?struct { ok: u32, err: u32 } {
|
||||
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 .buffer_new, .buffer_reserve, .buffer_push, .buffer_pop, .buffer_free => |x| .{ .ok = x.ok, .err = x.err },
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn isTerminator(op: Op) bool {
|
||||
if (op.bufferTargets() != null) return true;
|
||||
return switch (op) {
|
||||
inline .br, .cbr, .@"switch", .enum_switch, .enum_take, .aggregate_unpack, .cap_narrow, .ret, .trap => true,
|
||||
inline .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => true,
|
||||
.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 +486,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) {
|
||||
@@ -503,7 +546,22 @@ pub const Module = struct {
|
||||
/// of terminators are included.
|
||||
pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) void) void {
|
||||
switch (op) {
|
||||
.@"const", .trap => {},
|
||||
.buffer_new => |x| {
|
||||
f(ctx, x.n);
|
||||
f(ctx, x.cap);
|
||||
},
|
||||
.buffer_reserve => |x| {
|
||||
f(ctx, x.borrow);
|
||||
f(ctx, x.n);
|
||||
f(ctx, x.cap);
|
||||
},
|
||||
.buffer_push => |x| {
|
||||
f(ctx, x.borrow);
|
||||
f(ctx, x.value);
|
||||
},
|
||||
inline .buffer_pop, .buffer_free => |x| f(ctx, x.value),
|
||||
.buffer_len, .buffer_capacity, .buffer_view => |v| f(ctx, v),
|
||||
.@"const", .error_const, .trap => {},
|
||||
.copy, .assert => |v| f(ctx, v),
|
||||
.arith => |x| {
|
||||
f(ctx, x.a);
|
||||
@@ -533,7 +591,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 +600,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 +688,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,12 +718,17 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) std.mem.Allocator.Error!void {
|
||||
if (op.bufferTargets()) |t| {
|
||||
try buf.append(gpa, t.ok);
|
||||
try buf.append(gpa, t.err);
|
||||
return;
|
||||
}
|
||||
switch (op) {
|
||||
.br => |t| try buf.append(gpa, t.block),
|
||||
.cbr => |x| {
|
||||
@@ -670,10 +739,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 +752,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);
|
||||
},
|
||||
|
||||
+82
-9
@@ -560,7 +560,7 @@ const Parser = struct {
|
||||
boxed.* = inner;
|
||||
return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed };
|
||||
}
|
||||
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref, atomic };
|
||||
const Wrapper = enum { task, sender, receiver, mutex, guard, island, frozen, arc, iref, atomic, buffer };
|
||||
if (std.meta.stringToEnum(Wrapper, t.text)) |which| {
|
||||
try p.requireFeature(switch (which) {
|
||||
.task => "tasks",
|
||||
@@ -569,6 +569,7 @@ const Parser = struct {
|
||||
.island, .frozen, .iref => "islands",
|
||||
.arc => "arc",
|
||||
.atomic => "atomics",
|
||||
.buffer => "linear_buffers",
|
||||
}, t.span, t.text);
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
// Element rules (spec 04 §38.1) are checked by the type stage.
|
||||
@@ -587,6 +588,7 @@ const Parser = struct {
|
||||
.arc => .{ .arc = boxed },
|
||||
.iref => .{ .iref = boxed },
|
||||
.atomic => .{ .atomic = boxed },
|
||||
.buffer => .{ .buffer = boxed },
|
||||
};
|
||||
}
|
||||
if (eql(t.text, "cap")) {
|
||||
@@ -640,7 +642,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");
|
||||
@@ -871,6 +873,20 @@ const Parser = struct {
|
||||
const head = parts[0];
|
||||
|
||||
const op: air.Op = op: {
|
||||
if (eql(op_tok.text, "error.const")) {
|
||||
try p.requireFeature("error_values", op_tok.span, op_tok.text);
|
||||
const t = try p.expect(.word, "built-in error family and variant");
|
||||
const dot = std.mem.indexOfScalar(u8, t.text, '.') orelse return p.fail(t, "`B.variant`");
|
||||
const b = std.meta.stringToEnum(authority.Builtin, t.text[0..dot]) orelse {
|
||||
try p.report("E0004", t.span, "unknown built-in error family", &.{.{ .name = "name", .value = .{ .str = t.text[0..dot] } }});
|
||||
return error.SyntaxError;
|
||||
};
|
||||
const variant = b.variantIndex(t.text[dot + 1 ..]) orelse {
|
||||
try p.report("E0004", t.span, "unknown built-in error variant", &.{.{ .name = "name", .value = .{ .str = t.text[dot + 1 ..] } }});
|
||||
return error.SyntaxError;
|
||||
};
|
||||
break :op .{ .error_const = .{ .which = b, .variant = variant } };
|
||||
}
|
||||
if (eql(head, "const") and parts.len == 2) {
|
||||
if (eql(parts[1], "bool")) {
|
||||
const lit = try p.expect(.word, "`true` or `false`");
|
||||
@@ -909,6 +925,59 @@ const Parser = struct {
|
||||
const it = std.meta.stringToEnum(air.IntType, parts[2]) orelse return p.unknownOpcode(op_tok);
|
||||
break :op .{ .cast = .{ .mode = mode, .to = it, .a = try p.useValue() } };
|
||||
}
|
||||
if (std.mem.startsWith(u8, op_tok.text, "buffer.")) {
|
||||
try p.requireFeature("linear_buffers", op_tok.span, op_tok.text);
|
||||
const Name = enum { new, len, capacity, view, reserve, push, pop, free };
|
||||
const name = std.meta.stringToEnum(Name, op_tok.text[7..]) orelse return p.unknownOpcode(op_tok);
|
||||
switch (name) {
|
||||
.new => {
|
||||
const ty = try p.parseType();
|
||||
const n, const cap = try p.twoOperands();
|
||||
const ok, const err = try p.okErr();
|
||||
break :op .{ .buffer_new = .{ .ty = ty, .n = n, .cap = cap, .ok = ok, .err = err } };
|
||||
},
|
||||
.len => break :op .{ .buffer_len = try p.useValue() },
|
||||
.capacity => break :op .{ .buffer_capacity = try p.useValue() },
|
||||
.view => break :op .{ .buffer_view = try p.useValue() },
|
||||
.reserve => {
|
||||
const borrow, const n = try p.twoOperands();
|
||||
_ = try p.expect(.comma, "`,`");
|
||||
const cap = try p.useValue();
|
||||
const ok, const err = try p.okErr();
|
||||
break :op .{ .buffer_reserve = .{ .borrow = borrow, .n = n, .cap = cap, .ok = ok, .err = err } };
|
||||
},
|
||||
.push => {
|
||||
const borrow, const value = try p.twoOperands();
|
||||
const ok, const err = try p.okErr();
|
||||
break :op .{ .buffer_push = .{ .borrow = borrow, .value = value, .ok = ok, .err = err } };
|
||||
},
|
||||
.pop, .free => {
|
||||
const value = try p.useValue();
|
||||
const ok, const err = try p.okErr();
|
||||
break :op if (name == .pop) .{ .buffer_pop = .{ .value = value, .ok = ok, .err = err } } else .{ .buffer_free = .{ .value = value, .ok = ok, .err = err } };
|
||||
},
|
||||
}
|
||||
}
|
||||
if (eql(op_tok.text, "array.make")) {
|
||||
try p.requireFeature("linear_aggregates", op_tok.span, op_tok.text);
|
||||
const ty = try p.parseType();
|
||||
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 +1031,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 +1061,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 };
|
||||
@@ -1053,9 +1124,9 @@ const Parser = struct {
|
||||
.task_shield_begin, .channel_dup, .mutex_make, .mutex_take, .mutex_borrow => true,
|
||||
.island_root, .island_borrow, .island_freeze, .frozen_root, .frozen_borrow, .arc_from_frozen, .arc_clone, .arc_root, .arc_borrow, .iref_eq => true,
|
||||
.atomic_new, .atomic_take, .atomic_load, .atomic_rmw, .atomic_cmpxchg => true,
|
||||
.@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true,
|
||||
.@"const", .error_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,
|
||||
.buffer_len, .buffer_capacity, .buffer_view, .array_splat, .array_make, .value_swap, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
|
||||
else => false,
|
||||
};
|
||||
const may_bind = produces_value or op == .call or op == .intrinsic or op == .task_join;
|
||||
@@ -1333,14 +1404,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();
|
||||
|
||||
+150
-5
@@ -115,7 +115,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
|
||||
.cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}),
|
||||
.builtin => |b| try w.writeAll(@tagName(b)),
|
||||
.resource => |r| try w.writeAll(r.text()),
|
||||
.own, .own_array => |inner| {
|
||||
.own, .own_array, .buffer => |inner| {
|
||||
try w.print("{s}<", .{@tagName(t)});
|
||||
try printType(m, inner.*, w);
|
||||
try w.writeByte('>');
|
||||
@@ -179,6 +179,7 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
|
||||
},
|
||||
else => unreachable,
|
||||
},
|
||||
.error_const => |x| try w.print("error.const {s}.{s}", .{ @tagName(x.which), x.which.variants()[x.variant] }),
|
||||
.copy => |v| {
|
||||
try w.writeAll("copy ");
|
||||
try value(f, v, w);
|
||||
@@ -209,6 +210,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 +265,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 +324,39 @@ 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);
|
||||
.buffer_new => |x| {
|
||||
try w.writeAll("buffer.new ");
|
||||
try printType(m, x.ty, w);
|
||||
try w.print(" %{s}, %{s}", .{ f.values[x.n].name, f.values[x.cap].name });
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
inline .buffer_len, .buffer_capacity, .buffer_view => |v, tag| try one(f, w, switch (tag) {
|
||||
.buffer_len => "buffer.len",
|
||||
.buffer_capacity => "buffer.capacity",
|
||||
.buffer_view => "buffer.view",
|
||||
else => unreachable,
|
||||
}, v),
|
||||
.buffer_reserve => |x| {
|
||||
try w.print("buffer.reserve %{s}, %{s}, %{s}", .{ f.values[x.borrow].name, f.values[x.n].name, f.values[x.cap].name });
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
.buffer_push => |x| {
|
||||
try two(f, w, "buffer.push", x.borrow, x.value);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
inline .buffer_pop, .buffer_free => |x, tag| {
|
||||
try one(f, w, if (tag == .buffer_pop) "buffer.pop" else "buffer.free", x.value);
|
||||
try okErr(f, w, x.ok, x.err);
|
||||
},
|
||||
inline .own_new, .own_pack => |x, tag| {
|
||||
if (tag == .own_pack) {
|
||||
try w.writeAll("own.pack ");
|
||||
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 +680,103 @@ 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<u64>), none }
|
||||
\\fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
\\effects [mem.alloc]
|
||||
\\entry:
|
||||
\\ %n = const.u64 42
|
||||
\\ own.pack u64 %n, %heap, ok -> @got, err -> @failed
|
||||
\\got(%owner: own<u64>):
|
||||
\\ %items = array.make array<own<u64>,1>(%owner)
|
||||
\\ array.unpack array<own<u64>,1> %items, next -> @element
|
||||
\\element(%part: own<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<u64>):
|
||||
\\ 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<u64>):
|
||||
\\ %value = own.take %answer_owner
|
||||
\\ ret %value
|
||||
\\no_answer:
|
||||
\\ ret %n
|
||||
\\failed(%e: alloc_error, %original: u64):
|
||||
\\ ret %n
|
||||
);
|
||||
}
|
||||
|
||||
test "round-trip explicit error values" {
|
||||
try roundTrip(
|
||||
\\module test.errors
|
||||
\\air 0
|
||||
\\lang 0.1
|
||||
\\features [resources, ownership, heap, error_values, effects, capabilities]
|
||||
\\fn @main() -> alloc_error
|
||||
\\effects []
|
||||
\\entry:
|
||||
\\ %io = error.const io_error.invalid_input
|
||||
\\ %cap = error.const cap_error.not_subset
|
||||
\\ %e = error.const alloc_error.budget_exceeded
|
||||
\\ ret %e
|
||||
);
|
||||
}
|
||||
|
||||
test "round-trip initialized buffers" {
|
||||
try roundTrip(
|
||||
\\module test.buffers
|
||||
\\ air 0
|
||||
\\ lang 0.1
|
||||
\\ features [arrays, capabilities, effects, heap, linear_aggregates, linear_buffers, ownership, resources]
|
||||
\\fn @main(%heap: cap<mem.alloc>) -> u64
|
||||
\\effects [mem.alloc]
|
||||
\\entry:
|
||||
\\ %capacity = const.usize 1
|
||||
\\ %n = const.u64 42
|
||||
\\ buffer.new own<u64> %capacity, %heap, ok -> @made, err -> @failed
|
||||
\\made(%data: buffer<own<u64>>):
|
||||
\\ own.new %n, %heap, ok -> @owned, err -> @owner_failed
|
||||
\\owned(%owner: own<u64>):
|
||||
\\ %b = borrow.mut %data
|
||||
\\ buffer.push %b, %owner, ok -> @pushed, err -> @full
|
||||
\\full(%returned: own<u64>):
|
||||
\\ trap
|
||||
\\pushed:
|
||||
\\ %next_capacity = const.usize 2
|
||||
\\ buffer.reserve %b, %next_capacity, %heap, ok -> @grown, err -> @reserve_failed
|
||||
\\grown:
|
||||
\\ %length = buffer.len %b
|
||||
\\ %capacity_after = buffer.capacity %b
|
||||
\\ %view = buffer.view %b
|
||||
\\ borrow.end %view
|
||||
\\ buffer.pop %b, ok -> @popped, err -> @empty
|
||||
\\popped(%part: own<u64>):
|
||||
\\ %answer = own.take %part
|
||||
\\ borrow.end %b
|
||||
\\ buffer.free %data, ok -> @done, err -> @nonempty
|
||||
\\nonempty(%original: buffer<own<u64>>):
|
||||
\\ trap
|
||||
\\done:
|
||||
\\ ret %answer
|
||||
\\empty:
|
||||
\\ trap
|
||||
\\failed(%error: alloc_error):
|
||||
\\ trap
|
||||
\\owner_failed(%owner_error: alloc_error):
|
||||
\\ trap
|
||||
\\reserve_failed(%reserve_error: alloc_error):
|
||||
\\ trap
|
||||
);
|
||||
}
|
||||
+182
-2
@@ -30,8 +30,12 @@ pub const Report = struct {
|
||||
/// Checks a `.aji` module (frontend, then the AIR pipeline, with every
|
||||
/// diagnostic at its source location) or a text AIR module.
|
||||
pub fn checkFile(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report {
|
||||
return checkWithModules(arena, file_name, source, &.{});
|
||||
}
|
||||
|
||||
pub fn checkWithModules(arena: std.mem.Allocator, file_name: []const u8, source: []const u8, sources: []const frontend.modules.Source) !Report {
|
||||
if (!std.mem.endsWith(u8, file_name, ".aji")) return checkAir(arena, file_name, source);
|
||||
const lowered = switch (try frontend.compile(arena, file_name, source)) {
|
||||
const lowered = switch (try frontend.compileWithModules(arena, file_name, source, sources)) {
|
||||
.ok => |o| o,
|
||||
.err => |d| return .{ .status = .rejected, .diagnostics = try arena.dupe(diag.Diagnostic, &.{d}) },
|
||||
.unimplemented => |what| return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = what },
|
||||
@@ -73,7 +77,7 @@ pub fn checkLowered(arena: std.mem.Allocator, file_name: []const u8, lowered: fr
|
||||
for (r.diagnostics) |d| {
|
||||
const m = try frontend.mapDiagnostic(arena, d, file_name, lowered.lines);
|
||||
const dup = for (mapped.items) |prev| {
|
||||
if (prev.code == m.code and prev.span.?.line == m.span.?.line and prev.span.?.col == m.span.?.col) break true;
|
||||
if (prev.code == m.code and std.mem.eql(u8, prev.span.?.file, m.span.?.file) and prev.span.?.line == m.span.?.line and prev.span.?.col == m.span.?.col) break true;
|
||||
} else false;
|
||||
if (!dup) try mapped.append(arena, m);
|
||||
}
|
||||
@@ -109,3 +113,179 @@ test "malformed lowered AIR is an internal compiler error" {
|
||||
try std.testing.expectEqualStrings("E0001", d.fields[0].value.str);
|
||||
try std.testing.expect(d.span.?.line == 5 or d.span.?.line == 4);
|
||||
}
|
||||
|
||||
test "standard imports lower identically in either order" {
|
||||
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer a.deinit();
|
||||
const arena = a.allocator();
|
||||
const body = "fn main() -> u64\neffects []\n{ return std.math.min_u64(7, 11); }\n";
|
||||
const first = try checkFile(arena, "a.aji", try std.mem.concat(arena, u8, &.{ "module t\nimport std.math;\nimport std.bytes;\nimport std.utf8;\nimport std.fmt;\nimport std.encoding.hex;\nimport std.encoding.base64;\n", body }));
|
||||
const second = try checkFile(arena, "/another/directory/b.aji", try std.mem.concat(arena, u8, &.{ "module t\nimport std.encoding.base64;\nimport std.encoding.hex;\nimport std.bytes;\nimport std.math;\nimport std.fmt;\nimport std.utf8;\n", body }));
|
||||
try std.testing.expectEqual(Status.accepted, first.status);
|
||||
try std.testing.expectEqual(Status.accepted, second.status);
|
||||
try std.testing.expectEqualStrings(first.lowered.?.air, second.lowered.?.air);
|
||||
// Imported code enters the ordinary verifier with its original locations.
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; std/bytes.aji:") != null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; std/utf8.aji:") != null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; std/fmt.aji:") != null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; std/encoding/hex.aji:") != null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; std/encoding/base64.aji:") != null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.air, "intrinsic ") == null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.air, "own.") == null);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.air, "cap<") == null);
|
||||
}
|
||||
|
||||
test "standard source provenance maps diagnostics to the library file" {
|
||||
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer a.deinit();
|
||||
const arena = a.allocator();
|
||||
const report = try checkFile(arena, "client.aji", "module t\nimport std.math;\nfn main() -> u64\neffects []\n{ return std.math.clamp_u64(5, 9, 4); }\n");
|
||||
try std.testing.expectEqual(Status.accepted, report.status);
|
||||
const lowered = report.lowered.?;
|
||||
const assertion = std.mem.indexOf(u8, lowered.air, " assert ").?;
|
||||
const line: u32 = @intCast(std.mem.count(u8, lowered.air[0..assertion], "\n") + 1);
|
||||
const d = try frontend.mapDiagnostic(arena, .{
|
||||
.code = diag.lookup("E2101").?,
|
||||
.span = .{ .file = "client.aji", .line = line, .col = 5 },
|
||||
.message = "test mapping",
|
||||
}, "client.aji", lowered.lines);
|
||||
try std.testing.expectEqualStrings("std/math.aji", d.span.?.file);
|
||||
try std.testing.expectEqual(@as(u32, 20), d.span.?.line);
|
||||
}
|
||||
|
||||
test "standard type diagnostics use the public source name" {
|
||||
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer a.deinit();
|
||||
const arena = a.allocator();
|
||||
const cases = [_]struct { body: []const u8, found: []const u8 }{
|
||||
.{ .body = "let value: u16 = std.bytes.read_u16_le(b\"xx\");", .found = "std.bytes.ReadU16" },
|
||||
.{ .body = "let values = [std.bytes.ReadU16::ok(42); 2]; let value: [u16; 2] = values;", .found = "array<std.bytes.ReadU16, 2>" },
|
||||
};
|
||||
for (cases) |case| {
|
||||
const source = try std.fmt.allocPrint(arena, "module t\nimport std.bytes;\nfn main() -> u8\neffects []\n{{ {s} return 0; }}\n", .{case.body});
|
||||
const report = try checkFile(arena, "client.aji", source);
|
||||
try std.testing.expectEqual(Status.rejected, report.status);
|
||||
try std.testing.expectEqualStrings("E7005", report.diagnostics[0].code.id);
|
||||
const found = for (report.diagnostics[0].fields) |field| {
|
||||
if (std.mem.eql(u8, field.name, "found")) break field.value.str;
|
||||
} else return error.TestUnexpectedResult;
|
||||
try std.testing.expectEqualStrings(case.found, found);
|
||||
}
|
||||
}
|
||||
|
||||
test "package module order, nominal names and diagnostic paths are independent" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const a: frontend.modules.Source = .{ .name = "app.a", .file = "same.aji", .source = "module app.a\nstruct Pair { value: u64 }\nfn value(p: Pair) -> u64 effects [] { return p.value; }\n" };
|
||||
const b: frontend.modules.Source = .{ .name = "app.b", .file = "same.aji", .source = "module app.b\nimport app.a;\nfn value() -> u64 effects [] { return app.a.value(app.a.Pair { value: 42 }); }\n" };
|
||||
const body = "fn main() -> u64 effects [] { return app.b.value(); }\n";
|
||||
const first = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.a;\nimport app.b;\n" ++ body, &.{ a, b });
|
||||
const second = try checkWithModules(arena, "/elsewhere/root.aji", "module app.entry\nimport app.b;\nimport app.a;\n" ++ body, &.{ b, a });
|
||||
try std.testing.expectEqual(Status.accepted, first.status);
|
||||
try std.testing.expectEqual(Status.accepted, second.status);
|
||||
try std.testing.expectEqualStrings(first.lowered.?.air, second.lowered.?.air);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; same.aji:") != null);
|
||||
const bad = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.b;\nfn main() -> u64 effects [] { let p: app.a.Pair = app.a.Pair { value: 42 }; return 0; }", &.{ a, b });
|
||||
try std.testing.expectEqualStrings("E7002", bad.diagnostics[0].code.id);
|
||||
}
|
||||
|
||||
test "module syntax and verifier errors retain imported source provenance" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const root = "module app.entry\nimport app.lib;\nfn main() -> u64 effects [] { return 42; }";
|
||||
const syntax = try checkWithModules(arena, "entry.aji", root, &.{.{ .name = "app.lib", .file = "src/lib.aji", .source = "module app.lib\nfn broken(" }});
|
||||
try std.testing.expectEqualStrings("E7001", syntax.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("src/lib.aji", syntax.diagnostics[0].span.?.file);
|
||||
try std.testing.expectEqualStrings("expected", syntax.diagnostics[0].fields[0].name);
|
||||
const alias = try checkWithModules(arena, "entry.aji", root, &.{.{ .name = "app.lib", .file = "src/lib.aji", .source = "module app.lib\nfn broken() -> u8 effects [] { var b: [u8; 4] = zero; ref held = b; b[0] = 1; return held[0]; }" }});
|
||||
try std.testing.expectEqualStrings("E2101", alias.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("src/lib.aji", alias.diagnostics[0].span.?.file);
|
||||
}
|
||||
|
||||
test "module graph depth is bounded even with a cached shared tail" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
var sources: std.ArrayList(frontend.modules.Source) = .empty;
|
||||
for (0..257) |i| {
|
||||
const name = try std.fmt.allocPrint(arena, "app.m{d}", .{i});
|
||||
const source = if (i == 256) try std.fmt.allocPrint(arena, "module {s}\n", .{name}) else try std.fmt.allocPrint(arena, "module {s}\nimport app.m{d};\n", .{ name, i + 1 });
|
||||
try sources.append(arena, .{ .name = name, .file = name, .source = source });
|
||||
}
|
||||
const prefix = "module app.entry\nimport app.m200;\nimport app.m0;\nfn main() -> u64 effects [] { return 42; }";
|
||||
const excessive = try checkWithModules(arena, "root.aji", prefix, sources.items);
|
||||
try std.testing.expectEqualStrings("E7006", excessive.diagnostics[0].code.id);
|
||||
const valid = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.m1;\nfn main() -> u64 effects [] { return 42; }", sources.items);
|
||||
try std.testing.expectEqual(Status.accepted, valid.status);
|
||||
const many = try arena.alloc(frontend.modules.Source, 1025);
|
||||
@memset(many, sources.items[0]);
|
||||
const limited = try checkWithModules(arena, "root.aji", prefix, many);
|
||||
try std.testing.expectEqualStrings("E7006", limited.diagnostics[0].code.id);
|
||||
}
|
||||
|
||||
test "qualified module names are not limited by builtin path storage" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const component = try arena.alloc(u8, 300);
|
||||
@memset(component, 'a');
|
||||
const name = try std.fmt.allocPrint(arena, "app.{s}", .{component});
|
||||
const source = try std.fmt.allocPrint(arena, "module {s}\nstruct Pair {{ value: u64 }}\nfn total(p: Pair) -> u64 effects [] {{ return p.value; }}", .{name});
|
||||
const entry = try std.fmt.allocPrint(arena, "module app.entry\nimport {s};\nfn main() -> u64 effects [] {{ return {s}.total({s}.Pair {{ value: 42 }}); }}", .{ name, name, name });
|
||||
const checked = try checkWithModules(arena, "root.aji", entry, &.{.{ .name = name, .file = "lib.aji", .source = source }});
|
||||
try std.testing.expectEqual(Status.accepted, checked.status);
|
||||
}
|
||||
|
||||
test "generic specialization deduplicates nominal keys independent of module order and provenance" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const arena = state.allocator();
|
||||
const lib: frontend.modules.Source = .{ .name = "app.lib", .file = "lib.aji", .source = "module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return value; }" };
|
||||
const prefix = "module app.entry\n";
|
||||
const body = "struct Pair { value: u64 }\nfn main() -> u64 effects [] { let p = app.lib.id::<Pair>(Pair { value: 42 }); let a = app.lib.id::<u64>(p.value); return app.lib.id::<u64>(a); }";
|
||||
const first = try checkWithModules(arena, "entry.aji", prefix ++ "import app.lib;\nimport std.option;\n" ++ body, &.{lib});
|
||||
var moved = lib;
|
||||
moved.file = "elsewhere/lib.aji";
|
||||
const second_source = try std.mem.replaceOwned(u8, arena, prefix ++ "import std.option;\nimport app.lib;\n" ++ body, "id::<Pair>", "id::<app.entry.Pair>");
|
||||
const second = try checkWithModules(arena, "elsewhere/entry.aji", second_source, &.{moved});
|
||||
try std.testing.expectEqual(Status.accepted, first.status);
|
||||
try std.testing.expectEqual(Status.accepted, second.status);
|
||||
try std.testing.expectEqualStrings(first.lowered.?.air, second.lowered.?.air);
|
||||
try std.testing.expectEqual(@as(usize, 3), first.module.?.functions.len);
|
||||
try std.testing.expectEqual(@as(usize, 1), first.module.?.types.len);
|
||||
const bad = try checkWithModules(arena, "entry.aji", prefix ++ "import app.lib;\nfn main() -> u64 effects [] { return app.lib.id::<own<u64>>(0); }", &.{lib});
|
||||
try std.testing.expectEqualStrings("E7005", bad.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("constraint", bad.diagnostics[0].fields[1].name);
|
||||
const provenance = try checkWithModules(arena, "entry.aji", prefix ++ "import app.lib;\nfn main() -> u64 effects [] { return app.lib.id::<u64>(42); }", &.{.{ .name = "app.lib", .file = "lib.aji", .source = "module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return missing(value); }" }});
|
||||
try std.testing.expectEqualStrings("lib.aji", provenance.diagnostics[0].span.?.file);
|
||||
}
|
||||
|
||||
test "generic specialization count and parameter limits reject before lowering" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const arena = state.allocator();
|
||||
var source: std.ArrayList(u8) = .empty;
|
||||
try source.appendSlice(arena, "module app.entry\nfn marker<T>() -> u64 effects [] { return 0; }\nfn main() -> u64 effects [] {\n");
|
||||
for (1..4098) |n| try source.appendSlice(arena, try std.fmt.allocPrint(arena, "marker::<[u8; {d}]>();\n", .{n}));
|
||||
try source.appendSlice(arena, "return 42; }");
|
||||
const result = try frontend.compile(arena, "limit.aji", source.items);
|
||||
try std.testing.expect(result == .err);
|
||||
try std.testing.expectEqualStrings("E7006", result.err.code.id);
|
||||
const params = try frontend.compile(arena, "limit.aji", "module app.entry\nfn marker<A,B,C,D,E,F,G,H,I>() -> u64 effects [] { return 0; }\nfn main() -> u64 effects [] { return 42; }");
|
||||
try std.testing.expectEqualStrings("E7006", params.err.code.id);
|
||||
}
|
||||
|
||||
test "generic AIR names avoid source collisions and diagnostic names stay readable" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const arena = state.allocator();
|
||||
const source = "module app.entry\nfn id<T: Copy>(value: T) -> T effects [] { return value; }\nfn __aji_g_65d38d1a36ba3736939a86561ed8e7371f3c6dcce26722dd7876102d750f7052() -> u64 effects [] { return 0; }\nfn main() -> u64 effects [] { return id::<u64>(42); }";
|
||||
const result = try checkFile(arena, "collision.aji", source);
|
||||
try std.testing.expectEqual(Status.accepted, result.status);
|
||||
try std.testing.expect(std.mem.indexOf(u8, result.lowered.?.air, "call @__aji_g_65d38d1a36ba3736939a86561ed8e7371f3c6dcce26722dd7876102d750f7052_1(") != null);
|
||||
const arity = try checkFile(arena, "arity.aji", "module app.entry\nfn id<T: Copy>(value: T) -> T effects [] { return value; }\nfn main() -> u64 effects [] { return id::<u64>(); }");
|
||||
try std.testing.expectEqualStrings("E7005", arity.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("app.entry.id<u64>", arity.diagnostics[0].fields[0].value.str);
|
||||
}
|
||||
+19
-4
@@ -8,6 +8,9 @@ pub const lex = @import("frontend/lex.zig");
|
||||
pub const ast = @import("frontend/ast.zig");
|
||||
pub const parse = @import("frontend/parse.zig");
|
||||
pub const lower_mod = @import("frontend/lower.zig");
|
||||
pub const generics = @import("frontend/generics.zig");
|
||||
pub const modules = @import("frontend/modules.zig");
|
||||
pub const stdlib = @import("frontend/stdlib.zig");
|
||||
|
||||
pub const Span = ast.Span;
|
||||
|
||||
@@ -20,6 +23,10 @@ pub const Compiled = union(enum) {
|
||||
};
|
||||
|
||||
pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) std.mem.Allocator.Error!Compiled {
|
||||
return compileWithModules(arena, file, source, &.{});
|
||||
}
|
||||
|
||||
pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []const u8, sources: []const modules.Source) std.mem.Allocator.Error!Compiled {
|
||||
const parsed = try parse.parse(arena, source);
|
||||
const m = switch (parsed) {
|
||||
.ok => |m| m,
|
||||
@@ -33,19 +40,27 @@ pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) s
|
||||
}),
|
||||
} },
|
||||
};
|
||||
return switch (try lower_mod.lower(arena, m)) {
|
||||
const linked = try modules.link(arena, m, sources);
|
||||
const result = switch (linked) {
|
||||
.ok => |combined| switch (try generics.specialize(arena, combined)) {
|
||||
.ok => |concrete| try lower_mod.lower(arena, concrete),
|
||||
.err => |p| lower_mod.Result{ .err = p },
|
||||
},
|
||||
.err => |p| lower_mod.Result{ .err = p },
|
||||
};
|
||||
return switch (result) {
|
||||
.ok => |o| .{ .ok = o },
|
||||
.err => |p| blk: {
|
||||
const fields = try arena.alloc(diag.Field, p.fields.len);
|
||||
for (p.fields, fields) |pf, *f| f.* = .{ .name = pf.name, .value = .{ .str = pf.value } };
|
||||
break :blk .{ .err = .{
|
||||
.code = diag.lookup(p.code).?,
|
||||
.span = .{ .file = file, .line = p.span.start.line, .col = p.span.start.col },
|
||||
.span = .{ .file = p.span.file orelse file, .line = p.span.start.line, .col = p.span.start.col },
|
||||
.message = p.message,
|
||||
.fields = fields,
|
||||
} };
|
||||
},
|
||||
.unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ file, u.span.start.line, u.span.start.col, u.construct }) },
|
||||
.unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ u.span.file orelse file, u.span.start.line, u.span.start.col, u.construct }) },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,7 +75,7 @@ pub fn mapDiagnostic(arena: std.mem.Allocator, d: diag.Diagnostic, file: []const
|
||||
fields[d.fields.len + 1] = .{ .name = "air_col", .value = .{ .int = sp.col } };
|
||||
out.fields = fields;
|
||||
const src: ?Span = if (sp.line >= 1 and sp.line <= lines.len) lines[sp.line - 1] else null;
|
||||
out.span = .{ .file = file, .line = if (src) |s| s.start.line else 1, .col = if (src) |s| s.start.col else 1 };
|
||||
out.span = .{ .file = if (src) |s| s.file orelse file else file, .line = if (src) |s| s.start.line else 1, .col = if (src) |s| s.start.col else 1 };
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
+33
-6
@@ -6,13 +6,16 @@ const lex = @import("lex.zig");
|
||||
|
||||
pub const Pos = lex.Pos;
|
||||
|
||||
pub const Span = struct { start: Pos, end: Pos };
|
||||
pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null, namespace: ?[]const u8 = null, resolved: bool = false };
|
||||
|
||||
pub const Type = struct {
|
||||
span: Span,
|
||||
kind: union(enum) {
|
||||
/// A built-in or declared type name (`u8`, `bool`, `region`, `Pair`).
|
||||
name: []const u8,
|
||||
applied: struct { name: []const u8, args: []const Type },
|
||||
/// Static generic argument, never a runtime type (spec 15 §18).
|
||||
function_ref: struct { name: []const u8, args: []const Type = &.{} },
|
||||
/// `[T; N]`.
|
||||
array: struct { elem: *const Type, len: u64 },
|
||||
/// `ref<T>`, `own<T>`, `sender<T>`, … (`wrapper` names the constructor).
|
||||
@@ -54,6 +57,8 @@ pub const CastMode = enum { widen, checked, wrap };
|
||||
|
||||
pub const Expr = struct {
|
||||
span: Span,
|
||||
/// Complete Copy transfer is admitted only in a specialized template body.
|
||||
generic_transfer: bool = false,
|
||||
kind: Kind,
|
||||
|
||||
pub const Kind = union(enum) {
|
||||
@@ -62,7 +67,8 @@ pub const Expr = struct {
|
||||
bytes: []const u8,
|
||||
name: []const u8,
|
||||
/// `Enum::Variant` (applied to payload arguments by a `call`).
|
||||
variant: struct { @"enum": []const u8, name: []const u8 },
|
||||
variant: struct { @"enum": []const u8, name: []const u8, type_args: []const Type = &.{} },
|
||||
specialize: struct { base: *const Expr, args: []const Type },
|
||||
neg: *const Expr,
|
||||
not: *const Expr,
|
||||
deref: *const Expr,
|
||||
@@ -70,13 +76,14 @@ pub const Expr = struct {
|
||||
move: []const u8,
|
||||
binary: struct { op: BinOp, l: *const Expr, r: *const Expr },
|
||||
cast: struct { mode: CastMode, e: *const Expr, ty: Type },
|
||||
/// `callee(args)`; `type_arg` only for `channel.make<T>`.
|
||||
/// `callee(args)`; `type_arg` for `channel.make<T>` / `buffer.new<T>`.
|
||||
call: struct { callee: *const Expr, type_arg: ?Type, args: []const Expr },
|
||||
field: struct { e: *const Expr, name: []const u8 },
|
||||
/// `e[lo]` or `e[lo..hi]`.
|
||||
index: struct { e: *const Expr, lo: *const Expr, hi: ?*const Expr },
|
||||
struct_lit: struct { name: []const u8, fields: []const FieldInit },
|
||||
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,
|
||||
@@ -97,7 +104,7 @@ pub const Pattern = struct {
|
||||
int: []const u8,
|
||||
/// A variant with its enum (`Shape::Rect(w, h)`) or an outcome
|
||||
/// (`ok(n)`, `closed`; `qualifier == null`), with bound names.
|
||||
ctor: struct { qualifier: ?[]const u8, name: []const u8, binds: []const []const u8 },
|
||||
ctor: struct { qualifier: ?[]const u8, name: []const u8, binds: []const []const u8, type_args: []const Type = &.{} },
|
||||
},
|
||||
};
|
||||
|
||||
@@ -139,7 +146,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 },
|
||||
@@ -166,8 +173,16 @@ pub const Field = struct { name: []const u8, ty: Type, span: Span };
|
||||
|
||||
pub const Variant = struct { name: []const u8, payload: []const Type, span: Span };
|
||||
|
||||
pub const FunctionContract = struct { params: []const Type, ret: Type, effects: []const []const u8 };
|
||||
pub const TypeParam = struct { name: []const u8, constraints: []const []const u8, span: Span, callable: ?*const FunctionContract = null };
|
||||
pub const Requirement = struct { ty: Type, parameter: []const u8, property: []const u8, span: Span };
|
||||
|
||||
pub const TypeDecl = struct {
|
||||
generics: []const TypeParam = &.{},
|
||||
name: []const u8,
|
||||
/// Linker-chosen AIR identifier for a qualified imported type.
|
||||
air_name: ?[]const u8 = null,
|
||||
display_name: ?[]const u8 = null,
|
||||
span: Span,
|
||||
kind: union(enum) { @"struct": []const Field, @"enum": []const Variant },
|
||||
};
|
||||
@@ -175,7 +190,11 @@ pub const TypeDecl = struct {
|
||||
pub const Param = struct { name: []const u8, ty: Type, span: Span };
|
||||
|
||||
pub const FnDecl = struct {
|
||||
generics: []const TypeParam = &.{},
|
||||
name: []const u8,
|
||||
/// Linker-chosen AIR identifier for a qualified imported function.
|
||||
air_name: ?[]const u8 = null,
|
||||
display_name: ?[]const u8 = null,
|
||||
span: Span,
|
||||
params: []const Param,
|
||||
ret: Type,
|
||||
@@ -187,6 +206,14 @@ pub const FnDecl = struct {
|
||||
|
||||
pub const Module = struct {
|
||||
name: []const u8,
|
||||
imports: []const Import = &.{},
|
||||
scopes: []const ModuleScope = &.{},
|
||||
requirements: []const Requirement = &.{},
|
||||
types: []const TypeDecl,
|
||||
functions: []const FnDecl,
|
||||
};
|
||||
|
||||
pub const Import = struct { path: []const u8, span: Span };
|
||||
|
||||
/// Source name resolution stays separate from diagnostic file paths.
|
||||
pub const ModuleScope = struct { name: []const u8, entry: bool, qualified_self: bool = true, imports: []const Import };
|
||||
@@ -0,0 +1,638 @@
|
||||
//! Explicit, bounded monomorphization before ordinary AIR lowering.
|
||||
const std = @import("std");
|
||||
const ast = @import("ast.zig");
|
||||
const lower = @import("lower.zig");
|
||||
const authority = @import("../air/authority.zig");
|
||||
const A = std.mem.Allocator;
|
||||
const Error = error{ OutOfMemory, InvalidGeneric };
|
||||
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem };
|
||||
const Env = struct { params: []const ast.TypeParam = &.{}, args: []const ast.Type = &.{} };
|
||||
const Instance = struct { key: []const u8, name: []const u8, air_name: []const u8, signature: ?ast.FnDecl = null, decl: union(enum) { pending, ty: ast.TypeDecl, function: ast.FnDecl } = .pending };
|
||||
|
||||
pub fn specialize(arena: A, module: ast.Module) A.Error!Result {
|
||||
var g: Generator = .{ .arena = arena, .m = module };
|
||||
const out = g.run() catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.InvalidGeneric => return .{ .err = g.problem.? },
|
||||
};
|
||||
return .{ .ok = out };
|
||||
}
|
||||
|
||||
const Generator = struct {
|
||||
arena: A,
|
||||
m: ast.Module,
|
||||
instances: std.ArrayList(Instance) = .empty,
|
||||
requirements: std.ArrayList(ast.Requirement) = .empty,
|
||||
depth: usize = 0,
|
||||
type_depth: usize = 0,
|
||||
problem: ?lower.Problem = null,
|
||||
|
||||
fn fail(g: *Generator, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
g.problem = .{ .code = code, .span = span, .message = message, .fields = try g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) };
|
||||
return error.InvalidGeneric;
|
||||
}
|
||||
|
||||
fn bound(g: *Generator, name: []const u8, span: ast.Span) ?[]const u8 {
|
||||
if (span.resolved) return name;
|
||||
const origin = span.namespace orelse g.m.name;
|
||||
for (g.m.scopes) |scope| if (std.mem.eql(u8, scope.name, origin)) {
|
||||
if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| {
|
||||
const owner = name[0..at];
|
||||
if (std.mem.eql(u8, owner, origin)) return if (!scope.qualified_self) null else if (scope.entry) name[at + 1 ..] else name;
|
||||
for (scope.imports) |imp| if (std.mem.eql(u8, imp.path, owner)) return name;
|
||||
return null;
|
||||
}
|
||||
if (scope.entry) return name;
|
||||
for (g.m.types) |t| if (local(t.name, origin, name)) return t.name;
|
||||
for (g.m.functions) |f| if (local(f.name, origin, name)) return f.name;
|
||||
return null;
|
||||
};
|
||||
return name;
|
||||
}
|
||||
|
||||
fn typeDecl(g: *Generator, name: []const u8, span: ast.Span) ?ast.TypeDecl {
|
||||
const n = g.bound(name, span) orelse return null;
|
||||
for (g.m.types) |t| if (std.mem.eql(u8, t.name, n)) return t;
|
||||
return null;
|
||||
}
|
||||
fn function(g: *Generator, name: []const u8, span: ast.Span) ?ast.FnDecl {
|
||||
const n = g.bound(name, span) orelse return null;
|
||||
for (g.m.functions) |f| if (std.mem.eql(u8, f.name, n)) return f;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn checkBinding(g: *Generator, name: []const u8, span: ast.Span, env: Env) Error!void {
|
||||
for (env.params) |p| if (p.callable != null and std.mem.eql(u8, p.name, name)) return g.fail("E7006", span, "runtime binding shadows a static function parameter", name);
|
||||
}
|
||||
|
||||
fn boundFunction(env: Env, name: []const u8) ?ast.Type {
|
||||
for (env.params, env.args) |p, arg| if (p.callable != null and std.mem.eql(u8, p.name, name)) return arg;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn functionArgument(g: *Generator, arg: ast.Type, env: Env) Error!ast.Type {
|
||||
const f = arg.kind.function_ref;
|
||||
var out = arg;
|
||||
if (boundFunction(env, f.name)) |bound_arg| {
|
||||
if (f.args.len != 0) return g.fail("E7006", arg.span, "bound static function cannot be specialized again", f.name);
|
||||
out.kind = bound_arg.kind;
|
||||
} else {
|
||||
const target = g.function(f.name, arg.span) orelse return g.fail("E7002", arg.span, "unknown or inaccessible static function", f.name);
|
||||
const name = if (target.generics.len != 0)
|
||||
try g.instantiate(false, target, f.args, env, arg.span)
|
||||
else blk: {
|
||||
if (f.args.len != 0) return g.fail("E7006", arg.span, "non-generic function does not take static arguments", f.name);
|
||||
break :blk target.name;
|
||||
};
|
||||
out.kind = .{ .function_ref = .{ .name = name } };
|
||||
}
|
||||
out.span.resolved = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn sameType(g: *Generator, a: ast.Type, b: ast.Type) Error!bool {
|
||||
var left: std.ArrayList(u8) = .empty;
|
||||
var right: std.ArrayList(u8) = .empty;
|
||||
try g.identity(a, &left);
|
||||
try g.identity(b, &right);
|
||||
return std.mem.eql(u8, left.items, right.items);
|
||||
}
|
||||
|
||||
fn contractText(g: *Generator, contract: ast.FunctionContract, env: Env) Error![]const u8 {
|
||||
var out: std.ArrayList(u8) = .empty;
|
||||
try out.appendSlice(g.arena, "fn(");
|
||||
for (contract.params, 0..) |p, i| {
|
||||
if (i != 0) try out.append(g.arena, ',');
|
||||
try g.identity(try g.ty(p, env), &out);
|
||||
}
|
||||
try out.appendSlice(g.arena, ") -> ");
|
||||
try g.identity(try g.ty(contract.ret, env), &out);
|
||||
try out.appendSlice(g.arena, " effects [");
|
||||
for (contract.effects, 0..) |effect, i| {
|
||||
if (i != 0) try out.append(g.arena, ',');
|
||||
try out.appendSlice(g.arena, effect);
|
||||
}
|
||||
try out.append(g.arena, ']');
|
||||
return out.items;
|
||||
}
|
||||
|
||||
fn functionMismatch(g: *Generator, parameter: []const u8, contract: ast.FunctionContract, selected: ast.FnDecl, arg: ast.Type, env: Env, message: []const u8) Error {
|
||||
const params = try g.arena.alloc(ast.Type, selected.params.len);
|
||||
for (selected.params, params) |p, *t| t.* = p.ty;
|
||||
g.problem = .{ .code = "E7005", .span = arg.span, .message = message, .fields = try g.arena.dupe(lower.Problem.Field, &.{
|
||||
.{ .name = "parameter", .value = parameter },
|
||||
.{ .name = "function", .value = selected.display_name orelse selected.name },
|
||||
.{ .name = "expected", .value = try g.contractText(contract, env) },
|
||||
.{ .name = "found", .value = try g.contractText(.{ .params = params, .ret = selected.ret, .effects = selected.effects }, .{}) },
|
||||
}) };
|
||||
return error.InvalidGeneric;
|
||||
}
|
||||
|
||||
fn checkFunctionArgument(g: *Generator, parameter: []const u8, contract: ast.FunctionContract, arg: ast.Type, env: Env) Error!void {
|
||||
const name = arg.kind.function_ref.name;
|
||||
const selected = if (g.function(name, arg.span)) |f| f else blk: {
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name)) {
|
||||
break :blk instance.signature orelse return g.fail("E7006", arg.span, "cyclic static function contract resolution", parameter);
|
||||
};
|
||||
return g.fail("E7002", arg.span, "unknown static function specialization", name);
|
||||
};
|
||||
if (selected.params.len != contract.params.len or selected.from != null) return g.functionMismatch(parameter, contract, selected, arg, env, "static function parameter count or return contract mismatch");
|
||||
for (contract.params, selected.params) |expected, actual| {
|
||||
if (!try g.sameType(try g.ty(expected, env), try g.ty(actual.ty, .{}))) return g.functionMismatch(parameter, contract, selected, arg, env, "static function parameter type mismatch");
|
||||
}
|
||||
if (!try g.sameType(try g.ty(contract.ret, env), try g.ty(selected.ret, .{}))) return g.functionMismatch(parameter, contract, selected, arg, env, "static function return type mismatch");
|
||||
if (selected.effects.len != contract.effects.len) return g.functionMismatch(parameter, contract, selected, arg, env, "static function effect set mismatch");
|
||||
for (contract.effects) |expected| {
|
||||
for (selected.effects) |actual| {
|
||||
if (std.mem.eql(u8, expected, actual)) break;
|
||||
} else return g.functionMismatch(parameter, contract, selected, arg, env, "static function effect set mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(g: *Generator, name: []const u8, params: []const ast.TypeParam, span: ast.Span) Error!void {
|
||||
if (params.len > 8) return g.fail("E7006", span, "generic declaration limit or generic entry", name);
|
||||
for (params, 0..) |p, i| {
|
||||
if (!std.ascii.isUpper(p.name[0]) or g.typeDecl(p.name, p.span) != null or builtin(p.name)) return g.fail("E7006", p.span, "type parameter must be uppercase and not shadow a visible type", p.name);
|
||||
for (params[0..i]) |previous| if (std.mem.eql(u8, p.name, previous.name)) return g.fail("E7006", p.span, "duplicate type parameter", p.name);
|
||||
if (p.callable) |c| {
|
||||
if (p.constraints.len != 0 or g.function(p.name, p.span) != null) return g.fail("E7006", p.span, "invalid static function parameter", p.name);
|
||||
for (c.params) |t| try g.headerType(t, params, 0);
|
||||
try g.headerType(c.ret, params, 0);
|
||||
if (c.ret.kind == .wrapped) {
|
||||
const w = c.ret.kind.wrapped.wrapper;
|
||||
if (std.mem.eql(u8, w, "ref") or std.mem.eql(u8, w, "mut") or std.mem.eql(u8, w, "slice") or std.mem.eql(u8, w, "slice_mut")) return g.fail("E7006", c.ret.span, "static function contracts do not support borrowed returns", p.name);
|
||||
}
|
||||
for (c.effects, 0..) |effect, j| {
|
||||
if (authority.effectIndex(effect) == null) return g.fail("E0006", p.span, "unknown effect in static function contract", effect);
|
||||
for (c.effects[0..j]) |prev| if (std.mem.eql(u8, prev, effect)) return g.fail("E7006", p.span, "duplicate effect in static function contract", effect);
|
||||
}
|
||||
}
|
||||
for (p.constraints, 0..) |c, j| {
|
||||
if (std.meta.stringToEnum(Property, c) == null) return g.fail("E7006", p.span, "unknown structural constraint", c);
|
||||
for (p.constraints[0..j]) |previous| if (std.mem.eql(u8, c, previous)) return g.fail("E7006", p.span, "duplicate structural constraint", c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn headerType(g: *Generator, t: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void {
|
||||
if (depth >= 64) return g.fail("E7006", t.span, "type traversal exceeds depth 64", "type");
|
||||
switch (t.kind) {
|
||||
.name => |n| {
|
||||
for (params) |p| if (std.mem.eql(u8, n, p.name)) {
|
||||
if (p.callable != null) return g.fail("E7006", t.span, "static function parameter is not a type", n);
|
||||
return;
|
||||
};
|
||||
if (g.typeDecl(n, t.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", t.span, "template type needs explicit arguments", n);
|
||||
} else if (!builtin(n)) return g.fail("E7002", t.span, "unknown template signature type", n);
|
||||
},
|
||||
.applied => |x| {
|
||||
const d = g.typeDecl(x.name, t.span) orelse return g.fail("E7002", t.span, "unknown template signature type", x.name);
|
||||
if (d.generics.len == 0 or d.generics.len != x.args.len) return g.fail("E7006", t.span, "template type argument count mismatch", x.name);
|
||||
for (d.generics, x.args) |p, arg| try g.headerArgument(p, arg, params, depth + 1);
|
||||
},
|
||||
.array => |a| try g.headerType(a.elem.*, params, depth + 1),
|
||||
.wrapped => |w| try g.headerType(w.inner.*, params, depth + 1),
|
||||
.cap => |k| if (authority.kindIndex(k) == null) return g.fail("E7002", t.span, "unknown capability kind", k),
|
||||
.file => |mode| if (!(std.mem.eql(u8, mode, "read") or std.mem.eql(u8, mode, "write") or std.mem.eql(u8, mode, "append"))) return g.fail("E7002", t.span, "unknown file mode", mode),
|
||||
.function_ref => return g.fail("E7006", t.span, "static functions are not runtime types", "fn"),
|
||||
}
|
||||
}
|
||||
|
||||
fn headerArgument(g: *Generator, expected: ast.TypeParam, arg: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void {
|
||||
if (depth >= 64) return g.fail("E7006", arg.span, "generic argument traversal exceeds depth 64", expected.name);
|
||||
if (expected.callable == null) {
|
||||
if (arg.kind == .function_ref) return g.fail("E7005", arg.span, "expected a type argument, found a static function", expected.name);
|
||||
return g.headerType(arg, params, depth);
|
||||
}
|
||||
if (arg.kind != .function_ref) return g.fail("E7005", arg.span, "expected an explicit static function argument", expected.name);
|
||||
const f = arg.kind.function_ref;
|
||||
for (params) |parameter| if (std.mem.eql(u8, parameter.name, f.name) and parameter.callable != null) {
|
||||
if (f.args.len != 0) return g.fail("E7006", arg.span, "bound static function cannot be specialized again", f.name);
|
||||
return;
|
||||
};
|
||||
const target = g.function(f.name, arg.span) orelse return g.fail("E7002", arg.span, "unknown or inaccessible static function", f.name);
|
||||
if (target.generics.len != f.args.len) return g.fail("E7006", arg.span, "static function argument count mismatch", f.name);
|
||||
for (target.generics, f.args) |p, a| try g.headerArgument(p, a, params, depth + 1);
|
||||
}
|
||||
|
||||
fn run(g: *Generator) Error!ast.Module {
|
||||
var generic = false;
|
||||
for (g.m.types, 0..) |t, i| {
|
||||
for (g.m.types[0..i]) |previous| if (std.mem.eql(u8, t.name, previous.name)) return g.fail("E7006", t.span, "type defined twice", t.name);
|
||||
try g.validate(t.name, t.generics, t.span);
|
||||
switch (t.kind) {
|
||||
.@"struct" => |fs| for (fs, 0..) |f, j| {
|
||||
for (fs[0..j]) |prev| if (std.mem.eql(u8, f.name, prev.name)) return g.fail("E7006", f.span, "duplicate template field", f.name);
|
||||
},
|
||||
.@"enum" => |vs| {
|
||||
if (vs.len == 0) return g.fail("E7006", t.span, "enum needs a variant", t.name);
|
||||
for (vs, 0..) |v, j| for (vs[0..j]) |prev| if (std.mem.eql(u8, v.name, prev.name)) return g.fail("E7006", v.span, "duplicate template variant", v.name);
|
||||
},
|
||||
}
|
||||
if (t.generics.len != 0) switch (t.kind) {
|
||||
.@"struct" => |fs| for (fs) |field| try g.headerType(field.ty, t.generics, 0),
|
||||
.@"enum" => |vs| for (vs) |v| for (v.payload) |payload_type| try g.headerType(payload_type, t.generics, 0),
|
||||
};
|
||||
generic = generic or t.generics.len != 0;
|
||||
}
|
||||
for (g.m.functions, 0..) |f, i| {
|
||||
for (g.m.functions[0..i]) |previous| if (std.mem.eql(u8, f.name, previous.name)) return g.fail("E7006", f.span, "function defined twice", f.name);
|
||||
if (f.generics.len != 0 and std.mem.eql(u8, f.name, "main")) return g.fail("E7006", f.span, "entry cannot be generic", f.name);
|
||||
try g.validate(f.name, f.generics, f.span);
|
||||
if (f.generics.len != 0) {
|
||||
if (f.trusted != null) return g.fail("E7006", f.span, "trusted is not available in source templates", f.name);
|
||||
for (f.effects) |effect| if (authority.effectIndex(effect) == null) return g.fail("E0006", f.span, "unknown effect in template contract", effect);
|
||||
for (f.params, 0..) |p, j| {
|
||||
try g.checkBinding(p.name, p.span, .{ .params = f.generics });
|
||||
for (f.params[0..j]) |prev| if (std.mem.eql(u8, p.name, prev.name)) return g.fail("E7006", p.span, "duplicate value parameter", p.name);
|
||||
try g.headerType(p.ty, f.generics, 0);
|
||||
}
|
||||
try g.headerType(f.ret, f.generics, 0);
|
||||
}
|
||||
generic = generic or f.generics.len != 0;
|
||||
}
|
||||
if (!generic and !usesGenerics(ast.Module, g.m)) return g.m;
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var functions: std.ArrayList(ast.FnDecl) = .empty;
|
||||
for (g.m.types) |t| if (t.generics.len == 0) try types.append(g.arena, try g.walk(ast.TypeDecl, t, .{}));
|
||||
for (g.m.functions) |f| if (f.generics.len == 0) try functions.append(g.arena, try g.walk(ast.FnDecl, f, .{}));
|
||||
std.mem.sort(Instance, g.instances.items, {}, struct {
|
||||
fn less(_: void, a: Instance, b: Instance) bool {
|
||||
return std.mem.lessThan(u8, a.key, b.key);
|
||||
}
|
||||
}.less);
|
||||
for (g.instances.items, 0..) |*instance, i| {
|
||||
const base = instance.air_name;
|
||||
var candidate = base;
|
||||
var suffix: usize = 0;
|
||||
while (g.originalAirUsed(candidate) or usedAir(g.instances.items[0..i], candidate)) {
|
||||
suffix += 1;
|
||||
candidate = try std.fmt.allocPrint(g.arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
instance.air_name = candidate;
|
||||
switch (instance.decl) {
|
||||
.ty => |*t| t.air_name = candidate,
|
||||
.function => |*f| f.air_name = candidate,
|
||||
.pending => unreachable,
|
||||
}
|
||||
}
|
||||
for (g.instances.items) |instance| switch (instance.decl) {
|
||||
.ty => |t| try types.append(g.arena, t),
|
||||
.function => |f| try functions.append(g.arena, f),
|
||||
.pending => unreachable,
|
||||
};
|
||||
var out = g.m;
|
||||
out.types = types.items;
|
||||
out.functions = functions.items;
|
||||
out.requirements = g.requirements.items;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn instantiate(g: *Generator, comptime is_type: bool, template: if (is_type) ast.TypeDecl else ast.FnDecl, raw: []const ast.Type, env: Env, span: ast.Span) Error![]const u8 {
|
||||
if (g.depth >= 64) return g.fail("E7006", span, "generic argument or contract resolution exceeds depth 64", template.name);
|
||||
g.depth += 1;
|
||||
defer g.depth -= 1;
|
||||
if (template.generics.len == 0 or template.generics.len != raw.len) return g.fail("E7006", span, "explicit type argument count does not match declaration", template.name);
|
||||
const args = try g.arena.alloc(ast.Type, raw.len);
|
||||
var key: std.ArrayList(u8) = .empty;
|
||||
try key.appendSlice(g.arena, if (is_type) "type:" else "fn:");
|
||||
const owner = template.span.namespace orelse g.m.name;
|
||||
if (std.mem.indexOfScalar(u8, template.name, '.') == null) try key.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{owner}));
|
||||
try key.appendSlice(g.arena, template.name);
|
||||
try key.append(g.arena, '<');
|
||||
for (template.generics, raw, args, 0..) |p, arg, *out, i| {
|
||||
if (p.callable != null) {
|
||||
if (arg.kind != .function_ref) return g.fail("E7005", arg.span, "expected an explicit static function argument", p.name);
|
||||
out.* = try g.functionArgument(arg, env);
|
||||
} else {
|
||||
if (arg.kind == .function_ref) return g.fail("E7005", arg.span, "expected a type argument, found a static function", p.name);
|
||||
out.* = try g.ty(arg, env);
|
||||
}
|
||||
if (out.kind == .name and (std.mem.eql(u8, out.kind.name, "void") or std.mem.eql(u8, out.kind.name, "never"))) return g.fail("E7005", span, "generic arguments must be concrete non-void types", template.name);
|
||||
if (i != 0) try key.append(g.arena, ',');
|
||||
try g.identity(out.*, &key);
|
||||
}
|
||||
try key.append(g.arena, '>');
|
||||
if (key.items.len > 16384) return g.fail("E7006", span, "canonical specialization key exceeds 16384 bytes", template.name);
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.key, key.items)) return instance.name;
|
||||
if (g.instances.items.len >= 4096) return g.fail("E7006", span, "generic specialization exceeds fixed compiler limit", template.name);
|
||||
const hex = try g.arena.alloc(u8, key.items.len * 2);
|
||||
for (key.items, 0..) |b, i| {
|
||||
hex[2 * i] = "0123456789abcdef"[b >> 4];
|
||||
hex[2 * i + 1] = "0123456789abcdef"[b & 15];
|
||||
}
|
||||
const base = try std.fmt.allocPrint(g.arena, "__aji_g_{s}", .{hex});
|
||||
var air_name: []const u8 = base;
|
||||
var suffix: usize = 0;
|
||||
while (g.airUsed(air_name)) {
|
||||
suffix += 1;
|
||||
air_name = try std.fmt.allocPrint(g.arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
const name = if (std.mem.eql(u8, owner, g.m.name)) air_name else try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ owner, air_name });
|
||||
var digest: [32]u8 = undefined;
|
||||
std.crypto.hash.sha2.Sha256.hash(key.items, &digest, .{});
|
||||
const digest_hex = try g.arena.alloc(u8, 64);
|
||||
for (digest, 0..) |b, i| {
|
||||
digest_hex[2 * i] = "0123456789abcdef"[b >> 4];
|
||||
digest_hex[2 * i + 1] = "0123456789abcdef"[b & 15];
|
||||
}
|
||||
const final_air = try std.fmt.allocPrint(g.arena, "__aji_g_{s}", .{digest_hex});
|
||||
const index = g.instances.items.len;
|
||||
try g.instances.append(g.arena, .{ .key = key.items, .name = name, .air_name = final_air });
|
||||
const concrete_env: Env = .{ .params = template.generics, .args = args };
|
||||
if (!is_type) {
|
||||
var signature = template;
|
||||
signature.params = try g.walk([]const ast.Param, template.params, concrete_env);
|
||||
signature.ret = try g.ty(template.ret, concrete_env);
|
||||
signature.generics = &.{};
|
||||
signature.name = name;
|
||||
g.instances.items[index].signature = signature;
|
||||
}
|
||||
for (template.generics, args) |p, arg| {
|
||||
if (p.callable) |c| {
|
||||
try g.checkFunctionArgument(p.name, c.*, arg, concrete_env);
|
||||
} else try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = "", .span = span });
|
||||
}
|
||||
for (template.generics, args) |p, arg| for (p.constraints) |property| try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = property, .span = span });
|
||||
var body_template = template;
|
||||
body_template.generics = &.{};
|
||||
var concrete = try g.walk(@TypeOf(template), body_template, concrete_env);
|
||||
concrete.generics = &.{};
|
||||
concrete.name = name;
|
||||
concrete.air_name = final_air;
|
||||
concrete.display_name = key.items[if (is_type) 5 else 3..];
|
||||
g.instances.items[index].decl = if (is_type) .{ .ty = concrete } else .{ .function = concrete };
|
||||
return name;
|
||||
}
|
||||
|
||||
fn airUsed(g: *Generator, name: []const u8) bool {
|
||||
for (g.m.types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name) or std.mem.eql(u8, t.name, name) or std.mem.eql(u8, shortName(t.name), name)) return true;
|
||||
for (g.m.functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name) or std.mem.eql(u8, f.name, name) or std.mem.eql(u8, shortName(f.name), name)) return true;
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, shortName(instance.name), name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn originalAirUsed(g: *Generator, name: []const u8) bool {
|
||||
for (g.m.types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true;
|
||||
for (g.m.functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
fn instanceTypeKey(g: *Generator, name: []const u8) ?[]const u8 {
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name) and std.mem.startsWith(u8, instance.key, "type:")) return instance.key;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn identity(g: *Generator, t: ast.Type, out: *std.ArrayList(u8)) Error!void {
|
||||
switch (t.kind) {
|
||||
.name => |name| {
|
||||
if (g.typeDecl(name, t.span)) |d| {
|
||||
if (std.mem.indexOfScalar(u8, d.name, '.') == null) try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{g.m.name}));
|
||||
try out.appendSlice(g.arena, d.name);
|
||||
} else if (g.instanceTypeKey(name)) |key| {
|
||||
try out.appendSlice(g.arena, key[5..]);
|
||||
} else try out.appendSlice(g.arena, name);
|
||||
},
|
||||
.array => |a| {
|
||||
try out.appendSlice(g.arena, "[");
|
||||
try g.identity(a.elem.*, out);
|
||||
try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, ";{d}]", .{a.len}));
|
||||
},
|
||||
.wrapped => |w| {
|
||||
try out.appendSlice(g.arena, w.wrapper);
|
||||
try out.append(g.arena, '<');
|
||||
try g.identity(w.inner.*, out);
|
||||
try out.append(g.arena, '>');
|
||||
},
|
||||
.cap => |k| try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "cap<{s}>", .{k})),
|
||||
.file => |mode| try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "file<{s}>", .{mode})),
|
||||
.applied => unreachable,
|
||||
.function_ref => |f| {
|
||||
try out.appendSlice(g.arena, "fn ");
|
||||
const instance_key = for (g.instances.items) |instance| {
|
||||
if (std.mem.eql(u8, instance.name, f.name)) break instance.key;
|
||||
} else null;
|
||||
if (instance_key) |key| {
|
||||
try out.appendSlice(g.arena, key[3..]);
|
||||
} else {
|
||||
if (std.mem.indexOfScalar(u8, f.name, '.') == null) try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{g.m.name}));
|
||||
try out.appendSlice(g.arena, f.name);
|
||||
}
|
||||
},
|
||||
}
|
||||
if (out.items.len > 16384) return g.fail("E7006", t.span, "canonical specialization key exceeds 16384 bytes", "type");
|
||||
}
|
||||
|
||||
fn named(g: *Generator, name: []const u8, args: []const ast.Type, span: ast.Span, env: Env) Error!ast.Type {
|
||||
return g.ty(.{ .span = span, .kind = if (args.len == 0) .{ .name = name } else .{ .applied = .{ .name = name, .args = args } } }, env);
|
||||
}
|
||||
|
||||
fn ty(g: *Generator, input: ast.Type, env: Env) Error!ast.Type {
|
||||
if (g.type_depth >= 64) return g.fail("E7006", input.span, "structural type depth exceeds 64", "type");
|
||||
g.type_depth += 1;
|
||||
defer g.type_depth -= 1;
|
||||
var t = input;
|
||||
switch (input.kind) {
|
||||
.name => |name| {
|
||||
for (env.params, env.args) |p, arg| if (std.mem.eql(u8, name, p.name)) {
|
||||
if (p.callable != null) return g.fail("E7006", input.span, "static function parameter is not a type", name);
|
||||
return arg;
|
||||
};
|
||||
if (g.typeDecl(name, input.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", input.span, "generic type needs explicit arguments", name);
|
||||
t.kind.name = d.name;
|
||||
t.span.resolved = true;
|
||||
} else if (!builtin(name) and !g.generated(name)) return g.fail("E7002", input.span, "unknown or inaccessible type", name);
|
||||
},
|
||||
.applied => |x| {
|
||||
const d = g.typeDecl(x.name, input.span) orelse return g.fail("E7002", input.span, "unknown or inaccessible generic type", x.name);
|
||||
t.kind = .{ .name = try g.instantiate(true, d, x.args, env, input.span) };
|
||||
t.span.resolved = true;
|
||||
},
|
||||
.array => |a| t.kind.array.elem = try g.box(ast.Type, try g.ty(a.elem.*, env)),
|
||||
.wrapped => |w| t.kind.wrapped.inner = try g.box(ast.Type, try g.ty(w.inner.*, env)),
|
||||
.cap, .file => {},
|
||||
.function_ref => return g.fail("E7006", input.span, "static functions are not runtime types", "fn"),
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
fn generated(g: *Generator, name: []const u8) bool {
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn expression(g: *Generator, e: ast.Expr, env: Env) Error!ast.Expr {
|
||||
var out = e;
|
||||
if (e.kind == .move and env.params.len != 0) out.generic_transfer = true;
|
||||
switch (e.kind) {
|
||||
.name => |name| if (boundFunction(env, name) != null) return g.fail("E7006", e.span, "static function parameter is only a call target or named worker", name),
|
||||
.specialize => |x| {
|
||||
const name = path(g.arena, x.base.*) catch return error.OutOfMemory;
|
||||
if (name) |n| if (boundFunction(env, n) != null) return g.fail("E7006", e.span, "bound static function cannot be specialized again", n);
|
||||
const d = g.function(name orelse return g.fail("E7006", e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?);
|
||||
out.kind = .{ .name = try g.instantiate(false, d, x.args, env, e.span) };
|
||||
out.span.resolved = true;
|
||||
return out;
|
||||
},
|
||||
.call => |x| {
|
||||
out.kind.call.type_arg = try g.walk(?ast.Type, x.type_arg, env);
|
||||
const callee_name = try path(g.arena, x.callee.*);
|
||||
if (callee_name) |name| if (boundFunction(env, name)) |arg| {
|
||||
out.kind.call.callee = try g.box(ast.Expr, selectedExpr(x.callee.*, arg));
|
||||
out.kind.call.args = try g.walk([]const ast.Expr, x.args, env);
|
||||
return out;
|
||||
};
|
||||
if (x.callee.kind != .specialize and x.callee.kind != .variant) if (try path(g.arena, x.callee.*)) |name| if (g.function(name, x.callee.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", e.span, "generic function needs explicit arguments", name);
|
||||
};
|
||||
out.kind.call.callee = try g.box(ast.Expr, try g.expression(x.callee.*, env));
|
||||
const args = try g.arena.alloc(ast.Expr, x.args.len);
|
||||
for (x.args, args, 0..) |arg, *target, i| {
|
||||
if (i == 1 and callee_name != null and std.mem.eql(u8, callee_name.?, "task.spawn")) {
|
||||
if (try path(g.arena, arg)) |name| if (boundFunction(env, name)) |selected| {
|
||||
target.* = selectedExpr(arg, selected);
|
||||
continue;
|
||||
};
|
||||
}
|
||||
target.* = try g.expression(arg, env);
|
||||
}
|
||||
out.kind.call.args = args;
|
||||
return out;
|
||||
},
|
||||
.variant => |x| {
|
||||
const t = try g.named(x.@"enum", x.type_args, e.span, env);
|
||||
if (t.kind != .name) return g.fail("E7005", e.span, "enum constructor requires a named type", x.@"enum");
|
||||
out.kind.variant.@"enum" = t.kind.name;
|
||||
out.kind.variant.type_args = &.{};
|
||||
out.span.resolved = t.span.resolved;
|
||||
return out;
|
||||
},
|
||||
.struct_lit => |x| {
|
||||
const t = try g.named(x.name, x.type_args, e.span, env);
|
||||
if (t.kind != .name) return g.fail("E7005", e.span, "struct constructor requires a named type", x.name);
|
||||
out.kind.struct_lit.name = t.kind.name;
|
||||
out.kind.struct_lit.type_args = &.{};
|
||||
out.kind.struct_lit.fields = try g.walk([]const ast.FieldInit, x.fields, env);
|
||||
out.span.resolved = t.span.resolved;
|
||||
return out;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
out.kind = try g.walk(ast.Expr.Kind, e.kind, env);
|
||||
return out;
|
||||
}
|
||||
|
||||
fn box(g: *Generator, comptime T: type, value: T) A.Error!*const T {
|
||||
const out = try g.arena.create(T);
|
||||
out.* = value;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn walk(g: *Generator, comptime T: type, value: T, env: Env) Error!T {
|
||||
if (T == ast.Type) return g.ty(value, env);
|
||||
if (T == ast.Expr) return g.expression(value, env);
|
||||
if (T == ast.Pattern) {
|
||||
var out = value;
|
||||
if (value.kind == .ctor) for (value.kind.ctor.binds) |name| try g.checkBinding(name, value.span, env);
|
||||
if (value.kind == .ctor) if (value.kind.ctor.qualifier) |q| {
|
||||
const t = try g.named(q, value.kind.ctor.type_args, value.span, env);
|
||||
if (t.kind != .name) return g.fail("E7005", value.span, "enum pattern requires a named type", q);
|
||||
out.kind.ctor.qualifier = t.kind.name;
|
||||
out.kind.ctor.type_args = &.{};
|
||||
out.span.resolved = t.span.resolved;
|
||||
};
|
||||
return out;
|
||||
}
|
||||
if (T == ast.Param) try g.checkBinding(value.name, value.span, env);
|
||||
if (T == ast.Select) for (value.cancelled_binds) |name| try g.checkBinding(name, value.span, env);
|
||||
if (T == ast.Stmt) switch (value.kind) {
|
||||
.let => |x| for (x.names) |name| try g.checkBinding(name, value.span, env),
|
||||
inline .@"var", .borrow, .@"for", .scope, .lock => |x| try g.checkBinding(x.name, value.span, env),
|
||||
else => {},
|
||||
};
|
||||
if (T == ast.Span) return value;
|
||||
switch (@typeInfo(T)) {
|
||||
.@"struct" => |info| {
|
||||
var out = value;
|
||||
inline for (info.field_names, info.field_types) |name, FieldType| @field(out, name) = try g.walk(FieldType, @field(value, name), env);
|
||||
return out;
|
||||
},
|
||||
.@"union" => switch (value) {
|
||||
inline else => |payload, tag| return @unionInit(T, @tagName(tag), try g.walk(@TypeOf(payload), payload, env)),
|
||||
},
|
||||
.optional => |info| return if (value) |v| try g.walk(info.child, v, env) else null,
|
||||
.pointer => |info| {
|
||||
if (info.child == u8) return value;
|
||||
if (info.size == .slice) {
|
||||
const out = try g.arena.alloc(info.child, value.len);
|
||||
for (value, out) |v, *target| target.* = try g.walk(info.child, v, env);
|
||||
return out;
|
||||
}
|
||||
return try g.box(info.child, try g.walk(info.child, value.*, env));
|
||||
},
|
||||
else => return value,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pub const Property = enum { Copy, Send, Share, Freeze, Local };
|
||||
fn local(full: []const u8, owner: []const u8, short: []const u8) bool {
|
||||
return full.len == owner.len + short.len + 1 and std.mem.startsWith(u8, full, owner) and full[owner.len] == '.' and std.mem.eql(u8, full[owner.len + 1 ..], short);
|
||||
}
|
||||
fn builtin(name: []const u8) bool {
|
||||
const names = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool", "void", "never", "region", "stream", "listener", "alloc_error", "cap_error", "io_error" };
|
||||
for (names) |n| if (std.mem.eql(u8, n, name)) return true;
|
||||
return false;
|
||||
}
|
||||
fn path(arena: A, e: ast.Expr) A.Error!?[]const u8 {
|
||||
return switch (e.kind) {
|
||||
.name => |name| name,
|
||||
.field => |f| if (try path(arena, f.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, f.name }) else null,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn usesGenerics(comptime T: type, value: T) bool {
|
||||
if (T == ast.Type) if (value.kind == .applied or value.kind == .function_ref) return true;
|
||||
if (T == ast.Expr) switch (value.kind) {
|
||||
.specialize => return true,
|
||||
.variant => |x| if (x.type_args.len != 0) return true,
|
||||
.struct_lit => |x| if (x.type_args.len != 0) return true,
|
||||
else => {},
|
||||
};
|
||||
if (T == ast.Pattern) if (value.kind == .ctor and value.kind.ctor.type_args.len != 0) return true;
|
||||
switch (@typeInfo(T)) {
|
||||
.@"struct" => |info| {
|
||||
inline for (info.field_names, info.field_types) |name, FT| if (usesGenerics(FT, @field(value, name))) return true;
|
||||
},
|
||||
.@"union" => switch (value) {
|
||||
inline else => |payload| return usesGenerics(@TypeOf(payload), payload),
|
||||
},
|
||||
.optional => |info| return if (value) |v| usesGenerics(info.child, v) else false,
|
||||
.pointer => |info| {
|
||||
if (info.child == u8) return false;
|
||||
if (info.size == .slice) {
|
||||
for (value) |v| if (usesGenerics(info.child, v)) return true;
|
||||
} else return usesGenerics(info.child, value.*);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
fn selectedExpr(original: ast.Expr, arg: ast.Type) ast.Expr {
|
||||
var out = original;
|
||||
out.kind = .{ .name = arg.kind.function_ref.name };
|
||||
out.span.resolved = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn shortName(name: []const u8) []const u8 {
|
||||
return if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name;
|
||||
}
|
||||
|
||||
fn usedAir(instances: []const Instance, name: []const u8) bool {
|
||||
for (instances) |instance| if (std.mem.eql(u8, instance.air_name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
+504
-127
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
//! Pure linking of explicit source inputs; no filesystem or authority.
|
||||
const std = @import("std");
|
||||
const ast = @import("ast.zig");
|
||||
const parse = @import("parse.zig");
|
||||
const lower = @import("lower.zig");
|
||||
const stdlib = @import("stdlib.zig");
|
||||
const authority = @import("../air/authority.zig");
|
||||
|
||||
pub const Source = stdlib.Source;
|
||||
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem };
|
||||
const Error = error{ OutOfMemory, InvalidSource };
|
||||
const Node = struct { module: ast.Module, active: bool, height: usize = 0 };
|
||||
|
||||
pub fn reserved(name: []const u8) bool {
|
||||
const first = if (std.mem.indexOfScalar(u8, name, '.')) |at| name[0..at] else name;
|
||||
for ([_][]const u8{ "std", "slice", "buffer", "own", "region", "cap", "task", "channel", "mutex", "island", "frozen", "arc", "atomic" }) |word| {
|
||||
if (std.mem.eql(u8, first, word)) return true;
|
||||
}
|
||||
for (authority.intrinsics) |intrinsic| {
|
||||
const at = std.mem.indexOfScalar(u8, intrinsic.name, '.').?;
|
||||
if (std.mem.eql(u8, first, intrinsic.name[0..at])) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
pub fn link(arena: std.mem.Allocator, entry: ast.Module, sources: []const Source) std.mem.Allocator.Error!Result {
|
||||
var g: Graph = .{ .arena = arena, .sources = sources };
|
||||
const span: ast.Span = if (entry.functions.len != 0) entry.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } };
|
||||
const combined = g.run(entry, span) catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.InvalidSource => return .{ .err = g.problem.? },
|
||||
};
|
||||
return .{ .ok = combined };
|
||||
}
|
||||
|
||||
const Graph = struct {
|
||||
arena: std.mem.Allocator,
|
||||
sources: []const Source,
|
||||
nodes: std.ArrayList(Node) = .empty,
|
||||
problem: ?lower.Problem = null,
|
||||
|
||||
fn fail(g: *Graph, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
g.problem = .{ .code = code, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory };
|
||||
return error.InvalidSource;
|
||||
}
|
||||
|
||||
fn run(g: *Graph, entry: ast.Module, span: ast.Span) Error!ast.Module {
|
||||
if (g.sources.len > 1024) return g.fail("E7006", span, "more than 1024 mapped modules", entry.name);
|
||||
for (g.sources, 0..) |source, i| {
|
||||
if (reserved(source.name)) return g.fail("E7006", span, "package mapping uses a reserved namespace", source.name);
|
||||
for (g.sources[0..i]) |previous| if (std.mem.eql(u8, previous.name, source.name)) return g.fail("E7006", span, "module mapped twice", source.name);
|
||||
}
|
||||
try g.nodes.append(g.arena, .{ .module = entry, .active = true });
|
||||
const root_height = try g.imports(entry, 0);
|
||||
g.nodes.items[0].height = root_height;
|
||||
g.nodes.items[0].active = false;
|
||||
std.mem.sort(Node, g.nodes.items[1..], {}, struct {
|
||||
fn less(_: void, a: Node, b: Node) bool {
|
||||
return std.mem.lessThan(u8, a.module.name, b.module.name);
|
||||
}
|
||||
}.less);
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var functions: std.ArrayList(ast.FnDecl) = .empty;
|
||||
var scopes: std.ArrayList(ast.ModuleScope) = .empty;
|
||||
try types.appendSlice(g.arena, entry.types);
|
||||
try functions.appendSlice(g.arena, entry.functions);
|
||||
for (g.nodes.items, 0..) |node, i| {
|
||||
const m = node.module;
|
||||
try scopes.append(g.arena, .{ .name = m.name, .entry = i == 0, .qualified_self = i != 0 or !reserved(m.name), .imports = m.imports });
|
||||
if (i == 0) continue;
|
||||
for (m.types) |t| {
|
||||
var qualified = t;
|
||||
qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, t.name });
|
||||
qualified.air_name = try airName(g.arena, m.name, t.name, types.items, functions.items);
|
||||
try types.append(g.arena, qualified);
|
||||
}
|
||||
for (m.functions) |f| {
|
||||
var qualified = f;
|
||||
qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, f.name });
|
||||
qualified.air_name = try airName(g.arena, m.name, f.name, types.items, functions.items);
|
||||
try functions.append(g.arena, qualified);
|
||||
}
|
||||
}
|
||||
var result = entry;
|
||||
result.types = types.items;
|
||||
result.functions = functions.items;
|
||||
result.scopes = scopes.items;
|
||||
return result;
|
||||
}
|
||||
|
||||
fn imports(g: *Graph, m: ast.Module, depth: usize) Error!usize {
|
||||
var height: usize = 0;
|
||||
for (m.imports, 0..) |imp, i| {
|
||||
for (m.imports[0..i]) |previous| if (std.mem.eql(u8, imp.path, previous.path)) return g.fail("E7006", imp.span, "module imported twice", imp.path);
|
||||
height = @max(height, 1 + try g.visit(imp, depth + 1));
|
||||
}
|
||||
return height;
|
||||
}
|
||||
|
||||
fn visit(g: *Graph, imp: ast.Import, depth: usize) Error!usize {
|
||||
for (g.nodes.items) |node| if (std.mem.eql(u8, node.module.name, imp.path)) {
|
||||
if (node.active) return g.fail("E7006", imp.span, "cyclic module import", imp.path);
|
||||
if (depth + node.height > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path);
|
||||
return node.height;
|
||||
};
|
||||
if (depth > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path);
|
||||
const source = for (stdlib.registry) |source| {
|
||||
if (std.mem.eql(u8, source.name, imp.path)) break source;
|
||||
} else for (g.sources) |source| {
|
||||
if (std.mem.eql(u8, source.name, imp.path)) break source;
|
||||
} else return g.fail("E7002", imp.span, "unknown module in explicit source mapping", imp.path);
|
||||
const m = switch (try parse.parseWithFile(g.arena, source.source, source.file)) {
|
||||
.ok => |m| m,
|
||||
.err => |failure| {
|
||||
g.problem = .{
|
||||
.code = if (std.mem.startsWith(u8, source.name, "std.")) "E7900" else "E7001",
|
||||
.span = .{ .start = failure.pos, .end = failure.pos, .file = source.file, .namespace = source.name },
|
||||
.message = try std.fmt.allocPrint(g.arena, "expected {s}", .{failure.expected}),
|
||||
.fields = try g.arena.dupe(lower.Problem.Field, &.{ .{ .name = "expected", .value = failure.expected }, .{ .name = "found", .value = failure.found } }),
|
||||
};
|
||||
return error.InvalidSource;
|
||||
},
|
||||
};
|
||||
if (!std.mem.eql(u8, m.name, source.name)) return g.fail("E7006", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name);
|
||||
const index = g.nodes.items.len;
|
||||
try g.nodes.append(g.arena, .{ .module = m, .active = true });
|
||||
const height = try g.imports(m, depth);
|
||||
g.nodes.items[index].height = height;
|
||||
g.nodes.items[index].active = false;
|
||||
return g.nodes.items[index].height;
|
||||
}
|
||||
};
|
||||
|
||||
fn airName(arena: std.mem.Allocator, module: []const u8, name: []const u8, types: []const ast.TypeDecl, functions: []const ast.FnDecl) std.mem.Allocator.Error![]const u8 {
|
||||
const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ module, name });
|
||||
for (base) |*c| if (c.* == '.') {
|
||||
c.* = '_';
|
||||
};
|
||||
var candidate: []const u8 = base;
|
||||
var suffix: usize = 0;
|
||||
while (used(types, functions, candidate)) {
|
||||
suffix += 1;
|
||||
candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
fn used(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool {
|
||||
for (types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true;
|
||||
for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
+205
-42
@@ -15,8 +15,12 @@ pub const Failure = struct { pos: lex.Pos, expected: []const u8, found: []const
|
||||
pub const Result = union(enum) { ok: ast.Module, err: Failure };
|
||||
|
||||
pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result {
|
||||
return parseWithFile(arena, src, null);
|
||||
}
|
||||
|
||||
pub fn parseWithFile(arena: Allocator, src: []const u8, file: ?[]const u8) Allocator.Error!Result {
|
||||
const tokens = try lex.tokenize(arena, src);
|
||||
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens) };
|
||||
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens), .file = file };
|
||||
const m = p.module() catch |e| switch (e) {
|
||||
error.Syntax => return .{ .err = p.failure.? },
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
@@ -31,6 +35,8 @@ const Parser = struct {
|
||||
tokens: []Token,
|
||||
pos: usize = 0,
|
||||
failure: ?Failure = null,
|
||||
file: ?[]const u8 = null,
|
||||
module_name: ?[]const u8 = null,
|
||||
/// Struct literals are not allowed where a `{` starts a block (conditions).
|
||||
no_struct: bool = false,
|
||||
|
||||
@@ -99,7 +105,7 @@ const Parser = struct {
|
||||
}
|
||||
|
||||
fn span(p: *Parser, start: lex.Pos) ast.Span {
|
||||
return .{ .start = start, .end = p.prevEnd() };
|
||||
return .{ .start = start, .end = p.prevEnd(), .file = p.file, .namespace = p.module_name };
|
||||
}
|
||||
|
||||
fn box(p: *Parser, comptime T: type, v: T) Error!*const T {
|
||||
@@ -113,6 +119,14 @@ const Parser = struct {
|
||||
fn module(p: *Parser) Error!ast.Module {
|
||||
_ = try p.expectWord("module");
|
||||
const name = try p.path();
|
||||
p.module_name = name;
|
||||
var imports: std.ArrayList(ast.Import) = .empty;
|
||||
while (p.atWord("import")) {
|
||||
const start = p.next().pos;
|
||||
const path_name = try p.path();
|
||||
_ = try p.expect(.semicolon, "`;` after import");
|
||||
try imports.append(p.arena, .{ .path = path_name, .span = p.span(start) });
|
||||
}
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var fns: std.ArrayList(ast.FnDecl) = .empty;
|
||||
while (p.peek().tag != .eof) {
|
||||
@@ -122,7 +136,7 @@ const Parser = struct {
|
||||
try fns.append(p.arena, try p.fnDecl());
|
||||
} else return p.fail(p.peek(), "`struct`, `enum` or `fn`");
|
||||
}
|
||||
return .{ .name = name, .types = types.items, .functions = fns.items };
|
||||
return .{ .name = name, .imports = imports.items, .types = types.items, .functions = fns.items };
|
||||
}
|
||||
|
||||
fn path(p: *Parser) Error![]const u8 {
|
||||
@@ -142,6 +156,7 @@ const Parser = struct {
|
||||
const is_struct = p.atWord("struct");
|
||||
_ = p.next();
|
||||
const name = try p.ident("type name");
|
||||
const generics = try p.typeParams();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
if (is_struct) {
|
||||
var fields: std.ArrayList(ast.Field) = .empty;
|
||||
@@ -155,7 +170,7 @@ const Parser = struct {
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"struct" = fields.items } };
|
||||
return .{ .name = name, .generics = generics, .span = p.span(start), .kind = .{ .@"struct" = fields.items } };
|
||||
}
|
||||
var vs: std.ArrayList(ast.Variant) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
@@ -176,12 +191,13 @@ const Parser = struct {
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"enum" = vs.items } };
|
||||
return .{ .name = name, .generics = generics, .span = p.span(start), .kind = .{ .@"enum" = vs.items } };
|
||||
}
|
||||
|
||||
fn fnDecl(p: *Parser) Error!ast.FnDecl {
|
||||
const start = p.next().pos; // `fn`
|
||||
const name = try p.ident("function name");
|
||||
const generics = try p.typeParams();
|
||||
_ = try p.expect(.l_paren, "`(`");
|
||||
var params: std.ArrayList(ast.Param) = .empty;
|
||||
while (p.peek().tag != .r_paren) {
|
||||
@@ -219,7 +235,7 @@ const Parser = struct {
|
||||
trusted = t.text;
|
||||
}
|
||||
const body = try p.block();
|
||||
return .{ .name = name, .span = p.span(start), .params = params.items, .ret = ret, .from = from, .effects = effects.items, .trusted = trusted, .body = body };
|
||||
return .{ .name = name, .generics = generics, .span = p.span(start), .params = params.items, .ret = ret, .from = from, .effects = effects.items, .trusted = trusted, .body = body };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ types
|
||||
@@ -238,21 +254,98 @@ const Parser = struct {
|
||||
const t = p.peek();
|
||||
if (t.tag != .ident) return p.fail(t, "a type");
|
||||
_ = p.next();
|
||||
if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = t.text } };
|
||||
_ = p.next();
|
||||
if (std.mem.eql(u8, t.text, "cap")) {
|
||||
const k = try p.path();
|
||||
const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text;
|
||||
if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = name } };
|
||||
if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) {
|
||||
_ = p.next();
|
||||
const value = try p.path();
|
||||
try p.closeAngle();
|
||||
return .{ .span = p.span(start), .kind = .{ .cap = k } };
|
||||
return .{ .span = p.span(start), .kind = if (std.mem.eql(u8, name, "cap")) .{ .cap = value } else .{ .file = value } };
|
||||
}
|
||||
if (std.mem.eql(u8, t.text, "file")) {
|
||||
const m = try p.ident("`read`, `write` or `append`");
|
||||
try p.closeAngle();
|
||||
return .{ .span = p.span(start), .kind = .{ .file = m } };
|
||||
const args = try p.typeArgs();
|
||||
const wrappers = [_][]const u8{ "ref", "mut", "slice", "slice_mut", "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "iref", "atomic" };
|
||||
for (wrappers) |wrapper| if (std.mem.eql(u8, name, wrapper)) {
|
||||
if (args.len != 1) return p.fail(t, "one wrapper type argument");
|
||||
return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = name, .inner = try p.box(ast.Type, args[0]) } } };
|
||||
};
|
||||
return .{ .span = p.span(start), .kind = .{ .applied = .{ .name = name, .args = args } } };
|
||||
}
|
||||
|
||||
fn typeArgs(p: *Parser) Error![]const ast.Type {
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
var args: std.ArrayList(ast.Type) = .empty;
|
||||
try args.append(p.arena, try p.genericArg());
|
||||
while (p.peek().tag == .comma) {
|
||||
_ = p.next();
|
||||
try args.append(p.arena, try p.genericArg());
|
||||
}
|
||||
const inner = try p.typeExpr();
|
||||
try p.closeAngle();
|
||||
return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = t.text, .inner = try p.box(ast.Type, inner) } } };
|
||||
return args.items;
|
||||
}
|
||||
|
||||
fn genericArg(p: *Parser) Error!ast.Type {
|
||||
if (!p.atWord("fn")) return p.typeExpr();
|
||||
const start = p.next().pos;
|
||||
const name = try p.path();
|
||||
var args: []const ast.Type = &.{};
|
||||
if (p.peek().tag == .colon_colon) {
|
||||
_ = p.next();
|
||||
args = try p.typeArgs();
|
||||
}
|
||||
return .{ .span = p.span(start), .kind = .{ .function_ref = .{ .name = name, .args = args } } };
|
||||
}
|
||||
|
||||
fn functionContract(p: *Parser) Error!ast.FunctionContract {
|
||||
_ = try p.expectWord("fn");
|
||||
_ = try p.expect(.l_paren, "`(` in static function contract");
|
||||
var params: std.ArrayList(ast.Type) = .empty;
|
||||
while (p.peek().tag != .r_paren) {
|
||||
try params.append(p.arena, try p.typeExpr());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
_ = try p.expect(.arrow, "`->`");
|
||||
const ret = try p.typeExpr();
|
||||
_ = try p.expectWord("effects");
|
||||
_ = try p.expect(.l_bracket, "`[`");
|
||||
var effects: std.ArrayList([]const u8) = .empty;
|
||||
while (p.peek().tag != .r_bracket) {
|
||||
try effects.append(p.arena, try p.path());
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_bracket, "`]`");
|
||||
return .{ .params = params.items, .ret = ret, .effects = effects.items };
|
||||
}
|
||||
|
||||
fn typeParams(p: *Parser) Error![]const ast.TypeParam {
|
||||
if (p.peek().tag != .lt) return &.{};
|
||||
_ = p.next();
|
||||
var params: std.ArrayList(ast.TypeParam) = .empty;
|
||||
while (true) {
|
||||
const start = p.peek().pos;
|
||||
const name = try p.ident("a type parameter");
|
||||
var constraints: std.ArrayList([]const u8) = .empty;
|
||||
var callable: ?*const ast.FunctionContract = null;
|
||||
if (p.peek().tag == .colon) {
|
||||
_ = p.next();
|
||||
if (p.atWord("fn")) {
|
||||
callable = try p.box(ast.FunctionContract, try p.functionContract());
|
||||
} else {
|
||||
try constraints.append(p.arena, try p.ident("a structural property"));
|
||||
while (p.peek().tag == .plus) {
|
||||
_ = p.next();
|
||||
try constraints.append(p.arena, try p.ident("a structural property"));
|
||||
}
|
||||
}
|
||||
}
|
||||
try params.append(p.arena, .{ .name = name, .constraints = constraints.items, .span = p.span(start), .callable = callable });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
try p.closeAngle();
|
||||
return params.items;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ statements
|
||||
@@ -279,11 +372,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;
|
||||
@@ -294,7 +390,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)) {
|
||||
@@ -485,12 +581,17 @@ const Parser = struct {
|
||||
if (t.tag != .ident) return p.fail(t, "a pattern (`Enum::Variant`, an outcome, an integer or `_`)");
|
||||
_ = p.next();
|
||||
var qualifier: ?[]const u8 = null;
|
||||
var name = t.text;
|
||||
var name = try p.pathTail(t.text);
|
||||
var type_args: []const ast.Type = &.{};
|
||||
if (p.peek().tag == .colon_colon and p.peekAt(1).tag == .lt) {
|
||||
_ = p.next();
|
||||
type_args = try p.typeArgs();
|
||||
}
|
||||
if (p.peek().tag == .colon_colon) {
|
||||
_ = p.next();
|
||||
qualifier = t.text;
|
||||
qualifier = name;
|
||||
name = try p.ident("a variant name");
|
||||
}
|
||||
} else if (!std.mem.eql(u8, name, t.text)) return p.fail(p.peek(), "`::` after enum path");
|
||||
var binds: std.ArrayList([]const u8) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
_ = p.next();
|
||||
@@ -505,7 +606,7 @@ const Parser = struct {
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
return .{ .span = p.span(start), .kind = .{ .ctor = .{ .qualifier = qualifier, .name = name, .binds = binds.items } } };
|
||||
return .{ .span = p.span(start), .kind = .{ .ctor = .{ .qualifier = qualifier, .name = name, .binds = binds.items, .type_args = type_args } } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ expressions
|
||||
@@ -618,6 +719,20 @@ const Parser = struct {
|
||||
var e = try p.primary();
|
||||
while (true) {
|
||||
switch (p.peek().tag) {
|
||||
.colon_colon => {
|
||||
_ = p.next();
|
||||
if (p.peek().tag == .lt) {
|
||||
const base = try p.box(ast.Expr, e);
|
||||
const args = try p.typeArgs();
|
||||
e = .{ .span = p.span(start), .kind = .{ .specialize = .{ .base = base, .args = args } } };
|
||||
continue;
|
||||
}
|
||||
const base = if (e.kind == .specialize) e.kind.specialize.base.* else e;
|
||||
const name = try p.exprPath(base) orelse return p.fail(p.peek(), "an enum name before `::`");
|
||||
const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{};
|
||||
const variant = try p.ident("a variant name");
|
||||
e = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant, .type_args = type_args } } };
|
||||
},
|
||||
.dot => {
|
||||
_ = p.next();
|
||||
// After `.` a keyword is a member name (`task.cancelled`).
|
||||
@@ -627,7 +742,7 @@ const Parser = struct {
|
||||
const base = try p.box(ast.Expr, e);
|
||||
e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } };
|
||||
// `channel.make<T>(…)`: the only explicit type argument.
|
||||
if (std.mem.eql(u8, name, "make") and p.peek().tag == .lt and e.kind.field.e.kind == .name and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) {
|
||||
if (p.peek().tag == .lt and e.kind.field.e.kind == .name and ((std.mem.eql(u8, name, "make") and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) or (std.mem.eql(u8, name, "new") and std.mem.eql(u8, e.kind.field.e.kind.name, "buffer")))) {
|
||||
_ = p.next();
|
||||
const ty = try p.typeExpr();
|
||||
try p.closeAngle();
|
||||
@@ -636,6 +751,16 @@ const Parser = struct {
|
||||
e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } };
|
||||
}
|
||||
},
|
||||
.l_brace => {
|
||||
if (p.no_struct) return e;
|
||||
const base = if (e.kind == .specialize) e.kind.specialize.base.* else e;
|
||||
const name = try p.exprPath(base) orelse return e;
|
||||
const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{};
|
||||
const last = if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name;
|
||||
if (!std.ascii.isUpper(last[0])) return e;
|
||||
e = try p.structLiteral(start, name);
|
||||
e.kind.struct_lit.type_args = type_args;
|
||||
},
|
||||
.l_paren => {
|
||||
const args = try p.callArgs();
|
||||
const callee = try p.box(ast.Expr, e);
|
||||
@@ -677,6 +802,45 @@ const Parser = struct {
|
||||
return args.items;
|
||||
}
|
||||
|
||||
fn pathTail(p: *Parser, first: []const u8) Error![]const u8 {
|
||||
if (p.peek().tag != .dot) return first;
|
||||
var name: std.ArrayList(u8) = .empty;
|
||||
try name.appendSlice(p.arena, first);
|
||||
while (p.peek().tag == .dot) {
|
||||
_ = p.next();
|
||||
try name.append(p.arena, '.');
|
||||
try name.appendSlice(p.arena, try p.ident("a name after `.`"));
|
||||
}
|
||||
return name.items;
|
||||
}
|
||||
|
||||
fn exprPath(p: *Parser, e: ast.Expr) Error!?[]const u8 {
|
||||
return switch (e.kind) {
|
||||
.name => |name| name,
|
||||
.field => |field| blk: {
|
||||
const parent = try p.exprPath(field.e.*) orelse break :blk null;
|
||||
break :blk try std.fmt.allocPrint(p.arena, "{s}.{s}", .{ parent, field.name });
|
||||
},
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn structLiteral(p: *Parser, start: lex.Pos, name: []const u8) Error!ast.Expr {
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
var fields: std.ArrayList(ast.FieldInit) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fs = p.peek().pos;
|
||||
const fname = try p.ident("a field name");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const fe = try p.expr();
|
||||
try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = name, .fields = fields.items } } };
|
||||
}
|
||||
|
||||
fn primary(p: *Parser) Error!ast.Expr {
|
||||
const start = p.peek().pos;
|
||||
const t = p.peek();
|
||||
@@ -702,6 +866,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, "`]`");
|
||||
@@ -733,27 +908,15 @@ 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) {
|
||||
if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) {
|
||||
_ = p.next();
|
||||
const v = try p.ident("a variant name");
|
||||
return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } };
|
||||
}
|
||||
if (p.peek().tag == .l_brace and !p.no_struct and std.ascii.isUpper(t.text[0])) {
|
||||
_ = p.next();
|
||||
var fields: std.ArrayList(ast.FieldInit) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fs = p.peek().pos;
|
||||
const fname = try p.ident("a field name");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const fe = try p.expr();
|
||||
try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = t.text, .fields = fields.items } } };
|
||||
return p.structLiteral(start, t.text);
|
||||
}
|
||||
return .{ .span = p.span(start), .kind = .{ .name = t.text } };
|
||||
},
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
//! Compiler-pinned safe source modules. General linking lives in modules.zig.
|
||||
|
||||
pub const Source = struct { name: []const u8, file: []const u8, source: []const u8 };
|
||||
|
||||
pub const registry = [_]Source{
|
||||
.{ .name = "std.bytes", .file = "std/bytes.aji", .source = @embedFile("std_bytes_aji") },
|
||||
.{ .name = "std.deque", .file = "std/deque.aji", .source = @embedFile("std_deque_aji") },
|
||||
.{ .name = "std.encoding.base64", .file = "std/encoding/base64.aji", .source = @embedFile("std_encoding_base64_aji") },
|
||||
.{ .name = "std.encoding.hex", .file = "std/encoding/hex.aji", .source = @embedFile("std_encoding_hex_aji") },
|
||||
.{ .name = "std.fmt", .file = "std/fmt.aji", .source = @embedFile("std_fmt_aji") },
|
||||
.{ .name = "std.hash", .file = "std/hash.aji", .source = @embedFile("std_hash_aji") },
|
||||
.{ .name = "std.hashmap", .file = "std/hashmap.aji", .source = @embedFile("std_hashmap_aji") },
|
||||
.{ .name = "std.hashset", .file = "std/hashset.aji", .source = @embedFile("std_hashset_aji") },
|
||||
.{ .name = "std.heap", .file = "std/heap.aji", .source = @embedFile("std_heap_aji") },
|
||||
.{ .name = "std.io", .file = "std/io.aji", .source = @embedFile("std_io_aji") },
|
||||
.{ .name = "std.io.reader", .file = "std/io/reader.aji", .source = @embedFile("std_io_reader_aji") },
|
||||
.{ .name = "std.io.writer", .file = "std/io/writer.aji", .source = @embedFile("std_io_writer_aji") },
|
||||
.{ .name = "std.map", .file = "std/map.aji", .source = @embedFile("std_map_aji") },
|
||||
.{ .name = "std.math", .file = "std/math.aji", .source = @embedFile("std_math_aji") },
|
||||
.{ .name = "std.option", .file = "std/option.aji", .source = @embedFile("std_option_aji") },
|
||||
.{ .name = "std.path", .file = "std/path.aji", .source = @embedFile("std_path_aji") },
|
||||
.{ .name = "std.result", .file = "std/result.aji", .source = @embedFile("std_result_aji") },
|
||||
.{ .name = "std.utf8", .file = "std/utf8.aji", .source = @embedFile("std_utf8_aji") },
|
||||
.{ .name = "std.vec", .file = "std/vec.aji", .source = @embedFile("std_vec_aji") },
|
||||
};
|
||||
+167
-26
@@ -76,6 +76,16 @@ pub const Value = union(enum) {
|
||||
iref: struct { id: u64, slot: u32 },
|
||||
/// `atomic<T>`: index into the machine's atomic cells (spec 04 §42).
|
||||
atomic: u32,
|
||||
buffer: *Buffer,
|
||||
|
||||
pub const Buffer = struct {
|
||||
// The interpreter stores only the initialized prefix. Capacity is
|
||||
// charged to Aji authority independently of this host representation;
|
||||
// push's Value-array bookkeeping does not allocate from that authority.
|
||||
cell: *Cell,
|
||||
capacity: u64,
|
||||
elem: air.Type,
|
||||
};
|
||||
|
||||
/// The guarded value is a separate cell, so a place borrowed through a
|
||||
/// guard points at an ordinary cell.
|
||||
@@ -109,6 +119,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,
|
||||
};
|
||||
@@ -341,6 +354,7 @@ const Copier = struct {
|
||||
mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty,
|
||||
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
|
||||
graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty,
|
||||
buffers: std.AutoHashMapUnmanaged(*Value.Buffer, *Value.Buffer) = .empty,
|
||||
|
||||
fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value {
|
||||
return switch (v) {
|
||||
@@ -348,6 +362,7 @@ const Copier = struct {
|
||||
.array => |xs| .{ .array = try c.items(xs) },
|
||||
.local => |cl| .{ .local = try c.cell(cl) },
|
||||
.own => |cl| .{ .own = try c.cell(cl) },
|
||||
.buffer => |b| .{ .buffer = try c.buffer(b) },
|
||||
.place => |p| .{ .place = try c.place(p) },
|
||||
.slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } },
|
||||
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
|
||||
@@ -374,10 +389,20 @@ 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;
|
||||
}
|
||||
|
||||
fn buffer(c: *Copier, old: *Value.Buffer) std.mem.Allocator.Error!*Value.Buffer {
|
||||
if (c.buffers.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.Buffer);
|
||||
try c.buffers.put(c.tmp, old, n);
|
||||
n.* = .{ .cell = try c.cell(old.cell), .capacity = old.capacity, .elem = old.elem };
|
||||
return n;
|
||||
}
|
||||
|
||||
fn mutex(c: *Copier, old: *Value.MutexCell) std.mem.Allocator.Error!*Value.MutexCell {
|
||||
if (c.mutexes.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.MutexCell);
|
||||
@@ -821,6 +846,7 @@ const Machine = struct {
|
||||
.bool => .{ .boolean = c.bits != 0 },
|
||||
else => unreachable,
|
||||
}),
|
||||
.error_const => |x| return bind(vals, inst.result, .{ .builtin = .{ .which = x.which, .variant = x.variant } }),
|
||||
.copy => |v| return bind(vals, inst.result, vals[v]),
|
||||
.arith => |x| {
|
||||
const bits = arith(x.op, x.mode, x.ty, vals[x.a].int.bits, vals[x.b].int.bits) catch |e| return .{ .trap = kindOf(e) };
|
||||
@@ -858,6 +884,13 @@ const Machine = struct {
|
||||
return bind(vals, inst.result, .{ .int = .{ .ty = x.to, .bits = bits } });
|
||||
},
|
||||
.assert => |v| return if (vals[v].boolean) .next else .{ .trap = .assert },
|
||||
.buffer_new, .buffer_len, .buffer_capacity, .buffer_view, .buffer_reserve, .buffer_push, .buffer_pop, .buffer_free => return m.execBuffer(f, vals, inst),
|
||||
.array_make => |x| return bind(vals, inst.result, .{ .array = try m.gatherMut(vals, x.args) }),
|
||||
.aggregate_unpack => |x| {
|
||||
const fields = if (x.ty == .array) vals[x.value].array else vals[x.value].aggregate.fields;
|
||||
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 +910,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 +967,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 +1001,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 +1009,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 +1486,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 +1534,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 +1600,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,
|
||||
};
|
||||
}
|
||||
@@ -1752,6 +1785,93 @@ const Machine = struct {
|
||||
}
|
||||
}
|
||||
|
||||
fn bufferOf(v: Value) *Value.Buffer {
|
||||
return switch (v) {
|
||||
.buffer => |b| b,
|
||||
.place => |p| bufferOf(placePtr(p).*),
|
||||
else => unreachable,
|
||||
};
|
||||
}
|
||||
|
||||
fn execBuffer(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
|
||||
switch (inst.op) {
|
||||
.buffer_new => |x| {
|
||||
const capacity = usize_(vals[x.n]);
|
||||
const size = budget.accountedSize(m.module, x.ty, 0).?;
|
||||
const bytes = std.math.mul(u64, capacity, size) catch null;
|
||||
const authority_ = vals[x.cap].cap;
|
||||
if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .array = &.{} }, .ty = .void };
|
||||
const b = try m.heap().create(Value.Buffer);
|
||||
b.* = .{ .cell = cell, .capacity = capacity, .elem = x.ty };
|
||||
try m.owners.put(m.heap(), cell, .{ .authority = authority_, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .buffer = b };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.buffer_len, .buffer_capacity => |v| {
|
||||
const b = bufferOf(vals[v]);
|
||||
if (try m.raceCheck(b.cell, &.{}, false)) |r| return r;
|
||||
return bind(vals, inst.result, .{ .int = .{ .ty = .usize, .bits = if (inst.op == .buffer_len) b.cell.value.array.len else b.capacity } });
|
||||
},
|
||||
.buffer_view => |v| {
|
||||
const b = bufferOf(vals[v]);
|
||||
if (try m.raceCheck(b.cell, &.{}, false)) |r| return r;
|
||||
return bind(vals, inst.result, .{ .slice = .{ .place = .{ .cell = b.cell, .path = &.{} }, .start = 0, .len = b.cell.value.array.len } });
|
||||
},
|
||||
.buffer_reserve => |x| {
|
||||
const b = bufferOf(vals[x.borrow]);
|
||||
if (try m.raceCheck(b.cell, &.{}, true)) |r| return r;
|
||||
const capacity = usize_(vals[x.n]);
|
||||
if (capacity <= b.capacity) return .{ .jump = x.ok };
|
||||
const size = budget.accountedSize(m.module, b.elem, 0).?;
|
||||
const bytes = std.math.mul(u64, capacity, size) catch null;
|
||||
const authority_ = vals[x.cap].cap;
|
||||
if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err);
|
||||
const old = m.owners.get(b.cell).?;
|
||||
m.uncharge(old.authority, old.bytes);
|
||||
try m.owners.put(m.heap(), b.cell, .{ .authority = authority_, .bytes = bytes.? });
|
||||
b.capacity = capacity;
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.buffer_push => |x| {
|
||||
const b = bufferOf(vals[x.borrow]);
|
||||
if (try m.raceCheck(b.cell, &.{}, true)) |r| return r;
|
||||
const old = b.cell.value.array;
|
||||
if (old.len == b.capacity) {
|
||||
vals[f.blocks[x.err].params[0].value] = vals[x.value];
|
||||
return .{ .jump = x.err };
|
||||
}
|
||||
const items = try m.heap().alloc(Value, old.len + 1);
|
||||
@memcpy(items[0..old.len], old);
|
||||
items[old.len] = try m.deepCopy(vals[x.value]);
|
||||
b.cell.value = .{ .array = items };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.buffer_pop => |x| {
|
||||
const b = bufferOf(vals[x.value]);
|
||||
if (try m.raceCheck(b.cell, &.{}, true)) |r| return r;
|
||||
const old = b.cell.value.array;
|
||||
if (old.len == 0) return .{ .jump = x.err };
|
||||
vals[f.blocks[x.ok].params[0].value] = old[old.len - 1];
|
||||
b.cell.value = .{ .array = old[0 .. old.len - 1] };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
.buffer_free => |x| {
|
||||
const b = bufferOf(vals[x.value]);
|
||||
if (try m.raceCheck(b.cell, &.{}, true)) |r| return r;
|
||||
if (b.cell.value.array.len != 0) {
|
||||
vals[f.blocks[x.err].params[0].value] = vals[x.value];
|
||||
return .{ .jump = x.err };
|
||||
}
|
||||
const allocation = m.owners.fetchRemove(b.cell).?.value;
|
||||
m.uncharge(allocation.authority, allocation.bytes);
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
else => unreachable,
|
||||
}
|
||||
}
|
||||
|
||||
fn allocFailed(f: air.Function, vals: []Value, err: u32) Step {
|
||||
vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } };
|
||||
return .{ .jump = err };
|
||||
@@ -1761,6 +1881,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 +1913,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 +2082,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 +2120,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 +2138,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]);
|
||||
@@ -2202,7 +2343,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
|
||||
},
|
||||
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
|
||||
.local, .place, .slice => try s.write(null),
|
||||
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null),
|
||||
.resource, .own, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null),
|
||||
// A capability is opaque: only its kind is shown, never its identity.
|
||||
.cap => {
|
||||
try s.beginObject();
|
||||
|
||||
+93
-66
@@ -17,10 +17,10 @@ const usage =
|
||||
\\usage: aji <command> [args]
|
||||
\\
|
||||
\\commands:
|
||||
\\ check [--report unsafe] <file.air>
|
||||
\\ check [--report unsafe] <file.air | file.aji | --manifest aji.toml>
|
||||
\\ parse and verify a text AIR module; the unsafe report
|
||||
\\ lists trusted boundaries and unsafe operations
|
||||
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air | --manifest aji.toml>
|
||||
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji | --manifest aji.toml>
|
||||
\\ verify, then run @main and print the run record;
|
||||
\\ --fuel stops after N executed instructions;
|
||||
\\ --grant binds capability parameter P of @main
|
||||
@@ -29,16 +29,16 @@ const usage =
|
||||
\\ --seed N; scheduler: --quantum N, --task-limit N,
|
||||
\\ --schedule-seed N; --profile hosted uses the real OS and
|
||||
\\ writes the record only to --result-file PATH
|
||||
\\ lower [--annotate | --stats] <file.aji>
|
||||
\\ lower [--annotate | --stats] <file.aji | --manifest aji.toml>
|
||||
\\ print the canonical AIR a source module lowers to;
|
||||
\\ --annotate adds source spans as comments (not canonical);
|
||||
\\ --stats prints source/AIR size and expansion ratio
|
||||
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji>
|
||||
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji | --manifest aji.toml>
|
||||
\\ run @main under every schedule and weak-memory choice
|
||||
\\ (depth first, up to N runs, default 100000) and print the
|
||||
\\ distinct outcomes; "complete" is true when the whole
|
||||
\\ choice tree was explored (spec 04 §20.5)
|
||||
\\ report <file.air> verify, then print the audit report (spec 10 §6.1)
|
||||
\\ report <file.air | file.aji | --manifest aji.toml> verify, then print the audit report (spec 10 §6.1)
|
||||
\\ codes list diagnostic codes as JSON Lines
|
||||
\\ features print supported AIR format, language version and features
|
||||
\\ explain <code> show one diagnostic code
|
||||
@@ -76,32 +76,43 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
return .accepted;
|
||||
}
|
||||
if (std.mem.eql(u8, cmd, "report")) {
|
||||
if (args.len != 3) return usageError("report takes exactly one file");
|
||||
const path = args[2];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const result = try aji.check.checkAir(arena, path, source);
|
||||
const from_manifest = args.len == 4 and std.mem.eql(u8, args[2], "--manifest");
|
||||
if (args.len != 3 and !from_manifest) return usageError("report takes a file or --manifest PATH");
|
||||
const input = try readInput(arena, io, args[args.len - 1], from_manifest) orelse return .usage;
|
||||
const result = try aji.check.checkWithModules(arena, input.path, input.source, input.modules);
|
||||
for (result.diagnostics) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
}
|
||||
if (result.status == .unimplemented) return .unimplemented;
|
||||
const module = result.module orelse return .rejected;
|
||||
try aji.report.write(arena, module, out);
|
||||
try out.writeByte('\n');
|
||||
return .accepted;
|
||||
}
|
||||
if (std.mem.eql(u8, cmd, "lower")) {
|
||||
const annotate = args.len == 4 and std.mem.eql(u8, args[2], "--annotate");
|
||||
const stats = args.len == 4 and std.mem.eql(u8, args[2], "--stats");
|
||||
if (args.len != 3 and !annotate and !stats) return usageError("lower takes [--annotate | --stats] and one .aji file");
|
||||
const path = args[args.len - 1];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
switch (try aji.frontend.compile(arena, path, source)) {
|
||||
var annotate = false;
|
||||
var stats = false;
|
||||
var manifest_path: ?[]const u8 = null;
|
||||
var rest = args[2..];
|
||||
while (rest.len != 0) {
|
||||
if (std.mem.eql(u8, rest[0], "--annotate") and !annotate and !stats) {
|
||||
annotate = true;
|
||||
rest = rest[1..];
|
||||
} else if (std.mem.eql(u8, rest[0], "--stats") and !annotate and !stats) {
|
||||
stats = true;
|
||||
rest = rest[1..];
|
||||
} else if (std.mem.eql(u8, rest[0], "--manifest") and rest.len >= 2 and manifest_path == null) {
|
||||
manifest_path = rest[1];
|
||||
rest = rest[2..];
|
||||
} else break;
|
||||
}
|
||||
if ((manifest_path != null and rest.len != 0) or (manifest_path == null and rest.len != 1)) return usageError("lower takes [--annotate | --stats] and a file or --manifest PATH");
|
||||
const input = try readInput(arena, io, manifest_path orelse rest[0], manifest_path != null) orelse return .usage;
|
||||
const path = input.path;
|
||||
const source = input.source;
|
||||
if (manifest_path != null and !std.mem.endsWith(u8, path, ".aji")) return usageError("lower requires a .aji entry");
|
||||
switch (try aji.frontend.compileWithModules(arena, path, source, input.modules)) {
|
||||
.ok => |o| {
|
||||
if (stats) {
|
||||
// How much mechanical work the frontend took over.
|
||||
@@ -190,12 +201,16 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
var result_file: ?[]const u8 = null;
|
||||
var rest = args[2..];
|
||||
var unsafe_report = false;
|
||||
if (std.mem.eql(u8, cmd, "check") and rest.len == 3 and std.mem.eql(u8, rest[0], "--report")) {
|
||||
if (std.mem.eql(u8, cmd, "check") and rest.len >= 3 and std.mem.eql(u8, rest[0], "--report")) {
|
||||
if (!std.mem.eql(u8, rest[1], "unsafe")) return usageError("--report takes unsafe");
|
||||
unsafe_report = true;
|
||||
rest = rest[2..];
|
||||
}
|
||||
var manifest_path: ?[]const u8 = null;
|
||||
if (std.mem.eql(u8, cmd, "check") and rest.len >= 2 and std.mem.eql(u8, rest[0], "--manifest")) {
|
||||
manifest_path = rest[1];
|
||||
rest = rest[2..];
|
||||
}
|
||||
while (std.mem.eql(u8, cmd, "run") and rest.len >= 2) {
|
||||
const flag = rest[0];
|
||||
const value = rest[1];
|
||||
@@ -229,46 +244,18 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
rest = rest[2..];
|
||||
}
|
||||
options.world.files = files.items;
|
||||
var path: []const u8 = undefined;
|
||||
var input: aji.source_package.Input = undefined;
|
||||
if (manifest_path) |mp| {
|
||||
// spec 12 §1.2: the module is the manifest's entry; its grants
|
||||
// are applied, each replaced by a --grant for the same parameter.
|
||||
if (rest.len != 0) return usageError("a file argument cannot be combined with --manifest");
|
||||
const text = std.Io.Dir.cwd().readFileAlloc(io, mp, arena, .limited(1 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ mp, err });
|
||||
return .usage;
|
||||
};
|
||||
const m = switch (try aji.manifest.parse(arena, text)) {
|
||||
.ok => |m| m,
|
||||
.err => |e| {
|
||||
std.debug.print("aji: manifest {s}:{d}: {s}\n", .{ mp, e.line, e.message });
|
||||
return .usage;
|
||||
},
|
||||
};
|
||||
const entry = m.entry orelse {
|
||||
std.debug.print("aji: manifest {s}: [package] entry is required for aji run\n", .{mp});
|
||||
return .usage;
|
||||
};
|
||||
path = try std.fs.path.join(arena, &.{ std.fs.path.dirname(mp) orelse ".", entry });
|
||||
var merged: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
for (m.grants) |g| {
|
||||
const overridden = for (grants.items) |cg| {
|
||||
if (std.mem.eql(u8, cg.parameter, g.parameter)) break true;
|
||||
} else false;
|
||||
if (!overridden) try merged.append(arena, .{ .parameter = g.parameter, .kind = g.kind, .scope = g.scope });
|
||||
}
|
||||
try merged.appendSlice(arena, grants.items);
|
||||
options.grants = merged.items;
|
||||
input = try readInput(arena, io, mp, true) orelse return .usage;
|
||||
options.grants = try mergeGrants(arena, input.grants, grants.items);
|
||||
} else {
|
||||
if (rest.len != 1) return usageError("check and run take exactly one file");
|
||||
path = rest[0];
|
||||
if (rest.len != 1) return usageError("check and run take a file or --manifest PATH");
|
||||
input = try readInput(arena, io, rest[0], false) orelse return .usage;
|
||||
options.grants = grants.items;
|
||||
}
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const report = try aji.check.checkFile(arena, path, source);
|
||||
const path = input.path;
|
||||
const report = try aji.check.checkWithModules(arena, path, input.source, input.modules);
|
||||
for (report.diagnostics) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
@@ -335,21 +322,22 @@ fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out:
|
||||
var max_runs: u64 = 100_000;
|
||||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
var rest = argv;
|
||||
var manifest_path: ?[]const u8 = null;
|
||||
while (rest.len >= 2) {
|
||||
if (std.mem.eql(u8, rest[0], "--max-runs")) {
|
||||
max_runs = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--max-runs takes a positive integer");
|
||||
} else if (std.mem.eql(u8, rest[0], "--grant")) {
|
||||
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||||
} else if (std.mem.eql(u8, rest[0], "--manifest") and manifest_path == null) {
|
||||
manifest_path = rest[1];
|
||||
} else break;
|
||||
rest = rest[2..];
|
||||
}
|
||||
if (rest.len != 1) return usageError("explore takes exactly one file");
|
||||
const path = rest[0];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const report = try aji.check.checkFile(arena, path, source);
|
||||
if ((manifest_path != null and rest.len != 0) or (manifest_path == null and rest.len != 1)) return usageError("explore takes a file or --manifest PATH");
|
||||
const input = try readInput(arena, io, manifest_path orelse rest[0], manifest_path != null) orelse return .usage;
|
||||
const all_grants = try mergeGrants(arena, input.grants, grants.items);
|
||||
const path = input.path;
|
||||
const report = try aji.check.checkWithModules(arena, path, input.source, input.modules);
|
||||
for (report.diagnostics) |d| {
|
||||
try d.writeJson(out);
|
||||
try out.writeByte('\n');
|
||||
@@ -366,7 +354,7 @@ fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out:
|
||||
defer run_arena.deinit();
|
||||
var ex: aji.interp.Explore = .{ .prefix = prefix.items };
|
||||
const outcome = aji.interp.run(run_arena.allocator(), module, "main", .{
|
||||
.grants = grants.items,
|
||||
.grants = all_grants,
|
||||
.quantum = std.math.maxInt(u64),
|
||||
.explore = &ex,
|
||||
}) catch |err| switch (err) {
|
||||
@@ -442,7 +430,7 @@ fn writeRecord(arena: std.mem.Allocator, module: aji.air.Module, outcome: aji.in
|
||||
try out.writeAll(text[0 .. text.len - 1]);
|
||||
var j: std.json.Stringify = .{ .writer = out };
|
||||
try out.writeAll(",\"source_location\":");
|
||||
try j.write(.{ .file = path, .line = s.start.line, .col = s.start.col });
|
||||
try j.write(.{ .file = s.file orelse path, .line = s.start.line, .col = s.start.col });
|
||||
try out.writeAll("}");
|
||||
}
|
||||
|
||||
@@ -479,3 +467,42 @@ test parseGrant {
|
||||
try std.testing.expect(parseGrant("out=io.write").?.scope == null);
|
||||
try std.testing.expect(parseGrant("io.write") == null);
|
||||
}
|
||||
|
||||
test "standard library trap record identifies the bundled source" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const allocator = arena.allocator();
|
||||
const report = try aji.check.checkFile(allocator, "client.aji", "module t\nimport std.math;\nfn main() -> u64\neffects []\n{ return std.math.clamp_u64(5, 9, 4); }\n");
|
||||
try std.testing.expectEqual(aji.check.Status.accepted, report.status);
|
||||
const module = report.module.?;
|
||||
const outcome = try aji.interp.run(allocator, module, "main", .{ .fuel = 10000 });
|
||||
try std.testing.expect(outcome == .trapped);
|
||||
var output: std.Io.Writer.Allocating = .init(allocator);
|
||||
try writeRecord(allocator, module, outcome, null, report, "client.aji", &output.writer);
|
||||
const record = try std.json.parseFromSlice(std.json.Value, allocator, output.written(), .{});
|
||||
const location = record.value.object.get("source_location").?.object;
|
||||
try std.testing.expectEqualStrings("std/math.aji", location.get("file").?.string);
|
||||
try std.testing.expectEqual(@as(i64, 20), location.get("line").?.integer);
|
||||
}
|
||||
|
||||
fn readInput(arena: std.mem.Allocator, io: std.Io, path: []const u8, from_manifest: bool) !?aji.source_package.Input {
|
||||
return switch (if (from_manifest) try aji.source_package.load(arena, io, path) else try aji.source_package.single(arena, io, path)) {
|
||||
.ok => |input| input,
|
||||
.err => |err| blk: {
|
||||
std.debug.print("aji: {s}:{d}: {s}\n", .{ err.path, err.line, err.message });
|
||||
break :blk null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
fn mergeGrants(arena: std.mem.Allocator, baseline: []const aji.manifest.Grant, overrides: []const aji.interp.Grant) ![]const aji.interp.Grant {
|
||||
var result: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
for (baseline) |grant| {
|
||||
const replaced = for (overrides) |override| {
|
||||
if (std.mem.eql(u8, grant.parameter, override.parameter)) break true;
|
||||
} else false;
|
||||
if (!replaced) try result.append(arena, .{ .parameter = grant.parameter, .kind = grant.kind, .scope = grant.scope });
|
||||
}
|
||||
try result.appendSlice(arena, overrides);
|
||||
return result.items;
|
||||
}
|
||||
+60
-3
@@ -6,13 +6,18 @@
|
||||
//! drop or misplace authority.
|
||||
|
||||
const std = @import("std");
|
||||
const modules = @import("frontend/modules.zig");
|
||||
|
||||
pub const Grant = struct { parameter: []const u8, kind: []const u8, scope: ?[]const u8 };
|
||||
|
||||
pub const ModuleBinding = struct { name: []const u8, file: []const u8, line: u32 };
|
||||
|
||||
pub const Manifest = struct {
|
||||
name: []const u8,
|
||||
version: []const u8,
|
||||
entry: ?[]const u8,
|
||||
modules: []const ModuleBinding = &.{},
|
||||
has_modules: bool = false,
|
||||
/// `[capabilities]` in file order.
|
||||
grants: []const Grant,
|
||||
};
|
||||
@@ -46,14 +51,32 @@ fn isKey(s: []const u8) bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
fn isModuleName(name: []const u8) bool {
|
||||
var parts = std.mem.splitScalar(u8, name, '.');
|
||||
while (parts.next()) |part| {
|
||||
if (part.len == 0 or !(std.ascii.isAlphabetic(part[0]) or part[0] == '_')) return false;
|
||||
for (part[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_')) return false;
|
||||
}
|
||||
return name.len != 0;
|
||||
}
|
||||
|
||||
pub fn sourcePath(path: []const u8) bool {
|
||||
if (!std.mem.endsWith(u8, path, ".aji") or std.mem.indexOfAny(u8, path, "\\:\x00") != null) return false;
|
||||
var parts = std.mem.splitScalar(u8, path, '/');
|
||||
while (parts.next()) |part| if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||
const Section = enum { none, package, capabilities, metadata };
|
||||
const Section = enum { none, package, capabilities, metadata, modules };
|
||||
var section: Section = .none;
|
||||
var seen_sections: [3]bool = .{ false, false, false };
|
||||
var seen_sections: [4]bool = @splat(false);
|
||||
var name: ?[]const u8 = null;
|
||||
var version: ?[]const u8 = null;
|
||||
var entry: ?[]const u8 = null;
|
||||
var grants: std.ArrayList(Grant) = .empty;
|
||||
var bindings: std.ArrayList(ModuleBinding) = .empty;
|
||||
var entry_line: u32 = 0;
|
||||
var keys: std.StringHashMapUnmanaged(void) = .empty;
|
||||
|
||||
var lines = std.mem.splitScalar(u8, text, '\n');
|
||||
@@ -74,7 +97,7 @@ pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||
}
|
||||
const eq = std.mem.indexOfScalar(u8, line, '=') orelse return fail(arena, line_no, "expected key = \"value\"", .{});
|
||||
const key = std.mem.trim(u8, line[0..eq], " \t");
|
||||
if (!isKey(key)) return fail(arena, line_no, "malformed key", .{});
|
||||
if (!(if (section == .modules) isModuleName(key) else isKey(key))) return fail(arena, line_no, "malformed key", .{});
|
||||
const value = (try parseString(arena, std.mem.trim(u8, line[eq + 1 ..], " \t"))) orelse
|
||||
return fail(arena, line_no, "value of {s} must be a string \"...\" (escapes \\\", \\\\, \\n), optionally followed by a # comment", .{key});
|
||||
if (section == .none) return fail(arena, line_no, "key {s} outside a section", .{key});
|
||||
@@ -89,15 +112,29 @@ pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||
version = value;
|
||||
} else if (std.mem.eql(u8, key, "entry")) {
|
||||
entry = value;
|
||||
entry_line = line_no;
|
||||
} else return fail(arena, line_no, "unknown key {s} in [package]", .{key});
|
||||
},
|
||||
.capabilities => try grants.append(arena, parseGrantValue(key, value) orelse
|
||||
return fail(arena, line_no, "grant {s} must be \"kind[:scope]\"", .{key})),
|
||||
.modules => {
|
||||
if (modules.reserved(key)) return fail(arena, line_no, "reserved module namespace {s}", .{key});
|
||||
if (!sourcePath(value)) return fail(arena, line_no, "module {s} needs a portable relative .aji path", .{key});
|
||||
if (bindings.items.len >= 1024) return fail(arena, line_no, "at most 1024 modules are allowed", .{});
|
||||
try bindings.append(arena, .{ .name = key, .file = value, .line = line_no });
|
||||
},
|
||||
.metadata => {},
|
||||
.none => unreachable,
|
||||
}
|
||||
}
|
||||
const has_modules = seen_sections[3];
|
||||
if (has_modules) {
|
||||
const source_entry = entry orelse return fail(arena, line_no, "[modules] requires an entry .aji source", .{});
|
||||
if (!sourcePath(source_entry)) return fail(arena, entry_line, "[modules] requires a portable relative entry .aji path", .{});
|
||||
}
|
||||
return .{ .ok = .{
|
||||
.modules = bindings.items,
|
||||
.has_modules = has_modules,
|
||||
.name = name orelse return fail(arena, line_no, "[package] name is required", .{}),
|
||||
.version = version orelse return fail(arena, line_no, "[package] version is required", .{}),
|
||||
.entry = entry,
|
||||
@@ -177,3 +214,23 @@ test "strict parsing" {
|
||||
try expectErr("[package]\nname = \"a\"\nversion = \"1\"\n[capabilities]\nout = \":x\"\n", 5); // empty kind
|
||||
try expectErr("[package]\nname = \"a\"\n", 3); // missing version: reported at the end of the file
|
||||
}
|
||||
|
||||
test "explicit package module mapping and portable paths" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const prefix = "[package]\nname = \"a\"\nversion = \"1\"\nentry = \"src/main.aji\"\n[modules]\n";
|
||||
const good = try parse(arena, prefix ++ "app.model = \"src/model.aji\"\n");
|
||||
try std.testing.expect(good == .ok);
|
||||
try std.testing.expectEqualStrings("app.model", good.ok.modules[0].name);
|
||||
try std.testing.expect(good.ok.has_modules);
|
||||
for ([_][]const u8{
|
||||
"app.model = \"../model.aji\"", "app.model = \"/model.aji\"", "app.model = \"src//model.aji\"",
|
||||
"app.model = \"src/./model.aji\"", "app.model = \"src/model.air\"", "app.model = \"C:/model.aji\"",
|
||||
"std.bytes = \"model.aji\"", "task.work = \"model.aji\"", "io.work = \"model.aji\"",
|
||||
"app..model = \"model.aji\"", "app.0model = \"model.aji\"", "app-model = \"model.aji\"",
|
||||
}) |line| try expectErr(try std.mem.concat(arena, u8, &.{ prefix, line }), 6);
|
||||
try expectErr(prefix ++ "app.model = \"model.aji\"\napp.model = \"other.aji\"", 7);
|
||||
try expectErr("[package]\nname = \"a\"\nversion = \"1\"\nentry = \"main.air\"\n[modules]\n", 4);
|
||||
for ([_][]const u8{ "src\\model.aji", "a\x00.aji", "src/../a.aji", "src/.aji/../b.aji" }) |path| try std.testing.expect(!sourcePath(path));
|
||||
}
|
||||
+1
-1
@@ -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 => {
|
||||
.buffer_new, .buffer_reserve, .own_new, .own_pack, .own_array, .region_new, .region_array, .region_create, .channel_make, .island_create, .island_alloc, .arc_new => {
|
||||
info.allocations += 1;
|
||||
_ = try addOnce(arena, &info.direct, "mem.alloc");
|
||||
},
|
||||
|
||||
@@ -18,6 +18,7 @@ pub const check = @import("check.zig");
|
||||
pub const frontend = @import("frontend.zig");
|
||||
pub const report = @import("report.zig");
|
||||
pub const manifest = @import("manifest.zig");
|
||||
pub const source_package = @import("source_package.zig");
|
||||
|
||||
test {
|
||||
@import("std").testing.refAllDecls(@This());
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Explicit manifest source snapshot. No source is executed here.
|
||||
const std = @import("std");
|
||||
const manifest = @import("manifest.zig");
|
||||
const frontend = @import("frontend.zig");
|
||||
|
||||
pub const Input = struct {
|
||||
path: []const u8,
|
||||
source: []const u8,
|
||||
modules: []const frontend.modules.Source = &.{},
|
||||
grants: []const manifest.Grant = &.{},
|
||||
};
|
||||
pub const Failure = struct { path: []const u8, line: u32 = 0, message: []const u8 };
|
||||
pub const Result = union(enum) { ok: Input, err: Failure };
|
||||
const source_limit: usize = 64 << 20;
|
||||
|
||||
fn fail(arena: std.mem.Allocator, path: []const u8, err: anyerror) std.mem.Allocator.Error!Result {
|
||||
if (err == error.OutOfMemory) return error.OutOfMemory;
|
||||
return .{ .err = .{ .path = path, .message = try std.fmt.allocPrint(arena, "cannot read source: {t}", .{err}) } };
|
||||
}
|
||||
|
||||
pub fn single(arena: std.mem.Allocator, io: std.Io, path: []const u8) std.mem.Allocator.Error!Result {
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(source_limit)) catch |err| return fail(arena, path, err);
|
||||
return .{ .ok = .{ .path = path, .source = source } };
|
||||
}
|
||||
|
||||
pub fn load(arena: std.mem.Allocator, io: std.Io, path: []const u8) std.mem.Allocator.Error!Result {
|
||||
const text = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| return fail(arena, path, err);
|
||||
const m = switch (try manifest.parse(arena, text)) {
|
||||
.ok => |m| m,
|
||||
.err => |err| return .{ .err = .{ .path = path, .line = err.line, .message = err.message } },
|
||||
};
|
||||
const entry = m.entry orelse return .{ .err = .{ .path = path, .message = "[package] entry is required" } };
|
||||
const parent = std.fs.path.dirname(path) orelse ".";
|
||||
const entry_path = try std.fs.path.join(arena, &.{ parent, entry });
|
||||
if (!m.has_modules) {
|
||||
var result = try single(arena, io, entry_path);
|
||||
if (result == .ok) result.ok.grants = m.grants;
|
||||
return result;
|
||||
}
|
||||
const root = std.Io.Dir.cwd().openDir(io, parent, .{}) catch |err| return fail(arena, parent, err);
|
||||
defer root.close(io);
|
||||
const source = readSource(arena, io, root, entry, source_limit) catch |err| return fail(arena, entry, err);
|
||||
var remaining = source_limit - source.len;
|
||||
const bindings = try arena.dupe(manifest.ModuleBinding, m.modules);
|
||||
std.mem.sort(manifest.ModuleBinding, bindings, {}, struct {
|
||||
fn less(_: void, a: manifest.ModuleBinding, b: manifest.ModuleBinding) bool {
|
||||
return std.mem.lessThan(u8, a.name, b.name);
|
||||
}
|
||||
}.less);
|
||||
var sources: std.ArrayList(frontend.modules.Source) = .empty;
|
||||
for (bindings) |binding| {
|
||||
const bytes = readSource(arena, io, root, binding.file, remaining) catch |err| return fail(arena, binding.file, err);
|
||||
remaining -= bytes.len;
|
||||
try sources.append(arena, .{ .name = binding.name, .file = binding.file, .source = bytes });
|
||||
}
|
||||
return .{ .ok = .{ .path = entry_path, .source = source, .modules = sources.items, .grants = m.grants } };
|
||||
}
|
||||
|
||||
fn readSource(arena: std.mem.Allocator, io: std.Io, root: std.Io.Dir, path: []const u8, limit: usize) ![]const u8 {
|
||||
std.debug.assert(manifest.sourcePath(path));
|
||||
var dirs: std.ArrayList(std.Io.Dir) = .empty;
|
||||
defer for (dirs.items) |dir| dir.close(io);
|
||||
var current = root;
|
||||
var parts = std.mem.splitScalar(u8, path, '/');
|
||||
while (parts.next()) |part| {
|
||||
if (parts.peek() != null) {
|
||||
const next = try current.openDir(io, part, .{ .follow_symlinks = false });
|
||||
dirs.append(arena, next) catch |err| {
|
||||
next.close(io);
|
||||
return err;
|
||||
};
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
// Avoid opening a static pipe/device; the opened handle is checked too.
|
||||
if ((try current.statFile(io, part, .{ .follow_symlinks = false })).kind != .file) return error.NotRegularSource;
|
||||
const file = try current.openFile(io, part, .{ .follow_symlinks = false, .allow_directory = false });
|
||||
defer file.close(io);
|
||||
const stat = try file.stat(io);
|
||||
if (stat.kind != .file) return error.NotRegularSource;
|
||||
if (stat.size > limit) return error.StreamTooLong;
|
||||
var reader = file.reader(io, &.{});
|
||||
const bytes = reader.interface.allocRemaining(arena, .limited(limit + 1)) catch |err| switch (err) {
|
||||
error.ReadFailed => return reader.err.?,
|
||||
else => return err,
|
||||
};
|
||||
if (bytes.len > limit) return error.StreamTooLong;
|
||||
return bytes;
|
||||
}
|
||||
unreachable;
|
||||
}
|
||||
+58
-10
@@ -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).
|
||||
@@ -242,6 +242,11 @@ pub fn overlap(a: []const Seg, b: []const Seg) bool {
|
||||
const Edge = struct { target: u32, args: []const ValueId };
|
||||
|
||||
fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void {
|
||||
if (op.bufferTargets()) |t| {
|
||||
try out.append(arena, .{ .target = t.ok, .args = &.{} });
|
||||
try out.append(arena, .{ .target = t.err, .args = &.{} });
|
||||
return;
|
||||
}
|
||||
switch (op) {
|
||||
.br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }),
|
||||
.cbr => |x| {
|
||||
@@ -252,10 +257,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 +270,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 +308,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 +324,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 +343,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 } },
|
||||
@@ -384,7 +390,7 @@ fn step(w: *Walker, inst: air.Inst) !void {
|
||||
},
|
||||
.borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }),
|
||||
.borrow_index => |x| try w.derive(inst.result.?, x.borrow, .elem),
|
||||
.slice_make => |v| try w.derive(inst.result.?, v, null),
|
||||
.buffer_view, .slice_make => |v| try w.derive(inst.result.?, v, null),
|
||||
.slice_sub => |x| try w.derive(inst.result.?, x.slice, .elem),
|
||||
.slice_split => |x| {
|
||||
const l = inst.result.?;
|
||||
@@ -433,7 +439,49 @@ 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);
|
||||
},
|
||||
.buffer_new => {},
|
||||
.buffer_len, .buffer_capacity => |v| try w.useThrough(v, .shared),
|
||||
.buffer_reserve => |x| try w.useThrough(x.borrow, .exclusive),
|
||||
.buffer_push => |x| {
|
||||
try w.useThrough(x.borrow, .exclusive);
|
||||
if (w.isResource(x.value)) try w.consume(x.value, .moved);
|
||||
},
|
||||
.buffer_pop => |x| try w.useThrough(x.value, .exclusive),
|
||||
.buffer_free => |x| try w.consume(x.value, .moved),
|
||||
.own_pack => |x| {
|
||||
if (w.isResource(x.value)) try w.consume(x.value, .moved);
|
||||
},
|
||||
.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");
|
||||
|
||||
@@ -33,6 +33,7 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
|
||||
.atomic => |inner| accountedSize(m, inner.*, depth + 1),
|
||||
.mutex => |inner| std.math.add(u64, 8, accountedSize(m, inner.*, depth + 1) orelse return null) catch null,
|
||||
.own_array => 16,
|
||||
.buffer => 24,
|
||||
.slice, .slice_mut => 16,
|
||||
.builtin => |b| tagSize(b.variants().len),
|
||||
.array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1) orelse return null) catch null,
|
||||
@@ -87,6 +88,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 +152,7 @@ fn checkValueSizes(c: *verifier.Context) !void {
|
||||
for (b.params) |p| try v.visit(b.span, p.ty);
|
||||
for (b.insts) |inst| switch (inst.op) {
|
||||
.local_alloc => |t| try v.visit(inst.span, t),
|
||||
.array_splat => |x| try v.visit(inst.span, x.ty),
|
||||
inline .array_splat, .array_make, .aggregate_unpack, .own_pack, .buffer_new => |x| try v.visit(inst.span, x.ty),
|
||||
else => {},
|
||||
};
|
||||
}
|
||||
|
||||
+34
-1
@@ -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,38 @@ 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");
|
||||
},
|
||||
.buffer_new => |x| {
|
||||
try paramCount(c, f, inst.span, x.ok, 1, "buffer.new success takes buffer");
|
||||
try paramCount(c, f, inst.span, x.err, 1, "buffer.new failure takes alloc_error");
|
||||
},
|
||||
.buffer_reserve => |x| {
|
||||
try paramCount(c, f, inst.span, x.ok, 0, "buffer.reserve success takes no values");
|
||||
try paramCount(c, f, inst.span, x.err, 1, "buffer.reserve failure takes alloc_error");
|
||||
},
|
||||
.buffer_push => |x| {
|
||||
try paramCount(c, f, inst.span, x.ok, 0, "buffer.push success takes no values");
|
||||
try paramCount(c, f, inst.span, x.err, 1, "buffer.push failure returns value");
|
||||
},
|
||||
.buffer_pop => |x| {
|
||||
try paramCount(c, f, inst.span, x.ok, 1, "buffer.pop success takes value");
|
||||
try paramCount(c, f, inst.span, x.err, 0, "buffer.pop empty takes no values");
|
||||
},
|
||||
.buffer_free => |x| {
|
||||
try paramCount(c, f, inst.span, x.ok, 0, "buffer.free success takes no values");
|
||||
try paramCount(c, f, inst.span, x.err, 1, "buffer.free nonempty returns buffer");
|
||||
},
|
||||
.own_pack => |x| {
|
||||
try paramCount(c, f, inst.span, x.ok, 1, "own.pack success takes owner");
|
||||
try paramCount(c, f, inst.span, x.err, 2, "own.pack failure takes error and original value");
|
||||
},
|
||||
// `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");
|
||||
|
||||
@@ -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")) {
|
||||
.buffer_new, .buffer_reserve, .own_new, .own_pack, .own_array, .region_create, .region_new, .region_array, .island_create, .island_alloc, .arc_new => if (!contains(f.effects, "mem.alloc")) {
|
||||
try c.report("E3101", inst.span, "allocation requires the effect mem.alloc", &.{
|
||||
.{ .name = "function", .value = .{ .str = f.name } },
|
||||
.{ .name = "effect", .value = .{ .str = "mem.alloc" } },
|
||||
|
||||
+177
-23
@@ -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,19 +48,24 @@ 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, .buffer_new => |x| try wellFormed(c, inst.span, x.ty, .param, f.name),
|
||||
else => {},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// E1003: an aggregate that contains itself by value has no finite size.
|
||||
try checkFiniteLayouts(c);
|
||||
}
|
||||
|
||||
/// E1003 applies through arrays as well as direct nominal members.
|
||||
pub fn checkFiniteLayouts(c: *Context) !void {
|
||||
const m = c.module;
|
||||
const state = try c.arena.alloc(enum { white, grey, black }, m.types.len);
|
||||
@memset(state, .white);
|
||||
for (0..m.types.len) |i| try visitDecl(c, state, @intCast(i));
|
||||
}
|
||||
|
||||
fn visitDecl(c: *Context, state: anytype, i: u32) !void {
|
||||
fn visitDecl(c: *Context, state: anytype, i: u32) std.mem.Allocator.Error!void {
|
||||
if (state[i] == .black) return;
|
||||
if (state[i] == .grey) {
|
||||
const d = c.module.types[i];
|
||||
@@ -66,12 +75,21 @@ fn visitDecl(c: *Context, state: anytype, i: u32) !void {
|
||||
}
|
||||
state[i] = .grey;
|
||||
switch (c.module.types[i].kind) {
|
||||
.@"struct" => |fs| for (fs) |f| if (f.ty == .named) try visitDecl(c, state, f.ty.named),
|
||||
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| if (t == .named) try visitDecl(c, state, t.named),
|
||||
.@"struct" => |fs| for (fs) |f| try visitValue(c, state, f.ty),
|
||||
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try visitValue(c, state, t),
|
||||
}
|
||||
state[i] = .black;
|
||||
}
|
||||
|
||||
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, .buffer, .sender, .receiver, .mutex, .ref, .mut, .slice, .slice_mut, .guard, .task, .local => |inner| if (c.module.declares("linear_aggregates")) try visitValue(c, state, inner.*),
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
const Position = enum { member, param, ret, block_param, borrowed };
|
||||
|
||||
/// Where a type may appear (spec 07 §8.3, §8.8):
|
||||
@@ -85,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, .buffer, .region, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => pos != .member or c.module.declares("linear_aggregates"),
|
||||
else => true,
|
||||
};
|
||||
if (t == .own_array and c.module.declares("linear_aggregates") and c.module.isLinearType(t.own_array.*)) try c.report("E1001", span, "dynamic heap arrays require Copy content", &.{});
|
||||
// An atomic cell holds an AtomicScalar (spec 04 §23).
|
||||
if (t == .atomic and !isAtomicScalar(t.atomic.*)) try c.report("E1001", span, "atomic<T> needs bool or an integer of at most 64 bits", &.{
|
||||
.{ .name = "in", .value = .{ .str = owner } },
|
||||
@@ -117,6 +137,16 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
|
||||
}, owner);
|
||||
}
|
||||
|
||||
/// Validate a phantom or used source generic argument by ordinary type rules.
|
||||
pub fn checkTypeArgument(c: *Context, span: air.Span, t: Type) !void {
|
||||
try wellFormed(c, span, t, .param, "generic argument");
|
||||
try argumentLengths(c, span, t);
|
||||
}
|
||||
fn argumentLengths(c: *Context, span: air.Span, t: Type) !void {
|
||||
if (t == .array and (t.array.len == 0 or t.array.len > (1 << 32))) try c.report("E1001", span, "array length outside format-0 range", &.{});
|
||||
if (t.inner()) |inner| try argumentLengths(c, span, inner);
|
||||
}
|
||||
|
||||
/// `local.alloc` results are checked separately: their own type is storage.
|
||||
fn zeroable(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
@@ -228,6 +258,7 @@ const FnCtx = struct {
|
||||
fn resultType(m: air.Module, op: air.Op) ?Type {
|
||||
return switch (op) {
|
||||
.@"const" => |x| x.ty,
|
||||
.error_const => |x| .{ .builtin = x.which },
|
||||
.arith => |x| .{ .int = x.ty },
|
||||
.bit => |x| x.ty,
|
||||
.cmp => .bool,
|
||||
@@ -236,7 +267,7 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
|
||||
.struct_get => |x| m.types[x.decl].kind.@"struct"[x.field].ty,
|
||||
.enum_make => |x| .{ .named = x.decl },
|
||||
.call => |x| m.functions[x.callee].ret,
|
||||
.slice_len => .{ .int = .usize },
|
||||
.slice_len, .buffer_len, .buffer_capacity => .{ .int = .usize },
|
||||
.task_scope_begin => .scope,
|
||||
.task_cancelled => .bool,
|
||||
.task_shield_begin => .shield,
|
||||
@@ -246,7 +277,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,
|
||||
};
|
||||
}
|
||||
@@ -338,6 +369,35 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")
|
||||
}
|
||||
}
|
||||
|
||||
/// Structural Copy query for source constraints; borrows remain second-class.
|
||||
pub fn isCopy(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
.int, .bool, .builtin, .cap, .iref => true,
|
||||
.array => |a| isCopy(m, a.elem),
|
||||
.named => |i| aggregateAll(m, i, isCopy),
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Local is context-bound state, not the complement of Send (spec 15 §15).
|
||||
pub fn isLocalType(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
.local, .task, .scope, .shield, .guard => true,
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .mutex => |inner| isLocalType(m, inner.*),
|
||||
.array => |a| isLocalType(m, a.elem),
|
||||
.named => |i| switch (m.types[i].kind) {
|
||||
.@"struct" => |fs| for (fs) |f| {
|
||||
if (isLocalType(m, f.ty)) break true;
|
||||
} else false,
|
||||
.@"enum" => |vs| blk: {
|
||||
for (vs) |v| for (v.payload) |p| if (isLocalType(m, p)) break :blk true;
|
||||
break :blk false;
|
||||
},
|
||||
},
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// `Send` (spec 04 §35): may move to another task.
|
||||
pub fn isSend(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
@@ -346,7 +406,7 @@ pub fn isSend(m: air.Module, t: Type) bool {
|
||||
.island, .frozen, .arc, .iref => true,
|
||||
// Every access to a cell is an atomic operation (spec 04 §23).
|
||||
.atomic => true,
|
||||
.own, .own_array, .mutex => |inner| isSend(m, inner.*),
|
||||
.own, .own_array, .buffer, .mutex => |inner| isSend(m, inner.*),
|
||||
.ref, .slice => |inner| isShare(m, inner.*),
|
||||
.mut, .slice_mut => |inner| isSend(m, inner.*),
|
||||
.array => |a| isSend(m, a.elem),
|
||||
@@ -363,7 +423,7 @@ pub fn isShare(m: air.Module, t: Type) bool {
|
||||
// Its owner may mutate it: freeze to share (spec 04 §35).
|
||||
.island => false,
|
||||
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
|
||||
.own, .own_array, .ref, .slice => |inner| isShare(m, inner.*),
|
||||
.own, .own_array, .buffer, .ref, .slice => |inner| isShare(m, inner.*),
|
||||
// The lock synchronizes access (spec 04 §35, §40).
|
||||
.mutex => |inner| isSend(m, inner.*),
|
||||
.array => |a| isShare(m, a.elem),
|
||||
@@ -543,6 +603,17 @@ fn checkSelect(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "select")) !voi
|
||||
_ = f;
|
||||
}
|
||||
|
||||
fn bufferElement(fc: *FnCtx, span: air.Span, v: air.ValueId, mutable: bool) !?Type {
|
||||
const t = fc.typeOf(v);
|
||||
if ((t == .mut or (!mutable and t == .ref)) and t.inner().? == .buffer) return t.inner().?.buffer.*;
|
||||
try fc.kindError(span, v, if (mutable) "mut<buffer<T>>" else "ref<buffer<T>> or mut<buffer<T>>");
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn complete(t: Type) bool {
|
||||
return t != .void and t != .never and t != .local and !t.isBorrow() and !t.isTaskBound() and t != .guard;
|
||||
}
|
||||
|
||||
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
|
||||
const b = try arena.create(Type);
|
||||
b.* = t;
|
||||
@@ -559,7 +630,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
.copy => |v| return fc.ty[v],
|
||||
.local_alloc => |inner| return .{ .local = try boxed(a, inner) },
|
||||
.local_load => |v| fc.ty[v] orelse return null,
|
||||
.borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null,
|
||||
.buffer_view, .borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null,
|
||||
.value_swap => |x| fc.ty[x.borrow] orelse return null,
|
||||
.borrow_field => |x| fc.ty[x.borrow] orelse return null,
|
||||
.borrow_index => |x| fc.ty[x.borrow] orelse return null,
|
||||
.slice_sub => |x| fc.ty[x.slice] orelse return null,
|
||||
@@ -580,10 +652,13 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
};
|
||||
const invalid: Type = .void;
|
||||
return switch (op) {
|
||||
.buffer_view => if ((t == .ref or t == .mut) and t.inner().? == .buffer) (if (t == .mut) .{ .slice_mut = try boxed(a, t.inner().?.buffer.*) } else .{ .slice = try boxed(a, t.inner().?.buffer.*) }) else invalid,
|
||||
.value_swap => if (t == .mut) t.mut.* else invalid,
|
||||
.local_load => if (t == .local) t.local.* else invalid,
|
||||
.borrow_ref => switch (t) {
|
||||
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) },
|
||||
.named, .array => if (m.isLinearType(t)) .{ .ref = try boxed(a, t) } else invalid,
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .mutex, .buffer, .island, .frozen, .arc, .atomic => .{ .ref = try boxed(a, t) },
|
||||
.own => |inner| .{ .ref = inner },
|
||||
.own_array => |inner| .{ .slice = inner },
|
||||
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
|
||||
@@ -591,7 +666,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
|
||||
},
|
||||
.borrow_mut => switch (t) {
|
||||
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .island => .{ .mut = try boxed(a, t) },
|
||||
.named, .array => if (m.isLinearType(t)) .{ .mut = try boxed(a, t) } else invalid,
|
||||
.resource, .region, .task, .scope, .sender, .receiver, .buffer, .island => .{ .mut = try boxed(a, t) },
|
||||
.own => |inner| .{ .mut = inner },
|
||||
.own_array => |inner| .{ .slice_mut = inner },
|
||||
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
|
||||
@@ -719,11 +795,13 @@ 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", &.{
|
||||
.error_const => |x| if (x.variant >= x.which.variants().len) try fc.c.report("E1001", span, "invalid built-in error variant", &.{}),
|
||||
.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<T>");
|
||||
@@ -737,7 +815,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<T>"),
|
||||
.local_load => |v| {
|
||||
if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>");
|
||||
},
|
||||
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
|
||||
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, a resource, mut<T> or slice_mut<T>"),
|
||||
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
|
||||
@@ -745,12 +825,68 @@ 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<T> or mut<T>");
|
||||
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<T>");
|
||||
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<T>");
|
||||
try fc.expectValue(span, x.value, t.mut.*);
|
||||
if (!complete(t.mut.*)) try fc.kindError(span, x.value, "a complete value");
|
||||
},
|
||||
.buffer_new => |x| {
|
||||
try fc.expectValue(span, x.n, .{ .int = .usize });
|
||||
try fc.expectAllocCap(span, x.cap);
|
||||
if (!complete(x.ty)) return fc.kindError(span, x.n, "complete buffer content");
|
||||
try fc.expectParams(span, x.ok, &.{.{ .buffer = try boxed(fc.c.arena, x.ty) }});
|
||||
try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }});
|
||||
},
|
||||
.buffer_len, .buffer_capacity, .buffer_view => |v| {
|
||||
_ = try bufferElement(fc, span, v, false);
|
||||
},
|
||||
.buffer_reserve => |x| {
|
||||
_ = try bufferElement(fc, span, x.borrow, true);
|
||||
try fc.expectValue(span, x.n, .{ .int = .usize });
|
||||
try fc.expectAllocCap(span, x.cap);
|
||||
try fc.expectParams(span, x.err, &.{.{ .builtin = .alloc_error }});
|
||||
},
|
||||
.buffer_push => |x| {
|
||||
const t = try bufferElement(fc, span, x.borrow, true) orelse return;
|
||||
try fc.expectValue(span, x.value, t);
|
||||
try fc.expectParams(span, x.err, &.{t});
|
||||
},
|
||||
.buffer_pop => |x| {
|
||||
const t = try bufferElement(fc, span, x.value, true) orelse return;
|
||||
try fc.expectParams(span, x.ok, &.{t});
|
||||
},
|
||||
.buffer_free => |x| {
|
||||
const t = fc.typeOf(x.value);
|
||||
if (t != .buffer) return fc.kindError(span, x.value, "buffer<T>");
|
||||
try fc.expectParams(span, x.err, &.{t});
|
||||
},
|
||||
.array_make => |x| {
|
||||
if (x.ty != .array) return fc.c.report("E1001", span, "array.make needs an array type", &.{});
|
||||
if (x.args.len != x.ty.array.len) return fc.c.report("E1001", span, "array.make requires every element", &.{});
|
||||
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", &.{
|
||||
@@ -758,6 +894,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");
|
||||
@@ -775,6 +912,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<T>");
|
||||
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().?) }));
|
||||
@@ -807,7 +945,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];
|
||||
@@ -837,7 +978,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;
|
||||
@@ -848,21 +991,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<T>"),
|
||||
.own_free => |v| if (fc.typeOf(v) != .own and fc.typeOf(v) != .own_array) try fc.kindError(span, v, "own<T> or own_array<T>"),
|
||||
.own_free => |v| {
|
||||
const t = fc.typeOf(v);
|
||||
if (t != .own and t != .own_array) return fc.kindError(span, v, "own<T> or own_array<T>");
|
||||
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);
|
||||
@@ -870,14 +1024,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"),
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Aji standard library
|
||||
|
||||
Nineteen compiler-pinned modules implemented in ordinary safe `.aji`. Imports compile through the normal frontend and verifier. Modules are embedded with the compiler; an installed compiler needs no runtime std search path.
|
||||
|
||||
| Modules | Purpose |
|
||||
|---|---|
|
||||
| `std.math`, `std.bytes`, `std.hash` | checked arithmetic, byte operations, endian reads/writes, non-cryptographic hashes |
|
||||
| `std.utf8`, `std.encoding.hex`, `std.encoding.base64`, `std.fmt` | validation, caller-buffer encoding and decimal formatting |
|
||||
| `std.option`, `std.result` | explicit generic result values |
|
||||
| `std.vec`, `std.deque`, `std.map`, `std.hashmap`, `std.hashset`, `std.heap` | owning collections with explicit allocation, growth and draining |
|
||||
| `std.io`, `std.io.reader`, `std.io.writer` | bounded I/O and owning buffered file adapters |
|
||||
| `std.path` | pure lexical paths and caller-buffer normalization/join |
|
||||
|
||||
Owning collections support resources such as files and channel endpoints. Allocation requires explicit authority; resources must be consumed explicitly. Importing a module grants no capabilities. STD-0..7 is the intermediate foundation; remaining Std 0.1 system APIs and integration examples are tracked in the [plan](../docs/plan/standard-library.md).
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var data: [u8; 4] = zero;
|
||||
std.bytes.fill(mut data, 65);
|
||||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||||
return std.math.min_u64(42, 100);
|
||||
}
|
||||
```
|
||||
|
||||
Run `zig build`, then `zig-out/bin/aji run --fuel 1000000 examples/std/bytes.aji`. No grants are needed for the pure modules. `zig build conformance -- --filter source/std` exercises the library; the full suite also checks the Quick Reference example.
|
||||
|
||||
Endian APIs read/write u16/u32/u64 in LE/BE order. Reads return `std.bytes.ReadU16`, `ReadU32` or `ReadU64` (`ok(value)` / `short_input`); writes return `std.bytes.WriteResult` (`ok` / `short_output`). A short write leaves the entire destination unchanged. Pass a sub-slice for an offset. [Endian example](../examples/std/endian.aji) returns 305419896 and needs no grants.
|
||||
|
||||
`std.bytes.copy` reuses `WriteResult` and preserves the whole destination on short output. `find_slice` returns `FindResult::found(index)` / `not_found`; explicit slices compose a split without returned borrows. `std.math.checked_add/sub/mul_u64` and the `_usize` forms return typed `ok(value)` / `overflow` enums; wrapping stays with `+%`, `-%`, `*%`. The [bounded example](../examples/std/bounded.aji) returns 10 without grants.
|
||||
|
||||
`std.utf8.next/validate` use Unicode scalar values and explicit byte offsets. `std.encoding.hex` and `std.encoding.base64` encode/decode into caller-provided buffers; malformed input and short capacity are enum results, with no destination mutation on returned errors. Hex emits lowercase and accepts mixed case. Base64 is canonical, padded and uses the standard alphabet. The [text example](../examples/std/text.aji) returns 8364 without grants.
|
||||
|
||||
`std.fmt.write_u64/i64/usize/isize` write decimal ASCII into supplied buffers with `WriteResult::ok(count)` / `short_output`. Counts include a negative sign; short output stays unchanged, suffixes stay unchanged on success and no terminator is written. The [formatting example](../examples/std/format.aji) composes `value=-42 count=7` with explicit offsets and returns 17 without grants.
|
||||
|
||||
The compiler uses its embedded copy, so rebuild after editing these files. An installed compiler needs neither this checkout nor a runtime std search path. Standard enum types use fully qualified names in signatures, constructors and matches. Package imports and imported struct literals use explicit manifest mappings ([example](../examples/modules/aji.toml), spec 15 §14). Explicit generics and whole-value owning option/result templates are implemented; std.vec uses the initialized buffer contract with explicit reserve, bounded push and empty-only free.
|
||||
|
||||
[API reference](../docs/reference/std.md) · [Specification](../docs/spec/16-standard-library.md) · [Plan](../docs/plan/standard-library.md) · [Import RFC](../docs/rfcs/0016-standard-library-bootstrap.md) · [Endian RFC](../docs/rfcs/0017-standard-endian-results.md) · [Bounded operations RFC](../docs/rfcs/0018-bounded-standard-operations.md) · [Text RFC](../docs/rfcs/0019-standard-text-encodings.md)
|
||||
|
||||
[Formatting RFC](../docs/rfcs/0020-supplied-buffer-integer-formatting.md)
|
||||
|
||||
`std.option.Option<T>` and `std.result.Result<T, E>` use explicit specialization and ordinary exhaustive enum matching. `is_some::<T>`/`is_ok::<T,E>` 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<T> content. STD-6a/b adds initialized buffer<T> and std.vec; no bulk operation hides nested cleanup.
|
||||
|
||||
`std.vec` provides nine generic functions over Copy/owning values, including files and channel endpoints. Explicit new/reserve require allocation authority; push never grows, free requires empty contents. [Vector example](../examples/std/vector.aji) and [RFC 0024](../docs/rfcs/0024-linear-buffers-and-vectors.md).
|
||||
|
||||
`std.deque` provides eleven generic functions for a bounded owning ring, including push/pop at both ends. Allocation is explicit in new/reserve; failed growth, full push and nonempty free preserve the queue. Slots hold Option<T> and include its tag in the charge. Users drain/consume their elements before free. [Deque example](../examples/std/deque.aji) and [RFC 0025](../docs/rfcs/0025-owning-deque.md).
|
||||
|
||||
`std.hash` provides FNV-1a 64 and Castagnoli CRC-32C, with one fresh and one continuation function per algorithm. It reads byte slices with effects [], no allocation or authority; numeric results and chunking are deterministic. These are non-cryptographic algorithms and hashes never establish key equality. [Hash example](../examples/std/hash.aji) returns 42 without grants. `std.map` supports numeric keys; `std.hashmap` and `std.hashset` use explicit static hash/equality operations, and `std.heap` uses an explicit static order. Complete ownership, failure and cleanup contracts are in the [API reference](../docs/reference/std.md).
|
||||
|
||||
`std.io` composes exact/bounded reads and limited copies into caller storage. `std.io.reader`/`std.io.writer` own a file and a fixed buffer, with explicit finish/discard; a failed writer preserves its first error and never retries. `std.path` uses slash-separated bytes in every profile; lexical success grants no filesystem authority. [Path example](../examples/std/path.aji) returns 42 without grants.
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
module std.bytes
|
||||
|
||||
fn equal(a: slice<u8>, b: slice<u8>) -> bool
|
||||
effects []
|
||||
{
|
||||
if a.len != b.len { return false; }
|
||||
for i in 0..a.len {
|
||||
if a[i] != b[i] { return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn compare(a: slice<u8>, b: slice<u8>) -> i8
|
||||
effects []
|
||||
{
|
||||
var i: usize = 0;
|
||||
while i < a.len and i < b.len {
|
||||
if a[i] < b[i] { return -1; }
|
||||
if a[i] > b[i] { return 1; }
|
||||
i = i + 1;
|
||||
}
|
||||
if a.len < b.len { return -1; }
|
||||
if a.len > b.len { return 1; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
fn find(data: slice<u8>, byte: u8) -> usize
|
||||
effects []
|
||||
{
|
||||
for i in 0..data.len {
|
||||
if data[i] == byte { return i; }
|
||||
}
|
||||
return data.len;
|
||||
}
|
||||
|
||||
fn starts_with(data: slice<u8>, prefix: slice<u8>) -> bool
|
||||
effects []
|
||||
{
|
||||
if prefix.len > data.len { return false; }
|
||||
for i in 0..prefix.len {
|
||||
if data[i] != prefix[i] { return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn ends_with(data: slice<u8>, suffix: slice<u8>) -> bool
|
||||
effects []
|
||||
{
|
||||
if suffix.len > data.len { return false; }
|
||||
let start = data.len - suffix.len;
|
||||
for i in 0..suffix.len {
|
||||
if data[start + i] != suffix[i] { return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
fn fill(dst: slice_mut<u8>, byte: u8) -> void
|
||||
effects []
|
||||
{
|
||||
for i in 0..dst.len { dst[i] = byte; }
|
||||
}
|
||||
|
||||
// Endian results contain a value only on success.
|
||||
enum ReadU16 { ok(u16), short_input }
|
||||
enum ReadU32 { ok(u32), short_input }
|
||||
enum ReadU64 { ok(u64), short_input }
|
||||
enum WriteResult { ok, short_output }
|
||||
|
||||
fn read_u16_le(src: slice<u8>) -> std.bytes.ReadU16
|
||||
effects []
|
||||
{
|
||||
if src.len < 2 { return std.bytes.ReadU16::short_input; }
|
||||
let value: u16 = (src[0] as u16) | ((src[1] as u16) << 8);
|
||||
return std.bytes.ReadU16::ok(value);
|
||||
}
|
||||
|
||||
fn write_u16_le(dst: slice_mut<u8>, value: u16) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < 2 { return std.bytes.WriteResult::short_output; }
|
||||
dst[0] = value as% u8;
|
||||
dst[1] = (value >> 8) as% u8;
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
fn read_u16_be(src: slice<u8>) -> std.bytes.ReadU16
|
||||
effects []
|
||||
{
|
||||
if src.len < 2 { return std.bytes.ReadU16::short_input; }
|
||||
let value: u16 = ((src[0] as u16) << 8) | (src[1] as u16);
|
||||
return std.bytes.ReadU16::ok(value);
|
||||
}
|
||||
|
||||
fn write_u16_be(dst: slice_mut<u8>, value: u16) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < 2 { return std.bytes.WriteResult::short_output; }
|
||||
dst[0] = (value >> 8) as% u8;
|
||||
dst[1] = value as% u8;
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
fn read_u32_le(src: slice<u8>) -> std.bytes.ReadU32
|
||||
effects []
|
||||
{
|
||||
if src.len < 4 { return std.bytes.ReadU32::short_input; }
|
||||
let value: u32 = (src[0] as u32) | ((src[1] as u32) << 8) | ((src[2] as u32) << 16) | ((src[3] as u32) << 24);
|
||||
return std.bytes.ReadU32::ok(value);
|
||||
}
|
||||
|
||||
fn write_u32_le(dst: slice_mut<u8>, value: u32) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < 4 { return std.bytes.WriteResult::short_output; }
|
||||
dst[0] = value as% u8;
|
||||
dst[1] = (value >> 8) as% u8;
|
||||
dst[2] = (value >> 16) as% u8;
|
||||
dst[3] = (value >> 24) as% u8;
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
fn read_u32_be(src: slice<u8>) -> std.bytes.ReadU32
|
||||
effects []
|
||||
{
|
||||
if src.len < 4 { return std.bytes.ReadU32::short_input; }
|
||||
let value: u32 = ((src[0] as u32) << 24) | ((src[1] as u32) << 16) | ((src[2] as u32) << 8) | (src[3] as u32);
|
||||
return std.bytes.ReadU32::ok(value);
|
||||
}
|
||||
|
||||
fn write_u32_be(dst: slice_mut<u8>, value: u32) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < 4 { return std.bytes.WriteResult::short_output; }
|
||||
dst[0] = (value >> 24) as% u8;
|
||||
dst[1] = (value >> 16) as% u8;
|
||||
dst[2] = (value >> 8) as% u8;
|
||||
dst[3] = value as% u8;
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
fn read_u64_le(src: slice<u8>) -> std.bytes.ReadU64
|
||||
effects []
|
||||
{
|
||||
if src.len < 8 { return std.bytes.ReadU64::short_input; }
|
||||
let value: u64 = (src[0] as u64) | ((src[1] as u64) << 8) | ((src[2] as u64) << 16) | ((src[3] as u64) << 24) | ((src[4] as u64) << 32) | ((src[5] as u64) << 40) | ((src[6] as u64) << 48) | ((src[7] as u64) << 56);
|
||||
return std.bytes.ReadU64::ok(value);
|
||||
}
|
||||
|
||||
fn write_u64_le(dst: slice_mut<u8>, value: u64) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < 8 { return std.bytes.WriteResult::short_output; }
|
||||
dst[0] = value as% u8;
|
||||
dst[1] = (value >> 8) as% u8;
|
||||
dst[2] = (value >> 16) as% u8;
|
||||
dst[3] = (value >> 24) as% u8;
|
||||
dst[4] = (value >> 32) as% u8;
|
||||
dst[5] = (value >> 40) as% u8;
|
||||
dst[6] = (value >> 48) as% u8;
|
||||
dst[7] = (value >> 56) as% u8;
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
fn read_u64_be(src: slice<u8>) -> std.bytes.ReadU64
|
||||
effects []
|
||||
{
|
||||
if src.len < 8 { return std.bytes.ReadU64::short_input; }
|
||||
let value: u64 = ((src[0] as u64) << 56) | ((src[1] as u64) << 48) | ((src[2] as u64) << 40) | ((src[3] as u64) << 32) | ((src[4] as u64) << 24) | ((src[5] as u64) << 16) | ((src[6] as u64) << 8) | (src[7] as u64);
|
||||
return std.bytes.ReadU64::ok(value);
|
||||
}
|
||||
|
||||
fn write_u64_be(dst: slice_mut<u8>, value: u64) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < 8 { return std.bytes.WriteResult::short_output; }
|
||||
dst[0] = (value >> 56) as% u8;
|
||||
dst[1] = (value >> 48) as% u8;
|
||||
dst[2] = (value >> 40) as% u8;
|
||||
dst[3] = (value >> 32) as% u8;
|
||||
dst[4] = (value >> 24) as% u8;
|
||||
dst[5] = (value >> 16) as% u8;
|
||||
dst[6] = (value >> 8) as% u8;
|
||||
dst[7] = value as% u8;
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
fn copy(dst: slice_mut<u8>, src: slice<u8>) -> std.bytes.WriteResult
|
||||
effects []
|
||||
{
|
||||
if dst.len < src.len { return std.bytes.WriteResult::short_output; }
|
||||
slice.copy(mut dst, ref src);
|
||||
return std.bytes.WriteResult::ok;
|
||||
}
|
||||
|
||||
enum FindResult { found(usize), not_found }
|
||||
|
||||
fn find_slice(data: slice<u8>, needle: slice<u8>) -> std.bytes.FindResult
|
||||
effects []
|
||||
{
|
||||
if needle.len == 0 { return std.bytes.FindResult::found(0); }
|
||||
if needle.len > data.len { return std.bytes.FindResult::not_found; }
|
||||
let last = data.len - needle.len;
|
||||
var start: usize = 0;
|
||||
loop {
|
||||
if std.bytes.equal(ref data[start..start + needle.len], ref needle) {
|
||||
return std.bytes.FindResult::found(start);
|
||||
}
|
||||
if start == last { break; }
|
||||
start = start + 1;
|
||||
}
|
||||
return std.bytes.FindResult::not_found;
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
module std.deque
|
||||
import std.option;
|
||||
|
||||
struct Deque<T> { storage: buffer<std.option.Option<T>>, head: usize, length: usize }
|
||||
enum NewResult<T> { ok(Deque<T>), err(alloc_error) }
|
||||
enum PushResult<T> { ok, full(T) }
|
||||
enum ReserveResult { ok, err(alloc_error) }
|
||||
enum FreeResult<T> { ok, not_empty(Deque<T>) }
|
||||
enum ReplaceResult<T> { ok(T), out_of_bounds(T) }
|
||||
|
||||
fn new<T>(capacity: usize, heap: cap<mem.alloc>) -> NewResult<T>
|
||||
effects [mem.alloc]
|
||||
{
|
||||
match buffer.new<std.option.Option<T>>(capacity, heap) {
|
||||
ok(storage) => {
|
||||
{
|
||||
mut slots = storage;
|
||||
for index in 0usize..capacity {
|
||||
let empty = std.option.Option::<T>::none;
|
||||
buffer.push(slots, move empty) or trap;
|
||||
}
|
||||
}
|
||||
return NewResult::<T>::ok(Deque::<T> { storage: move storage, head: 0, length: 0 });
|
||||
}
|
||||
err(error) => { return NewResult::<T>::err(error); }
|
||||
}
|
||||
}
|
||||
|
||||
fn len<T>(value: ref<Deque<T>>) -> usize effects [] {
|
||||
return value.length;
|
||||
}
|
||||
|
||||
fn capacity<T>(value: ref<Deque<T>>) -> usize effects [] {
|
||||
ref slots = value.storage;
|
||||
return buffer.capacity(slots);
|
||||
}
|
||||
|
||||
fn reserve<T>(value: mut<Deque<T>>, capacity: usize, heap: cap<mem.alloc>) -> ReserveResult
|
||||
effects [mem.alloc]
|
||||
{
|
||||
let head = value.head;
|
||||
mut storage = value.storage;
|
||||
let old_capacity = buffer.capacity(storage);
|
||||
if capacity <= old_capacity { return ReserveResult::ok; }
|
||||
match buffer.reserve(storage, capacity, heap) {
|
||||
ok() => {}
|
||||
err(error) => { return ReserveResult::err(error); }
|
||||
}
|
||||
for index in old_capacity..capacity {
|
||||
let empty = std.option.Option::<T>::none;
|
||||
buffer.push(storage, move empty) or trap;
|
||||
}
|
||||
if head != 0usize {
|
||||
// Three reversals rotate the original slots left by head.
|
||||
mut slots = buffer.view(storage);
|
||||
for pass in 0usize..3usize {
|
||||
var first: usize = 0;
|
||||
var stop: usize = head;
|
||||
if pass == 1usize { first = head; stop = old_capacity; }
|
||||
if pass == 2usize { stop = old_capacity; }
|
||||
while first < stop {
|
||||
stop = stop - 1;
|
||||
if first < stop {
|
||||
let empty = std.option.Option::<T>::none;
|
||||
let left = value.swap(mut slots[first], move empty);
|
||||
let right = value.swap(mut slots[stop], move left);
|
||||
let hole = value.swap(mut slots[first], move right);
|
||||
match move hole {
|
||||
std.option.Option::<T>::none => {}
|
||||
std.option.Option::<T>::some(unexpected) => { trap; }
|
||||
}
|
||||
}
|
||||
first = first + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
value.head = 0;
|
||||
return ReserveResult::ok;
|
||||
}
|
||||
|
||||
fn push_back<T>(value: mut<Deque<T>>, item: T) -> PushResult<T> effects [] {
|
||||
let length = value.length;
|
||||
let head = value.head;
|
||||
mut storage = value.storage;
|
||||
let capacity = buffer.capacity(storage);
|
||||
if length == capacity { return PushResult::<T>::full(move item); }
|
||||
let room = capacity - head;
|
||||
let index = if length < room { head + length } else { length - room };
|
||||
mut slots = buffer.view(storage);
|
||||
let next = std.option.Option::<T>::some(move item);
|
||||
let previous = value.swap(mut slots[index], move next);
|
||||
match move previous {
|
||||
std.option.Option::<T>::none => {}
|
||||
std.option.Option::<T>::some(unexpected) => { trap; }
|
||||
}
|
||||
value.length = length + 1;
|
||||
return PushResult::<T>::ok;
|
||||
}
|
||||
|
||||
fn push_front<T>(value: mut<Deque<T>>, item: T) -> PushResult<T> effects [] {
|
||||
let length = value.length;
|
||||
let head = value.head;
|
||||
mut storage = value.storage;
|
||||
let capacity = buffer.capacity(storage);
|
||||
if length == capacity { return PushResult::<T>::full(move item); }
|
||||
let index = if head == 0usize { capacity - 1 } else { head - 1 };
|
||||
mut slots = buffer.view(storage);
|
||||
let next = std.option.Option::<T>::some(move item);
|
||||
let previous = value.swap(mut slots[index], move next);
|
||||
match move previous {
|
||||
std.option.Option::<T>::none => {}
|
||||
std.option.Option::<T>::some(unexpected) => { trap; }
|
||||
}
|
||||
value.head = index;
|
||||
value.length = length + 1;
|
||||
return PushResult::<T>::ok;
|
||||
}
|
||||
|
||||
fn pop_front<T>(value: mut<Deque<T>>) -> std.option.Option<T> effects [] {
|
||||
let length = value.length;
|
||||
if length == 0usize { return std.option.Option::<T>::none; }
|
||||
let head = value.head;
|
||||
mut storage = value.storage;
|
||||
let capacity = buffer.capacity(storage);
|
||||
mut slots = buffer.view(storage);
|
||||
let empty = std.option.Option::<T>::none;
|
||||
let previous = value.swap(mut slots[head], move empty);
|
||||
value.length = length - 1;
|
||||
if length == 1usize { value.head = 0; }
|
||||
else { value.head = if head == capacity - 1 { 0usize } else { head + 1 }; }
|
||||
match move previous {
|
||||
std.option.Option::<T>::some(item) => { return std.option.Option::<T>::some(move item); }
|
||||
std.option.Option::<T>::none => { trap; }
|
||||
}
|
||||
}
|
||||
|
||||
fn pop_back<T>(value: mut<Deque<T>>) -> std.option.Option<T> effects [] {
|
||||
let length = value.length;
|
||||
if length == 0usize { return std.option.Option::<T>::none; }
|
||||
let head = value.head;
|
||||
mut storage = value.storage;
|
||||
let capacity = buffer.capacity(storage);
|
||||
let offset = length - 1;
|
||||
let room = capacity - head;
|
||||
let index = if offset < room { head + offset } else { offset - room };
|
||||
mut slots = buffer.view(storage);
|
||||
let empty = std.option.Option::<T>::none;
|
||||
let previous = value.swap(mut slots[index], move empty);
|
||||
value.length = offset;
|
||||
if length == 1usize { value.head = 0; }
|
||||
match move previous {
|
||||
std.option.Option::<T>::some(item) => { return std.option.Option::<T>::some(move item); }
|
||||
std.option.Option::<T>::none => { trap; }
|
||||
}
|
||||
}
|
||||
|
||||
fn free<T>(value: Deque<T>) -> FreeResult<T> effects [] {
|
||||
if value.length != 0usize { return FreeResult::<T>::not_empty(move value); }
|
||||
let (storage, head, length) = struct.unpack(move value);
|
||||
{
|
||||
mut slots = storage;
|
||||
while buffer.len(slots) != 0usize {
|
||||
let empty = buffer.pop(slots) or trap;
|
||||
match move empty {
|
||||
std.option.Option::<T>::none => {}
|
||||
std.option.Option::<T>::some(unexpected) => { trap; }
|
||||
}
|
||||
}
|
||||
}
|
||||
buffer.free(move storage) or trap;
|
||||
return FreeResult::<T>::ok;
|
||||
}
|
||||
|
||||
fn get<T: Copy>(value: ref<Deque<T>>, index: usize) -> std.option.Option<T> effects [] {
|
||||
if index >= value.length { return std.option.Option::<T>::none; }
|
||||
let head = value.head;
|
||||
ref storage = value.storage;
|
||||
let room = buffer.capacity(storage) - head;
|
||||
let position = if index < room { head + index } else { index - room };
|
||||
ref slots = buffer.view(storage);
|
||||
match slots[position] {
|
||||
std.option.Option::<T>::some(item) => { return std.option.Option::<T>::some(item); }
|
||||
std.option.Option::<T>::none => { trap; }
|
||||
}
|
||||
}
|
||||
|
||||
fn replace<T>(value: mut<Deque<T>>, index: usize, item: T) -> ReplaceResult<T> effects [] {
|
||||
if index >= value.length { return ReplaceResult::<T>::out_of_bounds(move item); }
|
||||
let head = value.head;
|
||||
mut storage = value.storage;
|
||||
let room = buffer.capacity(storage) - head;
|
||||
let position = if index < room { head + index } else { index - room };
|
||||
mut slots = buffer.view(storage);
|
||||
let next = std.option.Option::<T>::some(move item);
|
||||
let previous = value.swap(mut slots[position], move next);
|
||||
match move previous {
|
||||
std.option.Option::<T>::some(old) => { return ReplaceResult::<T>::ok(move old); }
|
||||
std.option.Option::<T>::none => { trap; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
module std.encoding.base64
|
||||
|
||||
enum EncodeResult { ok(usize), short_output }
|
||||
enum DecodeResult { ok(usize), invalid_input, short_output }
|
||||
|
||||
fn encode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.base64.EncodeResult
|
||||
effects []
|
||||
{
|
||||
let groups = src.len / 3;
|
||||
let rest = src.len % 3;
|
||||
if groups > dst.len / 4 { return std.encoding.base64.EncodeResult::short_output; }
|
||||
let full = groups * 4;
|
||||
if rest != 0 and dst.len - full < 4 { return std.encoding.base64.EncodeResult::short_output; }
|
||||
let count = full + if rest == 0 { 0usize } else { 4usize };
|
||||
let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var i: usize = 0;
|
||||
var out: usize = 0;
|
||||
while src.len - i >= 3 {
|
||||
let a = src[i]; let b = src[i + 1]; let c = src[i + 2];
|
||||
dst[out] = alphabet[(a >> 2) as! usize];
|
||||
dst[out + 1] = alphabet[(((a & 3) << 4) | (b >> 4)) as! usize];
|
||||
dst[out + 2] = alphabet[(((b & 15) << 2) | (c >> 6)) as! usize];
|
||||
dst[out + 3] = alphabet[(c & 63) as! usize];
|
||||
i = i + 3; out = out + 4;
|
||||
}
|
||||
if rest != 0 {
|
||||
let a = src[i];
|
||||
let b: u8 = if rest == 2 { src[i + 1] } else { 0u8 };
|
||||
dst[out] = alphabet[(a >> 2) as! usize];
|
||||
dst[out + 1] = alphabet[(((a & 3) << 4) | (b >> 4)) as! usize];
|
||||
dst[out + 2] = if rest == 2 { alphabet[((b & 15) << 2) as! usize] } else { 61u8 };
|
||||
dst[out + 3] = 61;
|
||||
}
|
||||
return std.encoding.base64.EncodeResult::ok(count);
|
||||
}
|
||||
|
||||
fn decode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.base64.DecodeResult
|
||||
effects []
|
||||
{
|
||||
if src.len % 4 != 0 { return std.encoding.base64.DecodeResult::invalid_input; }
|
||||
if src.len == 0 { return std.encoding.base64.DecodeResult::ok(0); }
|
||||
let alphabet = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var values: [u8; 256] = [255; 256];
|
||||
for i in 0..alphabet.len { values[alphabet[i] as! usize] = i as! u8; }
|
||||
var padding: usize = 0;
|
||||
if src[src.len - 1] == 61 {
|
||||
padding = 1;
|
||||
if src[src.len - 2] == 61 { padding = 2; }
|
||||
}
|
||||
for i in 0..src.len - padding {
|
||||
if values[src[i] as! usize] == 255 { return std.encoding.base64.DecodeResult::invalid_input; }
|
||||
}
|
||||
if padding == 2 and (values[src[src.len - 3] as! usize] & 15) != 0 {
|
||||
return std.encoding.base64.DecodeResult::invalid_input;
|
||||
}
|
||||
if padding == 1 and (values[src[src.len - 2] as! usize] & 3) != 0 {
|
||||
return std.encoding.base64.DecodeResult::invalid_input;
|
||||
}
|
||||
let groups = src.len / 4;
|
||||
let count = groups * 3 - padding;
|
||||
if count > dst.len { return std.encoding.base64.DecodeResult::short_output; }
|
||||
for group in 0..groups {
|
||||
let i = group * 4; let out = group * 3;
|
||||
let a = values[src[i] as! usize]; let b = values[src[i + 1] as! usize];
|
||||
dst[out] = (a << 2) | (b >> 4);
|
||||
if out + 1 < count {
|
||||
let c = values[src[i + 2] as! usize];
|
||||
dst[out + 1] = (b << 4) | (c >> 2);
|
||||
if out + 2 < count {
|
||||
let d = values[src[i + 3] as! usize];
|
||||
dst[out + 2] = (c << 6) | d;
|
||||
}
|
||||
}
|
||||
}
|
||||
return std.encoding.base64.DecodeResult::ok(count);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
module std.encoding.hex
|
||||
|
||||
enum EncodeResult { ok(usize), short_output }
|
||||
enum DecodeResult { ok(usize), invalid_input, short_output }
|
||||
|
||||
fn encode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.hex.EncodeResult
|
||||
effects []
|
||||
{
|
||||
if src.len > dst.len / 2 { return std.encoding.hex.EncodeResult::short_output; }
|
||||
let count = src.len * 2;
|
||||
let alphabet = b"0123456789abcdef";
|
||||
for i in 0..src.len {
|
||||
let byte = src[i];
|
||||
dst[i * 2] = alphabet[(byte >> 4) as! usize];
|
||||
dst[i * 2 + 1] = alphabet[(byte & 15) as! usize];
|
||||
}
|
||||
return std.encoding.hex.EncodeResult::ok(count);
|
||||
}
|
||||
|
||||
fn decode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.hex.DecodeResult
|
||||
effects []
|
||||
{
|
||||
if src.len % 2 != 0 { return std.encoding.hex.DecodeResult::invalid_input; }
|
||||
var digits: [u8; 256] = [255; 256];
|
||||
for value in 0u8..10u8 { digits[(value + 48) as! usize] = value; }
|
||||
for value in 0u8..6u8 {
|
||||
digits[(value + 65) as! usize] = value + 10;
|
||||
digits[(value + 97) as! usize] = value + 10;
|
||||
}
|
||||
for i in 0..src.len {
|
||||
if digits[src[i] as! usize] == 255 { return std.encoding.hex.DecodeResult::invalid_input; }
|
||||
}
|
||||
let count = src.len / 2;
|
||||
if count > dst.len { return std.encoding.hex.DecodeResult::short_output; }
|
||||
for i in 0..count {
|
||||
let high = digits[src[i * 2] as! usize];
|
||||
let low = digits[src[i * 2 + 1] as! usize];
|
||||
dst[i] = (high << 4) | low;
|
||||
}
|
||||
return std.encoding.hex.DecodeResult::ok(count);
|
||||
}
|
||||
Loaded 100 of 807 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user