From a2ca2935067e621ae10f8afba9c15cc09bf17b0b Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Tue, 6 Oct 2026 15:12:55 +0300 Subject: [PATCH] cli: add recoverable endian APIs and qualified std enums --- docs/agent/README.md | 4 +- docs/agent/quick-reference.md | 15 +++ docs/design/open-questions.md | 6 + docs/plan/phase-6-source-language.md | 2 +- docs/plan/standard-library.md | 17 ++- docs/reference/grammar.ebnf | 6 +- docs/reference/std.md | 35 +++++ docs/rfcs/0017-standard-endian-results.md | 127 ++++++++++++++++++ docs/spec/15-source-language.md | 8 +- docs/spec/16-standard-library.md | 22 +++ examples/std/endian.aji | 16 +++ src/check.zig | 20 +++ src/frontend/ast.zig | 2 + src/frontend/lower.zig | 123 +++++++++-------- src/frontend/parse.zig | 39 +++++- src/frontend/stdlib.zig | 42 ++++-- std/README.md | 8 +- std/bytes.aji | 124 +++++++++++++++++ .../source/quickref/std_endian.aji | 20 +++ .../source/std/endian_air_equivalence.aji | 11 ++ tests/conformance/source/std/endian_alias.aji | 9 ++ .../source/std/endian_bare_outcome.aji | 9 ++ .../source/std/endian_compound_type.aji | 25 ++++ .../source/std/endian_match_duplicate.aji | 9 ++ .../source/std/endian_match_incomplete.aji | 9 ++ .../source/std/endian_match_wildcard.aji | 9 ++ .../std/endian_missing_constructor_import.aji | 9 ++ .../source/std/endian_missing_payload.aji | 9 ++ .../source/std/endian_missing_type_import.aji | 12 ++ .../source/std/endian_payload_type.aji | 9 ++ .../std/endian_result_is_not_integer.aji | 9 ++ .../source/std/endian_type_namespace.aji | 30 +++++ tests/conformance/source/std/endian_u16.aji | 114 ++++++++++++++++ tests/conformance/source/std/endian_u32.aji | 114 ++++++++++++++++ tests/conformance/source/std/endian_u64.aji | 114 ++++++++++++++++ .../source/std/endian_unknown_match_type.aji | 9 ++ .../source/std/endian_unknown_type.aji | 12 ++ .../source/std/endian_unknown_variant.aji | 9 ++ .../source/std/endian_unqualified_type.aji | 12 ++ .../source/std/endian_value_width.aji | 9 ++ .../source/std/endian_variant_wrong_enum.aji | 15 +++ .../source/std/endian_write_needs_mut.aji | 9 ++ tests/conformance/std/endian_payload_type.air | 16 +++ tests/conformance/std/endian_read.air | 63 +++++++++ tools/source_coverage.py | 3 + 45 files changed, 1205 insertions(+), 89 deletions(-) create mode 100644 docs/rfcs/0017-standard-endian-results.md create mode 100644 examples/std/endian.aji create mode 100644 tests/conformance/source/quickref/std_endian.aji create mode 100644 tests/conformance/source/std/endian_air_equivalence.aji create mode 100644 tests/conformance/source/std/endian_alias.aji create mode 100644 tests/conformance/source/std/endian_bare_outcome.aji create mode 100644 tests/conformance/source/std/endian_compound_type.aji create mode 100644 tests/conformance/source/std/endian_match_duplicate.aji create mode 100644 tests/conformance/source/std/endian_match_incomplete.aji create mode 100644 tests/conformance/source/std/endian_match_wildcard.aji create mode 100644 tests/conformance/source/std/endian_missing_constructor_import.aji create mode 100644 tests/conformance/source/std/endian_missing_payload.aji create mode 100644 tests/conformance/source/std/endian_missing_type_import.aji create mode 100644 tests/conformance/source/std/endian_payload_type.aji create mode 100644 tests/conformance/source/std/endian_result_is_not_integer.aji create mode 100644 tests/conformance/source/std/endian_type_namespace.aji create mode 100644 tests/conformance/source/std/endian_u16.aji create mode 100644 tests/conformance/source/std/endian_u32.aji create mode 100644 tests/conformance/source/std/endian_u64.aji create mode 100644 tests/conformance/source/std/endian_unknown_match_type.aji create mode 100644 tests/conformance/source/std/endian_unknown_type.aji create mode 100644 tests/conformance/source/std/endian_unknown_variant.aji create mode 100644 tests/conformance/source/std/endian_unqualified_type.aji create mode 100644 tests/conformance/source/std/endian_value_width.aji create mode 100644 tests/conformance/source/std/endian_variant_wrong_enum.aji create mode 100644 tests/conformance/source/std/endian_write_needs_mut.aji create mode 100644 tests/conformance/std/endian_payload_type.air create mode 100644 tests/conformance/std/endian_read.air diff --git a/docs/agent/README.md b/docs/agent/README.md index 73893eb..e1424f5 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -89,6 +89,8 @@ The groups `quick_reference`, `source_docs` and `air_docs` come from the `doc_gr ## 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 complexity growth and the plan tracks the next APIs. +`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. diff --git a/docs/agent/quick-reference.md b/docs/agent/quick-reference.md index fc6eaec..22e71f8 100644 --- a/docs/agent/quick-reference.md +++ b/docs/agent/quick-reference.md @@ -339,3 +339,18 @@ effects [] ``` `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`. There are no aliases or user generics in this increment. + +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. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 0cf1113..e26ea1f 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -212,3 +212,9 @@ The source frontend had no import resolution and the package manifest no depende ## 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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 05224cf..87001e3 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a | P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes | | P6-10 | todo | Phase exit review | all | plan status | exit criterion passes | -The std bootstrap implements a closed two-module import subset (`STD-0`, [plan](standard-library.md)); P6-3 remains open for general user modules, imported types and dependency resolution. P6-4 remains open for generics. No full Phase 6 task is marked complete by that subset. +The std bootstrap and endian increment implement a closed two-module import subset and qualified standard enum types/constructors/patterns (`STD-0/1a`, [plan](standard-library.md)). P6-3 remains open for general user modules, imported struct literals and dependency resolution. P6-4 remains open for generics. No full Phase 6 task is marked complete by that subset. diff --git a/docs/plan/standard-library.md b/docs/plan/standard-library.md index f7f7c69..9ec5f5d 100644 --- a/docs/plan/standard-library.md +++ b/docs/plan/standard-library.md @@ -20,8 +20,8 @@ Without external source dependencies, Aji should support ordinary CLI tools, sto |---|---|---| | 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 | this bootstrap increment | compiler-pinned, closed registry; no package lookup | -| General modules/imported types | P6-3 pending | needed before publishing owning collection types | +| Built-in standard imports and enum types | STD-0/1a branch implementation | compiler-pinned, closed registry; qualified enum types/constructors/patterns; no package lookup | +| General modules/imported struct literals | P6-3 pending | needed before publishing owning collection types | | User generics/structural constraints | P6-4 pending | needed for reusable `Vec`, `HashMap`, option/result | | `linear_aggregates` | reserved, unscheduled | independent vertical RFC/phase gate for owners/resources in containers | | Extended filesystem, IPv6/DNS, args/env, TLS/crypto | not promised by current runtime | audit each primitive, authority, error and profile model before implementation | @@ -47,13 +47,14 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob | ID | Status | Work | Depends | Done when | |---|---|---|---|---| | STD-0 | done (branch implementation; RFC Proposed) | bootstrap spec, source std, closed imports, conformance, documentation and complexity measurement | existing source frontend | bootstrap exit criterion above and required repository checks pass | -| STD-1 | todo | endian u16/u32/u64, bounded copy/split/search, checked arithmetic API decisions | STD-0 | contracts define short-input/output failure, no partial mutation, empty and maximal values; fixtures and rejected alias examples pass | -| STD-2 | todo | UTF-8 validation/iteration, hex/base64 and formatting into supplied buffers | STD-1 | malformed text and insufficient capacity are explicit; no implicit heap; standard vectors and boundary cases pass | +| STD-1a | done (branch implementation; RFC Proposed) | 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 | todo | bounded copy/split/search, checked arithmetic API decisions | STD-1a | contracts define capacity/overflow failure, no partial mutation, empty inputs and aliasing; independent fixtures pass | +| STD-2 | todo | UTF-8 validation/iteration, hex/base64 and formatting into supplied buffers | STD-1a/1b | malformed text and insufficient capacity are explicit; no implicit heap; standard vectors and boundary cases pass | | STD-3 | todo | general modules and imported type names (P6-3) | STD-0 | deterministic resolution, collisions/cycles and diagnostics specified and covered | | STD-4 | todo | source generics (P6-4), constraints and option/result | STD-3 | deterministic specialization and rejected constraint examples; source/AIR budgets measured | | STD-5 | todo | independent `linear_aggregates` RFC and vertical implementation phase | STD-3/4 for its source surface | spec → AIR → verifier → interpreter → source/lowering → Quick Reference → AIR/source tests; linear elements consumed on every path | | STD-6 | todo | buffer, Vec, Deque, HashMap, HashSet, BinaryHeap | STD-4/5 | allocate/grow/remove/free contracts, allocation failure leaves documented state, linear elements survive moves and are consumed; no hidden destruction | -| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1/2; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority | +| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority | | STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry | | STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material | | 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 | @@ -76,3 +77,9 @@ Required: `zig build`, `zig build test`, `zig build conformance`, `zig fmt --che 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. diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf index dc922f4..2011904 100644 --- a/docs/reference/grammar.ebnf +++ b/docs/reference/grammar.ebnf @@ -28,7 +28,7 @@ fn_decl = "fn" ident "(" [ param { "," param } ] ")" "->" type [ "from" id block ; (* `trusted` is reserved and rejected, E7006 *) param = ident ":" type ; -type = int_type | "bool" | "void" | "never" | ident +type = int_type | "bool" | "void" | "never" | path | "[" type ";" int_lit "]" | wrapper "<" type ">" | "cap" "<" path ">" @@ -64,7 +64,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 "::" 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 "," ) "}" ; @@ -89,7 +89,7 @@ member = ident | keyword ; (* after `.` a keyword is 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 *) + | path "::" ident (* enum variant; applied by a call *) | "[" expr ";" int_lit "]" | "(" expr ")" | if_expr | match_expr | block ; diff --git a/docs/reference/std.md b/docs/reference/std.md index ac08ce9..b553c7b 100644 --- a/docs/reference/std.md +++ b/docs/reference/std.md @@ -36,3 +36,38 @@ effects [] 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`) | Result | Write functions (`dst: slice_mut, 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`. diff --git a/docs/rfcs/0017-standard-endian-results.md b/docs/rfcs/0017-standard-endian-results.md new file mode 100644 index 0000000..2b14d26 --- /dev/null +++ b/docs/rfcs/0017-standard-endian-results.md @@ -0,0 +1,127 @@ +# RFC 0017: Recoverable endian operations and qualified standard enums + +Status: Proposed +Scope: STD-1a, safe `std.bytes` algorithms and closed-registry enum names; AIR format 0 unchanged +Language version: 0.1 +Supersedes: — + +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` 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. diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index 8b61808..8e169fa 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -474,10 +474,14 @@ The compiler MUST provide the standard modules listed in spec 16 §2, pinned to An imported 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 outside the grammar (`E7001`). -Lowering MUST append the complete function declarations of the imported modules after the program's declarations, in lexicographic module order and source declaration order within each module. For 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 function, 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. 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. +Lowering MUST append the complete 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. 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 (`std/math.aji` or `std/bytes.aji`) 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. -This increment exposes functions with built-in parameter/result types only. General user modules, dependency resolution, aliases, imported type names and generics require separate specifications. +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 current standard registry exports enums only. Qualified named types and enum variants do not introduce member methods, reflection, general user modules, dependency resolution, aliases, imported struct literals or generics; those require separate specifications. diff --git a/docs/spec/16-standard-library.md b/docs/spec/16-standard-library.md index 477be6d..7592c4e 100644 --- a/docs/spec/16-standard-library.md +++ b/docs/spec/16-standard-library.md @@ -31,3 +31,25 @@ Inputs are byte slices, not encoded text. No UTF-8 validation or locale interpre - `fill(dst: slice_mut, 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) -> 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, 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. diff --git a/examples/std/endian.aji b/examples/std/endian.aji new file mode 100644 index 0000000..bf33485 --- /dev/null +++ b/examples/std/endian.aji @@ -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; } + } +} diff --git a/src/check.zig b/src/check.zig index 07b2b10..f50cdc7 100644 --- a/src/check.zig +++ b/src/check.zig @@ -144,3 +144,23 @@ test "standard source provenance maps diagnostics to the library file" { 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" }, + }; + 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); + } +} diff --git a/src/frontend/ast.zig b/src/frontend/ast.zig index 3f4cb2a..fac2134 100644 --- a/src/frontend/ast.zig +++ b/src/frontend/ast.zig @@ -168,6 +168,8 @@ pub const Variant = struct { name: []const u8, payload: []const Type, span: Span pub const TypeDecl = struct { name: []const u8, + /// Linker-chosen AIR identifier for a qualified standard type. + air_name: ?[]const u8 = null, span: Span, kind: union(enum) { @"struct": []const Field, @"enum": []const Variant }, }; diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index fd20d48..a352e59 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -327,14 +327,22 @@ const Lowerer = struct { } fn tyText(l: *Lowerer, t: Ty) []const u8 { + return l.typeText(t, false); + } + + fn diagnosticTyText(l: *Lowerer, t: Ty) []const u8 { + return l.typeText(t, true); + } + + fn typeText(l: *Lowerer, t: Ty, source_names: bool) []const u8 { return switch (t) { .int => |x| x, .bool => "bool", .void => "void", .never => "never", - .named => |i| l.typeNames[i], - .array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.tyText(a.elem), a.len }) catch "array", - .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.tyText(x.*) }) catch "borrow", + .named => |i| if (source_names and l.m.types[i].air_name != null) l.m.types[i].name else l.typeNames[i], + .array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.typeText(a.elem, source_names), a.len }) catch "array", + .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow", .scope => "scope", .shield => "shield", .region => "region", @@ -396,7 +404,7 @@ const Lowerer = struct { const names = try l.arena.alloc([]const u8, l.m.types.len); for (l.m.types, names, 0..) |t, *n, i| { for (l.m.types[0..i]) |prev| if (std.mem.eql(u8, prev.name, t.name)) return l.fail("E7006", t.span, "type defined twice", &.{.{ .name = "name", .value = t.name }}); - n.* = try l.fmt("@{s}", .{t.name}); + n.* = try l.fmt("@{s}", .{t.air_name orelse t.name}); } l.typeNames = names; for (l.m.functions) |f| { @@ -479,7 +487,7 @@ const Lowerer = struct { /// `type @T = struct { … }` / `enum { … }` in canonical form. fn typeDeclText(l: *Lowerer, t: ast.TypeDecl) Error![]const u8 { var w: std.ArrayList(u8) = .empty; - try w.appendSlice(l.arena, try l.fmt("type @{s} = ", .{t.name})); + try w.appendSlice(l.arena, try l.fmt("type @{s} = ", .{t.air_name orelse t.name})); switch (t.kind) { .@"struct" => |fields| { try w.appendSlice(l.arena, "struct {"); @@ -549,7 +557,7 @@ const Lowerer = struct { .frozen => l.wrap(.frozen, in), .arc => l.wrap(.arc, in), .iref => l.wrap(.iref, in), - .atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.tyText(in) }}), + .atomic => if (atomicScalar(in)) l.wrap(.atomic, in) else l.fail("E7005", t.span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(in) }}), }; }, .cap => |k| { @@ -969,7 +977,7 @@ const Lowerer = struct { try l.term(try l.retText(v), s.span); } } else { - if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = l.tyText(l.ret) }}); + if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = l.diagnosticTyText(l.ret) }}); try l.endScopes(0, s.span); try l.term("ret", s.span); } @@ -1016,7 +1024,7 @@ const Lowerer = struct { fn checkTy(l: *Lowerer, span: Span, found: Ty, want: Ty) Error!void { if (found == .never or found.eql(want)) return; - return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = l.tyText(want) }, .{ .name = "found", .value = l.tyText(found) } }); + return l.fail("E7005", span, "type mismatch", &.{ .{ .name = "expected", .value = l.diagnosticTyText(want) }, .{ .name = "found", .value = l.diagnosticTyText(found) } }); } /// `while cond { body }` (cond null: `loop { body }`). Carried state: @@ -1071,7 +1079,7 @@ const Lowerer = struct { const depth = l.bindings.items.len; defer l.bindings.shrinkRetainingCapacity(depth); const ty = l.peekType(lo) orelse l.peekType(hi) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{}); - if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = l.tyText(ty) }}); + if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = l.diagnosticTyText(ty) }}); const a = try l.expr(lo, ty); try l.checkTy(lo.span, a.ty, ty); const b = try l.expr(hi, ty); @@ -1244,7 +1252,7 @@ const Lowerer = struct { .int => |x| { const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{}); - if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = l.tyText(ty) }}); + if (ty != .int) return l.fail("E7005", e.span, "an integer literal where another type is expected", &.{.{ .name = "expected", .value = l.diagnosticTyText(ty) }}); const v = parse_mod.parseIntText(x.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{}); const n = ty.int; const bits = intBits(n); @@ -1260,7 +1268,7 @@ const Lowerer = struct { }, .deref => |x| { const r = try l.expr(x.*, null); - const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.tyText(r.ty) }}); + const in = r.ty.inner() orelse return l.fail("E7005", e.span, "`*` reads through a borrow", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }}); if (r.ty == .slice or r.ty == .slice_mut or in == .array) return l.fail("E7006", e.span, "read slice and array elements with `s[i]`, not `*`", &.{}); // The verifier's code (spec 15 §1 rule 2, spec 04 §28). if (in == .atomic) return l.fail("E4202", e.span, "an atomic cell is read only by atomic operations: use `atomic.load(r, ordering)`", &.{}); @@ -1310,7 +1318,7 @@ const Lowerer = struct { if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{}); const from = l.peekType(x.e.*) orelse to; const v = try l.expr(x.e.*, from); - if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = l.tyText(v.ty) }}); + if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = l.diagnosticTyText(v.ty) }}); // `as` widens without loss, by the verifier's own rule (spec 02 §2). if (x.mode == .widen) { const a = std.meta.stringToEnum(air_module.IntType, v.ty.int).?; @@ -1341,7 +1349,7 @@ const Lowerer = struct { .or_trap => |x| return l.orTrap(e, x.*), .move => |n| { const b = l.lookup(n) orelse return l.unknown(e.span, n); - if (!b.ty.isLinear()) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.tyText(b.ty) } }); + if (!b.ty.isLinear()) return l.fail("E7006", e.span, "`move` applies to linear values; copyable values are passed plainly", &.{ .{ .name = "name", .value = n }, .{ .name = "type", .value = l.diagnosticTyText(b.ty) } }); return .{ .name = b.value, .ty = b.ty }; }, } @@ -1434,21 +1442,21 @@ const Lowerer = struct { if (std.mem.eql(u8, p, "own.take")) { if (args.len != 1) return l.fail("E7005", e.span, "`own.take` takes one owner", &.{}); const o = try l.consuming(args[0], null); - if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own`", &.{.{ .name = "found", .value = l.tyText(o.ty) }}); + if (o.ty != .own) return l.fail("E7005", args[0].span, "`own.take` takes an `own`", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }}); return l.def("v", o.ty.own.*, try l.fmt("own.take %{s}", .{o.name}), e.span); } if (std.mem.eql(u8, p, "own.free") or std.mem.eql(u8, p, "region.destroy")) { if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one linear value", &.{}); const o = try l.consuming(args[0], null); const ok = if (std.mem.eql(u8, p, "own.free")) (o.ty == .own or o.ty == .own_array) else o.ty == .region; - if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own` or `own_array`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = l.tyText(o.ty) }}); + if (!ok) return l.fail("E7005", args[0].span, if (std.mem.eql(u8, p, "own.free")) "`own.free` takes an `own` or `own_array`" else "`region.destroy` takes a region", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }}); try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span); return .{ .name = "", .ty = .void }; } if (std.mem.eql(u8, p, "region.reset")) { if (args.len != 1 or args[0].kind != .name) return l.fail("E7005", e.span, "`region.reset` takes the region by name", &.{}); const r = l.lookup(args[0].kind.name) orelse return l.unknown(args[0].span, args[0].kind.name); - if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = l.tyText(r.ty) }}); + if (r.ty != .region) return l.fail("E7005", args[0].span, "`region.reset` takes a region", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }}); try l.emit(try l.fmt("region.reset %{s}", .{r.value}), e.span); return .{ .name = "", .ty = .void }; } @@ -1535,7 +1543,7 @@ const Lowerer = struct { try l.checkTy(fi.e.span, v.ty, ft); try args.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); } - return l.def("s", t, try l.fmt("struct.make @{s}({s})", .{ name, args.items }), e.span); + return l.def("s", t, try l.fmt("struct.make {s}({s})", .{ l.tyText(t), args.items }), e.span); } fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value { @@ -1552,14 +1560,14 @@ const Lowerer = struct { try l.checkTy(a.span, av.ty, ty); try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", av.name })); } - return l.def("e", t, try l.fmt("enum.make @{s}.{s}({s})", .{ enum_name, variant, names.items }), e.span); + return l.def("e", t, try l.fmt("enum.make {s}.{s}({s})", .{ l.tyText(t), variant, names.items }), e.span); } /// `v.f` on a struct value: `struct.get` (borrows come in layer 4). fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value { var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{}); if (bt.isBorrow()) bt = bt.inner().?; - const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = l.tyText(bt) }}); + const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = l.diagnosticTyText(bt) }}); if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.name }}); const f = for (d.kind.@"struct") |x| { if (std.mem.eql(u8, x.name, name)) break x; @@ -1588,7 +1596,7 @@ const Lowerer = struct { const vt: Ty = if (a.value) |v| v.ty else .void; if (vt == .never) continue; if (result_ty) |prev| { - if (!prev.eql(vt)) return l.fail("E7005", a.span, try l.fmt("the branches of this `{s}` have different types", .{what}), &.{ .{ .name = "expected", .value = l.tyText(prev) }, .{ .name = "found", .value = l.tyText(vt) } }); + if (!prev.eql(vt)) return l.fail("E7005", a.span, try l.fmt("the branches of this `{s}` have different types", .{what}), &.{ .{ .name = "expected", .value = l.diagnosticTyText(prev) }, .{ .name = "found", .value = l.diagnosticTyText(vt) } }); } else result_ty = vt; }; if (result_ty == null) { @@ -1633,11 +1641,12 @@ const Lowerer = struct { const vs = d.kind.@"enum"; const blocks = try l.arena.alloc(usize, m.arms.len); var head: std.ArrayList(u8) = .empty; - try head.appendSlice(l.arena, try l.fmt("enum.switch @{s} %{s}", .{ d.name, sv.name })); + try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ l.tyText(st), sv.name })); for (m.arms, blocks, 0..) |arm, *blk, i| { if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null) return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.name }}); const c = arm.pattern.kind.ctor; + if (std.mem.startsWith(u8, c.qualifier.?, "std.") and l.enumType(c.qualifier.?) == null) return l.unknown(arm.pattern.span, c.qualifier.?); if (!std.mem.eql(u8, c.qualifier.?, d.name)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.name }, .{ .name = "found", .value = c.qualifier.? } }); const vi = for (vs, 0..) |v, k| { if (std.mem.eql(u8, v.name, c.name)) break k; @@ -1675,7 +1684,7 @@ const Lowerer = struct { return l.mergeArms(m.span, "match", ends.items, vars, before, "endmatch"); } - if (st != .int) return l.fail("E7005", m.scrutinee.span, "`match` needs an enum or integer value; use `if` for booleans", &.{.{ .name = "found", .value = l.tyText(st) }}); + if (st != .int) return l.fail("E7005", m.scrutinee.span, "`match` needs an enum or integer value; use `if` for booleans", &.{.{ .name = "found", .value = l.diagnosticTyText(st) }}); var head: std.ArrayList(u8) = .empty; try head.appendSlice(l.arena, try l.fmt("switch.{s} %{s}, ", .{ st.int, sv.name })); const blocks = try l.arena.alloc(usize, m.arms.len); @@ -1964,7 +1973,7 @@ const Lowerer = struct { .field => |f| { const base = try l.placeRaw(f.e.*, mutable, span); const st = base.v.ty.inner() orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{}); - const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = l.tyText(st) }}); + const d = l.decl(st) orelse return l.fail("E7005", place.span, "field of a value that is not a struct", &.{.{ .name = "found", .value = l.diagnosticTyText(st) }}); if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{}); const fd = for (d.kind.@"struct") |x| { if (std.mem.eql(u8, x.name, f.name)) break x; @@ -1979,7 +1988,7 @@ const Lowerer = struct { const base = try l.placeRaw(x.e.*, mutable, span); l.unchecked = outer_unchecked; const bt = base.v.ty; - const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = l.tyText(bt) }}); + const elem = elemOf(bt) orelse return l.fail("E7005", place.span, "indexing needs an array or a slice", &.{.{ .name = "found", .value = l.diagnosticTyText(bt) }}); if (x.hi) |hi| { // `s[a..b]`: slice.sub with start a and length b - a (checked). var sl = base.v; @@ -2056,7 +2065,7 @@ const Lowerer = struct { else => null, }; if (arr) |n| return l.def("len", .{ .int = "usize" }, try l.fmt("const.usize {d}", .{n}), e.span); - if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = l.tyText(bt) }}); + if (bt != .slice and bt != .slice_mut) return l.fail("E7005", e.span, "`.len` needs an array or a slice", &.{.{ .name = "found", .value = l.diagnosticTyText(bt) }}); const s_ = try l.expr(base, bt); return l.def("len", .{ .int = "usize" }, try l.fmt("slice.len %{s}", .{s_.name}), e.span); } @@ -2070,7 +2079,7 @@ const Lowerer = struct { const rb = l.rootBinding(base) orelse return l.fail("E7002", base.span, "unknown name", &.{}); const mutable = rb.ty.isMutBorrow() or rb.kind == .storage and rb.mutable; const p = try l.placeBorrow(base, mutable, true, s.span); - if (p.v.ty != .slice and p.v.ty != .slice_mut) return l.fail("E7005", base.span, "`split_at` splits a slice", &.{.{ .name = "found", .value = l.tyText(p.v.ty) }}); + if (p.v.ty != .slice and p.v.ty != .slice_mut) return l.fail("E7005", base.span, "`split_at` splits a slice", &.{.{ .name = "found", .value = l.diagnosticTyText(p.v.ty) }}); const k = try l.expr(e.kind.call.args[0], .{ .int = "usize" }); try l.checkTy(e.kind.call.args[0].span, k.ty, .{ .int = "usize" }); const left = try l.freshName(names[0]); @@ -2088,9 +2097,9 @@ const Lowerer = struct { var temps: std.ArrayList([]const u8) = .empty; const d = try l.argument(args[0], null, &temps); const src = try l.argument(args[1], null, &temps); - if (d.ty != .slice_mut) return l.fail("E7005", args[0].span, "`slice.copy` writes to `mut dst` (a `slice_mut`)", &.{.{ .name = "found", .value = l.tyText(d.ty) }}); - if (src.ty != .slice and src.ty != .slice_mut) return l.fail("E7005", args[1].span, "`slice.copy` reads from `ref src` (a `slice`)", &.{.{ .name = "found", .value = l.tyText(src.ty) }}); - if (!d.ty.inner().?.eql(src.ty.inner().?)) return l.fail("E7005", args[1].span, "`slice.copy` copies between slices of the same element type", &.{ .{ .name = "expected", .value = l.tyText(d.ty.inner().?) }, .{ .name = "found", .value = l.tyText(src.ty.inner().?) } }); + if (d.ty != .slice_mut) return l.fail("E7005", args[0].span, "`slice.copy` writes to `mut dst` (a `slice_mut`)", &.{.{ .name = "found", .value = l.diagnosticTyText(d.ty) }}); + if (src.ty != .slice and src.ty != .slice_mut) return l.fail("E7005", args[1].span, "`slice.copy` reads from `ref src` (a `slice`)", &.{.{ .name = "found", .value = l.diagnosticTyText(src.ty) }}); + if (!d.ty.inner().?.eql(src.ty.inner().?)) return l.fail("E7005", args[1].span, "`slice.copy` copies between slices of the same element type", &.{ .{ .name = "expected", .value = l.diagnosticTyText(d.ty.inner().?) }, .{ .name = "found", .value = l.diagnosticTyText(src.ty.inner().?) } }); try l.emit(try l.fmt("slice.copy %{s}, %{s}", .{ d.name, src.name }), e.span); try l.endNow(temps.items, e.span); return .{ .name = "", .ty = .void }; @@ -2223,7 +2232,7 @@ const Lowerer = struct { const br = a.kind.borrow; if (br.mutable) return l.fail("E7005", a.span, "atomic operations take `ref` of the cell, never `mut`", &.{}); const b = try l.bindingOf(br.place.*, "an atomic cell"); - if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic`", &.{.{ .name = "found", .value = l.tyText(b.ty) }}); + if (b.ty != .atomic) return l.fail("E7005", a.span, "an atomic operation takes `ref` of an `atomic`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); const r = try l.def(br.place.kind.name, try l.wrap(.ref, b.ty), try l.fmt("borrow.ref %{s}", .{b.value}), a.span); try temps.append(l.arena, r.name); return r; @@ -2231,7 +2240,7 @@ const Lowerer = struct { const b = try l.bindingOf(a, "an atomic cell"); if (b.ty == .atomic) return l.fail("E7005", a.span, "pass the cell as `ref a` (or a `ref` binding of it): atomic operations go through a shared borrow", &.{.{ .name = "suggestion", .value = try l.fmt("ref {s}", .{a.kind.name}) }}); if (b.ty == .ref and b.ty.inner().? == .atomic) return .{ .name = b.value, .ty = b.ty }; - return l.fail("E7005", a.span, "an atomic operation takes a `ref>`", &.{.{ .name = "found", .value = l.tyText(b.ty) }}); + return l.fail("E7005", a.span, "an atomic operation takes a `ref>`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); } fn atomicCall(l: *Lowerer, e: ast.Expr, p: []const u8, args: []const ast.Expr) Error!Value { @@ -2239,13 +2248,13 @@ const Lowerer = struct { if (eq(u8, p, "atomic.new")) { if (args.len != 1) return l.fail("E7005", e.span, "`atomic.new` takes the initial value", &.{}); const v = try l.expr(args[0], null); - if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.tyText(v.ty) }}); + if (!atomicScalar(v.ty)) return l.fail("E7005", args[0].span, "atomic needs bool or an integer of at most 64 bits", &.{.{ .name = "found", .value = l.diagnosticTyText(v.ty) }}); return l.def("atomic", try l.wrap(.atomic, v.ty), try l.fmt("atomic.new %{s}", .{v.name}), e.span); } if (eq(u8, p, "atomic.take")) { if (args.len != 1) return l.fail("E7005", e.span, "`atomic.take` takes one cell", &.{}); const c = try l.consuming(args[0], null); - if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic`", &.{.{ .name = "found", .value = l.tyText(c.ty) }}); + if (c.ty != .atomic) return l.fail("E7005", args[0].span, "`atomic.take` takes an `atomic`", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }}); return l.def("v", c.ty.inner().?, try l.fmt("atomic.take %{s}", .{c.name}), e.span); } if (eq(u8, p, "atomic.fence")) { @@ -2274,7 +2283,7 @@ const Lowerer = struct { return .{ .name = "", .ty = .void }; } const op: []const u8 = if (eq(u8, p, "atomic.swap")) "xchg" else p["atomic.".len..]; - if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = l.tyText(t) }}); + if ((eq(u8, op, "add.wrap") or eq(u8, op, "sub.wrap")) and t != .int) return l.fail("E7005", args[1].span, "`atomic.add.wrap` and `atomic.sub.wrap` need an integer cell", &.{.{ .name = "found", .value = l.diagnosticTyText(t) }}); const v = try l.def("old", t, try l.fmt("atomic.{s}.{s} %{s}, %{s}", .{ op, ord, c.name, operand.name }), e.span); try l.endNow(temps.items, e.span); return v; @@ -2320,7 +2329,7 @@ const Lowerer = struct { return v; } if ((b.ty == .mut or (b.ty == .ref and !mutable)) and std.meta.activeTag(b.ty.inner().?) == tag) return .{ .name = b.value, .ty = b.ty }; - return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = l.tyText(b.ty) }}); + return l.fail("E7005", a.span, try l.fmt("{s} is expected here", .{what}), &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); } /// The task and channel operations that are plain calls; null for any @@ -2334,7 +2343,7 @@ const Lowerer = struct { if (eq(p, "task.spawn")) { if (args.len < 2) return l.fail("E7005", e.span, "`task.spawn` takes a scope, a function and its arguments", &.{}); const sb = try l.bindingOf(args[0], "a task scope"); - if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.tyText(sb.ty) }}); + if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.diagnosticTyText(sb.ty) }}); const scope_name = sb.value; if (args[1].kind != .name) return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); const fname = args[1].kind.name; @@ -2355,7 +2364,7 @@ const Lowerer = struct { if (eq(p, "task.join")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{}); const t = try l.consuming(args[0], null); - if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task`", &.{.{ .name = "found", .value = l.tyText(t.ty) }}); + if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join` takes a `task`", &.{.{ .name = "found", .value = l.diagnosticTyText(t.ty) }}); const rt = t.ty.task.*; if (rt == .void) { try l.emit(try l.fmt("task.join %{s}", .{t.name}), e.span); @@ -2366,7 +2375,7 @@ const Lowerer = struct { if (eq(p, "task.cancel")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.cancel` takes one task, by name", &.{}); const b = try l.bindingOf(args[0], "a task"); - if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task`", &.{.{ .name = "found", .value = l.tyText(b.ty) }}); + if (b.ty != .task) return l.fail("E7005", args[0].span, "`task.cancel` takes a `task`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); try l.emit(try l.fmt("task.cancel %{s}", .{b.value}), e.span); return .{ .name = "", .ty = .void }; } @@ -2392,7 +2401,7 @@ const Lowerer = struct { if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{}); const o = try l.consuming(args[0], null); const want: std.meta.Tag(Ty) = if (eq(p, "island.freeze")) .island else .frozen; - if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island`" else "`arc.from_frozen` takes a `frozen`", &.{.{ .name = "found", .value = l.tyText(o.ty) }}); + if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, if (want == .island) "`island.freeze` takes an `island`" else "`arc.from_frozen` takes a `frozen`", &.{.{ .name = "found", .value = l.diagnosticTyText(o.ty) }}); const out = if (want == .island) try l.wrap(.frozen, o.ty.inner().?) else try l.wrap(.arc, o.ty.inner().?); return try l.def(if (want == .island) "frozen" else "arc", out, try l.fmt("{s} %{s}", .{ p, o.name }), e.span); } @@ -2400,7 +2409,7 @@ const Lowerer = struct { if (args.len != 1) return l.fail("E7005", e.span, "this operation takes one graph owner", &.{}); const o = try l.consuming(args[0], null); const want: std.meta.Tag(Ty) = if (eq(p, "island.destroy")) .island else if (eq(p, "frozen.release")) .frozen else .arc; - if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = l.tyText(o.ty) } }); + if (std.meta.activeTag(o.ty) != want) return l.fail("E7005", args[0].span, "this operation takes another graph owner", &.{ .{ .name = "operation", .value = p }, .{ .name = "found", .value = l.diagnosticTyText(o.ty) } }); try l.emit(try l.fmt("{s} %{s}", .{ p, o.name }), e.span); return .{ .name = "", .ty = .void }; } @@ -2414,7 +2423,7 @@ const Lowerer = struct { return v; } if (b.ty == .ref and b.ty.inner().? == .arc) return try l.def("arc", b.ty.inner().?, try l.fmt("arc.clone %{s}", .{b.value}), e.span); - return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc`", &.{.{ .name = "found", .value = l.tyText(b.ty) }}); + return l.fail("E7005", args[0].span, "`arc.clone` takes an `arc`", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); } if (eq(p, "island.at") or eq(p, "frozen.at") or eq(p, "arc.at")) return l.fail("E7006", e.span, "a graph access is a borrow: bind it with `ref x = island.at(g, r);` or `mut x = island.at(g, r);`", &.{}); @@ -2427,13 +2436,13 @@ const Lowerer = struct { if (eq(p, "mutex.take")) { if (args.len != 1) return l.fail("E7005", e.span, "`mutex.take` takes one mutex", &.{}); const m = try l.consuming(args[0], null); - if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = l.tyText(m.ty) }}); + if (m.ty != .mutex) return l.fail("E7005", args[0].span, "`mutex.take` takes a `mutex`", &.{.{ .name = "found", .value = l.diagnosticTyText(m.ty) }}); return try l.def("v", m.ty.mutex.*, try l.fmt("mutex.take %{s}", .{m.name}), e.span); } if (eq(p, "channel.close_sender")) { if (args.len != 1) return l.fail("E7005", e.span, "`channel.close_sender` takes one sender", &.{}); const tx = try l.consuming(args[0], null); - if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender`", &.{.{ .name = "found", .value = l.tyText(tx.ty) }}); + if (tx.ty != .sender) return l.fail("E7005", args[0].span, "`channel.close_sender` takes a `sender`", &.{.{ .name = "found", .value = l.diagnosticTyText(tx.ty) }}); try l.emit(try l.fmt("channel.close_sender %{s}", .{tx.name}), e.span); return .{ .name = "", .ty = .void }; } @@ -2455,8 +2464,8 @@ const Lowerer = struct { try temps.append(l.arena, v.name); break :blk v; }, - .ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.tyText(b.ty) }}), - else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.tyText(b.ty) }}), + .ref => if (b.ty.ref.* == .mutex) .{ .name = b.value, .ty = b.ty } else return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}), + else => return l.fail("E7005", place.span, "`lock` needs a mutex", &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}), }; const elem = mr.ty.ref.mutex.*; const depth = l.bindings.items.len; @@ -2627,7 +2636,7 @@ const Lowerer = struct { /// scope, task, shield or guard, at any depth. Endpoints inside are the /// reserved `channel_transfer`, left to the verifier (`E0006`). fn elementRule(l: *Lowerer, t: Ty, span: Span, what: []const u8) Error!void { - if (try l.forbiddenIn(t, 0)) |bad| return l.fail("E7005", span, try l.fmt("{s} contains no borrow, scope, task, shield or guard", .{what}), &.{ .{ .name = "type", .value = l.tyText(t) }, .{ .name = "found", .value = l.tyText(bad) } }); + if (try l.forbiddenIn(t, 0)) |bad| return l.fail("E7005", span, try l.fmt("{s} contains no borrow, scope, task, shield or guard", .{what}), &.{ .{ .name = "type", .value = l.diagnosticTyText(t) }, .{ .name = "found", .value = l.diagnosticTyText(bad) } }); } fn forbiddenIn(l: *Lowerer, t: Ty, depth: u32) Error!?Ty { @@ -2657,7 +2666,7 @@ const Lowerer = struct { const tag = std.meta.stringToEnum(std.meta.Tag(Ty), owner).?; if (std.meta.activeTag(b.ty) == tag) return l.fail("E7005", a.span, try l.fmt("this takes a borrow of the {s}, not the owner: bind `{s} g = {s};` in an enclosing block and pass `g`", .{ owner, if (mutable) "mut" else "ref", a.kind.name }), &.{.{ .name = "name", .value = a.kind.name }}); const ok = (b.ty == .ref or (b.ty == .mut and !mutable) or (b.ty == .mut and mutable)) and std.meta.activeTag(b.ty.inner().?) == tag; - if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = l.tyText(b.ty) }}); + if (!ok or (mutable and b.ty != .mut)) return l.fail("E7005", a.span, try l.fmt("a {s} borrow of an `{s}` is expected here", .{ if (mutable) "`mut`" else "`ref` or `mut`", owner }), &.{.{ .name = "found", .value = l.diagnosticTyText(b.ty) }}); return .{ .name = b.value, .ty = b.ty }; } @@ -2671,7 +2680,7 @@ const Lowerer = struct { if (ac.args.len != 2) return l.fail("E7005", place.span, "`.at` takes the graph's borrow binding and an `iref`", &.{}); const g = try l.graphBorrow(ac.args[0], owner, mutable); const r = try l.expr(ac.args[1], null); - if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.tyText(r.ty) }}); + if (r.ty != .iref) return l.fail("E7005", ac.args[1].span, "an `iref` is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(r.ty) }}); const op = if (std.mem.eql(u8, owner, "island")) "island.borrow" else if (std.mem.eql(u8, owner, "frozen")) "frozen.borrow" else "arc.borrow"; const target = r.ty.inner().?; const v = try l.def(name, if (mutable) try l.wrap(.mut, target) else try l.wrap(.ref, target), try l.fmt("{s} %{s}, %{s}", .{ op, g.name, r.name }), s.span); @@ -2701,14 +2710,14 @@ const Lowerer = struct { const want: Ty = if (o == .bytes) try l.wrap(.slice, .{ .int = "u8" }) else try l.wrap(.slice_mut, .{ .int = "u8" }); if (o == .buffer and a.kind == .bytes) return l.fail("E7005", a.span, "this operand is a buffer the operation writes: pass `mut buf`", &.{}); const v = try l.argument(a, want, temps); - if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = l.tyText(want) }, .{ .name = "found", .value = l.tyText(v.ty) } }); + if (!v.ty.eql(want)) return l.fail("E7005", a.span, if (o == .bytes) "bytes are passed as a borrow: `ref buf`, `ref buf[a..b]` or a byte string `b\"…\"`" else "a buffer is passed as `mut buf` or `mut buf[a..b]`", &.{ .{ .name = "expected", .value = l.diagnosticTyText(want) }, .{ .name = "found", .value = l.diagnosticTyText(v.ty) } }); break :blk v; }, .borrowed => |rs| try l.resourceOperand(a, rs, temps), .consumed => |rs| blk: { const v = try l.consuming(a, null); if (v.ty != .resource or std.mem.indexOfScalar(authority.Resource, rs, v.ty.resource) == null) - return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = l.tyText(v.ty) } }); + return l.fail("E7005", a.span, "this operation consumes a resource of another type", &.{ .{ .name = "operation", .value = x.name }, .{ .name = "found", .value = l.diagnosticTyText(v.ty) } }); break :blk v; }, }; @@ -2730,7 +2739,7 @@ const Lowerer = struct { else => null, }; if (r == null or std.mem.indexOfScalar(authority.Resource, rs, r.?) == null) - return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = l.tyText(b.ty) } }); + return l.fail("E7005", a.span, "this operation needs a resource of another type", &.{ .{ .name = "expected", .value = expected }, .{ .name = "found", .value = l.diagnosticTyText(b.ty) } }); if (b.ty == .mut) return .{ .name = b.value, .ty = b.ty }; const v = try l.def(a.kind.name, try l.wrap(.mut, b.ty), try l.fmt("borrow.mut %{s}", .{b.value}), a.span); try temps.append(l.arena, v.name); @@ -2745,7 +2754,7 @@ const Lowerer = struct { fn expectCap(l: *Lowerer, a: ast.Expr, kind: []const u8) Error!Value { const c = try l.expr(a, null); - if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = l.tyText(c.ty) } }); + if (c.ty != .cap) return l.fail("E7005", a.span, "a capability is expected here", &.{ .{ .name = "expected", .value = try l.fmt("cap<{s}>", .{kind}) }, .{ .name = "found", .value = l.diagnosticTyText(c.ty) } }); return c; } @@ -2838,7 +2847,7 @@ const Lowerer = struct { if (std.mem.eql(u8, path, "task.join_cancel")) { try want(l, e.span, args, 1, path); const t = try l.consuming(args[0], null); - if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task`", &.{.{ .name = "found", .value = l.tyText(t.ty) }}); + if (t.ty != .task) return l.fail("E7005", args[0].span, "`task.join_cancel` takes a `task`", &.{.{ .name = "found", .value = l.diagnosticTyText(t.ty) }}); const rt = t.ty.task.*; const ok: []const Ty = if (rt == .void) &.{} else &.{rt}; return .{ .text = try l.fmt("task.join.cancel %{s}", .{t.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = ok }, .{ .role = "cancelled", .params = &.{t.ty} } }) }; @@ -2872,23 +2881,23 @@ const Lowerer = struct { if (std.mem.eql(u8, path, "channel.close_receiver")) { try want(l, e.span, args, 1, path); const rx = try l.consuming(args[0], null); - if (rx.ty != .receiver) return l.fail("E7005", args[0].span, "`channel.close_receiver` takes a `receiver`", &.{.{ .name = "found", .value = l.tyText(rx.ty) }}); + if (rx.ty != .receiver) return l.fail("E7005", args[0].span, "`channel.close_receiver` takes a `receiver`", &.{.{ .name = "found", .value = l.diagnosticTyText(rx.ty) }}); return .{ .text = try l.fmt("channel.close_receiver %{s}", .{rx.name}), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{} }, .{ .role = "pending", .params = &.{rx.ty} } }) }; } if (std.mem.eql(u8, path, "cap.narrow.prefix")) { try want(l, e.span, args, 2, path); const c = try l.expr(args[0], null); - if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.tyText(c.ty) }}); + if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }}); var temps: std.ArrayList([]const u8) = .empty; const bytes = try l.wrap(.slice, .{ .int = "u8" }); const p = try l.argument(args[1], bytes, &temps); - if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = l.tyText(p.ty) }}); + if (!p.ty.eql(bytes)) return l.fail("E7005", args[1].span, "the path is a byte string or a `ref` borrow of bytes", &.{.{ .name = "found", .value = l.diagnosticTyText(p.ty) }}); return .{ .text = try l.fmt("cap.narrow.prefix %{s}, %{s}", .{ c.name, p.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }), .temps = temps.items }; } if (std.mem.eql(u8, path, "cap.narrow.budget")) { try want(l, e.span, args, 2, path); const c = try l.expr(args[0], null); - if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.tyText(c.ty) }}); + if (c.ty != .cap) return l.fail("E7005", args[0].span, "a capability is expected here", &.{.{ .name = "found", .value = l.diagnosticTyText(c.ty) }}); const n = try l.expr(args[1], usize_ty); try l.checkTy(args[1].span, n.ty, usize_ty); return .{ .text = try l.fmt("cap.narrow.budget %{s}, %{s}", .{ c.name, n.name }), .outcomes = try l.outs(&.{ .{ .role = "ok", .params = &.{c.ty} }, .{ .role = "err", .params = &.{.{ .builtin = .cap_error }} } }) }; diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index 97857de..cec4e14 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -250,6 +250,10 @@ const Parser = struct { const t = p.peek(); if (t.tag != .ident) return p.fail(t, "a type"); _ = p.next(); + if (p.peek().tag == .dot) { + const name = try p.pathTail(t.text); + return .{ .span = p.span(start), .kind = .{ .name = name } }; + } if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = t.text } }; _ = p.next(); if (std.mem.eql(u8, t.text, "cap")) { @@ -497,12 +501,12 @@ 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); 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(); @@ -630,6 +634,12 @@ const Parser = struct { var e = try p.primary(); while (true) { switch (p.peek().tag) { + .colon_colon => { + const name = try p.exprPath(e) orelse return p.fail(p.peek(), "an enum name before `::`"); + _ = p.next(); + const variant = try p.ident("a variant name"); + e = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant } } }; + }, .dot => { _ = p.next(); // After `.` a keyword is a member name (`task.cancelled`). @@ -689,6 +699,29 @@ 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 primary(p: *Parser) Error!ast.Expr { const start = p.peek().pos; const t = p.peek(); diff --git a/src/frontend/stdlib.zig b/src/frontend/stdlib.zig index d6c916e..8682650 100644 --- a/src/frontend/stdlib.zig +++ b/src/frontend/stdlib.zig @@ -29,6 +29,8 @@ pub fn link(arena: std.mem.Allocator, module: ast.Module) std.mem.Allocator.Erro var functions: std.ArrayList(ast.FnDecl) = .empty; try functions.appendSlice(arena, module.functions); + var types: std.ArrayList(ast.TypeDecl) = .empty; + try types.appendSlice(arena, module.types); // Registry order is lexicographic; import declaration order never affects AIR. for (registry) |entry| { const imported = for (module.imports) |imp| { @@ -43,33 +45,45 @@ pub fn link(arena: std.mem.Allocator, module: ast.Module) std.mem.Allocator.Erro .message = "malformed bundled standard source: a compiler bug", } }, }; - // The bootstrap registry intentionally exposes no imported types/dependencies. + // Bundled source spells standard type references by their full path. std.debug.assert(std.mem.eql(u8, library.name, entry.name)); - std.debug.assert(library.types.len == 0 and library.imports.len == 0); + std.debug.assert(library.imports.len == 0); + for (library.types) |t| { + std.debug.assert(t.kind == .@"enum"); + var qualified = t; + qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, t.name }); + qualified.air_name = try airName(arena, entry.name, t.name, types.items, functions.items); + try types.append(arena, qualified); + } for (library.functions) |f| { var qualified = f; qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, f.name }); - const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ entry.name, f.name }); - for (base) |*c| if (c.* == '.') { - c.* = '_'; - }; - var candidate: []const u8 = base; - var suffix: usize = 0; - while (airNameUsed(module.types, functions.items, candidate)) { - suffix += 1; - candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix }); - } - qualified.air_name = candidate; + qualified.air_name = try airName(arena, entry.name, f.name, types.items, functions.items); try functions.append(arena, qualified); } } var combined = module; + combined.types = types.items; combined.functions = functions.items; return .{ .ok = combined }; } +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 (airNameUsed(types, functions, candidate)) { + suffix += 1; + candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix }); + } + return candidate; +} + fn airNameUsed(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool { - for (types) |t| if (std.mem.eql(u8, t.name, name)) return true; + 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; } diff --git a/std/README.md b/std/README.md index 6cf6067..5331b2f 100644 --- a/std/README.md +++ b/std/README.md @@ -1,6 +1,6 @@ # Aji standard library -Bootstrap implementation in ordinary safe `.aji`: `math.aji` and `bytes.aji`. They are embedded with the compiler and compiled through the normal frontend/verifier when imported. They are library modules, not standalone `main` programs. +Implementation in ordinary safe `.aji`: `math.aji` and `bytes.aji`, with 21 functions and four public result enums. They are embedded with the compiler and compiled through the normal frontend/verifier when imported. They are library modules, not standalone `main` programs. ```aji module example @@ -19,6 +19,8 @@ effects [] 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. -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. General user imports, imported types, generics and owning collections are still future work. +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. -[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) +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. General user imports, imported struct literals, generics and owning collections are still future work. + +[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) diff --git a/std/bytes.aji b/std/bytes.aji index fee88b5..aacce8d 100644 --- a/std/bytes.aji +++ b/std/bytes.aji @@ -59,3 +59,127 @@ 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) -> 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, 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) -> 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, 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) -> 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, 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) -> 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, 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) -> 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, 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) -> 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, 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; +} diff --git a/tests/conformance/source/quickref/std_endian.aji b/tests/conformance/source/quickref/std_endian.aji new file mode 100644 index 0000000..e8605b8 --- /dev/null +++ b/tests/conformance/source/quickref/std_endian.aji @@ -0,0 +1,20 @@ +// expect: run +// result: 305419896 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3 +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; } + } +} diff --git a/tests/conformance/source/std/endian_air_equivalence.aji b/tests/conformance/source/std/endian_air_equivalence.aji new file mode 100644 index 0000000..308cd79 --- /dev/null +++ b/tests/conformance/source/std/endian_air_equivalence.aji @@ -0,0 +1,11 @@ +// expect: run +// result: {"variant":"ok","payload":[4660]} +// equivalent: std/endian_read.air +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> std.bytes.ReadU16 +effects [] +{ return std.bytes.read_u16_le(b"\x34\x12"); } diff --git a/tests/conformance/source/std/endian_alias.aji b/tests/conformance/source/std/endian_alias.aji new file mode 100644 index 0000000..e51ce3e --- /dev/null +++ b/tests/conformance/source/std/endian_alias.aji @@ -0,0 +1,9 @@ +// expect: reject E2101 E2101 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ var b: [u8; 2] = zero; ref saved = b; let r = std.bytes.write_u16_le(mut b, 1); return 0; } diff --git a/tests/conformance/source/std/endian_bare_outcome.aji b/tests/conformance/source/std/endian_bare_outcome.aji new file mode 100644 index 0000000..b5e5874 --- /dev/null +++ b/tests/conformance/source/std/endian_bare_outcome.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ match std.bytes.read_u16_le(b"xx") { ok(v) => { return 0; } short_input => { return 1; } } } diff --git a/tests/conformance/source/std/endian_compound_type.aji b/tests/conformance/source/std/endian_compound_type.aji new file mode 100644 index 0000000..d679b4e --- /dev/null +++ b/tests/conformance/source/std/endian_compound_type.aji @@ -0,0 +1,25 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §13; docs/spec/16-standard-library.md §2.3 +module test.endian +import std.bytes; + +struct Packet { word: std.bytes.ReadU32 } + +fn read_first(words: slice) -> u32 +effects [] +{ + match words[0] { + std.bytes.ReadU32::ok(value) => { return value; } + std.bytes.ReadU32::short_input => { return 0; } + } +} + +fn main() -> u32 +effects [] +{ + let packet = Packet { word: std.bytes.ReadU32::ok(42) }; + let words: [std.bytes.ReadU32; 2] = [packet.word; 2]; + return read_first(ref words); +} diff --git a/tests/conformance/source/std/endian_match_duplicate.aji b/tests/conformance/source/std/endian_match_duplicate.aji new file mode 100644 index 0000000..a4729c2 --- /dev/null +++ b/tests/conformance/source/std/endian_match_duplicate.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ match std.bytes.read_u16_le(b"xx") { std.bytes.ReadU16::ok(v) => { return 0; } std.bytes.ReadU16::ok(w) => { return 1; } std.bytes.ReadU16::short_input => { return 2; } } } diff --git a/tests/conformance/source/std/endian_match_incomplete.aji b/tests/conformance/source/std/endian_match_incomplete.aji new file mode 100644 index 0000000..b159ebd --- /dev/null +++ b/tests/conformance/source/std/endian_match_incomplete.aji @@ -0,0 +1,9 @@ +// expect: reject E7004 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ match std.bytes.read_u16_le(b"xx") { std.bytes.ReadU16::ok(v) => { return 0; } } } diff --git a/tests/conformance/source/std/endian_match_wildcard.aji b/tests/conformance/source/std/endian_match_wildcard.aji new file mode 100644 index 0000000..689c3a0 --- /dev/null +++ b/tests/conformance/source/std/endian_match_wildcard.aji @@ -0,0 +1,9 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ match std.bytes.read_u16_le(b"xx") { std.bytes.ReadU16::ok(v) => { return 0; } _ => { return 1; } } } diff --git a/tests/conformance/source/std/endian_missing_constructor_import.aji b/tests/conformance/source/std/endian_missing_constructor_import.aji new file mode 100644 index 0000000..baa43dc --- /dev/null +++ b/tests/conformance/source/std/endian_missing_constructor_import.aji @@ -0,0 +1,9 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian + + +fn main() -> u8 +effects [] +{ let r = std.bytes.ReadU16::short_input; return 0; } diff --git a/tests/conformance/source/std/endian_missing_payload.aji b/tests/conformance/source/std/endian_missing_payload.aji new file mode 100644 index 0000000..cf9b29b --- /dev/null +++ b/tests/conformance/source/std/endian_missing_payload.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ let r = std.bytes.ReadU16::ok; return 0; } diff --git a/tests/conformance/source/std/endian_missing_type_import.aji b/tests/conformance/source/std/endian_missing_type_import.aji new file mode 100644 index 0000000..d2e74aa --- /dev/null +++ b/tests/conformance/source/std/endian_missing_type_import.aji @@ -0,0 +1,12 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian + + +fn take(r: std.bytes.ReadU16) -> void +effects [] +{} +fn main() -> u8 +effects [] +{ return 0; } diff --git a/tests/conformance/source/std/endian_payload_type.aji b/tests/conformance/source/std/endian_payload_type.aji new file mode 100644 index 0000000..9f025df --- /dev/null +++ b/tests/conformance/source/std/endian_payload_type.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ let r = std.bytes.ReadU16::ok(true); return 0; } diff --git a/tests/conformance/source/std/endian_result_is_not_integer.aji b/tests/conformance/source/std/endian_result_is_not_integer.aji new file mode 100644 index 0000000..8615e37 --- /dev/null +++ b/tests/conformance/source/std/endian_result_is_not_integer.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ let r: u16 = std.bytes.read_u16_le(b"xx"); return 0; } diff --git a/tests/conformance/source/std/endian_type_namespace.aji b/tests/conformance/source/std/endian_type_namespace.aji new file mode 100644 index 0000000..e612fac --- /dev/null +++ b/tests/conformance/source/std/endian_type_namespace.aji @@ -0,0 +1,30 @@ +// expect: run +// result: 0 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +enum ReadU16 { Local(u8) } +struct __aji_std_bytes_ReadU16 { marker: u8 } +fn __aji_std_bytes_ReadU16_1() -> u8 +effects [] +{ return 7; } + +fn relay(r: std.bytes.ReadU16) -> std.bytes.ReadU16 +effects [] +{ return r; } + +fn main() -> u8 +effects [] +{ + let std: u8 = 1; + let result: std.bytes.ReadU16 = relay(std.bytes.ReadU16::ok(0x1234)); + match result { + std.bytes.ReadU16::ok(value) => { assert(value == 0x1234); } + std.bytes.ReadU16::short_input => { trap; } + } + let local = ReadU16::Local(std); + match local { ReadU16::Local(value) => { assert(value == 1); } } + return __aji_std_bytes_ReadU16_1() - 7; +} diff --git a/tests/conformance/source/std/endian_u16.aji b/tests/conformance/source/std/endian_u16.aji new file mode 100644 index 0000000..fa2de22 --- /dev/null +++ b/tests/conformance/source/std/endian_u16.aji @@ -0,0 +1,114 @@ +// expect: run +// result: 0 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn expect_read(result: std.bytes.ReadU16, expected: u16) -> void +effects [] +{ + match result { + std.bytes.ReadU16::ok(value) => { assert(value == expected); } + std.bytes.ReadU16::short_input => { trap; } + } +} + +fn expect_short_read(result: std.bytes.ReadU16) -> void +effects [] +{ + match result { + std.bytes.ReadU16::ok(value) => { trap; } + std.bytes.ReadU16::short_input => {} + } +} + +fn expect_write(result: std.bytes.WriteResult) -> void +effects [] +{ + match result { + std.bytes.WriteResult::ok => {} + std.bytes.WriteResult::short_output => { trap; } + } +} + +fn expect_short_write(result: std.bytes.WriteResult) -> void +effects [] +{ + match result { + std.bytes.WriteResult::ok => { trap; } + std.bytes.WriteResult::short_output => {} + } +} + +fn fixture(value: u16, le: slice, be: slice) -> void +effects [] +{ + expect_read(std.bytes.read_u16_le(ref le), value); + expect_read(std.bytes.read_u16_be(ref be), value); + var buf: [u8; 10] = [165; 10]; + expect_write(std.bytes.write_u16_le(mut buf[1..3], value)); + assert(std.bytes.equal(ref buf[1..3], ref le)); + assert(buf[0] == 165); + for i in 3usize..buf.len { assert(buf[i] == 165); } + expect_read(std.bytes.read_u16_le(ref buf[1..10]), value); + expect_write(std.bytes.write_u16_be(mut buf[1..10], value)); + assert(std.bytes.equal(ref buf[1..3], ref be)); + assert(buf[0] == 165); + for i in 3usize..buf.len { assert(buf[i] == 165); } + expect_read(std.bytes.read_u16_be(ref buf[1..10]), value); +} + +fn main() -> u8 +effects [] +{ + // Every short length, including zero; error writes preserve the whole array. + var buf: [u8; 10] = [165; 10]; + for size in 0usize..2usize { + expect_short_read(std.bytes.read_u16_le(ref buf[1..1 + size])); + expect_short_read(std.bytes.read_u16_be(ref buf[1..1 + size])); + expect_short_write(std.bytes.write_u16_le(mut buf[1..1 + size], 65535)); + expect_short_write(std.bytes.write_u16_be(mut buf[1..1 + size], 65535)); + for i in 0..buf.len { assert(buf[i] == 165); } + } + // Expected bytes are fixed by Python int.to_bytes, independently of std's algorithm. + fixture(0, b"\x00\x00", b"\x00\x00"); + fixture(1, b"\x01\x00", b"\x00\x01"); + fixture(65535, b"\xff\xff", b"\xff\xff"); + fixture(32768, b"\x00\x80", b"\x80\x00"); + fixture(21845, b"\x55\x55", b"\x55\x55"); + fixture(258, b"\x02\x01", b"\x01\x02"); + fixture(65197, b"\xad\xfe", b"\xfe\xad"); + fixture(30078, b"\x7e\x75", b"\x75\x7e"); + fixture(3740, b"\x9c\x0e", b"\x0e\x9c"); + fixture(31293, b"\x3d\x7a", b"\x7a\x3d"); + fixture(58065, b"\xd1\xe2", b"\xe2\xd1"); + fixture(26864, b"\xf0\x68", b"\x68\xf0"); + fixture(39631, b"\xcf\x9a", b"\x9a\xcf"); + fixture(22646, b"\x76\x58", b"\x58\x76"); + fixture(34206, b"\x9e\x85", b"\x85\x9e"); + fixture(47885, b"\x0d\xbb", b"\xbb\x0d"); + fixture(47204, b"\x64\xb8", b"\xb8\x64"); + fixture(58243, b"\x83\xe3", b"\xe3\x83"); + fixture(55416, b"\x78\xd8", b"\xd8\x78"); + fixture(4283, b"\xbb\x10", b"\x10\xbb"); + fixture(13816, b"\xf8\x35", b"\x35\xf8"); + fixture(43928, b"\x98\xab", b"\xab\x98"); + fixture(5670, b"\x26\x16", b"\x16\x26"); + fixture(50429, b"\xfd\xc4", b"\xc4\xfd"); + fixture(6951, b"\x27\x1b", b"\x1b\x27"); + fixture(1626, b"\x5a\x06", b"\x06\x5a"); + fixture(42424, b"\xb8\xa5", b"\xa5\xb8"); + fixture(62732, b"\x0c\xf5", b"\xf5\x0c"); + fixture(19262, b"\x3e\x4b", b"\x4b\x3e"); + fixture(12581, b"\x25\x31", b"\x31\x25"); + // Exercise every bit position as well as the fixed encoding fixtures. + for bit in 0u16..16u16 { + let value = 1u16 << bit; + expect_write(std.bytes.write_u16_le(mut buf, value)); + expect_read(std.bytes.read_u16_le(ref buf), value); + expect_write(std.bytes.write_u16_be(mut buf, value)); + expect_read(std.bytes.read_u16_be(ref buf), value); + } + return 0; +} diff --git a/tests/conformance/source/std/endian_u32.aji b/tests/conformance/source/std/endian_u32.aji new file mode 100644 index 0000000..b834916 --- /dev/null +++ b/tests/conformance/source/std/endian_u32.aji @@ -0,0 +1,114 @@ +// expect: run +// result: 0 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn expect_read(result: std.bytes.ReadU32, expected: u32) -> void +effects [] +{ + match result { + std.bytes.ReadU32::ok(value) => { assert(value == expected); } + std.bytes.ReadU32::short_input => { trap; } + } +} + +fn expect_short_read(result: std.bytes.ReadU32) -> void +effects [] +{ + match result { + std.bytes.ReadU32::ok(value) => { trap; } + std.bytes.ReadU32::short_input => {} + } +} + +fn expect_write(result: std.bytes.WriteResult) -> void +effects [] +{ + match result { + std.bytes.WriteResult::ok => {} + std.bytes.WriteResult::short_output => { trap; } + } +} + +fn expect_short_write(result: std.bytes.WriteResult) -> void +effects [] +{ + match result { + std.bytes.WriteResult::ok => { trap; } + std.bytes.WriteResult::short_output => {} + } +} + +fn fixture(value: u32, le: slice, be: slice) -> void +effects [] +{ + expect_read(std.bytes.read_u32_le(ref le), value); + expect_read(std.bytes.read_u32_be(ref be), value); + var buf: [u8; 10] = [165; 10]; + expect_write(std.bytes.write_u32_le(mut buf[1..5], value)); + assert(std.bytes.equal(ref buf[1..5], ref le)); + assert(buf[0] == 165); + for i in 5usize..buf.len { assert(buf[i] == 165); } + expect_read(std.bytes.read_u32_le(ref buf[1..10]), value); + expect_write(std.bytes.write_u32_be(mut buf[1..10], value)); + assert(std.bytes.equal(ref buf[1..5], ref be)); + assert(buf[0] == 165); + for i in 5usize..buf.len { assert(buf[i] == 165); } + expect_read(std.bytes.read_u32_be(ref buf[1..10]), value); +} + +fn main() -> u8 +effects [] +{ + // Every short length, including zero; error writes preserve the whole array. + var buf: [u8; 10] = [165; 10]; + for size in 0usize..4usize { + expect_short_read(std.bytes.read_u32_le(ref buf[1..1 + size])); + expect_short_read(std.bytes.read_u32_be(ref buf[1..1 + size])); + expect_short_write(std.bytes.write_u32_le(mut buf[1..1 + size], 4294967295)); + expect_short_write(std.bytes.write_u32_be(mut buf[1..1 + size], 4294967295)); + for i in 0..buf.len { assert(buf[i] == 165); } + } + // Expected bytes are fixed by Python int.to_bytes, independently of std's algorithm. + fixture(0, b"\x00\x00\x00\x00", b"\x00\x00\x00\x00"); + fixture(1, b"\x01\x00\x00\x00", b"\x00\x00\x00\x01"); + fixture(4294967295, b"\xff\xff\xff\xff", b"\xff\xff\xff\xff"); + fixture(2147483648, b"\x00\x00\x00\x80", b"\x80\x00\x00\x00"); + fixture(1431655765, b"\x55\x55\x55\x55", b"\x55\x55\x55\x55"); + fixture(16909060, b"\x04\x03\x02\x01", b"\x01\x02\x03\x04"); + fixture(185903060, b"\xd4\xa7\x14\x0b", b"\x0b\x14\xa7\xd4"); + fixture(2037551487, b"\x7f\x91\x72\x79", b"\x79\x72\x91\x7f"); + fixture(2312196622, b"\x0e\x52\xd1\x89", b"\x89\xd1\x52\x0e"); + fixture(3350121379, b"\xa3\xcb\xae\xc7", b"\xc7\xae\xcb\xa3"); + fixture(1919861753, b"\xf9\xc3\x6e\x72", b"\x72\x6e\xc3\xf9"); + fixture(2075794910, b"\xde\x1d\xba\x7b", b"\x7b\xba\x1d\xde"); + fixture(2934997640, b"\x88\x82\xf0\xae", b"\xae\xf0\x82\x88"); + fixture(3004148163, b"\xc3\xa9\x0f\xb3", b"\xb3\x0f\xa9\xc3"); + fixture(2571791918, b"\x2e\x6e\x4a\x99", b"\x99\x4a\x6e\x2e"); + fixture(3086068765, b"\x1d\xac\xf1\xb7", b"\xb7\xf1\xac\x1d"); + fixture(3288209780, b"\x74\x19\xfe\xc3", b"\xc3\xfe\x19\x74"); + fixture(595502178, b"\x62\xa4\x7e\x23", b"\x23\x7e\xa4\x62"); + fixture(246423927, b"\x77\x21\xb0\x0e", b"\x0e\xb0\x21\x77"); + fixture(4061270332, b"\x3c\x11\x12\xf2", b"\xf2\x12\x11\x3c"); + fixture(2716554228, b"\xf4\x53\xeb\xa1", b"\xa1\xeb\x53\xf4"); + fixture(19619250, b"\xb2\x5d\x2b\x01", b"\x01\x2b\x5d\xb2"); + fixture(908296138, b"\xca\x7f\x23\x36", b"\x36\x23\x7f\xca"); + fixture(1856085160, b"\xa8\x9c\xa1\x6e", b"\x6e\xa1\x9c\xa8"); + fixture(2157080593, b"\x11\x70\x92\x80", b"\x80\x92\x70\x11"); + fixture(3019974009, b"\x79\x25\x01\xb4", b"\xb4\x01\x25\x79"); + fixture(877787239, b"\x67\xf8\x51\x34", b"\x34\x51\xf8\x67"); + fixture(4107084175, b"\x8f\x21\xcd\xf4", b"\xf4\xcd\x21\x8f"); + fixture(2223566135, b"\x37\xed\x88\x84", b"\x84\x88\xed\x37"); + fixture(1062036093, b"\x7d\x62\x4d\x3f", b"\x3f\x4d\x62\x7d"); + // Exercise every bit position as well as the fixed encoding fixtures. + for bit in 0u32..32u32 { + let value = 1u32 << bit; + expect_write(std.bytes.write_u32_le(mut buf, value)); + expect_read(std.bytes.read_u32_le(ref buf), value); + expect_write(std.bytes.write_u32_be(mut buf, value)); + expect_read(std.bytes.read_u32_be(ref buf), value); + } + return 0; +} diff --git a/tests/conformance/source/std/endian_u64.aji b/tests/conformance/source/std/endian_u64.aji new file mode 100644 index 0000000..0859cc9 --- /dev/null +++ b/tests/conformance/source/std/endian_u64.aji @@ -0,0 +1,114 @@ +// expect: run +// result: 0 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn expect_read(result: std.bytes.ReadU64, expected: u64) -> void +effects [] +{ + match result { + std.bytes.ReadU64::ok(value) => { assert(value == expected); } + std.bytes.ReadU64::short_input => { trap; } + } +} + +fn expect_short_read(result: std.bytes.ReadU64) -> void +effects [] +{ + match result { + std.bytes.ReadU64::ok(value) => { trap; } + std.bytes.ReadU64::short_input => {} + } +} + +fn expect_write(result: std.bytes.WriteResult) -> void +effects [] +{ + match result { + std.bytes.WriteResult::ok => {} + std.bytes.WriteResult::short_output => { trap; } + } +} + +fn expect_short_write(result: std.bytes.WriteResult) -> void +effects [] +{ + match result { + std.bytes.WriteResult::ok => { trap; } + std.bytes.WriteResult::short_output => {} + } +} + +fn fixture(value: u64, le: slice, be: slice) -> void +effects [] +{ + expect_read(std.bytes.read_u64_le(ref le), value); + expect_read(std.bytes.read_u64_be(ref be), value); + var buf: [u8; 10] = [165; 10]; + expect_write(std.bytes.write_u64_le(mut buf[1..9], value)); + assert(std.bytes.equal(ref buf[1..9], ref le)); + assert(buf[0] == 165); + for i in 9usize..buf.len { assert(buf[i] == 165); } + expect_read(std.bytes.read_u64_le(ref buf[1..10]), value); + expect_write(std.bytes.write_u64_be(mut buf[1..10], value)); + assert(std.bytes.equal(ref buf[1..9], ref be)); + assert(buf[0] == 165); + for i in 9usize..buf.len { assert(buf[i] == 165); } + expect_read(std.bytes.read_u64_be(ref buf[1..10]), value); +} + +fn main() -> u8 +effects [] +{ + // Every short length, including zero; error writes preserve the whole array. + var buf: [u8; 10] = [165; 10]; + for size in 0usize..8usize { + expect_short_read(std.bytes.read_u64_le(ref buf[1..1 + size])); + expect_short_read(std.bytes.read_u64_be(ref buf[1..1 + size])); + expect_short_write(std.bytes.write_u64_le(mut buf[1..1 + size], 18446744073709551615)); + expect_short_write(std.bytes.write_u64_be(mut buf[1..1 + size], 18446744073709551615)); + for i in 0..buf.len { assert(buf[i] == 165); } + } + // Expected bytes are fixed by Python int.to_bytes, independently of std's algorithm. + fixture(0, b"\x00\x00\x00\x00\x00\x00\x00\x00", b"\x00\x00\x00\x00\x00\x00\x00\x00"); + fixture(1, b"\x01\x00\x00\x00\x00\x00\x00\x00", b"\x00\x00\x00\x00\x00\x00\x00\x01"); + fixture(18446744073709551615, b"\xff\xff\xff\xff\xff\xff\xff\xff", b"\xff\xff\xff\xff\xff\xff\xff\xff"); + fixture(9223372036854775808, b"\x00\x00\x00\x00\x00\x00\x00\x80", b"\x80\x00\x00\x00\x00\x00\x00\x00"); + fixture(6148914691236517205, b"\x55\x55\x55\x55\x55\x55\x55\x55", b"\x55\x55\x55\x55\x55\x55\x55\x55"); + fixture(72623859790382856, b"\x08\x07\x06\x05\x04\x03\x02\x01", b"\x01\x02\x03\x04\x05\x06\x07\x08"); + fixture(15292073328584422715, b"\x3b\xf5\x7f\xe5\xab\x5b\x38\xd4", b"\xd4\x38\x5b\xab\xe5\x7f\xf5\x3b"); + fixture(16250661963492436153, b"\xb9\x28\xeb\xc2\xf4\xf2\x85\xe1", b"\xe1\x85\xf2\xf4\xc2\xeb\x28\xb9"); + fixture(10437458558198301272, b"\x58\x42\x45\x37\x42\x4d\xd9\x90", b"\x90\xd9\x4d\x42\x37\x45\x42\x58"); + fixture(17041513473160135133, b"\xdd\x41\xbe\xca\x36\x9e\x7f\xec", b"\xec\x7f\x9e\x36\xca\xbe\x41\xdd"); + fixture(228321258174005107, b"\x73\xbf\x21\x80\xf9\x28\x2b\x03", b"\x03\x2b\x28\xf9\x80\x21\xbf\x73"); + fixture(3870920093340187, b"\x1b\x12\x1e\xd1\x94\xc0\x0d\x00", b"\x00\x0d\xc0\x94\xd1\x1e\x12\x1b"); + fixture(10610674309359647252, b"\x14\xba\xbe\x0c\x11\xb0\x40\x93", b"\x93\x40\xb0\x11\x0c\xbe\xba\x14"); + fixture(10430557097931907062, b"\xf6\x1f\xa9\xc7\x6a\xc8\xc0\x90", b"\x90\xc0\xc8\x6a\xc7\xa9\x1f\xf6"); + fixture(3219893636986986552, b"\x38\x60\x26\xff\x33\x5c\xaf\x2c", b"\x2c\xaf\x5c\x33\xff\x26\x60\x38"); + fixture(8545323553216493439, b"\x7f\x77\x3f\x20\x7f\x16\x97\x76", b"\x76\x97\x16\x7f\x20\x3f\x77\x7f"); + fixture(8990680145927224152, b"\x58\x3b\x26\x43\xf5\x4f\xc5\x7c", b"\x7c\xc5\x4f\xf5\x43\x26\x3b\x58"); + fixture(12294589648129633388, b"\x6c\x2c\xf6\x3b\x25\x28\x9f\xaa", b"\xaa\x9f\x28\x25\x3b\xf6\x2c\x6c"); + fixture(7802525658554814316, b"\x6c\xcf\x07\x35\xbf\x23\x48\x6c", b"\x6c\x48\x23\xbf\x35\x07\xcf\x6c"); + fixture(3321086216808458160, b"\xb0\x67\x50\x7d\x51\xde\x16\x2e", b"\x2e\x16\xde\x51\x7d\x50\x67\xb0"); + fixture(6819651081902464023, b"\x17\x9c\xe7\xe4\x86\x44\xa4\x5e", b"\x5e\xa4\x44\x86\xe4\xe7\x9c\x17"); + fixture(2183293185793142392, b"\x78\x2e\xbb\xbb\x95\x9d\x4c\x1e", b"\x1e\x4c\x9d\x95\xbb\xbb\x2e\x78"); + fixture(5544438551056829737, b"\x29\x4d\xb9\x8a\x7c\xcd\xf1\x4c", b"\x4c\xf1\xcd\x7c\x8a\xb9\x4d\x29"); + fixture(7373447788311746792, b"\xe8\x18\x36\x80\xb2\xbf\x53\x66", b"\x66\x53\xbf\xb2\x80\x36\x18\xe8"); + fixture(4804431457320197428, b"\x34\x5d\x48\x99\xf4\xc4\xac\x42", b"\x42\xac\xc4\xf4\x99\x48\x5d\x34"); + fixture(13174703505296887866, b"\x3a\x90\x50\x16\x09\xf3\xd5\xb6", b"\xb6\xd5\xf3\x09\x16\x50\x90\x3a"); + fixture(12286828819404160673, b"\xa1\xfe\x9d\x7c\xb6\x95\x83\xaa", b"\xaa\x83\x95\xb6\x7c\x9d\xfe\xa1"); + fixture(8427543257253372388, b"\xe4\x61\xd3\x01\xf1\xa5\xf4\x74", b"\x74\xf4\xa5\xf1\x01\xd3\x61\xe4"); + fixture(6325739954515741802, b"\x6a\x0c\x68\x32\xf9\x8a\xc9\x57", b"\x57\xc9\x8a\xf9\x32\x68\x0c\x6a"); + fixture(3169332480603093103, b"\x6f\x78\x74\x69\x19\xbb\xfb\x2b", b"\x2b\xfb\xbb\x19\x69\x74\x78\x6f"); + // Exercise every bit position as well as the fixed encoding fixtures. + for bit in 0u64..64u64 { + let value = 1u64 << bit; + expect_write(std.bytes.write_u64_le(mut buf, value)); + expect_read(std.bytes.read_u64_le(ref buf), value); + expect_write(std.bytes.write_u64_be(mut buf, value)); + expect_read(std.bytes.read_u64_be(ref buf), value); + } + return 0; +} diff --git a/tests/conformance/source/std/endian_unknown_match_type.aji b/tests/conformance/source/std/endian_unknown_match_type.aji new file mode 100644 index 0000000..f1d3fcf --- /dev/null +++ b/tests/conformance/source/std/endian_unknown_match_type.aji @@ -0,0 +1,9 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ match std.bytes.read_u16_le(b"xx") { std.bytes.Missing::ok(v) => { return 0; } std.bytes.Missing::short_input => { return 1; } } } diff --git a/tests/conformance/source/std/endian_unknown_type.aji b/tests/conformance/source/std/endian_unknown_type.aji new file mode 100644 index 0000000..47a2adf --- /dev/null +++ b/tests/conformance/source/std/endian_unknown_type.aji @@ -0,0 +1,12 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn take(r: std.bytes.Missing) -> void +effects [] +{} +fn main() -> u8 +effects [] +{ return 0; } diff --git a/tests/conformance/source/std/endian_unknown_variant.aji b/tests/conformance/source/std/endian_unknown_variant.aji new file mode 100644 index 0000000..6c104db --- /dev/null +++ b/tests/conformance/source/std/endian_unknown_variant.aji @@ -0,0 +1,9 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ let r = std.bytes.ReadU16::missing; return 0; } diff --git a/tests/conformance/source/std/endian_unqualified_type.aji b/tests/conformance/source/std/endian_unqualified_type.aji new file mode 100644 index 0000000..945fecc --- /dev/null +++ b/tests/conformance/source/std/endian_unqualified_type.aji @@ -0,0 +1,12 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn take(r: ReadU16) -> void +effects [] +{} +fn main() -> u8 +effects [] +{ return 0; } diff --git a/tests/conformance/source/std/endian_value_width.aji b/tests/conformance/source/std/endian_value_width.aji new file mode 100644 index 0000000..9734800 --- /dev/null +++ b/tests/conformance/source/std/endian_value_width.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ var b: [u8; 2] = zero; let r = std.bytes.write_u16_le(mut b, 1u32); return 0; } diff --git a/tests/conformance/source/std/endian_variant_wrong_enum.aji b/tests/conformance/source/std/endian_variant_wrong_enum.aji new file mode 100644 index 0000000..66bb03f --- /dev/null +++ b/tests/conformance/source/std/endian_variant_wrong_enum.aji @@ -0,0 +1,15 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +enum ReadU16 { ok(u16), short_input } +fn main() -> u8 +effects [] +{ + match std.bytes.read_u16_le(b"xx") { + ReadU16::ok(value) => { return 0; } + ReadU16::short_input => { return 1; } + } +} diff --git a/tests/conformance/source/std/endian_write_needs_mut.aji b/tests/conformance/source/std/endian_write_needs_mut.aji new file mode 100644 index 0000000..d529cf1 --- /dev/null +++ b/tests/conformance/source/std/endian_write_needs_mut.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/16-standard-library.md §2.3; docs/spec/15-source-language.md §13 +module test.endian +import std.bytes; + +fn main() -> u8 +effects [] +{ var b: [u8; 2] = zero; let r = std.bytes.write_u16_le(ref b, 1); return 0; } diff --git a/tests/conformance/std/endian_payload_type.air b/tests/conformance/std/endian_payload_type.air new file mode 100644 index 0000000..96044af --- /dev/null +++ b/tests/conformance/std/endian_payload_type.air @@ -0,0 +1,16 @@ +; expect: reject E1001 +; phase: 0 +; spec: docs/spec/07a-air-instructions.md; docs/spec/16-standard-library.md §2.3 +module test.endian_payload_type +air 0 +lang 0.1 +features [] + +type @ReadU16 = enum { ok(u16), short_input } + +fn @main() -> @ReadU16 +effects [] +entry: + %wrong = const.u32 4660 + %result = enum.make @ReadU16.ok(%wrong) + ret %result diff --git a/tests/conformance/std/endian_read.air b/tests/conformance/std/endian_read.air new file mode 100644 index 0000000..118c88b --- /dev/null +++ b/tests/conformance/std/endian_read.air @@ -0,0 +1,63 @@ +; expect: run +; result: {"variant":"ok","payload":[4660]} +; phase: 1 +; spec: docs/spec/16-standard-library.md §2.3; docs/spec/07a-air-instructions.md +module test.endian_read +air 0 +lang 0.1 +features [arrays, ownership] + +type @ReadU16 = enum { ok(u16), short_input } + +fn @main() -> @ReadU16 +effects [] +entry: + %storage = local.alloc array + local.zero %storage + %m = borrow.mut %storage + %dst = slice.make %m + %zero = const.usize 0 + %one = const.usize 1 + %lo = const.u8 52 + %hi = const.u8 18 + %d0 = borrow.index %dst, %zero + store %d0, %lo + borrow.end %d0 + %d1 = borrow.index %dst, %one + store %d1, %hi + borrow.end %d1 + borrow.end %dst + borrow.end %m + %r = borrow.ref %storage + %src = slice.make %r + %result = call @read_u16_le(%src) + borrow.end %src + borrow.end %r + ret %result + +fn @read_u16_le(%src: slice) -> @ReadU16 +effects [] +entry: + %n = slice.len %src + %two = const.usize 2 + %short = lt.usize %n, %two + cbr %short, @short_input(), @decode() +short_input: + %failure = enum.make @ReadU16.short_input() + ret %failure +decode: + %zero = const.usize 0 + %one = const.usize 1 + %e0 = borrow.index %src, %zero + %b0 = load %e0 + borrow.end %e0 + %e1 = borrow.index %src, %one + %b1 = load %e1 + borrow.end %e1 + %lo = cast.checked.u16 %b0 + %hi = cast.checked.u16 %b1 + %eight = const.u16 8 + %shifted = shl.u16 %hi, %eight + %value = or.u16 %lo, %shifted + %success = enum.make @ReadU16.ok(%value) + ret %success diff --git a/tools/source_coverage.py b/tools/source_coverage.py index defbb2f..18e7737 100644 --- a/tools/source_coverage.py +++ b/tools/source_coverage.py @@ -20,6 +20,9 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source") # (area, construct, regex, needs a reject test) CHECKLIST = [ + ("stdlib", "qualified standard enum type", r": std\.bytes\.(ReadU(?:16|32|64)|WriteResult)\b", True), + ("stdlib", "qualified standard enum constructor", r"std\.bytes\.(ReadU(?:16|32|64)|WriteResult)::\w+(?:\(|;)", True), + ("stdlib", "qualified standard enum match", r"std\.bytes\.(ReadU(?:16|32|64)|WriteResult)::\w+(?:\([^)]*\))? =>", True), ("stdlib", "built-in module import", r"^import std\.", True), ("stdlib", "qualified standard call", r"std\.(bytes|math)\.\w+\(", True), ("scalars", "checked arithmetic", r"[^%]\+ [a-z0-9]", False),