cli: add explicit source generics and Copy option/result
Specialize explicit function, struct and enum templates into deterministic ordinary AIR, with structural constraints and bounded expansion. Preserve source provenance and readable names in specialization diagnostics. Add Copy-only std.option/std.result and vertical specification, grammar, Quick Reference, RFC and source coverage updates. Keep linear aggregates and existing unsupported source from-returns explicit follow-up work. Repair the finite-layout check through arrays under the existing E1003 contract, with positive and rejected source/AIR fixtures. Validation: build, unit tests, 640 conformance cases, 82/82 source constructs, 32-seed generic task stress, agent-reference, formatting, hosted smoke, 20 generic and 36 package CLI checks. Record three-encoding documentation budgets; AIR reference is unchanged.
This commit is contained in:
93 files changed
+1587
-75
No files matched your search
@@ -102,3 +102,5 @@ RFC 0019 text/encodings (cl100k, relative to bounded): Quick Reference 6,082 →
|
||||
RFC 0020 supplied-buffer decimal formatting (cl100k, relative to text): Quick Reference 6,163 → 6,220 (+0.9%); other source docs 36,042 → 37,128 (+3.0%); full source docs excluding AIR 42,205 → 43,348 (+2.7%). The library page is 7,730 tokens. AIR remains unchanged. Four scalar writers reuse ordinary source and one Copy enum; full contracts and explicit record composition stay on demand. Cumulative source growth from the pre-stdlib baseline is +27.6%, with the existing owner-review justification recorded in RFC 0020. No compression benefit is inferred from documentation or fixtures.
|
||||
|
||||
RFC 0021 package modules (cl100k, relative to formatting): Quick Reference 6,220 → 6,501 (+4.5%); other source docs 37,128 → 38,822 (+4.6%); full source docs excluding AIR 43,348 → 45,323 (+4.6%). New on-demand `language/modules.md` is 1,566 tokens, library/std.md and AIR remain unchanged. The front door has one checked module example; package input/name/loader contracts stay on demand. Cumulative source growth is +33.4%, documented for owner review; no compression benefit is claimed. Pure modules need no new AIR feature or verifier state.
|
||||
|
||||
RFC 0022 explicit generics (cl100k, relative to modules): Quick Reference 6,501 → 6,948 (+6.9%); other source docs 38,822 → 41,086 (+5.8%); full source docs excluding AIR 45,323 → 48,034 (+6.0%). New on-demand `language/generics.md` is 1,324 tokens; `library/std.md` is 8,380 tokens. AIR remains 160,797 bytes. Cumulative source growth is +41.3%, and Quick Reference exceeds its 4–6k target; the RFC explains the cost for owner review and calls for separate front-door consolidation/selective API reading. Explicit specialization adds no AIR instruction or verifier transfer state; documentation growth alone does not establish a compression benefit.
|
||||
@@ -338,7 +338,7 @@ effects []
|
||||
}
|
||||
```
|
||||
|
||||
`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.
|
||||
`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`. Aliases are unavailable; explicit generics use §12.
|
||||
|
||||
Endian reads/writes cover `u16/u32/u64` in LE and BE. Pass a sub-slice for an offset. Reads return `std.bytes.ReadUW` with `ok(uW)`/`short_input`; writes return `std.bytes.WriteResult` with `ok`/`short_output`. A short destination is unchanged. Handle them with qualified enum patterns (not intrinsic outcome patterns):
|
||||
|
||||
@@ -387,3 +387,26 @@ effects []
|
||||
```
|
||||
|
||||
Use `aji check|lower|report|run|explore --manifest aji.toml`; `run` and `explore` instantiate manifest grants. A file-only command does not discover packages. Qualified workers work in `task.spawn(s, app.work.run, args)` with ordinary `move`, borrow and join rules. Missing/direct-import names: `E7002`; cycles/header mismatch/duplicates: `E7006`. Read `/docs/language/modules.md` for limits and file-loading rules. `lower --stats` counts entry source against combined AIR, so it is not a whole-package size metric.
|
||||
|
||||
## 12. Generics
|
||||
|
||||
Declare type parameters on functions, structs or enums: `<T>`, `<T: Copy>` or `<T: Copy + Send>`. Every use supplies all types: `Pair<u64>` in annotations, `Pair::<u64> { ... }`, `identity::<u64>(42)` and `Option::<u64>::some(42)` in expressions/patterns. Qualified forms require a direct import. No inference, traits, defaults or overloads. `task.spawn(s, worker::<u64>, args)` specializes a static worker with the ordinary ownership/effect rules.
|
||||
|
||||
```aji
|
||||
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; }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`std.option.Option<T: Copy>` has `some(T)`/`none`; `std.result.Result<T: Copy, E: Copy>` has `ok(T)`/`err(E)`. `is_some::<T>` and `is_ok::<T, E>` classify them; match to extract payloads. Owning/borrowed payloads still reject. Unknown names: `E7002`; missing/extra arguments, duplicate/unknown constraints or expansion limits: `E7006`; unsatisfied constraints: `E7005` with `parameter`, `constraint`, `found`. Borrow conflicts, moves, effects and cleanup keep their existing rules.
|
||||
|
||||
Each required specialization is checked as concrete code; an unused template body is not a proof for future types. `Copy` gives no arithmetic or ordering operation. Read `/docs/language/generics.md` for exact Copy/Send/Share/Freeze/Local rules, deterministic keys and fixed limits; `/docs/library/std.md` for option/result contracts.
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
> QUICK.md
|
||||
docs/agent/quick-reference.md
|
||||
docs/agent/source-notes.md :: ## 12. Where to read more
|
||||
docs/agent/source-notes.md :: ## 13. Where to read more
|
||||
|
||||
> language/syntax.md
|
||||
docs/reference/grammar.ebnf
|
||||
@@ -21,6 +21,9 @@ docs/spec/15-source-language.md :: ## 6. Fallible operations and `match`
|
||||
|
||||
docs/spec/15-source-language.md :: ## 13. Built-in standard modules
|
||||
|
||||
> language/generics.md
|
||||
docs/spec/15-source-language.md :: ## 15. Explicit source generics
|
||||
|
||||
> language/modules.md
|
||||
docs/spec/15-source-language.md :: ## 14. Package source modules
|
||||
docs/spec/12-packages-and-build.md :: ### 1.3 Package source mapping
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
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.
|
||||
|
||||
## 12. Where to read more
|
||||
## 13. 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 bytes/math/UTF-8/hex/Base64/decimal integers, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| generic declarations/applications, property constraints and specialization limits | `/docs/language/generics.md` |
|
||||
| explicit package imports, qualified types, manifest file inputs | `/docs/language/modules.md` |
|
||||
| exact syntax, every construct, `match` and outcomes | `/docs/language/syntax.md` |
|
||||
| integer semantics, conversions, Copy/Send/Share, traps | `/docs/language/types.md` |
|
||||
|
||||
@@ -242,3 +242,13 @@ Formatting needs a defined byte representation, insufficient-capacity state and
|
||||
General source modules need explicit build inputs, stable ordering/provenance, local name binding and a choice of import visibility before reusable types can be published. Ambient directory/manifest discovery would make verification depend on environment state; transitive names would make one module's public surface depend on unrelated imports.
|
||||
|
||||
**Resolved on the STD-3 branch (RFC 0021 Proposed):** spec 12 §1.3 supplies an explicit `[modules]` name-to-source map, with bounded no-follow loading inside the chosen package root. Spec 15 §14 specifies an acyclic graph, direct qualified imports, module-local names, qualified struct literals, module-aware spawning, stable mangling and whole-graph verification through existing AIR. All declarations are available through import; aliases, re-exports, visibility modifiers, dependencies and generics remain separate work. File-only commands never discover manifests.
|
||||
|
||||
## Q-033 — Generic specialization and property constraints
|
||||
|
||||
The source plan names monomorphized generics but does not define application syntax, checking of unused templates, specialization bounds or precise Freeze/Local constraints.
|
||||
|
||||
**Resolved on the STD-4 branch (RFC 0022 Proposed):** spec 15 §15 defines explicit `::<...>` expression arguments, applied type names, ordered canonical specializations and concrete-body checking. Copy/Send/Share reuse existing rules; Freeze is format-0 IslandSafe content and Local is context-bound state, with explicit propagation rather than complementing Send. No trait inference or generic runtime representation is added; ordinary aggregate restrictions remain until linear_aggregates.
|
||||
|
||||
## Q-034 — Source calls returning borrows
|
||||
|
||||
During STD-4 validation, existing `from` declarations still return the frontend's unimplemented outcome and borrow bindings accept places rather than borrow-returning calls. Generics preserve the syntax/metadata and this existing limitation; they do not add an implicit lifetime or a new binding spelling. A separate source/lifetime increment must specify and implement the binding/temporary-end rules vertically before public libraries return retained borrowed views.
|
||||
@@ -133,7 +133,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| P6-1 | todo | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous |
|
||||
| P6-2 | todo | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics |
|
||||
| P6-3 | done (branch implementation; RFC 0021 Proposed) | Explicit package modules, direct imports and qualified nominal types | P6-2 | `src/frontend/modules.zig`, spec 15 §14 | deterministic graph/name resolution; source/AIR and CLI tests |
|
||||
| P6-4 | todo | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/types.zig` | generic code instantiates deterministically; constraint violations diagnosed |
|
||||
| P6-4 | done (branch implementation; RFC 0022 Proposed) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed |
|
||||
| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
|
||||
| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN |
|
||||
| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code |
|
||||
@@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| 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 [standard-library track](standard-library.md) implements six compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; P6-4 remains open for generics. These increments do not complete Phase 6.
|
||||
The [standard-library track](standard-library.md) implements eight compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
|
||||
@@ -22,7 +22,7 @@ Without external source dependencies, Aji should support ordinary CLI tools, sto
|
||||
| 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; six 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 | P6-4 pending | needed for reusable `Vec<T>`, `HashMap<K,V>`, option/result |
|
||||
| User generics/structural constraints | STD-4 branch implementation (P6-4; RFC Proposed) | 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 |
|
||||
|
||||
@@ -52,7 +52,7 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob
|
||||
| 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 | todo | source generics (P6-4), constraints and option/result | STD-3 | deterministic specialization and rejected constraint examples; source/AIR budgets measured |
|
||||
| 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 | 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-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority |
|
||||
@@ -108,3 +108,9 @@ Spec 16 §2.8 and RFC 0020 specify the invariant, existing verifier/runtime rule
|
||||
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.
|
||||
@@ -18,17 +18,23 @@ item = type_decl | fn_decl ;
|
||||
path = ident { "." ident } ;
|
||||
|
||||
type_decl = struct_decl | enum_decl ;
|
||||
struct_decl = "struct" ident "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
struct_decl = "struct" ident [ type_params ] "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
field = ident ":" type ;
|
||||
enum_decl = "enum" ident "{" variant { "," variant } [ "," ] "}" ;
|
||||
enum_decl = "enum" ident [ type_params ] "{" variant { "," variant } [ "," ] "}" ;
|
||||
variant = ident [ "(" type { "," type } ")" ] ;
|
||||
|
||||
fn_decl = "fn" ident "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
|
||||
fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
|
||||
"effects" "[" [ path { "," path } ] "]"
|
||||
block ; (* `trusted` is reserved and rejected, E7006 *)
|
||||
param = ident ":" type ;
|
||||
type_params = "<" type_param { "," type_param } ">" ;
|
||||
type_param = ident [ ":" property { "+" property } ] ;
|
||||
property = "Copy" | "Send" | "Share" | "Freeze" | "Local" ;
|
||||
type_args = "<" type { "," type } ">" ;
|
||||
application = "::" type_args ; (* explicit; no inference, spec 15 §15 *)
|
||||
|
||||
type = int_type | "bool" | "void" | "never" | path
|
||||
| path type_args
|
||||
| "[" type ";" int_lit "]"
|
||||
| wrapper "<" type ">"
|
||||
| "cap" "<" path ">"
|
||||
@@ -64,7 +70,7 @@ if_expr = "if" expr block [ "else" ( if_expr | block ) ] ;
|
||||
match_expr = "match" expr "{" { arm } "}" ;
|
||||
arm = pattern "=>" ( block | expr "," ) ;
|
||||
pattern = "_" | int_lit (* integer matches only; `_` is required there *)
|
||||
| path "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *)
|
||||
| path [ application ] "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *)
|
||||
| ident [ "(" ident { "," ident } ")" ] ; (* outcome of a fallible operation: ok(n), closed *)
|
||||
|
||||
select_stmt = "select" "{" { select_arm } "cancelled" [ "(" ident { "," ident } ")" ] "=>" ( block | expr "," ) "}" ;
|
||||
@@ -84,12 +90,12 @@ unary = ( "-" | "not" | "*" ) unary
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] place
|
||||
| "move" ident
|
||||
| postfix ;
|
||||
postfix = primary { "." member | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
postfix = primary { application | "." member | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *)
|
||||
call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ;
|
||||
primary = int_lit | "true" | "false" | string
|
||||
| ident | path "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *)
|
||||
| path "::" ident (* enum variant; applied by a call *)
|
||||
| ident | path [ application ] "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *)
|
||||
| path [ application ] "::" ident (* enum variant; applied by a call *)
|
||||
| "[" expr ";" int_lit "]"
|
||||
| "(" expr ")"
|
||||
| if_expr | match_expr | block ;
|
||||
|
||||
@@ -214,3 +214,16 @@ effects []
|
||||
```
|
||||
|
||||
This checked program is `examples/std/format.aji` and `tests/conformance/source/std/fmt_example.aji`. It returns 17 without grants. Each operation preserves its own destination on short output; a sequence is not transactional across earlier successful calls. Existing alias checks apply even when a write would return short output. Smaller scalar widths require an explicit widening conversion to an appropriate writer; wider integers, float formatting and parsing are outside this increment.
|
||||
|
||||
## Copy option/result templates
|
||||
|
||||
Requires direct `import std.option;` / `import std.result;`; explicit generic spelling is spec 15 §15.
|
||||
|
||||
| Declaration | Contract |
|
||||
|---|---|
|
||||
| `std.option.Option<T: Copy>` | `some(T)`, `none` |
|
||||
| `std.option.is_some<T: Copy>(value: Option<T>) -> bool` | true for some; false for none; effects [] |
|
||||
| `std.result.Result<T: Copy, E: Copy>` | `ok(T)`, `err(E)` |
|
||||
| `std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool` | true for ok; false for err; effects [] |
|
||||
|
||||
All are ordinary safe source/static specialization, with no allocation or authority. Generic helper calls use `is_some::<u64>(value)` / `is_ok::<u64, u8>(value)`. Constructors and patterns use `std.option.Option::<u64>::some(value)` or `std.result.Result::<u64, u8>::err(code)`; names and variant matches remain explicit even for none. Extract values by exhaustive match; an err variant is not intrinsic outcome syntax. Owners/resources/endpoints and borrows fail Copy constraints with E7005, until a separate linear-aggregate feature supplies their contracts. No must-use or implicit unwrap/default/conversion is introduced. [Checked example](../../examples/std/generics.aji) returns 42 without grants.
|
||||
@@ -49,3 +49,7 @@ Because of it, a graph never holds outside authority or a mutable ownership edge
|
||||
|
||||
An `ArcSafe` value may be held by an `arc` (spec 03 §24): the last release destroys it by freeing memory only, with no user or resource action. In format 0 it is exactly `IslandSafe`. `Share` alone is not enough; for example, a `mutex<T>` is `Share` but not `ArcSafe`.
|
||||
|
||||
|
||||
## Format-0 source constraints
|
||||
|
||||
Spec 15 §15 fixes the exact property queries used by explicit generic specialization. Copy includes integers, booleans, built-in enums, capabilities, `iref` and aggregates of Copy members; borrows and linear values are excluded. Send/Share use spec 04 §35. Freeze currently equals IslandSafe plain graph content; it does not promise conversion of arbitrary owners or resources. Local has task/scope/shield/guard/internal-storage base cases and propagates through borrow/own/own_array/mutex wrappers and arrays/aggregates containing Local content. It is not the complement of Send. These properties add no methods, effects, unsafe declarations or implicit resource actions.
|
||||
@@ -0,0 +1,102 @@
|
||||
# RFC 0022: Explicit source generics and Copy option/result
|
||||
|
||||
Status: Proposed
|
||||
Scope: STD-4 / P6-4; source language 0.1, AIR format 0 unchanged
|
||||
|
||||
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<T> 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<u64>> 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
|
||||
|
||||
```aji
|
||||
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<T>/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
|
||||
|
||||
```aji
|
||||
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<u64>. 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::<u64> rejects E2101, and passing the same slice to two live specialized workers rejects E4101. Send<task<u64>>, Share<region>, Freeze<cap<io.write>> and Local<u64> 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<T> 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. RFC status is Proposed for owner review.
|
||||
|
||||
## 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.
|
||||
@@ -94,10 +94,10 @@ Every trap has a stable code in the `T0xxx` range of [`../reference/error-codes.
|
||||
|
||||
## 7. Generics
|
||||
|
||||
Aji supports monomorphized generics.
|
||||
Aji supports explicit monomorphized generics (source contract: spec 15 §15). Calls use `swap::<u64>(mut a, mut b)`; type annotations use `Pair<u64>`.
|
||||
|
||||
```aji
|
||||
fn swap<T>(a: mut<T>, b: mut<T>) { ... }
|
||||
fn swap<T: Copy>(a: mut<T>, b: mut<T>) -> void effects [] { ... }
|
||||
```
|
||||
|
||||
Version 0.1 does not require user-defined traits/typeclasses. Generic constraints use compiler-known structural properties such as `Copy`, `Send`, `Share`, `Freeze` and `Local`.
|
||||
|
||||
@@ -475,9 +475,9 @@ Other rules:
|
||||
|
||||
The compiler MUST provide the standard modules listed in spec 16 §2, pinned to its own version. An import of `std` or a `std.*` path 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 standard 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`).
|
||||
An imported standard 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 rejected (`E7006`, §15).
|
||||
|
||||
Lowering MUST append the complete type and function declarations of the imported modules after the program's declarations, in lexicographic module order and source declaration order within each module. For a type or 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 declaration, 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.
|
||||
Lowering MUST append the complete non-generic type and function declarations of the imported modules after the program's declarations, in lexicographic module order and source declaration order within each module. For a type or 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 declaration, 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. Generic templates follow §15. 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.
|
||||
|
||||
@@ -487,7 +487,7 @@ Standard enum types are named by their full path, for example `std.bytes.ReadU32
|
||||
|
||||
A constructor or pattern is written `std.bytes.ReadU32::ok(value)` or `std.bytes.ReadU32::short_input`. Constructors, payload typing and exhaustive enum matches obey §5/§6 without a library-specific exception. A wrong payload or variant from another enum is `E7005`, an unknown variant `E7002`, a missing arm `E7004`, and duplicate/wildcard enum arms `E7006`. These are ordinary Copy enum values; this increment does not add a must-use or linear-result rule. Source type diagnostics MUST name standard types by their public qualified source path, including inside compound types; AIR output still uses the generated identifiers. Library source uses the same full type paths in signatures, constructors and matches. Standard types lower with the collision-free naming rule above; their declarations precede function declarations as in §2.
|
||||
|
||||
The current standard registry exports enums only. Qualified named types and enum variants do not introduce member methods, reflection, dependency resolution, aliases or generics. Package modules and qualified struct literals are specified in §14.
|
||||
The standard registry exports ordinary enums and generic enum templates (§15). Qualified named types and enum variants introduce no member methods, reflection, dependency resolution or aliases. Generic standard forms use §15. Package modules and qualified struct literals are specified in §14.
|
||||
|
||||
## 14. Package source modules
|
||||
|
||||
@@ -497,7 +497,7 @@ The frontend MUST take an entry source and an explicit mapping of module names t
|
||||
|
||||
Each mapped source MUST declare exactly its mapped module name. An imported source need not define `main`; only the entry's unqualified `main` is the program entry. A module's own function named `main` is an ordinary qualified function. All top-level declarations and fields are available through explicit import; no visibility modifier or re-export is introduced. Modules have no executable top-level initialization.
|
||||
|
||||
Imports form an acyclic directed graph. The linker MUST parse each reachable module once, reject self-import/cycles, duplicate imports, duplicate mappings and mismatched headers with `E7006`, and unknown imports with `E7002`. Source syntax errors in a package module use `E7001` at that module's file/line/column. Imports are visited in source order for first-error selection; all complete declarations of reachable modules, including unused functions, enter verification. Unreachable mapped source is not parsed or linked. Compiler input limits are 1,024 mapped modules and import depth 256; exceeding them is `E7006`. These are fixed implementation input limits, not runtime fuel or semantics-changing flags.
|
||||
Imports form an acyclic directed graph. The linker MUST parse each reachable module once, reject self-import/cycles, duplicate imports, duplicate mappings and mismatched headers with `E7006`, and unknown imports with `E7002`. Source syntax errors in a package module use `E7001` at that module's file/line/column. Imports are visited in source order for first-error selection; all complete non-generic declarations of reachable modules, including unused functions, enter verification; templates follow §15. Unreachable mapped source is not parsed or linked. Compiler input limits are 1,024 mapped modules and import depth 256; exceeding them is `E7006`. These are fixed implementation input limits, not runtime fuel or semantics-changing flags.
|
||||
|
||||
Module names use source paths. The first component of a package mapping MUST NOT be `std` or a namespace of a built-in operation (`slice`, `own`, `region`, `cap`, `task`, `channel`, `mutex`, `island`, `frozen`, `arc`, `atomic`, or the first component of a registered intrinsic). Such a mapping is `E7006` (a manifest error at the CLI). Root source names retain their existing grammar; duplicate entry/module identity is rejected when imported.
|
||||
|
||||
@@ -505,7 +505,7 @@ Module names use source paths. The first component of a package mapping MUST NOT
|
||||
|
||||
A module sees its own functions and types by short name, and declarations of directly imported modules by full path. Imports MUST NOT inject short names, aliases or transitive visibility. An entry outside reserved built-in namespaces can also qualify its own declarations with its module name; built-in operations retain precedence. An inaccessible or unknown function/type/member is `E7002`, even if a different module linked the declaration. Qualified names resolve by module identity, independently of local bindings with the same prefix. A value may have a type inferred from a directly imported function contract without importing that type's defining module; spelling the type or its constructors by name still requires a direct import. Module-local calls MUST NOT capture an entry's similarly named function; named types from different modules are nominally distinct.
|
||||
|
||||
Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref<app.model.Pair>` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals remain forbidden in unparenthesized conditions, where `{` starts a block. This adds no methods, reflection, generic arguments or permission to store forbidden linear/borrowed values in aggregates.
|
||||
Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref<app.model.Pair>` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals remain forbidden in unparenthesized conditions, where `{` starts a block. This adds no methods, reflection or permission to store forbidden linear/borrowed values in aggregates. Generic forms are specified separately in §15.
|
||||
|
||||
A qualified named function MAY be passed as the function operand of `task.spawn(scope, app.work.run, ...)`. Existing Send/effect/structured-lifetime rules still apply; there is no function value, dynamic dispatch or detached task. All other calls use the existing argument, borrow, move, failure and effect rules.
|
||||
|
||||
@@ -514,3 +514,27 @@ A qualified named function MAY be passed as the function operand of `task.spawn(
|
||||
Entry declarations retain their existing AIR names. Imported declarations use §13's collision-free mangling, with all reachable standard/package modules appended in lexicographic module order and source order within each module. Type declarations still precede functions. Valid canonical AIR MUST be independent of import order, mapping order, directory/profile and source file paths for identical source bytes and module bindings. Whole-graph AIR feature closure is explicit as before. Source provenance MUST use each imported source's supplied file path; the CLI supplies its manifest-relative path. AST module identity is distinct from a diagnostic path, so coinciding file labels cannot change name resolution.
|
||||
|
||||
The combined AIR MUST pass the ordinary verifier and runs as a single format-0 module. There is no new opcode, AIR feature, verifier state, runtime primitive, initialization, implicit heap allocation or authority. Existing enum/struct layout, alias, initialization, borrow, ownership, resource, task and effect transfer functions apply across module calls unchanged. All return/cleanup paths remain explicit; imported code is not trusted by virtue of its module. Existing file-only and standard-only programs retain their lowering and behavior. Package imports require the new explicit mapping; previous unknown import paths become valid only when supplied.
|
||||
|
||||
## 15. Explicit source generics
|
||||
|
||||
### 15.1 Declarations and applications
|
||||
|
||||
Functions, structs and enums MAY declare 1–8 type parameters immediately after their name, e.g. `fn identity<T>(value: T) -> T effects [] { return value; }`, `struct Pair<T: Copy> { left: T, right: T }`, `enum Option<T: Copy> { some(T), none }`. Parameters MUST be distinct uppercase identifiers, MUST NOT shadow a visible type/builtin type, and have no default. Constraints are optional compiler-known `Copy`, `Send`, `Share`, `Freeze` or `Local`, joined by `+`; repeated/unknown constraints are `E7006`. Generic `main` is forbidden (`E7006`). No user traits, overloads, type inference, const/lifetime/effect parameters or specialization overrides are introduced.
|
||||
|
||||
Every generic use MUST supply exactly its ordered type arguments. Type annotations use `Pair<u64>`; expression applications use `identity::<u64>(42)`, `Pair::<u64> { left: 20, right: 22 }` and `Option::<u64>::some(42)`. Enum patterns use `Option::<u64>::some(value)` and `Option::<u64>::none`. The `::<...>` spelling separates generic application from comparisons; bare `f<T>(...)` is outside the expression grammar. Qualified forms obey §14's direct-import rules. `task.spawn(s, worker::<u64>, ...)` statically specializes the worker; this creates no function value. Existing `channel.make<T>(...)` retains its spelling and single type argument.
|
||||
|
||||
Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; parameters are types, not values or operations. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT enable linear or borrowed aggregate members.
|
||||
|
||||
Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity, effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source.
|
||||
|
||||
### 15.2 Structural constraints
|
||||
|
||||
Constraints are requirements on concrete types, not compiler authority to infer effects or repair ownership. `Copy` follows existing value duplication: scalars, built-in enums, capabilities, `iref` and aggregates of Copy values; borrows and linear values are not Copy. `Send` and `Share` use exactly spec 04 §35. In format 0, `Freeze` is exactly `IslandSafe` (spec 03 §22): plain content accepted by deep graph conversion, including `iref`; it does not promise conversion of owners/resources/wrappers. `Local` identifies context-bound `task`, `scope`, `shield` and `guard` (and internal local storage); it propagates through borrows, own/own_array/mutex wrappers and arrays/aggregates containing Local content. Scalars, authority, resources, regions, endpoints and graph owners/handles are not Local. Local is not the complement of Send. No unsafe/manual property declarations are added.
|
||||
|
||||
A type can satisfy several constraints; each requirement MUST be checked. Constraints add no operations or trait dispatch: a body using arithmetic with `T: Copy` still requires an arithmetic-compatible concrete specialization. Effects, `from`, `move`, lends and cleanup remain explicit in every specialization.
|
||||
|
||||
### 15.3 Deterministic monomorphization and safety
|
||||
|
||||
A specialization is keyed by template module identity, declaration kind/name and the ordered structural identity of concrete arguments. Named arguments use nominal defining-module identity, independent of source filename, short/qualified spelling or import/provider order. Each key MUST emit at most one concrete declaration; repeated same-key recursion reuses it. Type-specialization cycles still obey ordinary finite-layout rules. Expanding specialization is bounded by 4,096 generated declarations and active expansion depth 64 (`E7006`), with structural type traversal bounded at depth 64. These are fixed compiler input limits, not runtime fuel or semantic flags.
|
||||
|
||||
Non-generic declarations retain their AIR names and order. Generated types and functions append in lexicographic specialization-key order within their categories. Their AIR identifier starts with `__aji_g_` followed by lowercase SHA-256 of the canonical key bytes; collisions with original names or earlier keys in sorted order receive the smallest unused `_1`, `_2`, … suffix. The canonical key is `type:` or `fn:`, full defining-module/declaration path, and ordered `<...>` arguments. Named arguments use full nominal paths, applied arguments recursively spell their template/arguments, arrays spell `[T;N]` with decimal N, wrappers/cap/file spell `name<T>`; argument separators are commas without whitespace. Full keys, not hashes, determine identity and reuse. Keys are limited to 16,384 bytes (`E7006`). Every required body lowers to existing format-0 constructs, and the combined module MUST pass the ordinary verifier. There is no new AIR instruction/feature, verifier transfer state, runtime dispatch, implicit allocation/refcount/destructor, effect inference or authority. Source provenance retains template locations and the locations of supplied argument types. Generic borrow/owner/task contracts use the existing runtime/interpreter rules unchanged. Existing monomorphic source and AIR retain meaning and canonical lowering. The finite-layout verifier now visits array elements as well as direct nominal members, closing a prior E1003 implementation gap without changing the normative no-recursive-value rule. Existing unimplemented source `from`-returns remain unimplemented; specialization retains their contract rather than inventing borrow lifetimes.
|
||||
@@ -10,7 +10,7 @@ APIs SHOULD offer one canonical operation for a common need, small documentation
|
||||
|
||||
## 2. Bootstrap module registry
|
||||
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.math` and `std.utf8`. They are implemented in safe `.aji` with `effects []`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/math.aji` and `std/utf8.aji`, respectively. 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.
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.math`, `std.option`, `std.result` and `std.utf8`. They are implemented in safe `.aji` with `effects []`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji` and `std/utf8.aji`, respectively. 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`
|
||||
|
||||
@@ -137,3 +137,16 @@ The functions MUST produce the exact ASCII decimal representation of value: `0`
|
||||
When dst can hold the complete representation, the function MUST write exactly that prefix, preserve every remaining byte and return `ok(count)` with its length, including any sign. Otherwise it MUST return `short_output` and leave the entire destination unchanged. Empty output always fails, including for zero. Capacity MUST be checked before any write. To append, the caller passes a sub-slice at an explicit offset and advances it only after success; no implicit cursor, returned borrow, growable string or format-string language is introduced. Text copying uses `std.bytes.copy`; byte-to-hex encoding remains `std.encoding.hex`.
|
||||
|
||||
The preserved invariant is exclusive writes only within the supplied initialized slice, no escaping borrow, and no partial mutation on returned failure. Functions declare `effects []`, allocate no heap, use constant scalar auxiliary storage and O(decimal digit count) work. Existing call, initialization, alias, lifetime, bounds and enum verifier rules apply; conflicting live borrows MUST reject even on short output. No new verifier state, runtime rule, diagnostic, AIR feature or authority is added. Valid slices and every scalar value MUST NOT produce arithmetic, cast or bounds traps; interpreter fuel exhaustion remains an environment outcome and is outside the returned-error preservation guarantee. Behavior is identical in deterministic and hosted profiles. Existing APIs, source syntax and AIR format 0 retain their contracts.
|
||||
|
||||
### 2.9 Copy option and result
|
||||
|
||||
The compiler registry MUST also include `std.option` and `std.result`. They declare ordinary generic enums:
|
||||
|
||||
```aji
|
||||
enum Option<T: Copy> { some(T), none }
|
||||
enum Result<T: Copy, E: Copy> { ok(T), err(E) }
|
||||
```
|
||||
|
||||
`std.option.is_some<T: Copy>(value: Option<T>) -> bool` and `std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool` declare `effects []`, allocate no heap and classify the active variant. They neither extract nor implicitly consume any payload. Call them using spec 15 §15's explicit expression arguments, e.g. `std.option.is_some::<u64>(value)`. Types/constructors/patterns are fully qualified and require a direct import; exhaustive matches extract payloads through ordinary enum rules. `none` still requires a type argument. `err(E)` is an ordinary enum variant, not the intrinsic outcome shorthand.
|
||||
|
||||
These APIs are restricted to Copy arguments under format 0's existing aggregate-member rules. They MUST NOT accept owners, resources, endpoints or borrows as payloads. Invalid generic constraints use `E7005`; naming/arity/exhaustiveness/alias diagnostics remain the existing source/verifier codes. No must-use obligation, implicit default, prelude, borrow aggregate, new AIR primitive or failure conversion is introduced. Each specialization is a normal Copy enum/static function, deterministic under spec 15 §15. The later linear-aggregate feature is required before owning option/result types can be promised.
|
||||
Reference in new issue
Block a user