Files
aji/docs/plan/standard-library.md
T
dev 1eaf968f4f cli: add explicit built-in error values
Add the error_values feature and error.const through specification, AIR,
verification, interpretation and source lowering. Error values are Copy data
with no allocation, effects or authority. Keep enum.make semantics frozen.

Cover all registered tags, feature negotiation, payload/type errors and
authority rejection in AIR/source; verify canonical and hosted CLI behavior.
Record reference-bundle costs and the map preflight-validation prerequisite.
2026-10-07 08:09:49 +03:00

22 KiB
Raw Blame History

Standard library implementation plan

Non-normative. Started on feat/std-bootstrap, 2026-10-06, at the owner's request. Normative contracts live in spec 16 and the relevant source/runtime specifications. This track gives reusable libraries priority; P7/P8 remain on hold for B1 analysis. B1 frozen inputs and private held-out tasks do not guide API design and MUST NOT be inspected or changed by this work.

Target and design constraints

Without external source dependencies, Aji should support ordinary CLI tools, storage components, network services and structured concurrent programs. The mandatory semantic surface stays small.

  • Prefer safe .aji over new AIR opcodes or opaque runtime implementations.
  • One canonical API for a common operation; effects, borrows, moves, failure and allocation budgets remain visible.
  • Caller-provided slices first; owning/growing buffers request cap<mem.alloc> and expose failure and explicit consumption.
  • Separate features (implementation support), effects (behavior) and capabilities (authority). Importing a module grants none.
  • Avoid a broad trait hierarchy. Begin with concrete adapters; add abstractions only when they reduce contracts and repair work.
  • Library functions use the existing verifier. A trusted crypto/TLS boundary is a separate audited dependency with a deterministic-profile model. Do not implement homemade cryptography.
  • Runtime capabilities and primitive coverage must be specified through every layer before a wrapper promises them. No implicit cleanup, detached tasks, reflection or ambient environment access.

Current prerequisites

Capability Current state Consequence
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 and enum types STD-0/1a/2a/2b branch implementation compiler-pinned, closed registry; eleven modules; qualified enum types/constructors/patterns; no package lookup
General modules/imported struct literals STD-3 branch implementation (P6-3; RFC Proposed) explicit manifest mapping, direct qualified names, ordinary verifier
User generics/structural constraints STD-4 branch implementation (P6-4; RFC Proposed) needed for reusable Vec<T>, HashMap<K,V>, option/result
linear_aggregates STD-5 branch implementation (RFC Proposed) whole-value owning structs/enums/fixed arrays; initialized buffer/std.vec implemented by STD-6a/b
Extended filesystem, IPv6/DNS, args/env, TLS/crypto not promised by current runtime audit each primitive, authority, error and profile model before implementation

A Vec<u64> prototype is not completion of Vec<T>. The collection gate requires valid and rejected examples for Vec<File>, HashMap<Key, Own<Value>> and Vec<sender<Job>>, plus cleanup and failure paths. No linked list is planned.

Milestones

Milestone Deliverable Exit criterion
Bootstrap std.math, std.bytes, compiler-pinned import, normative API, source tests and bundle entry all functions lower to existing AIR, verify and run; bad calls/aliases reject; import order does not affect canonical AIR; no hidden allocations or authority
Std 0.1 — system utilities core bytes/math/mem/slice/hash, option/result, buffer and owning collections, UTF-8/fmt, hex/base64, small I/O/fs/path/time/random/log APIs a CLI and bounded storage utility written in .aji use only std, explicit grants, documented failure/cleanup and deterministic fixture tests
Integration gate public, independently chosen 5–10k LOC application ownership, cancellation, bounded memory and error cleanup work together; API/documentation costs recorded; defects become general repairs
Std 0.2 — network services TCP, IPv4/IPv6, DNS, task/channel helpers, JSON DOM, URI, bounded HTTP/1.1 a local concurrent JSON/HTTP service passes deterministic fixtures and hosted smoke tests without external source packages
Std 0.3 — internet services audited secure random, SHA-256/SHA-512/HMAC/constant-time compare, TLS client/server, complete HTTP client/server and buffered I/O verified caller contracts, audited trusted boundary, certificate validation, explicit network authority, bounded buffers and deterministic failure fixtures

CLI args/env move before the Std 0.1 exit, rather than waiting for Std 0.3: they are required by the CLI target. Their capabilities and startup contracts need a vertical feature. Secure entropy is distinct from deterministic test randomness. Typed JSON schema generation waits for an independently justified compile-time facility; the DOM comes first.

SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protobuf, GUI, templating, regex and broad compression suites remain package-ecosystem work. TLS may initially depend on a vetted host crypto library; “no external source dependencies for callers” does not mean “no trusted native dependency.”

Tasks

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-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 done (branch implementation; RFC Proposed) bounded copy/search, split composition and recoverable arithmetic for u64/usize STD-1a contracts define capacity/overflow failure, no partial mutation, empty inputs and aliasing; independent fixtures pass
STD-2a done (branch implementation; RFC Proposed) UTF-8 next/validate and supplied-buffer hex/base64 STD-1a/1b malformed text and insufficient capacity are explicit, output unchanged on returned errors; independent vectors and boundary cases pass
STD-2b done (branch implementation; RFC Proposed) decimal u64/i64/usize/isize formatting into supplied buffers STD-2a minimal explicit format contract, no implicit heap, capacity/empty/maximal scalar tests and caller example
STD-3 done (branch implementation; RFC Proposed) general modules and imported type names (P6-3) STD-0 deterministic resolution, collisions/cycles and diagnostics specified and covered
STD-4 done (branch implementation; RFC Proposed) source generics (P6-4), constraints and option/result STD-3 deterministic specialization and rejected constraint examples; source/AIR budgets measured
STD-5 done (branch implementation; RFC Proposed) independent whole-value 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-6a done (branch implementation; RFC 0024 Proposed) dynamic initialized buffer storage/drain contract (Q-036) STD-4/5 vertical allocate/grow/push/pop/view/free; allocation failures preserve state, returned owners consumed; no hidden destruction
STD-6b done (branch implementation; RFC 0024 Proposed) safe std.vec for Copy/owners/files/channel endpoints STD-6a explicit reserve, bounded push, moving pop/replace, empty-only free; deterministic and failure/cleanup tests
STD-6c done (branch implementation; RFC 0025 Proposed) safe std.deque for Copy/owners/files/endpoints STD-6a/b bounded ring, both ends, failure-preserving explicit growth, complete resource transfer and empty-only free
STD-6d todo (hash foundation done; maps proposed) HashMap, HashSet, BinaryHeap STD-6a/b/c safe collection contracts, including HashMap<Key, Own>, recoverable failures and explicit draining
STD-6d.1 done (branch implementation; RFC 0026 Proposed) pure std.hash: FNV-1a 64 / CRC32C, fresh/extend STD-1b four safe functions, exact byte/chunk conventions, independent public vectors and CLI/profile checks
STD-6d.2a done (branch implementation; RFC 0027 Proposed) pure built-in error construction prerequisite STD-6d.1 vertical error_values feature, no authority/effect/resource changes; preflight allocation validation
STD-6d.2 proposed; not implemented U64Map first; general HashMap<K,V> key policy Q-037 STD-6d.1 reviewable contract, then executable safe map with ownership/failure/collision tests; general-key gate remains open
STD-7 todo concrete I/O adapters, buffered I/O and lexical paths STD-1b/2a/2b; 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
STD-11 todo JSON DOM, URI and bounded HTTP/1.1 STD-6/10 depth/size/header/body limits, malformed-input errors, streaming/EOF and cleanup tests
STD-12 todo vetted crypto backend and TLS vertical RFC STD-10/11 explicit trusted dependency, certificate/trust/entropy inputs, audit and deterministic model
STD-13 todo HTTP client/server integration and Std 0.3 review STD-12 internet-service exit criterion

Each task can be split into reviewable increments; only executable exit criteria mark it done. Owning containers are the next semantic priority, but pure byte/text operations need not wait for them. P7 is reconsidered after B1 analysis and the integration gate; this plan does not unilaterally reopen it.

API review and Model Capability Compression

For each increment record public signatures, conceptual additions, syntax forms, diagnostics, required verifier state, allocations/budgets and cleanup obligations. Run zig build agent-reference and tools/agent_bundle_tokens.py --source; report Quick Reference and Source Reference Bundle growth by group. Library reference pages are read on demand.

Use general public use cases and fixtures to measure documentation read, output size, verifier failures, repair cycles and ownership visibility. Performance and allocations also matter, but an API with five overlapping forms needs evidence. No language/API design decision is made from tasks M/C or the private corpus, and no compression benefit is claimed before measurement.

Bootstrap verification

Required: zig build, zig build test, zig build conformance, zig fmt --check build.zig build.zig.zon src tools tests/extended, python3 tools/source_coverage.py, and zig build agent-reference. Because imported code reaches the ordinary CLI, also run python3 tests/hosted/smoke.py. Run tests use fuel, never wall-clock termination.

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.

STD-1b verification

Eight further pure functions reuse existing primitives: std.bytes.copy and find_slice, plus checked add/sub/mul for u64 and usize. Copy reuses WriteResult; three additional ordinary Copy enums represent substring matches and arithmetic results. Wrapping remains an operator. Splitting composes a search with explicit caller-bounded slice operations; no borrowed aggregate, iterator, cursor, compiler/runtime change or hidden allocation is added.

The preserved invariant is shared-read/exclusive-write access only within the supplied slices, no escaping borrows and no mutation on short output. Existing verifier/call/alias/enum rules and interpreter behavior suffice. Valid/rejected source fixtures and hand-written AIR twins cover the contracts; current diagnostics and AIR format 0 are unchanged. Tests include all 81 input/output length pairs through eight, disjoint split borrows, overlapping and empty short-output aliases, 428 search cases, seven split cases and 320 independently computed arithmetic operand pairs exercised through both widths. The interpreter's numeric vectors use its default air64; library usize limits are computed with target-width wrapping subtraction. RFC 0018 records the final repository checks and complexity measurements. STD-2 can now start with UTF-8 and supplied-buffer encodings.

STD-2a verification

Six functions and six ordinary result enums add UTF-8 next/validate and supplied-buffer hex/Base64 to the closed registry. UTF-8 returns a scalar plus consumed bytes; caller offsets carry iteration state. Hex accepts both ASCII letter cases and emits lowercase; Base64 accepts canonical padded standard text with zero unused bits. Decode validates all input before capacity/mutation, so malformed input wins over insufficient output and every returned error preserves the destination. Size guards avoid intermediate overflow.

All algorithms are safe source using existing verifier/runtime rules, fixed frame storage and explicit slice borrows. No borrow escapes, owner/resource is consumed, heap allocation is hidden, AIR meaning changes or authority is granted. Valid/rejected examples, stable existing diagnostics, deterministic interpreter tests and compatibility are specified in spec 16 §2.5–§2.7 and RFC 0019. The registry embeds three additional modules without a resolver or dependency extension. Tests cover independent Python scalar/byte vectors, UTF-8 boundaries/truncation/surrogates, all input byte values, canonical pad bits, every relevant capacity, late invalid bytes, output suffixes, disjoint same-allocation buffers, namespace collisions and hand-written AIR equivalence. Formatting remains STD-2b; this increment does not mark the original whole text/formatting task complete.

STD-2b verification

Four safe decimal writers and one ordinary result enum complete the supplied-buffer formatting increment. No heap, retained cursor, format-string language, runtime primitive or syntax is added. Counts include a negative sign, suffixes remain unchanged and insufficient capacity preserves the complete destination. Counting precedes mutation; signed magnitude uses -(value + 1) then an unsigned increment, avoiding signed-minimum negation. Explicit caller offsets and std.bytes.copy compose a record; failure preserves the individual call's destination, not earlier successful calls.

Spec 16 §2.8 and RFC 0020 specify the invariant, existing verifier/runtime rules, valid/rejected examples, diagnostic impact, deterministic execution and unchanged AIR format 0. Independent Python decimal vectors exercise zero, all small values, decimal/binary transitions, seeded scalar inputs, both 64-bit limits and every capacity from zero through 22, checking all guard/suffix bytes. Target-width fixtures guard conversions against the target limits; the current interpreter executes at air64. Source/AIR result equivalence, explicit record composition, disjoint borrows, qualified types/collisions and rejection of conflicting borrows (including short output), missing imports, invalid payloads/types and incomplete matches cover the public boundary. RFC 0020 records required checks and source/AIR documentation budgets. Next semantic prerequisites for owning buffers and containers remain STD-3/4/5; a decimal writer does not complete general formatting or owning strings.

STD-3 verification

P6-3 now links explicit package sources through the same frontend as compiler-pinned std. Manifest mappings supply source bytes; pure linking checks an acyclic graph, module identity and direct-import visibility, then emits collision-free deterministic AIR. Imported functions, structs, enums and qualified task workers use existing ownership, lifetime, effect and scheduler rules. Check/lower/report instantiate no grants; run/explore use explicit manifest grants and overrides. Package sources have portable bounded paths, no symlink traversal and a 64 MiB aggregate source budget; file-only commands never discover manifests.

RFC 0021 records invariants, diagnostics, compatibility, complete validation and documentation growth. General modules and imported struct literals are implemented on this branch; dependencies and external package resolution are separate work. The next semantic step is STD-4/P6-4 generics and structural constraints, followed by the independent linear-aggregate gate. Owning collections still require both gates.

STD-4 verification

Explicit function/struct/enum generics specialize deterministically to ordinary AIR. Structural Copy/Send/Share/Freeze/Local constraints, header checking, nominal identity, direct-import visibility and fixed expansion limits are specified by spec 15 §15 and RFC 0022. Every concrete specialization passes ordinary ownership/effect/task verification; unused bodies make no validity promise for future types. The compiler registry adds safe Copy-only std.option/std.result with classification helpers. No allocation, implicit cleanup, AIR opcode or authority is added.

The finite-layout E1003 check now traverses arrays, repairing a prior verifier gap with source/AIR fixtures. Existing source from-returns remain unimplemented and are logged as Q-034 rather than given an invented lifetime/binding contract. RFC 0022 records complete validation and source/AIR budget measurements. Next is STD-5: the independent linear_aggregates vertical feature, required before containers or option/result can own resources. P6-4's generic/structural specialization task is implemented on this branch; this does not complete Phase 6.

STD-5 verification

RFC 0023 and spec 03 §25 implement whole-value linear structs/enums/fixed arrays vertically. Construction consumes nested owners; complete unpack, exhaustive match move, explicit exchange and own.pack failure preserve ownership on every normal path. Standard option/result accept owning payloads; observational classification helpers keep Copy constraints. Existing availability, alias/task-loan, Send/Share, budget and scheduler rules apply without per-field holes or hidden cleanup. No new diagnostic/effect/capability is introduced.

Source/AIR tests cover nested ownership, allocation success/failure, repeated exchange with a one-owner budget, enum replacement, borrowed fixed arrays, channels, tasks, mutexes, regions, atomics and rejected copies/leaks/aliases/recursive ownership. The interpreter preserves borrowed SSA identity across whole replacement and collection; individual own<array<T,N>> is distinguished from a repeated own_array allocation. RFC 0023 records final checks and documentation budgets. STD-6 starts with Q-036: dynamic storage, initialized length and explicit drain must be specified before growing resource collections. STD-5 does not complete Vec or Std 0.1.

STD-6a/b/c verification

Initialized buffer and safe Vec/Deque use existing ownership/borrow/task rules and deterministic allocation budgets. Deque is ordinary library source: Option represents vacancy, both ends exchange complete elements, and explicit growth rotates a ring only after allocation succeeds. Nonempty free returns the queue, so no library action closes user resources. Slot charges include Option's enum tag. Ordinary visible representation fields have a documented invariant, with no unsafe bypass.

RFC 0024 records storage/Vec validation. RFC 0025 records the deque API/budget measurements and validation: independent Python deque traces, all small head/length combinations under growth, wrapped owners, files/senders/workers, failure/cleanup and borrow/constraint rejections. Maps/sets/heaps are STD-6d; this increment does not complete Std 0.1.

Hash foundation and next map contract

STD-6d.1/RFC 0026 adds safe std.hash with four byte-only fresh/continuation operations, no new semantics or heap authority. FNV/CRC constants and public vectors are independently verified; hashes never replace key equality. The map contract proposal specifies numeric-key U64Map, bounded insert, returned replacement/full ownership, tombstone lookup, moving removal/drain and explicit peak-charged rehash. No map module is implemented; Q-037 keeps general key policy explicit, and HashMap<Key, Own>/HashSet/BinaryHeap remain required by STD-6d.