83 lines
8.5 KiB
Markdown
83 lines
8.5 KiB
Markdown
# RFC 0020: Supplied-buffer integer formatting
|
|
|
|
Status: Proposed
|
|
Scope: STD-2b, safe standard source; language 0.1 and AIR format 0 unchanged
|
|
|
|
This branch contains the proposed spec, implementation and tests. Owner acceptance remains separate from branch implementation.
|
|
|
|
## Motivation and contract
|
|
|
|
Bounded CLI/storage records need decimal integer text without allocating or parsing format strings. Four monomorphic `std.fmt.write_u64/i64/usize/isize` functions and one Copy `WriteResult { ok(usize), short_output }` suffice. Full contracts are integrated in spec 16 §2.8; the registry adds `std.fmt` at `std/fmt.aji`.
|
|
|
|
Output is exact decimal ASCII, with a sign only for negative values, no leading zeroes except zero itself, and no terminator. A successful count includes the sign; only the output prefix changes. Insufficient capacity, including an empty destination, returns `short_output` before writing and preserves the whole destination. All values are supported, including signed minima. Existing byte copy and explicit caller offsets compose records. Each call's failure guarantee does not roll back earlier successful calls.
|
|
|
|
The increment improves deterministic behavior, explicit failure and implementation simplicity. Model Capability Compression remains an empirical hypothesis. General format strings, radix switches, floats, wider integers, text parsing, owning strings and writer protocols are outside this step.
|
|
|
|
## Memory and verifier invariant
|
|
|
|
Only the provided exclusive initialized slice is written, within its bounds. No borrow escapes, owner/resource is consumed, heap is allocated or authority/task is created. Existing initialization, call, shared/exclusive alias, lifetime, bounds and enum rules enforce this invariant. Live conflicting borrows reject even for a call that would return short output. No new verifier state, transfer function or privilege exists.
|
|
|
|
## Runtime and deterministic behavior
|
|
|
|
Safe source counts decimal digits by unsigned division before checking capacity. Signed magnitude is computed as unsigned `-(value + 1) + 1` on the negative path, avoiding direct negation of the signed minimum; nonnegative signed values convert directly. The sign is counted before capacity checking. Successful writes fill the digits from right to left, preserving the suffix. No temporary digit buffer, table or heap is needed; auxiliary scalar storage is constant and work is O(decimal digit count).
|
|
|
|
All functions declare `effects []` and use ordinary integer operations, slices, branches and enums. No AIR instruction/feature, trusted implementation, runtime rule or profile distinction is added. Bounds, arithmetic and checked conversions are valid for every input value and supplied slice. Interpreter fuel exhaustion remains an environment outcome, outside the returned-error preservation guarantee.
|
|
|
|
## Valid example
|
|
|
|
```aji
|
|
module example
|
|
import std.fmt;
|
|
fn main() -> std.fmt.WriteResult effects [] {
|
|
var text: [u8; 3] = zero;
|
|
return std.fmt.write_i64(mut text, -42);
|
|
}
|
|
```
|
|
|
|
This produces bytes `-42` and `ok(3)`. `examples/std/format.aji` and its conformance copy compose `value=-42 count=7` with explicit offsets and return 17. Independent scalar fixtures check all capacities, untouched guard/suffix bytes, zero, signed minima, unsigned maxima and decimal/binary boundaries. A disjoint split with a live borrow of the other half is valid.
|
|
|
|
## Rejected example and diagnostics
|
|
|
|
```aji
|
|
module example
|
|
import std.fmt;
|
|
fn main() -> u8 effects [] {
|
|
var text: [u8; 4] = zero;
|
|
ref held = text;
|
|
let result = std.fmt.write_i64(mut text[0..0], -1);
|
|
return held[0];
|
|
}
|
|
```
|
|
|
|
The conflicting exclusive borrow rejects with existing `E2101`, despite short capacity. Wrong destination/value/enum payload types use `E7005`; unknown/missing imports use `E7002`; incomplete matches use `E7004`. No new code or diagnostic envelope is needed. The result is Copy and introduces no must-use rule. A hand-written AIR result fixture checks the ordinary enum payload/count independently of source lowering.
|
|
|
|
## Compatibility and spec integration
|
|
|
|
Spec 16 §2 and §2.8 add the sixth closed-registry module and complete formatting contract. Spec 15 §13 resolution stays unchanged; Q-031 records the decision. Reference, Quick Reference navigation, examples and plan STD-2b expose the API through the existing source bundle. Existing source/AIR and library APIs preserve their meanings; importing grants no authority. Canonical ordering, collision handling and source provenance use existing linking; unit checks cover all six modules in different orders/directories. No migration is required.
|
|
|
|
## Agent complexity impact
|
|
|
|
- New concepts: a supplied-buffer decimal writer and its byte count; the existing explicit capacity/result convention is reused.
|
|
- New verifier state, syntax, AIR instructions, effects, capabilities and diagnostics: zero.
|
|
- API additions: four scalar function names and one ordinary Copy enum, documented on demand. Smaller widths explicitly convert to an appropriate writer. There is no generic specialization, retained offset or cleanup obligation.
|
|
- Interactions: target-width integers, checked conversion, signed limits, slice offsets, exclusive borrows, exhaustive enum matches and interpreter fuel.
|
|
- Repairability: a short write preserves every destination byte, all numeric inputs are valid, and exact byte count exposes the next caller offset. Whole-record transactionality is not implied.
|
|
- Existing primitives suffice; a runtime formatter or format-string language would add complexity without improving this contract.
|
|
|
|
Measured against the completed STD-2a worktree with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
|
|
|
|
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
|
|---|---|---|---|
|
|
| Quick Reference | 6,163 → 6,220 (+0.9%) | 6,184 → 6,241 (+0.9%) | 6,356 → 6,415 (+0.9%) |
|
|
| Other source docs | 36,042 → 37,128 (+3.0%) | 36,159 → 37,248 (+3.0%) | 37,048 → 38,154 (+3.0%) |
|
|
| Full source docs without AIR | 42,205 → 43,348 (+2.7%) | 42,343 → 43,489 (+2.7%) | 43,404 → 44,569 (+2.7%) |
|
|
| AIR docs in source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
|
|
|
Standalone AIR remains 160,797 bytes, 48 sections and 19 files. The on-demand library page grows from 6,644/6,677/6,849 to 7,730/7,766/7,955 tokens: the decimal grammar, signed/target limits, capacity/failure and append composition are explicit, with one checked complete example. Quick Reference grows by only a routing sentence. Cumulative source growth from the pre-stdlib 33,981 cl100k baseline is +27.6% (43,348); Quick Reference grows from 5,511 to 6,220 (+12.9%). The existing 20% review crossing stays explicit for owner review, without claiming model capability compression. Future library-reference splitting/selective reading remains the plan; this change adds no source grammar or AIR documentation.
|
|
|
|
Branch checks: `zig build`, `zig build test`, full conformance (544 passed, zero failed/pending), `zig fmt --check build.zig build.zig.zon src tools tests/extended`, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke pass. The executable formatting example returns 17 without grants. Fifteen new conformance files (seven source runs, seven source rejections, one AIR run) cover 523 unsigned and 984 signed independent decimal vectors, each through both fixed/target-width APIs and all capacities 0..22. All source runs execute twice for deterministic outcomes. Target-width vectors guard conversions against the target limits; the reference interpreter currently runs air64. Zero/min/max, powers of ten/two and neighbors, every small magnitude, seeded inputs, untouched guard/suffix bytes, short-output alias rejection, names/types/payloads, exhaustive matches, disjoint live borrows and source/AIR result equivalence pass. Canonical import order/provenance checks cover all six modules without heap/capability/intrinsic instructions.
|
|
|
|
## Alternatives and remaining work
|
|
|
|
An unchecked signed negation fails at the minimum value. Writing before discovering short capacity creates partial record state. Returning only a count/sentinel hides failure, and returning an output borrow adds unnecessary lifetime state. A format-string parser, radix/configuration object, public sizing helpers or synonymous append variants multiply APIs. Decimal writers plus existing copy and explicit offsets suffice for this step. Owning collections still depend on general modules, generics and `linear_aggregates`; completing STD-2b does not remove those gates.
|