Files
aji/docs/rfcs/0022-explicit-source-generics.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

14 KiB
Raw Permalink Blame History

RFC 0022: Explicit source generics and Copy option/result

Status: Implemented Scope: STD-4 / P6-4; source language 0.1, AIR format 0 unchanged Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.

This branch contains proposed normative text, implementation and tests. Owner acceptance remains separate from branch implementation.

Motivation and contract

General modules supply reusable nominal types; generic functions/types now remove monomorphic duplication without adding runtime dispatch or inferred authority. Spec 15 §15 defines explicit specialization of functions, structs and enums. Spec 16 §2.9 adds std.option/std.result. Q-033 records the previously unspecified syntax/checking/constraint decisions. Source grammar and Quick Reference are updated in the same change.

Declarations use <T> or <T: Copy + Send>; function/worker/constructor/pattern applications use ::<...>, while type annotations use Name<...>. Arguments are always explicit, ordered and complete. There are no traits, defaults, overloads, const/lifetime/effect parameters or argument inference. Qualified applications preserve direct-import visibility and module-local binding. Generic main is forbidden. Existing channel.make spelling is unchanged.

Headers, signature names/arity, structural constraints, duplicate declarations/parameters/fields/variants, effects and trusted restrictions are checked even on unused templates. Bodies are checked as concrete required specializations; accepting an unused body does not prove it works for arbitrary types. All ordinary non-generic reachable declarations still verify even if unused. The frontend does not guess missing moves, effects, authority or cleanup.

Copy, Send and Share reuse ordinary type rules. Format-0 Freeze means IslandSafe plain graph content; Local describes context-bound task/scope/shield/guard/storage and explicitly specified wrapper/aggregate propagation, not the complement of Send. These queries provide no operations: Copy does not promise arithmetic, ordering or equality for every concrete type. Unknown/duplicate constraints reject E7006; an unsatisfied property is E7005 at the application with parameter/constraint/found fields. Generic arguments, including phantom arguments, must be well formed by ordinary type rules.

Preserved memory and concurrency invariant

Every emitted specialization obeys existing ownership, initialization, bounds, alias, lifetime, resource, Send/Share, task and effect rules. No borrow escapes, resource duplicates, cleanup disappears or mutable sharing becomes implicit because its type came from a parameter. Named owners/resources still require explicit move and consumption on every path. Task lends remain unavailable until join and disjoint mutable slices remain independent. No implicit heap allocation, refcount, destructor or detached task is introduced.

Generic functions can transfer individual owners with explicit move; generic aggregate fields still cannot hold them. Copy-only Option/Result reject owners/resources/endpoints/borrows. A generic Cell<own> still hits the reserved linear_aggregates gate (E0006). Owning option/result and containers remain STD-5/6 work.

Verifier and AIR rule

An AST specialization pass substitutes concrete types before existing lowering. Every required specialization becomes an ordinary named struct/enum or static function. No generic opcode, AIR type constructor, AIR feature or new verifier transfer state is introduced. The ordinary combined AIR verifier remains authoritative for memory/effects/tasks; source constraints use its structural property queries and type well-formedness rules. Concrete headers, parameter types and public effects are preserved. The AIR feature header is the existing dependency closure of emitted code, without fictitious runtime features for phantom type arguments.

The finite-layout check is repaired to follow array elements, as well as direct nominal members. Arrays cannot hide a by-value recursive aggregate under the existing E1003 contract (spec 07 §8.3). Positive and rejected AIR/source fixtures cover this. Before lowering concrete generic bodies, the same layout query rejects cycles, avoiding recursive lowering of zero-initialized cyclic types. This closes an implementation gap without extending format-0 semantics.

Runtime and deterministic behavior

There is no generic representation, runtime loader, dynamic dispatch or new interpreter primitive. Concrete calls, enum payloads, struct fields, owned values, borrows and workers run under the existing deterministic interpreter and scheduler. Compiler memory used to specialize templates does not allocate program heap or grant authority.

A key consists of declaration kind, defining module/name and ordered structural concrete argument identities, independent of import/provider order, diagnostic file labels and short/qualified spelling. Nominal module types remain distinct. Same-key recursion reuses a pending instance; expanding recursion is bounded. Instances append in sorted key order after ordinary declarations, with types before functions. AIR names use lowercase SHA-256 key bytes with smallest unused numeric suffixes, assigned in sorted key order against original/generated names. Full keys determine identity; hashes do not. This handles collisions without order-dependent naming. Source diagnostics preserve template provenance, and display names show readable concrete source types/functions rather than internal encoded identifiers.

Fixed compiler limits are 8 parameters per declaration, 4,096 generated declarations, active expansion depth 64, structural type traversal depth 64 and canonical key length 16,384 bytes. Limits reject E7006; they are not runtime fuel or semantics-changing flags. Recursively spelled applied type keys avoid repeated hex expansion; output AIR names remain compact. Existing monomorphic input preserves canonical AIR. Source from-returns retain the existing unimplemented outcome; Q-034 tracks their missing lifetime/binding implementation rather than inventing a contract here.

Valid example

module demo.generic
import std.option;
fn identity<T: Copy>(value: T) -> T effects [] { return value; }
fn main() -> u64 effects [] {
    let value = std.option.Option::<u64>::some(identity::<u64>(42));
    match value {
        std.option.Option::<u64>::some(n) => { return n; }
        std.option.Option::<u64>::none => { return 0; }
    }
}

The checked examples/std/generics.aji returns 42 without grants. The registry includes Option<T: Copy> { some(T), none } and Result<T: Copy, E: Copy> { ok(T), err(E) }, with is_some/is_ok<T,E> classification helpers declaring effects []. Matching is ordinary exhaustive enum matching, not intrinsic outcome shorthand. No implicit unwrap, default, conversion or must-use rule is added.

Additional runnable source fixtures swap two exclusive scalar borrows, read through a generic shared parameter, transfer an owner to a generic identity with explicit move and take it exactly once, invoke generic effectful code with an entry capability, specialize a qualified package template with a caller's nominal type, recurse with one cached instance, and lend disjoint buffers to specialized workers.

Rejected examples and diagnostic impact

module demo.generic
fn marker<T: Copy>() -> u64 effects [] { return 42; }
fn main() -> u64 effects [] { return marker::<own<u64>>(); }

This rejects E7005 at the argument application, identifying T, Copy and own. Missing arguments, arity, generic entry, duplicate/unknown properties, shadowed parameters and expansion limits use E7006. Missing/inaccessible templates/types use E7002; malformed syntax uses E7001. Existing E7003, E2101, E3101 and E4101 reject missing moves, alias conflicts, omitted effects and duplicate task lends. Incomplete option/result matches remain E7004. Unsupported linear aggregate members still use E0006; recursive layout uses E1003. There is no new diagnostic code or envelope. Errors and traps in imported generic bodies retain the template file/line.

For example, passing mut a twice to swap:: rejects E2101, and passing the same slice to two live specialized workers rejects E4101. Send<task>, Share, Freeze<cap<io.write>> and Local reject rather than silently changing behavior. Unknown signature types or trusted clauses in unused templates reject, while unused body operations are deliberately not concretely checked until instantiated.

Compatibility and integration

Spec 15 §13/§14 distinguish complete ordinary declarations from templates under §15; source grammar, type property reference and spec 01 overview point to the explicit forms. The source bundle includes an on-demand language/generics.md; std signatures/constraints are in library/std.md. Two safe embedded modules add two enum templates and two helper templates; the existing six modules, 39 monomorphic functions and 14 enums retain contracts. No package discovery, ambient authority or dependency fetch is added.

Previously invalid explicit source generic syntax becomes valid; monomorphic source/AIR and legacy channel.make remain compatible. Fixing array layout recursion rejects previously misaccepted but normatively invalid AIR. Existing unsupported from-return behavior remains visible and separately tracked. STD-4 completes the generic/structural-specialization task on this branch; full Phase 6 and owning containers remain incomplete. The owner adopted this implemented contract with the intermediate std merge (2026-10-07).

Agent complexity impact

  • New concepts: ordered explicit type parameters/arguments, concrete specialization versus unused-body checking, structural property requirements and bounded compile-time expansion.
  • New source forms: declaration parameter lists, optional property lists, applied type names and explicit expression/pattern specialization. Existing qualified names, fields, variants, casts and static worker operands compose with them. No new keyword, trait search, lifetime syntax, runtime instruction, effect, capability or diagnostic code.
  • Frontend state: template environment, canonical instance cache/pending markers, argument obligations, depth/key/count budgets, stable names and resolved internal references. Verifier transfer state/runtime state: unchanged. Structural queries and finite layout traversal reuse ordinary types.
  • Interactions: nominal modules, nested structs/enums/arrays, casts, builtin channel type arguments, Copy aggregates, individual linear arguments, exclusive/shared borrows, effectful calls and structured tasks. No argument inference hides ownership or contract choices.
  • Repairability: explicit parameter/property/found fields and template source locations support direct repairs. Missing moves/effects and forbidden payloads keep existing codes. Readable display names accompany compact generated AIR names. Successful unused-template checking is explicitly limited, avoiding a false universal guarantee.
  • Existing AIR primitives suffice. Manual per-type duplication makes API contracts drift; runtime dictionaries/trait dispatch add trusted semantics; inference and overload search add ambiguity; arbitrary user properties need a separate contract. Generic source templates address this step without expanding those mechanisms.

Measurements and final branch validation are recorded below. Documentation growth is a cost, not evidence of Model Capability Compression; public general conformance/integration fixtures do not decide benchmark semantics and private held-out tasks were not inspected.

Measured with tools/agent_bundle_tokens.py --source, relative to STD-3 (c96199e):

Group cl100k o200k Qwen2.5
Quick Reference 6,501 → 6,948 (+6.9%) 6,522 → 6,972 (+6.9%) 6,704 → 7,172 (+7.0%)
Other source docs 38,822 → 41,086 (+5.8%) 38,940 → 41,212 (+5.8%) 39,889 → 42,228 (+5.9%)
Full source docs excluding AIR 45,323 → 48,034 (+6.0%) 45,462 → 48,184 (+6.0%) 46,593 → 49,400 (+6.0%)
On-demand library/std.md 7,730 → 8,380 (+8.4%) 7,766 → 8,417 (+8.4%) 7,955 → 8,621 (+8.4%)
AIR reference 42,454 → 42,454 (+0.0%) 42,602 → 42,602 (+0.0%) 43,827 → 43,827 (+0.0%)

The new on-demand language/generics.md is 1,324 / 1,329 / 1,371 tokens. AIR stays 160,797 bytes (48 sections from 19 files). Cumulative cl100k source growth from the pre-stdlib baseline is 33,981 → 48,034 (+41.3%); Quick Reference is 5,511 → 6,948 (+26.1%). The existing >20% owner-review requirement still applies. This RFC explains the cost: explicit instantiation/header/body rules, five structural queries and bounded deterministic specialization must be visible to an agent. Quick Reference exceeds the 4–6k target; future catalogs should remain on demand and the front door needs a separate consolidation review. No measured compression benefit is asserted.

Branch validation

zig build, zig build test, zig build conformance, zig build agent-reference, the repository-wide zig fmt --check and git diff --check pass. Full conformance: 640 passed, 0 failed, 0 pending (61 added cases). Source coverage: 82/82 constructs, including six generic forms, with 155 run/accept and 225 rejected source fixtures. Generic worker/lend tests also pass 32 schedule seeds with stress quanta 1, 2 and 7 plus their default quantum 1,000.

tests/hosted/source_generics.py passes 20 CLI checks, source_modules.py passes 36 existing package checks, and hosted smoke passes file, stdin, scoped-access and real TCP checks. The generic CLI checks include canonical lower/reverify/run equivalence, explicit package loading with caller-defined nominal types, readable errors and imported-template error/trap provenance. Scheduler/conformance runs use explicit fuel rather than wall-clock cutoffs.