Files
aji/docs/rfcs/0018-bounded-standard-operations.md
dev ad75ffe021
ci / build (ubuntu-latest) (push) Successful in 4m52s
ci / extended (push) Failing after 3h0m2s
ci / build (macos-latest) (push) Canceled after 0s
docs: adopt intermediate standard library foundation
Record the owner-requested STD-0..7 merge boundary and adoption of implemented
RFCs 0016-0035, whose normative rules and vertical implementations land together.
Update repository and std status; keep remaining Std 0.1 and service milestones
in the backlog. Track Q-034/P6-11 as the next source-language task and retain
the existing P7/P8 gate.

Implementation checks are recorded in RFC 0035 and the std plan; this change
updates adoption metadata and planning only.
2026-10-07 13:42:50 +03:00

136 lines
13 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# RFC 0018: Bounded copy/search and recoverable unsigned arithmetic
Status: Implemented
Scope: STD-1b, safe standard library APIs; existing source and AIR format 0 unchanged
Language version: 0.1
Supersedes: —
Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
The proposed spec, reference implementation and tests are integrated on the work branch for review. Only the owner changes an RFC to Accepted. RFCs 0016/0017 remain the historical records for imports and endian operations.
## Motivation
Storage and protocol code needs whole-input byte copy with capacity failure, substring lookup with an unambiguous empty-input result, and overflow-aware buffer sizing. Existing primitive copy and arithmetic trap on invalid capacity/overflow; manually repeating guards adds repair work. Standard functions can express these operations using existing verified source.
This increment improves semantic explicitness, deterministic behavior, memory safety and implementation simplicity. It adds eight functions and three ordinary result enums, with no new language feature or verifier state. A reduction in model capability requirements remains an empirical hypothesis.
## Precise invariant
Copy accesses only supplied initialized slices and mutates exactly the source-length prefix of sufficient exclusive output. A short-output result leaves the entire destination unchanged and reads no source elements. Search only reads shared input. No borrowed value escapes, heap allocation occurs, resource is consumed, authority is created or task starts. Arithmetic returns a payload exactly when the mathematical result fits the operand type; neither overflow nor a zero multiplier traps.
## Normative rule changes
Integrated text is spec 16 §2.1.1/§2.4, with the primitive-versus-recoverable copy distinction clarified in spec 15 §6:
- `std.bytes.copy(dst, src)` MUST return `WriteResult::short_output` before any element access when output is short. Success MUST copy the whole input into the output prefix and preserve the remainder. Empty input succeeds. Existing alias rules reject overlapping shared/exclusive borrows regardless of runtime capacity; this is not `memmove`.
- `find_slice(data, needle)` MUST return `FindResult::found(index)` at the first match or `not_found`. Empty needle MUST return `found(0)`, including empty data. A found offset may equal the data length and is not necessarily a readable index. No borrow is returned or retained.
- Splitting at the first separator composes that search with existing explicit slices or `split_at`. There is no split function returning an aggregate of borrows or implicit cursor. Empty separator gives an empty left part and the whole right part; repeated splitting requires a caller-chosen progress rule.
- `checked_add_u64`, `checked_sub_u64`, `checked_mul_u64` return `std.math.U64Result`; the `_usize` forms return `std.math.UsizeResult`. Both enums have `ok(value)` and `overflow`. Representability determines success; unsigned underflow is overflow. `usize` follows target width.
- Normal arithmetic still traps on overflow. Wrapping stays with `+%`, `-%`, `*%`; no synonymous library wrappers are added. Generalized widths, signed/saturating arithmetic and generics are outside this increment.
## Verifier implications
No new abstract state, transfer function, diagnostic or privilege. Existing slice initialization/lifetime, shared/exclusive alias, call typing and Copy enum payload/match rules apply. Capacity guards do not grant an alias exception. A disjoint `split_at` pair from one allocation can be copied; two sub-slices of the same parent retain the existing conservative overlap rule. Results are ordinary Copy values with no must-use checking.
## Interpreter / runtime implications
No runtime change. Copy checks capacity, then calls the existing primitive `slice.copy`. Search checks empty/oversize needles, bounds a scan by `data.len - needle.len`, and uses existing equality and sub-slices. It checks the final start before incrementing, avoiding an overflowing end-plus-one loop bound. Search has constant auxiliary storage and O(data length × needle length) worst-case byte comparisons.
Unsigned arithmetic uses prechecks before checked operations: add checks available headroom, subtract compares operands, and multiply short-circuits the divisor check when its second operand is zero. The unsigned maximum is computed as `0 -% 1` in the operand type, without host constants or assumptions about pointer width. No implicit widening occurs.
All APIs are safe `.aji` with `effects []`, no heap/authority/concurrency effect and identical deterministic/hosted behavior. Valid slices and scalar operands do not produce bounds, arithmetic, cast or shift traps. Interpreter fuel remains an environment limit and is not a returned library error; the unchanged-output guarantee applies to `short_output`, not interruption mid-execution.
## AIR changes
None. Functions lower to ordinary calls, branches, arithmetic, borrows, `slice.copy`, `enum.make` and `enum.switch`, under the existing published feature closure. There is no new instruction, type kind, feature entry or interpretation. AIR format 0 remains frozen.
## Valid example
```aji
module example
import std.bytes;
import std.math;
fn encode(dst: slice_mut<u8>, data: slice<u8>) -> usize
effects []
{
match std.math.checked_add_usize(data.len, 1) {
std.math.UsizeResult::ok(total) => {
if total > dst.len { return 0; }
match std.bytes.copy(mut dst, ref data) {
std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; }
std.bytes.WriteResult::short_output => { return 0; }
}
}
std.math.UsizeResult::overflow => { return 0; }
}
}
```
`examples/std/bounded.aji` adds a main that encodes a zero-terminated byte record, searches its delimiter and verifies untouched output bytes. The conformance copy returns 10 without grants. `bounded_split.aji` checks first-separator composition, including empty inputs and separators.
## Rejected example
```aji
module example
import std.bytes;
fn main() -> u8
effects []
{
var buf: [u8; 4] = zero;
let result = std.bytes.copy(mut buf, ref buf);
return 0;
}
```
Existing `E2101` reports the conflicting shared borrow and the call's argument conflict. `bounded_copy_alias.aji` captures both diagnostics. Holding a shared borrow of the array and copying into its empty prefix is also rejected; runtime capacity checks do not weaken verification.
## Diagnostics impact
No new codes. Wrong operands/result payloads use `E7005` (AIR payload typing `E1001`); unknown/absent imports use `E7002`; incomplete matches use `E7004`; conflicting copy borrows use `E2101`. Existing diagnostic counts and source mapping remain unchanged. Capacity and overflow are result variants, not diagnostics or traps.
## Spec integration
- Spec 16 §2.1.1: six recoverable arithmetic functions, two result enums, exact representability and operator policy.
- Spec 16 §2.4: copy, search result enum, first-separator composition, capacity/empty/alias/profile contracts.
- Spec 15 §6: distinguishes primitive trapping copy from recoverable byte copy; no new grammar or lowering rule.
- API reference and Quick Reference: signatures, ordinary result handling, source example and on-demand contracts.
- Plan and Q-029: bounded split/arithmetic decisions and remaining general-module/generic work.
## Compatibility and migration
No source/AIR syntax, ownership, alias, effect, capability, runtime or existing API meaning changes. Existing `find` retains its single-byte length sentinel, including absence on empty data. Substring search uses an enum because an empty needle can successfully match empty data at offset zero. The distinct operations are intentionally documented together, without silently changing `find`'s result type. Import composition now includes eight additional functions and three enums; existing whole-module composition and collision-free names still apply. No migration required.
## Agent complexity impact
- New concepts: bounded whole-input copy; first substring offset including empty needles; recoverable scalar overflow. Results reuse ordinary enum handling.
- New verifier state: none. No new borrow return/lifetime or cleanup obligation.
- New syntax/instructions: none. Eight monomorphic function names and three ordinary result enum names are added, on demand.
- Interactions: slice aliases, disjoint split borrows, sub-slice bounds, Copy results, qualified standard type names, target-sized integers, short-circuit evaluation and interpreter fuel.
- Repairability: short copies cannot partially overwrite records; arithmetic sizing errors become typed results; search distinguishes absence from an empty match. Explicit splitting keeps borrow scopes visible. Callers can still ignore Copy results under existing rules; no measured compression claim is made.
- Existing primitives express all algorithms. No compiler change or trusted intrinsic is needed. Wrapping operators already suffice, so wrappers are omitted.
- New source diagnostic codes: zero. General width/signed APIs wait for a separate contract rather than proliferating wrappers.
- Quick Reference adds only a short routing paragraph; the signature catalog and full contracts remain in on-demand `library/std.md`.
Measured against the endian increment (`a2ca293`) with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`:
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|---|---|---|---|
| Quick Reference (`QUICK.md`, includes navigation) | 6,000 → 6,082 (+1.4%) | 6,019 → 6,102 (+1.4%) | 6,189 → 6,272 (+1.3%) |
| Other source docs | 31,918 → 33,628 (+5.4%) | 32,001 → 33,718 (+5.4%) | 32,838 → 34,572 (+5.3%) |
| Full source docs without AIR | 37,918 → 39,710 (+4.7%) | 38,020 → 39,820 (+4.7%) | 39,027 → 40,844 (+4.7%) |
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
Standalone AIR remains 160,797 bytes, 48 sections and 19 files. Incremental source bundle growth stays below the 10% warning threshold. The library page grows from 2,533/2,532/2,654 to 4,223/4,229/4,367 tokens: eight APIs need capacity, empty-match, split progress, target-width and overflow contracts, plus one checked sizing/copy example. This is on-demand documentation; the Quick Reference only gains an 82-token routing paragraph (cl100k) instead of a repeated arithmetic catalog. Its approximately 6k target remains a front-door constraint for future increments.
Branch checks: build, unit tests/Quick Reference extraction, full conformance (505 passed, zero failed/pending), formatting, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke all pass. The bounded example returns 10 without grants. Twenty-three new conformance tests exercise all 81 length/capacity pairs through eight, disjoint same-allocation copy, overlapping/empty short-output aliases, 428 substring cases, seven split cases and 320 independently computed arithmetic pairs through both u64 and usize APIs. Arithmetic fixtures include zero multipliers, underflow, addition headroom and multiplication near limits, plus seeded fixed random inputs. They use the interpreter's default `air64`; no 32-bit runtime test is claimed. Copy and arithmetic source runs match hand-written AIR; an AIR wrong-payload fixture rejects with `E1001`. All run tests execute twice for determinism, and accepted source lowers canonically and deterministically.
## Alternatives considered
An ambiguous length sentinel for substring search needs an extra empty-needle convention from the caller. A numeric result enum directly distinguishes absence. A split iterator or returned slice aggregate adds lifetime state and cursor semantics before imported structs/borrowed aggregates are specified; explicit existing slicing suffices. A silent partial copy makes output validity caller-dependent. A memmove wrapper cannot bypass the existing alias rule. Duplicating wrapping operators expands the API without changing the contract. Adding generics or a generic Result to this increment would substantially enlarge its semantic surface.
## Unresolved questions
Q-029 records these API decisions as resolved on the branch. General generics, imported structs, borrowed aggregates and must-use values remain separate work. The reference interpreter currently executes `air64`; arithmetic fixtures use that target, while the usize implementation computes its limit in target width. Q-027's empty byte-literal gap is unchanged; empty tests use existing zero-length slices.