cli: add recoverable endian APIs and qualified std enums
This commit is contained in:
45 files changed
+1205
-89
No files matched your search
@@ -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.
|
||||
Reference in new issue
Block a user