cli: add recoverable endian APIs and qualified std enums

This commit is contained in:
dev committed 2026-10-06 15:12:55 +03:00
1 parent 10a370471b
commit a2ca293506
45 files changed
+1205 -89

No files matched your search

+3 -1
View File
@@ -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.
+15
View File
@@ -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.
+6
View File
@@ -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.
+1 -1
View File
@@ -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.
+12 -5
View File
@@ -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<T>`, `HashMap<K,V>`, 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.
+3 -3
View File
@@ -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 ;
+35
View File
@@ -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<u8>`) | Result | Write functions (`dst: slice_mut<u8>, value: uW`) | Result |
|---|---|---|---|---|
| 16 | `std.bytes.read_u16_le`, `std.bytes.read_u16_be` | `std.bytes.ReadU16` | `std.bytes.write_u16_le`, `std.bytes.write_u16_be` | `std.bytes.WriteResult` |
| 32 | `std.bytes.read_u32_le`, `std.bytes.read_u32_be` | `std.bytes.ReadU32` | `std.bytes.write_u32_le`, `std.bytes.write_u32_be` | `std.bytes.WriteResult` |
| 64 | `std.bytes.read_u64_le`, `std.bytes.read_u64_be` | `std.bytes.ReadU64` | `std.bytes.write_u64_le`, `std.bytes.write_u64_be` | `std.bytes.WriteResult` |
Read enums have exactly `ok(uW)` and `short_input`. `WriteResult` has exactly `ok` and `short_output`. These are ordinary Copy enums, handled with qualified enum patterns; they are not intrinsic outcome matches. They can be passed or returned through user functions. No generic must-use rule is introduced.
```aji
module demo.endian
import std.bytes;
fn main() -> u32
effects []
{
var wire: [u8; 6] = zero;
match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
std.bytes.WriteResult::ok => {}
std.bytes.WriteResult::short_output => { return 0; }
}
match std.bytes.read_u32_be(ref wire[1..5]) {
std.bytes.ReadU32::ok(value) => { return value; }
std.bytes.ReadU32::short_input => { return 0; }
}
}
```
Missing enum arm: `E7004`; duplicate/wildcard enum arm: `E7006`; unknown type/variant or missing import: `E7002`; wrong width/payload, immutable destination or variant from another enum: `E7005`; conflicting destination borrows: `E2101`. Existing `or trap` only applies to fallible built-in operations, so it is not used with these enums.
The example is checked in `source/quickref/std_endian.aji`; fixtures for every width/order and all short lengths are in `source/std/endian_u*.aji`.
+127
View File
@@ -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<T,E>` would be preferable once independently specified source generics exist; adding those now would enlarge this increment substantially. Three monomorphic read results keep success payloads width-correct with existing mechanisms. Runtime intrinsics would expand the trusted boundary for algorithms safe source already expresses.
## Unresolved questions
Q-028 records the short-buffer/result decision as resolved in this branch. Must-use results, general modules, imported structs and generics are separate design questions, not implicitly implemented. Q-027's existing empty byte-literal discrepancy is unchanged; empty input/output fixtures use zero-length sub-slices.
+6 -2
View File
@@ -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.
+22
View File
@@ -31,3 +31,25 @@ Inputs are byte slices, not encoded text. No UTF-8 validation or locale interpre
- `fill(dst: slice_mut<u8>, byte: u8) -> void`: writes every byte of `dst`, including zero writes for an empty slice.
The library MUST NOT read or write outside a passed slice and MUST NOT retain or return any borrow. The verifier enforces existing shared/exclusive borrowing, lifetime and bounds rules; there is no library privilege or new transfer function. Read-only functions only read their slices; `fill` writes only its exclusive slice. None consumes an owner or resource. These operations MUST NOT trap for valid byte slices and scalar operands, apart from the execution environment's fuel limit.
### 2.3 Endian reads and writes in `std.bytes`
The library provides `read_u16_le`, `read_u16_be`, `read_u32_le`, `read_u32_be`, `read_u64_le`, `read_u64_be`, and the corresponding `write_` functions. Width/order are part of the function name; no native-endian default exists. `le` is least-significant byte first; `be` is most-significant byte first. These functions operate on the beginning of the passed slice. To use an offset, pass an explicit sub-slice. There is no cursor state or alignment requirement.
Public result enums:
```aji
enum ReadU16 { ok(u16), short_input }
enum ReadU32 { ok(u32), short_input }
enum ReadU64 { ok(u64), short_input }
enum WriteResult { ok, short_output }
```
These declarations belong to `std.bytes` and are named with that prefix (spec 15 §13). For width `W` and byte count `N = W / 8`:
- `read_uW_ORDER(src: slice<u8>) -> std.bytes.ReadUW` MUST return `short_input` when `src.len < N`, without reading elements. Otherwise it MUST return `ok(value)` decoded from exactly the first N bytes. Extra bytes MUST NOT affect the result. `value = Σ src[i] × 2^(8i)` for LE and `Σ src[i] × 2^(8(N-1-i))` for BE, for `0 <= i < N`.
- `write_uW_ORDER(dst: slice_mut<u8>, value: uW) -> std.bytes.WriteResult` MUST return `short_output` when `dst.len < N` and leave every destination byte unchanged. Otherwise it MUST write exactly the first N bytes in the selected order, leave the remaining bytes unchanged and return `ok`.
Short slices are recoverable enum results, not traps. A successful zero value is distinct from a short input. These APIs declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. They have no concurrency or authority requirements beyond the ordinary slice borrow contract. All capacity checks precede all accesses/mutations. Valid slices and values MUST NOT produce bounds, arithmetic, cast or shift traps; interpreter fuel exhaustion remains an environment outcome.
The verifier uses the existing enum payload, call, shared/exclusive borrow, lifetime and bounds rules. There is no new transfer function, runtime primitive or AIR feature. Ordinary enum construction and exhaustive `enum.switch` lower the result handling. Existing `E7002`, `E7004`, `E7005`, `E7006`, `E2101` cover invalid names/matches/calls and aliasing. The behavior is identical in deterministic and hosted profiles. Existing AIR and the existing nine library operations retain their semantics; imported source receives additional declarations pinned to the compiler version.