cli: bootstrap verified std bytes and math with source imports
This commit is contained in:
52 files changed
+1000
-22
No files matched your search
@@ -86,3 +86,9 @@ The groups `quick_reference`, `source_docs` and `air_docs` come from the `doc_gr
|
||||
[`quick-reference.md`](quick-reference.md) is the front door of the Source Reference Bundle (`QUICK.md`). It targets 4–6k tokens (about 4.4k with the navigation table, cl100k), covers most programs, and is kept consistent with spec 15.
|
||||
|
||||
**Its examples are checked.** Every ```aji block must be an excerpt of a program in `tests/conformance/source/quickref/`. Comments and whitespace are ignored, and `…` matches any text. Those programs are conformance tests, so each example is part of a program that verifies and runs. `zig build test` and `zig build agent-reference` fail on an example that is not. The concurrency programs (§7) are PENDING until layers 7–8 exist.
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
@@ -316,3 +316,26 @@ scope s { // every task spawned in s must
|
||||
| E2111 | graph content not plain data | store only integers, booleans, enums, structs/arrays of them and `iref`s in a graph |
|
||||
| T0010 | `iref` of another graph | use a handle with the graph it came from |
|
||||
| T0001–T0009 | runtime trap | see `kind` and `source_location` |
|
||||
|
||||
## 10. Standard library
|
||||
|
||||
Import a bundled module after the module header; call its functions by their full path. `std.bytes` and `std.math` are safe source, declare `effects []` and allocate no heap. No grants are needed. Read `/docs/library/std.md` for the API.
|
||||
|
||||
```aji
|
||||
module demo.standard
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var data: [u8; 4] = zero;
|
||||
std.bytes.fill(mut data, 65);
|
||||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||||
let index = std.bytes.find(ref data, 65);
|
||||
if index < data.len { assert(data[index] == 65); }
|
||||
return std.math.clamp_u64(42, 0, 100);
|
||||
}
|
||||
```
|
||||
|
||||
`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.
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
> QUICK.md
|
||||
docs/agent/quick-reference.md
|
||||
docs/agent/source-notes.md :: ## 10. Where to read more
|
||||
docs/agent/source-notes.md :: ## 11. Where to read more
|
||||
|
||||
> language/syntax.md
|
||||
docs/reference/grammar.ebnf
|
||||
@@ -19,6 +19,12 @@ docs/spec/15-source-language.md :: ## 4. Statements and control flow
|
||||
docs/spec/15-source-language.md :: ## 5. Expressions
|
||||
docs/spec/15-source-language.md :: ## 6. Fallible operations and `match`
|
||||
|
||||
docs/spec/15-source-language.md :: ## 13. Built-in standard modules
|
||||
|
||||
> library/std.md
|
||||
docs/spec/16-standard-library.md
|
||||
docs/reference/std.md
|
||||
|
||||
> language/types.md
|
||||
docs/spec/15-source-language.md :: ## 3. Types
|
||||
docs/spec/02-types-and-values.md :: ## 2. Integer semantics
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
Text that exists only for the Source Reference Bundle (`source-bundle.txt`). Non-normative: it points at the normative files and states which source layers are implemented.
|
||||
|
||||
## 10. Where to read more
|
||||
## 11. Where to read more
|
||||
|
||||
The other files in `/docs` hold the full rules. Open one only when this page is not enough.
|
||||
|
||||
| Need | Read |
|
||||
|---|---|
|
||||
| built-in `std.math`/`std.bytes`, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| exact syntax, every construct, `match` and outcomes | `/docs/language/syntax.md` |
|
||||
| integer semantics, conversions, Copy/Send/Share, traps | `/docs/language/types.md` |
|
||||
| borrows, scopes, frame storage, slices, initialization | `/docs/language/ownership.md` |
|
||||
|
||||
@@ -202,3 +202,13 @@ Points 1–3 and 5 are editorial. Point 4 fixes FIFO, which spec 04 §38 already
|
||||
|
||||
Found by the independent author of `program_atomic_stats.air` (P5-9b). AIR has `array.splat` but no way to build an array from distinct element values. A six-element constant array costs a mutable borrow, six `borrow.index`/`store`/`borrow.end` triples and six index constants. `.aji` has the same gap: it has `[e; N]` but no array literal. The options are an `array.make T (%a, %b, …)` instruction (a value constructor like `struct.make`) with an `.aji` literal `[a, b, c]`, or no change. This is a convenience question, not a correctness one. It is not urgent, and any RFC for it must report its agent-complexity cost.
|
||||
|
||||
|
||||
## Q-026 — Standard library distribution and initial source imports
|
||||
|
||||
The source frontend had no import resolution and the package manifest no dependencies. A source-only std therefore needed either manual concatenation or a specified import path.
|
||||
|
||||
**Resolved in the std bootstrap branch:** spec 15 §13 defines a closed compiler-pinned registry, fully qualified calls, deterministic name mangling and library source locations. Spec 16 defines the initial pure API. General user modules and imported types remain STD-3/P6-3; no filesystem search is invented. RFC 0016 records the proposal; its status stays Proposed until the owner accepts it.
|
||||
|
||||
## 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.
|
||||
@@ -139,6 +139,10 @@ Targets for Phase 6A, measured on dev tasks:
|
||||
| feature-header diagnostics | 0 (the frontend infers the feature closure) |
|
||||
| safety guarantees | unchanged, because the same AIR is verified | Every Phase 3+ semantic RFC re-measures the Agent Reference Bundle (`docs/agent/README.md`).
|
||||
|
||||
## Standard library track
|
||||
|
||||
At the owner’s request (2026-10-06), reusable std APIs take priority in a separate work branch. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
|
||||
|
||||
## Task conventions
|
||||
|
||||
- IDs are `P<phase>-<n>` and never reused. A task split later becomes `P1-4a`, `P1-4b`.
|
||||
|
||||
@@ -140,3 +140,5 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| P6-8 | todo | Formatter | P6-2 | `aji fmt` | idempotent; output parses to the same AST |
|
||||
| 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.
|
||||
@@ -0,0 +1,78 @@
|
||||
# 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 | this bootstrap increment | compiler-pinned, closed registry; no package lookup |
|
||||
| General modules/imported types | 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 |
|
||||
|
||||
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-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-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-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.
|
||||
@@ -12,7 +12,8 @@
|
||||
- Every construct has one canonical spelling (spec 15 §1).
|
||||
*)
|
||||
|
||||
module = "module" path { item } ;
|
||||
module = "module" path { std_import } { item } ;
|
||||
std_import = "import" path ";" ; (* contextual word, spec 15 §13 *)
|
||||
item = type_decl | fn_decl ;
|
||||
path = ident { "." ident } ;
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# Standard library API
|
||||
|
||||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external dependencies or grants.
|
||||
|
||||
All functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||||
|
||||
| Module | Function signature | Result/failure |
|
||||
|---|---|---|
|
||||
| `std.math` | `min_u64(a: u64, b: u64) -> u64` | smaller operand |
|
||||
| `std.math` | `max_u64(a: u64, b: u64) -> u64` | larger operand |
|
||||
| `std.math` | `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` | inclusive clamp; `T0002` if `lower > upper` |
|
||||
| `std.bytes` | `equal(a: slice<u8>, b: slice<u8>) -> bool` | byte equality |
|
||||
| `std.bytes` | `compare(a: slice<u8>, b: slice<u8>) -> i8` | unsigned lexicographic order: exactly -1/0/1 |
|
||||
| `std.bytes` | `find(data: slice<u8>, byte: u8) -> usize` | first index; `data.len` if absent |
|
||||
| `std.bytes` | `starts_with(data: slice<u8>, prefix: slice<u8>) -> bool` | empty prefix matches |
|
||||
| `std.bytes` | `ends_with(data: slice<u8>, suffix: slice<u8>) -> bool` | empty suffix matches |
|
||||
| `std.bytes` | `fill(dst: slice_mut<u8>, byte: u8) -> void` | fills caller-provided storage |
|
||||
|
||||
```aji
|
||||
module demo.standard
|
||||
import std.bytes;
|
||||
import std.math;
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var data: [u8; 4] = zero;
|
||||
std.bytes.fill(mut data, 65);
|
||||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||||
let index = std.bytes.find(ref data, 65);
|
||||
if index < data.len { assert(data[index] == 65); }
|
||||
return std.math.clamp_u64(42, 0, 100);
|
||||
}
|
||||
```
|
||||
|
||||
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/`.
|
||||
@@ -0,0 +1,121 @@
|
||||
# RFC 0016: Standard library bootstrap and built-in source imports
|
||||
|
||||
Status: Proposed
|
||||
Scope: `.aji` source composition and safe pure standard modules; AIR format 0 unchanged
|
||||
Language version: 0.1
|
||||
Supersedes: —
|
||||
|
||||
This branch contains the proposed spec text, reference implementation and tests for review. Only the owner changes the RFC to Accepted; implementation on a work branch does not constitute acceptance.
|
||||
|
||||
## Motivation
|
||||
|
||||
Reusable byte operations reduce repeated loop/borrow code and the reasoning burden of basic system software. The current frontend has no modules/import resolution or user generics, while linear aggregates are reserved. Beginning with safe non-owning byte functions makes progress without pretending that resource-owning collections already work.
|
||||
|
||||
The proposal improves implementation simplicity, deterministic behavior, auditability and machine repairability. Its value for Model Capability Compression is a hypothesis to measure, not a result inferred from smoke tasks. The full roadmap is `docs/plan/standard-library.md`.
|
||||
|
||||
## Precise invariant
|
||||
|
||||
Imported standard source is ordinary code under the same verifier: immutable slices only read, exclusive slices only write, no borrow escapes, no resource is consumed, no authority is created, no hidden heap allocation occurs. Every source call lowers to a normal AIR call with a collision-free identifier.
|
||||
|
||||
## Normative rule changes
|
||||
|
||||
The complete proposed text is integrated into spec 15 §2/§13, spec 16 and `reference/grammar.ebnf`/`reference/std.md` in this branch. It defines a closed compiler-pinned module registry, contextual `import std.bytes;`, fully qualified calls, lexicographic composition, collision-free name mangling, library source provenance and nine pure API contracts.
|
||||
|
||||
This proposal covers only `std.bytes` and `std.math`. It does not make general package imports, aliases, imported types or generic collections available. The whole imported module is lowered, so unused declarations also contribute to the feature closure. Dependency pruning is deferred until there is evidence that the simple strategy becomes costly.
|
||||
|
||||
## Verifier implications
|
||||
|
||||
No new state, transfer functions, diagnostics or trusted exemptions. Calls, slices, alias checks, frame lifetime, bounds and initialization use the existing rules. Module/function limits apply to the combined module, including all standard declarations. Imported source cannot bypass verification.
|
||||
|
||||
## Interpreter / runtime implications
|
||||
|
||||
No new runtime rule. Ordinary function calls execute pure operations under fuel. `fill` writes only caller-provided storage. No initialization on import, hidden cleanup, allocation or task creation. Invalid clamp bounds trap `T0002` at the assertion in `std/math.aji`; valid byte slices do not trap due to library arithmetic or bounds.
|
||||
|
||||
## AIR changes
|
||||
|
||||
None. There is no new feature registry entry or opcode: the source import is composition, not an AIR construct. Dots are not allowed in format-0 global identifiers; standard functions therefore use deterministic collision-free `__aji_std_bytes_equal`-style names, with numeric suffixes when needed. The compiler emits the existing feature closure. Existing AIR constructs, types and effects retain their frozen semantics.
|
||||
|
||||
## Valid example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 4] = zero;
|
||||
std.bytes.fill(mut buf, 65);
|
||||
assert(std.bytes.equal(ref buf, b"AAAA"));
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## Rejected example
|
||||
|
||||
```aji
|
||||
module example
|
||||
import std.bytes;
|
||||
|
||||
fn main() -> u8
|
||||
effects []
|
||||
{
|
||||
var buf: [u8; 4] = zero;
|
||||
ref saved = buf;
|
||||
std.bytes.fill(mut buf, 65);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
The exclusive borrow conflicts with `saved`: `E2101`. Current verification reports it at both the borrowed argument and the call, as captured by the conformance test; no new rule or code is introduced. A wrong slice type/arity is `E7005`, an unknown import/member or absent import is `E7002`, a duplicate import is `E7006`, malformed import/type-argument syntax is `E7001`.
|
||||
|
||||
## Diagnostics impact
|
||||
|
||||
No new code. Library diagnostics and traps use the stable bundled source path and original positions; AIR locations remain available. User diagnostics retain their existing file and source mapping. Source-mapping deduplication compares the file as well as code/line/column, so separate files cannot silently suppress one another.
|
||||
|
||||
## Spec integration
|
||||
|
||||
- Spec 15 §2/§13: imports, resolution, lowering and source provenance.
|
||||
- Spec 16: standard library contract and bootstrap modules.
|
||||
- Reference grammar: import syntax; API reference: signatures/failure table.
|
||||
- Source Reference Bundle: import rules in `language/syntax.md`, APIs in the on-demand `library/std.md`, navigation and a checked Quick Reference example.
|
||||
|
||||
The AIR bundle is unchanged; the functions need only existing AIR contracts. The spec remains authoritative after owner acceptance.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
AIR format 0 is unchanged, with no new instruction, type, verifier/runtime rule or interpretation. Programs without imports keep identical canonical AIR; the contextual word `import` still works as an ordinary local/function name. User functions/types with generated-name collisions are preserved and standard symbols get suffixes. A local binding named `std` does not change fully qualified standard resolution. No migration required.
|
||||
|
||||
General user imports, public types and generics need their own source specifications. Resource-owning collections require the independent vertical `linear_aggregates` RFC; this proposal cannot be used as permission to weaken ownership.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
- New concepts: compiler-bundled module import and fully qualified library call; nine named pure operations.
|
||||
- New verifier state: none.
|
||||
- New syntax forms: one import statement; qualified calls reuse existing dotted call expressions. No new AIR instruction.
|
||||
- Interactions: existing call typing, frame/slice borrows, bounds, function naming, feature closure and source spans. No capability or effect is inferred away.
|
||||
- Repairability: reuse checked functions instead of rewriting loops; absent import/type/alias mistakes reuse stable diagnostics. `find` uses a length sentinel that callers must check. No benefit is claimed until measured.
|
||||
- Existing primitives suffice for every algorithm; source composition removes the need for manual source concatenation.
|
||||
- Public generics are not invented; the three integer functions explicitly say `u64`. The source-side budget includes this temporary monomorphic surface.
|
||||
- New source diagnostics: none; existing codes gain import/member cases.
|
||||
|
||||
Measured with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source` on the bootstrap branch:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference (`QUICK.md`, includes navigation) | 5,511 → 5,777 (+4.8%) | 5,529 → 5,797 (+4.8%) | 5,664 → 5,948 (+5.0%) |
|
||||
| Other source docs | 28,470 → 30,461 (+7.0%) | 28,552 → 30,546 (+7.0%) | 29,238 → 31,307 (+7.1%) |
|
||||
| Full source docs without AIR | 33,981 → 36,238 (+6.6%) | 34,081 → 36,343 (+6.6%) | 34,902 → 37,255 (+6.7%) |
|
||||
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
|
||||
|
||||
The new on-demand API page costs 1,346/1,347/1,406 tokens. Standalone AIR bundle size stays 160,797 bytes, 48 sections, 19 files. Growth is below the 10% warning threshold. Nine APIs replace repeated user loops without adding verifier state; later additions must remeasure rather than assuming this budget scales.
|
||||
|
||||
Branch checks: build, unit tests, Quick Reference extraction, full conformance (456 passed, zero failed/pending), formatting and source coverage (69/69) pass. Hosted file/stdin/TCP smoke tests pass. Evaluation harness self-tests pass (22 tests; one environment-dependent skip). The source run tests execute twice for determinism, and one std test compares against hand-written AIR. Boundary tests cover empty slices, embedded zero/high bytes, length ordering, repeated/absent search results, every u8 fill value, sub-slice mutation, u64 extremes and inverted clamp bounds. Collision tests exercise both user type/function names and the local `std` name; mapping and CLI record tests preserve library provenance.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Manual copying/concatenation makes library source and diagnostics hard to track. Hidden std intrinsics enlarge the trusted surface for ordinary algorithms. Implementing general packages and generics first delays pure reusable code; the closed two-module registry provides a bounded first increment while keeping those prerequisites explicit. Implicit prelude and aliases increase name-resolution choices and are omitted.
|
||||
|
||||
## Unresolved questions
|
||||
|
||||
Q-026 records the import/distribution decision. Q-027 records the existing discrepancy between the spec and frontend for empty byte literals; tests pass zero-length slices with the existing `ref storage[0..0]` form. Typed schemas, crypto backend choice, TLS trust configuration, cancellation-safe container cleanup and extended runtime capabilities are separate roadmap gates.
|
||||
@@ -58,6 +58,7 @@ effects [io.read, io.write]
|
||||
```
|
||||
|
||||
- A file holds one module: `module <dotted.path>`, then type and function declarations in any order.
|
||||
- Between the module header and declarations, `import <dotted.path>;` imports a built-in standard module (§13). `import` is contextual at this position; it remains an ordinary identifier elsewhere.
|
||||
- `//` starts a line comment.
|
||||
- Function `f` lowers to `@f`; type `T` to `@T`.
|
||||
- **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then the body block.
|
||||
@@ -466,3 +467,17 @@ Other rules:
|
||||
|
||||
- `*c` and any other ordinary read of a cell is `E4202`.
|
||||
- Effects are declared by the programmer (spec 05 §13).
|
||||
|
||||
## 13. Built-in standard modules
|
||||
|
||||
The compiler MUST provide the standard modules listed in spec 16 §2, pinned to its own version. An import MUST resolve only against that closed registry: no file-system search, environment variable, network fetch, package manifest, or build extension participates. Unknown modules are `E7002`; duplicate imports are `E7006`. Imports MUST precede declarations; a misplaced import or missing semicolon is `E7001`.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,33 @@
|
||||
# 16. Standard Library
|
||||
|
||||
## 1. Contract
|
||||
|
||||
The standard library SHOULD make CLI programs, storage components, network services and structured concurrent programs possible without external source dependencies. Scope and sequencing are tracked in `docs/plan/standard-library.md`; that roadmap does not imply that unimplemented APIs are available.
|
||||
|
||||
Standard APIs MUST expose allocation, authority, effects, ownership transfer and recoverable failure in their public contracts. Safe library source MUST pass the ordinary verifier. Unsafe or foreign implementations MUST use an explicit audited trusted boundary under spec 13; they MUST NOT masquerade as verified source. The library MUST NOT obtain ambient host authority.
|
||||
|
||||
APIs SHOULD offer one canonical operation for a common need, small documentation requirements, bounded memory behavior and stable repair guidance (spec 14 §8). Resource cleanup remains explicit. Pure byte/path transformations do not grant authority over files or sockets.
|
||||
|
||||
## 2. Bootstrap module registry
|
||||
|
||||
The built-in registry contains `std.math` and `std.bytes`. Both are implemented in safe `.aji` with `effects []`. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile, have no concurrency effects and allocate no heap memory. Ordinary interpreter fuel limits apply.
|
||||
|
||||
### 2.1 `std.math`
|
||||
|
||||
- `min_u64(a: u64, b: u64) -> u64` returns the smaller operand.
|
||||
- `max_u64(a: u64, b: u64) -> u64` returns the larger operand.
|
||||
- `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` returns `lower` below the range, `upper` above it, or `value` inside it. The inclusive range MUST satisfy `lower <= upper`; violation traps `T0002` before returning a value.
|
||||
|
||||
These are monomorphic functions, not a generic arithmetic facility. Checked/wrapping operators retain their existing semantics (spec 02); importing this module does not alter them.
|
||||
|
||||
### 2.2 `std.bytes`
|
||||
|
||||
Inputs are byte slices, not encoded text. No UTF-8 validation or locale interpretation occurs. Read-only parameters are `slice<u8>`.
|
||||
|
||||
- `equal(a, b) -> bool`: true exactly when lengths and all bytes agree.
|
||||
- `compare(a, b) -> i8`: unsigned-byte lexicographic comparison; returns exactly `-1`, `0` or `1`. The shorter of two matching prefixes sorts first.
|
||||
- `find(data, byte: u8) -> usize`: index of the first occurrence; `data.len` when absent. A found index is valid only for the searched slice and exactly when the result is less than its length. Indexing retains the ordinary bounds-check rules (`T0008` for an absent result used as an index).
|
||||
- `starts_with(data, prefix) -> bool`, `ends_with(data, suffix) -> bool`: true for matching prefixes/suffixes, including empty ones; false when the candidate is longer than `data`.
|
||||
- `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.
|
||||
@@ -25,6 +25,7 @@ The specification is split by semantic domain. Rationale for major decisions liv
|
||||
| [13-contracts-and-unsafe.md](13-contracts-and-unsafe.md) | Normative draft | Contracts, proof status and unsafe boundaries |
|
||||
| [14-agent-efficiency.md](14-agent-efficiency.md) | Normative draft (design objectives) | Agent efficiency, Model Capability Compression, design review requirement |
|
||||
| [15-source-language.md](15-source-language.md) | Normative draft | The agent-facing source language `.aji` 0.1 (Phase 6A), lowering to AIR |
|
||||
| [16-standard-library.md](16-standard-library.md) | Normative draft | Standard library contracts and built-in pure modules |
|
||||
|
||||
## Reading order
|
||||
|
||||
|
||||
Reference in new issue
Block a user