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
@@ -21,6 +21,7 @@ jobs:
|
||||
- run: zig build conformance -- --stress 200
|
||||
- run: zig build && python3 tests/hosted/smoke.py
|
||||
- run: python3 tests/hosted/source_modules.py
|
||||
- run: python3 tests/hosted/source_generics.py
|
||||
- run: zig-out/bin/aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air
|
||||
- run: zig build agent-reference
|
||||
- name: Source construct coverage (Phase 6A)
|
||||
|
||||
@@ -17,6 +17,7 @@ zig build run -- check f.air # verify a text AIR module
|
||||
zig build run -- run f.air # verify and execute @main (deterministic profile)
|
||||
python3 tests/hosted/smoke.py # hosted profile against the real OS
|
||||
python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts
|
||||
python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance
|
||||
(cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests
|
||||
zig fmt --check build.zig src tools
|
||||
```
|
||||
|
||||
@@ -32,6 +32,8 @@ pub fn build(b: *std.Build) void {
|
||||
mod.addAnonymousImport("std_encoding_hex_aji", .{ .root_source_file = b.path("std/encoding/hex.aji") });
|
||||
mod.addAnonymousImport("std_fmt_aji", .{ .root_source_file = b.path("std/fmt.aji") });
|
||||
mod.addAnonymousImport("std_math_aji", .{ .root_source_file = b.path("std/math.aji") });
|
||||
mod.addAnonymousImport("std_option_aji", .{ .root_source_file = b.path("std/option.aji") });
|
||||
mod.addAnonymousImport("std_result_aji", .{ .root_source_file = b.path("std/result.aji") });
|
||||
mod.addAnonymousImport("std_utf8_aji", .{ .root_source_file = b.path("std/utf8.aji") });
|
||||
|
||||
// CLI: `aji`.
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,12 @@
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -237,3 +237,55 @@ test "qualified module names are not limited by builtin path storage" {
|
||||
const checked = try checkWithModules(arena, "root.aji", entry, &.{.{ .name = name, .file = "lib.aji", .source = source }});
|
||||
try std.testing.expectEqual(Status.accepted, checked.status);
|
||||
}
|
||||
|
||||
test "generic specialization deduplicates nominal keys independent of module order and provenance" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const arena = state.allocator();
|
||||
const lib: frontend.modules.Source = .{ .name = "app.lib", .file = "lib.aji", .source = "module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return value; }" };
|
||||
const prefix = "module app.entry\n";
|
||||
const body = "struct Pair { value: u64 }\nfn main() -> u64 effects [] { let p = app.lib.id::<Pair>(Pair { value: 42 }); let a = app.lib.id::<u64>(p.value); return app.lib.id::<u64>(a); }";
|
||||
const first = try checkWithModules(arena, "entry.aji", prefix ++ "import app.lib;\nimport std.option;\n" ++ body, &.{lib});
|
||||
var moved = lib;
|
||||
moved.file = "elsewhere/lib.aji";
|
||||
const second_source = try std.mem.replaceOwned(u8, arena, prefix ++ "import std.option;\nimport app.lib;\n" ++ body, "id::<Pair>", "id::<app.entry.Pair>");
|
||||
const second = try checkWithModules(arena, "elsewhere/entry.aji", second_source, &.{moved});
|
||||
try std.testing.expectEqual(Status.accepted, first.status);
|
||||
try std.testing.expectEqual(Status.accepted, second.status);
|
||||
try std.testing.expectEqualStrings(first.lowered.?.air, second.lowered.?.air);
|
||||
try std.testing.expectEqual(@as(usize, 3), first.module.?.functions.len);
|
||||
try std.testing.expectEqual(@as(usize, 1), first.module.?.types.len);
|
||||
const bad = try checkWithModules(arena, "entry.aji", prefix ++ "import app.lib;\nfn main() -> u64 effects [] { return app.lib.id::<own<u64>>(0); }", &.{lib});
|
||||
try std.testing.expectEqualStrings("E7005", bad.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("constraint", bad.diagnostics[0].fields[1].name);
|
||||
const provenance = try checkWithModules(arena, "entry.aji", prefix ++ "import app.lib;\nfn main() -> u64 effects [] { return app.lib.id::<u64>(42); }", &.{.{ .name = "app.lib", .file = "lib.aji", .source = "module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return missing(value); }" }});
|
||||
try std.testing.expectEqualStrings("lib.aji", provenance.diagnostics[0].span.?.file);
|
||||
}
|
||||
|
||||
test "generic specialization count and parameter limits reject before lowering" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const arena = state.allocator();
|
||||
var source: std.ArrayList(u8) = .empty;
|
||||
try source.appendSlice(arena, "module app.entry\nfn marker<T>() -> u64 effects [] { return 0; }\nfn main() -> u64 effects [] {\n");
|
||||
for (1..4098) |n| try source.appendSlice(arena, try std.fmt.allocPrint(arena, "marker::<[u8; {d}]>();\n", .{n}));
|
||||
try source.appendSlice(arena, "return 42; }");
|
||||
const result = try frontend.compile(arena, "limit.aji", source.items);
|
||||
try std.testing.expect(result == .err);
|
||||
try std.testing.expectEqualStrings("E7006", result.err.code.id);
|
||||
const params = try frontend.compile(arena, "limit.aji", "module app.entry\nfn marker<A,B,C,D,E,F,G,H,I>() -> u64 effects [] { return 0; }\nfn main() -> u64 effects [] { return 42; }");
|
||||
try std.testing.expectEqualStrings("E7006", params.err.code.id);
|
||||
}
|
||||
|
||||
test "generic AIR names avoid source collisions and diagnostic names stay readable" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const arena = state.allocator();
|
||||
const source = "module app.entry\nfn id<T: Copy>(value: T) -> T effects [] { return value; }\nfn __aji_g_65d38d1a36ba3736939a86561ed8e7371f3c6dcce26722dd7876102d750f7052() -> u64 effects [] { return 0; }\nfn main() -> u64 effects [] { return id::<u64>(42); }";
|
||||
const result = try checkFile(arena, "collision.aji", source);
|
||||
try std.testing.expectEqual(Status.accepted, result.status);
|
||||
try std.testing.expect(std.mem.indexOf(u8, result.lowered.?.air, "call @__aji_g_65d38d1a36ba3736939a86561ed8e7371f3c6dcce26722dd7876102d750f7052_1(") != null);
|
||||
const arity = try checkFile(arena, "arity.aji", "module app.entry\nfn id<T: Copy>(value: T) -> T effects [] { return value; }\nfn main() -> u64 effects [] { return id::<u64>(); }");
|
||||
try std.testing.expectEqualStrings("E7005", arity.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("app.entry.id<u64>", arity.diagnostics[0].fields[0].value.str);
|
||||
}
|
||||
+6
-2
@@ -8,6 +8,7 @@ pub const lex = @import("frontend/lex.zig");
|
||||
pub const ast = @import("frontend/ast.zig");
|
||||
pub const parse = @import("frontend/parse.zig");
|
||||
pub const lower_mod = @import("frontend/lower.zig");
|
||||
pub const generics = @import("frontend/generics.zig");
|
||||
pub const modules = @import("frontend/modules.zig");
|
||||
pub const stdlib = @import("frontend/stdlib.zig");
|
||||
|
||||
@@ -41,7 +42,10 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
|
||||
};
|
||||
const linked = try modules.link(arena, m, sources);
|
||||
const result = switch (linked) {
|
||||
.ok => |combined| try lower_mod.lower(arena, combined),
|
||||
.ok => |combined| switch (try generics.specialize(arena, combined)) {
|
||||
.ok => |concrete| try lower_mod.lower(arena, concrete),
|
||||
.err => |p| lower_mod.Result{ .err = p },
|
||||
},
|
||||
.err => |p| lower_mod.Result{ .err = p },
|
||||
};
|
||||
return switch (result) {
|
||||
@@ -56,7 +60,7 @@ pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []
|
||||
.fields = fields,
|
||||
} };
|
||||
},
|
||||
.unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ file, u.span.start.line, u.span.start.col, u.construct }) },
|
||||
.unimplemented => |u| .{ .unimplemented = try std.fmt.allocPrint(arena, "{s}:{d}:{d}: {s}", .{ u.span.file orelse file, u.span.start.line, u.span.start.col, u.construct }) },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+14
-4
@@ -6,13 +6,14 @@ const lex = @import("lex.zig");
|
||||
|
||||
pub const Pos = lex.Pos;
|
||||
|
||||
pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null, namespace: ?[]const u8 = null };
|
||||
pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null, namespace: ?[]const u8 = null, resolved: bool = false };
|
||||
|
||||
pub const Type = struct {
|
||||
span: Span,
|
||||
kind: union(enum) {
|
||||
/// A built-in or declared type name (`u8`, `bool`, `region`, `Pair`).
|
||||
name: []const u8,
|
||||
applied: struct { name: []const u8, args: []const Type },
|
||||
/// `[T; N]`.
|
||||
array: struct { elem: *const Type, len: u64 },
|
||||
/// `ref<T>`, `own<T>`, `sender<T>`, … (`wrapper` names the constructor).
|
||||
@@ -62,7 +63,8 @@ pub const Expr = struct {
|
||||
bytes: []const u8,
|
||||
name: []const u8,
|
||||
/// `Enum::Variant` (applied to payload arguments by a `call`).
|
||||
variant: struct { @"enum": []const u8, name: []const u8 },
|
||||
variant: struct { @"enum": []const u8, name: []const u8, type_args: []const Type = &.{} },
|
||||
specialize: struct { base: *const Expr, args: []const Type },
|
||||
neg: *const Expr,
|
||||
not: *const Expr,
|
||||
deref: *const Expr,
|
||||
@@ -75,7 +77,7 @@ pub const Expr = struct {
|
||||
field: struct { e: *const Expr, name: []const u8 },
|
||||
/// `e[lo]` or `e[lo..hi]`.
|
||||
index: struct { e: *const Expr, lo: *const Expr, hi: ?*const Expr },
|
||||
struct_lit: struct { name: []const u8, fields: []const FieldInit },
|
||||
struct_lit: struct { name: []const u8, fields: []const FieldInit, type_args: []const Type = &.{} },
|
||||
array_rep: struct { e: *const Expr, len: u64 },
|
||||
or_trap: *const Expr,
|
||||
if_expr: *const If,
|
||||
@@ -97,7 +99,7 @@ pub const Pattern = struct {
|
||||
int: []const u8,
|
||||
/// A variant with its enum (`Shape::Rect(w, h)`) or an outcome
|
||||
/// (`ok(n)`, `closed`; `qualifier == null`), with bound names.
|
||||
ctor: struct { qualifier: ?[]const u8, name: []const u8, binds: []const []const u8 },
|
||||
ctor: struct { qualifier: ?[]const u8, name: []const u8, binds: []const []const u8, type_args: []const Type = &.{} },
|
||||
},
|
||||
};
|
||||
|
||||
@@ -166,10 +168,15 @@ pub const Field = struct { name: []const u8, ty: Type, span: Span };
|
||||
|
||||
pub const Variant = struct { name: []const u8, payload: []const Type, span: Span };
|
||||
|
||||
pub const TypeParam = struct { name: []const u8, constraints: []const []const u8, span: Span };
|
||||
pub const Requirement = struct { ty: Type, parameter: []const u8, property: []const u8, span: Span };
|
||||
|
||||
pub const TypeDecl = struct {
|
||||
generics: []const TypeParam = &.{},
|
||||
name: []const u8,
|
||||
/// Linker-chosen AIR identifier for a qualified imported type.
|
||||
air_name: ?[]const u8 = null,
|
||||
display_name: ?[]const u8 = null,
|
||||
span: Span,
|
||||
kind: union(enum) { @"struct": []const Field, @"enum": []const Variant },
|
||||
};
|
||||
@@ -177,9 +184,11 @@ pub const TypeDecl = struct {
|
||||
pub const Param = struct { name: []const u8, ty: Type, span: Span };
|
||||
|
||||
pub const FnDecl = struct {
|
||||
generics: []const TypeParam = &.{},
|
||||
name: []const u8,
|
||||
/// Linker-chosen AIR identifier for a qualified imported function.
|
||||
air_name: ?[]const u8 = null,
|
||||
display_name: ?[]const u8 = null,
|
||||
span: Span,
|
||||
params: []const Param,
|
||||
ret: Type,
|
||||
@@ -193,6 +202,7 @@ pub const Module = struct {
|
||||
name: []const u8,
|
||||
imports: []const Import = &.{},
|
||||
scopes: []const ModuleScope = &.{},
|
||||
requirements: []const Requirement = &.{},
|
||||
types: []const TypeDecl,
|
||||
functions: []const FnDecl,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
//! Explicit, bounded monomorphization before ordinary AIR lowering.
|
||||
const std = @import("std");
|
||||
const ast = @import("ast.zig");
|
||||
const lower = @import("lower.zig");
|
||||
const authority = @import("../air/authority.zig");
|
||||
const A = std.mem.Allocator;
|
||||
const Error = error{ OutOfMemory, InvalidGeneric };
|
||||
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem };
|
||||
const Env = struct { params: []const ast.TypeParam = &.{}, args: []const ast.Type = &.{} };
|
||||
const Instance = struct { key: []const u8, name: []const u8, air_name: []const u8, decl: union(enum) { pending, ty: ast.TypeDecl, function: ast.FnDecl } = .pending };
|
||||
|
||||
pub fn specialize(arena: A, module: ast.Module) A.Error!Result {
|
||||
var g: Generator = .{ .arena = arena, .m = module };
|
||||
const out = g.run() catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.InvalidGeneric => return .{ .err = g.problem.? },
|
||||
};
|
||||
return .{ .ok = out };
|
||||
}
|
||||
|
||||
const Generator = struct {
|
||||
arena: A,
|
||||
m: ast.Module,
|
||||
instances: std.ArrayList(Instance) = .empty,
|
||||
requirements: std.ArrayList(ast.Requirement) = .empty,
|
||||
depth: usize = 0,
|
||||
type_depth: usize = 0,
|
||||
problem: ?lower.Problem = null,
|
||||
|
||||
fn fail(g: *Generator, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
g.problem = .{ .code = code, .span = span, .message = message, .fields = try g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) };
|
||||
return error.InvalidGeneric;
|
||||
}
|
||||
|
||||
fn bound(g: *Generator, name: []const u8, span: ast.Span) ?[]const u8 {
|
||||
if (span.resolved) return name;
|
||||
const origin = span.namespace orelse g.m.name;
|
||||
for (g.m.scopes) |scope| if (std.mem.eql(u8, scope.name, origin)) {
|
||||
if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| {
|
||||
const owner = name[0..at];
|
||||
if (std.mem.eql(u8, owner, origin)) return if (!scope.qualified_self) null else if (scope.entry) name[at + 1 ..] else name;
|
||||
for (scope.imports) |imp| if (std.mem.eql(u8, imp.path, owner)) return name;
|
||||
return null;
|
||||
}
|
||||
if (scope.entry) return name;
|
||||
for (g.m.types) |t| if (local(t.name, origin, name)) return t.name;
|
||||
for (g.m.functions) |f| if (local(f.name, origin, name)) return f.name;
|
||||
return null;
|
||||
};
|
||||
return name;
|
||||
}
|
||||
|
||||
fn typeDecl(g: *Generator, name: []const u8, span: ast.Span) ?ast.TypeDecl {
|
||||
const n = g.bound(name, span) orelse return null;
|
||||
for (g.m.types) |t| if (std.mem.eql(u8, t.name, n)) return t;
|
||||
return null;
|
||||
}
|
||||
fn function(g: *Generator, name: []const u8, span: ast.Span) ?ast.FnDecl {
|
||||
const n = g.bound(name, span) orelse return null;
|
||||
for (g.m.functions) |f| if (std.mem.eql(u8, f.name, n)) return f;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn validate(g: *Generator, name: []const u8, params: []const ast.TypeParam, span: ast.Span) Error!void {
|
||||
if (params.len > 8) return g.fail("E7006", span, "generic declaration limit or generic entry", name);
|
||||
for (params, 0..) |p, i| {
|
||||
if (!std.ascii.isUpper(p.name[0]) or g.typeDecl(p.name, p.span) != null or builtin(p.name)) return g.fail("E7006", p.span, "type parameter must be uppercase and not shadow a visible type", p.name);
|
||||
for (params[0..i]) |previous| if (std.mem.eql(u8, p.name, previous.name)) return g.fail("E7006", p.span, "duplicate type parameter", p.name);
|
||||
for (p.constraints, 0..) |c, j| {
|
||||
if (std.meta.stringToEnum(Property, c) == null) return g.fail("E7006", p.span, "unknown structural constraint", c);
|
||||
for (p.constraints[0..j]) |previous| if (std.mem.eql(u8, c, previous)) return g.fail("E7006", p.span, "duplicate structural constraint", c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn headerType(g: *Generator, t: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void {
|
||||
if (depth >= 64) return g.fail("E7006", t.span, "type traversal exceeds depth 64", "type");
|
||||
switch (t.kind) {
|
||||
.name => |n| {
|
||||
for (params) |p| if (std.mem.eql(u8, n, p.name)) return;
|
||||
if (g.typeDecl(n, t.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", t.span, "template type needs explicit arguments", n);
|
||||
} else if (!builtin(n)) return g.fail("E7002", t.span, "unknown template signature type", n);
|
||||
},
|
||||
.applied => |x| {
|
||||
const d = g.typeDecl(x.name, t.span) orelse return g.fail("E7002", t.span, "unknown template signature type", x.name);
|
||||
if (d.generics.len == 0 or d.generics.len != x.args.len) return g.fail("E7006", t.span, "template type argument count mismatch", x.name);
|
||||
for (x.args) |arg| try g.headerType(arg, params, depth + 1);
|
||||
},
|
||||
.array => |a| try g.headerType(a.elem.*, params, depth + 1),
|
||||
.wrapped => |w| try g.headerType(w.inner.*, params, depth + 1),
|
||||
.cap => |k| if (authority.kindIndex(k) == null) return g.fail("E7002", t.span, "unknown capability kind", k),
|
||||
.file => |mode| if (!(std.mem.eql(u8, mode, "read") or std.mem.eql(u8, mode, "write") or std.mem.eql(u8, mode, "append"))) return g.fail("E7002", t.span, "unknown file mode", mode),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(g: *Generator) Error!ast.Module {
|
||||
var generic = false;
|
||||
for (g.m.types, 0..) |t, i| {
|
||||
for (g.m.types[0..i]) |previous| if (std.mem.eql(u8, t.name, previous.name)) return g.fail("E7006", t.span, "type defined twice", t.name);
|
||||
try g.validate(t.name, t.generics, t.span);
|
||||
switch (t.kind) {
|
||||
.@"struct" => |fs| for (fs, 0..) |f, j| {
|
||||
for (fs[0..j]) |prev| if (std.mem.eql(u8, f.name, prev.name)) return g.fail("E7006", f.span, "duplicate template field", f.name);
|
||||
},
|
||||
.@"enum" => |vs| {
|
||||
if (vs.len == 0) return g.fail("E7006", t.span, "enum needs a variant", t.name);
|
||||
for (vs, 0..) |v, j| for (vs[0..j]) |prev| if (std.mem.eql(u8, v.name, prev.name)) return g.fail("E7006", v.span, "duplicate template variant", v.name);
|
||||
},
|
||||
}
|
||||
if (t.generics.len != 0) switch (t.kind) {
|
||||
.@"struct" => |fs| for (fs) |field| try g.headerType(field.ty, t.generics, 0),
|
||||
.@"enum" => |vs| for (vs) |v| for (v.payload) |payload_type| try g.headerType(payload_type, t.generics, 0),
|
||||
};
|
||||
generic = generic or t.generics.len != 0;
|
||||
}
|
||||
for (g.m.functions, 0..) |f, i| {
|
||||
for (g.m.functions[0..i]) |previous| if (std.mem.eql(u8, f.name, previous.name)) return g.fail("E7006", f.span, "function defined twice", f.name);
|
||||
if (f.generics.len != 0 and std.mem.eql(u8, f.name, "main")) return g.fail("E7006", f.span, "entry cannot be generic", f.name);
|
||||
try g.validate(f.name, f.generics, f.span);
|
||||
if (f.generics.len != 0) {
|
||||
if (f.trusted != null) return g.fail("E7006", f.span, "trusted is not available in source templates", f.name);
|
||||
for (f.effects) |effect| if (authority.effectIndex(effect) == null) return g.fail("E0006", f.span, "unknown effect in template contract", effect);
|
||||
for (f.params, 0..) |p, j| {
|
||||
for (f.params[0..j]) |prev| if (std.mem.eql(u8, p.name, prev.name)) return g.fail("E7006", p.span, "duplicate value parameter", p.name);
|
||||
try g.headerType(p.ty, f.generics, 0);
|
||||
}
|
||||
try g.headerType(f.ret, f.generics, 0);
|
||||
}
|
||||
generic = generic or f.generics.len != 0;
|
||||
}
|
||||
if (!generic and !usesGenerics(ast.Module, g.m)) return g.m;
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var functions: std.ArrayList(ast.FnDecl) = .empty;
|
||||
for (g.m.types) |t| if (t.generics.len == 0) try types.append(g.arena, try g.walk(ast.TypeDecl, t, .{}));
|
||||
for (g.m.functions) |f| if (f.generics.len == 0) try functions.append(g.arena, try g.walk(ast.FnDecl, f, .{}));
|
||||
std.mem.sort(Instance, g.instances.items, {}, struct {
|
||||
fn less(_: void, a: Instance, b: Instance) bool {
|
||||
return std.mem.lessThan(u8, a.key, b.key);
|
||||
}
|
||||
}.less);
|
||||
for (g.instances.items, 0..) |*instance, i| {
|
||||
const base = instance.air_name;
|
||||
var candidate = base;
|
||||
var suffix: usize = 0;
|
||||
while (g.originalAirUsed(candidate) or usedAir(g.instances.items[0..i], candidate)) {
|
||||
suffix += 1;
|
||||
candidate = try std.fmt.allocPrint(g.arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
instance.air_name = candidate;
|
||||
switch (instance.decl) {
|
||||
.ty => |*t| t.air_name = candidate,
|
||||
.function => |*f| f.air_name = candidate,
|
||||
.pending => unreachable,
|
||||
}
|
||||
}
|
||||
for (g.instances.items) |instance| switch (instance.decl) {
|
||||
.ty => |t| try types.append(g.arena, t),
|
||||
.function => |f| try functions.append(g.arena, f),
|
||||
.pending => unreachable,
|
||||
};
|
||||
var out = g.m;
|
||||
out.types = types.items;
|
||||
out.functions = functions.items;
|
||||
out.requirements = g.requirements.items;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn instantiate(g: *Generator, comptime is_type: bool, template: if (is_type) ast.TypeDecl else ast.FnDecl, raw: []const ast.Type, env: Env, span: ast.Span) Error![]const u8 {
|
||||
if (template.generics.len == 0 or template.generics.len != raw.len) return g.fail("E7006", span, "explicit type argument count does not match declaration", template.name);
|
||||
const args = try g.arena.alloc(ast.Type, raw.len);
|
||||
var key: std.ArrayList(u8) = .empty;
|
||||
try key.appendSlice(g.arena, if (is_type) "type:" else "fn:");
|
||||
const owner = template.span.namespace orelse g.m.name;
|
||||
if (std.mem.indexOfScalar(u8, template.name, '.') == null) try key.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{owner}));
|
||||
try key.appendSlice(g.arena, template.name);
|
||||
try key.append(g.arena, '<');
|
||||
for (raw, args, 0..) |arg, *out, i| {
|
||||
out.* = try g.ty(arg, env);
|
||||
if (out.kind == .name and (std.mem.eql(u8, out.kind.name, "void") or std.mem.eql(u8, out.kind.name, "never"))) return g.fail("E7005", span, "generic arguments must be concrete non-void types", template.name);
|
||||
if (i != 0) try key.append(g.arena, ',');
|
||||
try g.identity(out.*, &key);
|
||||
}
|
||||
try key.append(g.arena, '>');
|
||||
if (key.items.len > 16384) return g.fail("E7006", span, "canonical specialization key exceeds 16384 bytes", template.name);
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.key, key.items)) return instance.name;
|
||||
if (g.depth >= 64 or g.instances.items.len >= 4096) return g.fail("E7006", span, "generic specialization exceeds fixed compiler limit", template.name);
|
||||
const hex = try g.arena.alloc(u8, key.items.len * 2);
|
||||
for (key.items, 0..) |b, i| {
|
||||
hex[2 * i] = "0123456789abcdef"[b >> 4];
|
||||
hex[2 * i + 1] = "0123456789abcdef"[b & 15];
|
||||
}
|
||||
const base = try std.fmt.allocPrint(g.arena, "__aji_g_{s}", .{hex});
|
||||
var air_name: []const u8 = base;
|
||||
var suffix: usize = 0;
|
||||
while (g.airUsed(air_name)) {
|
||||
suffix += 1;
|
||||
air_name = try std.fmt.allocPrint(g.arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
const name = if (std.mem.eql(u8, owner, g.m.name)) air_name else try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ owner, air_name });
|
||||
var digest: [32]u8 = undefined;
|
||||
std.crypto.hash.sha2.Sha256.hash(key.items, &digest, .{});
|
||||
const digest_hex = try g.arena.alloc(u8, 64);
|
||||
for (digest, 0..) |b, i| {
|
||||
digest_hex[2 * i] = "0123456789abcdef"[b >> 4];
|
||||
digest_hex[2 * i + 1] = "0123456789abcdef"[b & 15];
|
||||
}
|
||||
const final_air = try std.fmt.allocPrint(g.arena, "__aji_g_{s}", .{digest_hex});
|
||||
const index = g.instances.items.len;
|
||||
try g.instances.append(g.arena, .{ .key = key.items, .name = name, .air_name = final_air });
|
||||
for (template.generics, args) |p, arg| try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = "", .span = span });
|
||||
for (template.generics, args) |p, arg| for (p.constraints) |property| try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = property, .span = span });
|
||||
g.depth += 1;
|
||||
defer g.depth -= 1;
|
||||
var concrete = try g.walk(@TypeOf(template), template, .{ .params = template.generics, .args = args });
|
||||
concrete.generics = &.{};
|
||||
concrete.name = name;
|
||||
concrete.air_name = final_air;
|
||||
concrete.display_name = key.items[if (is_type) 5 else 3..];
|
||||
g.instances.items[index].decl = if (is_type) .{ .ty = concrete } else .{ .function = concrete };
|
||||
return name;
|
||||
}
|
||||
|
||||
fn airUsed(g: *Generator, name: []const u8) bool {
|
||||
for (g.m.types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name) or std.mem.eql(u8, t.name, name) or std.mem.eql(u8, shortName(t.name), name)) return true;
|
||||
for (g.m.functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name) or std.mem.eql(u8, f.name, name) or std.mem.eql(u8, shortName(f.name), name)) return true;
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, shortName(instance.name), name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn originalAirUsed(g: *Generator, name: []const u8) bool {
|
||||
for (g.m.types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true;
|
||||
for (g.m.functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
fn instanceTypeKey(g: *Generator, name: []const u8) ?[]const u8 {
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name) and std.mem.startsWith(u8, instance.key, "type:")) return instance.key;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn identity(g: *Generator, t: ast.Type, out: *std.ArrayList(u8)) Error!void {
|
||||
switch (t.kind) {
|
||||
.name => |name| {
|
||||
if (g.typeDecl(name, t.span)) |d| {
|
||||
if (std.mem.indexOfScalar(u8, d.name, '.') == null) try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{g.m.name}));
|
||||
try out.appendSlice(g.arena, d.name);
|
||||
} else if (g.instanceTypeKey(name)) |key| {
|
||||
try out.appendSlice(g.arena, key[5..]);
|
||||
} else try out.appendSlice(g.arena, name);
|
||||
},
|
||||
.array => |a| {
|
||||
try out.appendSlice(g.arena, "[");
|
||||
try g.identity(a.elem.*, out);
|
||||
try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, ";{d}]", .{a.len}));
|
||||
},
|
||||
.wrapped => |w| {
|
||||
try out.appendSlice(g.arena, w.wrapper);
|
||||
try out.append(g.arena, '<');
|
||||
try g.identity(w.inner.*, out);
|
||||
try out.append(g.arena, '>');
|
||||
},
|
||||
.cap => |k| try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "cap<{s}>", .{k})),
|
||||
.file => |mode| try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "file<{s}>", .{mode})),
|
||||
.applied => unreachable,
|
||||
}
|
||||
if (out.items.len > 16384) return g.fail("E7006", t.span, "canonical specialization key exceeds 16384 bytes", "type");
|
||||
}
|
||||
|
||||
fn named(g: *Generator, name: []const u8, args: []const ast.Type, span: ast.Span, env: Env) Error!ast.Type {
|
||||
return g.ty(.{ .span = span, .kind = if (args.len == 0) .{ .name = name } else .{ .applied = .{ .name = name, .args = args } } }, env);
|
||||
}
|
||||
|
||||
fn ty(g: *Generator, input: ast.Type, env: Env) Error!ast.Type {
|
||||
if (g.type_depth >= 64) return g.fail("E7006", input.span, "structural type depth exceeds 64", "type");
|
||||
g.type_depth += 1;
|
||||
defer g.type_depth -= 1;
|
||||
var t = input;
|
||||
switch (input.kind) {
|
||||
.name => |name| {
|
||||
for (env.params, env.args) |p, arg| if (std.mem.eql(u8, name, p.name)) return arg;
|
||||
if (g.typeDecl(name, input.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", input.span, "generic type needs explicit arguments", name);
|
||||
t.kind.name = d.name;
|
||||
t.span.resolved = true;
|
||||
} else if (!builtin(name) and !g.generated(name)) return g.fail("E7002", input.span, "unknown or inaccessible type", name);
|
||||
},
|
||||
.applied => |x| {
|
||||
const d = g.typeDecl(x.name, input.span) orelse return g.fail("E7002", input.span, "unknown or inaccessible generic type", x.name);
|
||||
t.kind = .{ .name = try g.instantiate(true, d, x.args, env, input.span) };
|
||||
t.span.resolved = true;
|
||||
},
|
||||
.array => |a| t.kind.array.elem = try g.box(ast.Type, try g.ty(a.elem.*, env)),
|
||||
.wrapped => |w| t.kind.wrapped.inner = try g.box(ast.Type, try g.ty(w.inner.*, env)),
|
||||
.cap, .file => {},
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
fn generated(g: *Generator, name: []const u8) bool {
|
||||
for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn expression(g: *Generator, e: ast.Expr, env: Env) Error!ast.Expr {
|
||||
var out = e;
|
||||
switch (e.kind) {
|
||||
.specialize => |x| {
|
||||
const name = path(g.arena, x.base.*) catch return error.OutOfMemory;
|
||||
const d = g.function(name orelse return g.fail("E7006", e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?);
|
||||
out.kind = .{ .name = try g.instantiate(false, d, x.args, env, e.span) };
|
||||
out.span.resolved = true;
|
||||
return out;
|
||||
},
|
||||
.call => |x| {
|
||||
if (x.callee.kind != .specialize and x.callee.kind != .variant) if (try path(g.arena, x.callee.*)) |name| if (g.function(name, x.callee.span)) |d| {
|
||||
if (d.generics.len != 0) return g.fail("E7006", e.span, "generic function needs explicit arguments", name);
|
||||
};
|
||||
},
|
||||
.variant => |x| {
|
||||
const t = try g.named(x.@"enum", x.type_args, e.span, env);
|
||||
if (t.kind != .name) return g.fail("E7005", e.span, "enum constructor requires a named type", x.@"enum");
|
||||
out.kind.variant.@"enum" = t.kind.name;
|
||||
out.kind.variant.type_args = &.{};
|
||||
out.span.resolved = t.span.resolved;
|
||||
return out;
|
||||
},
|
||||
.struct_lit => |x| {
|
||||
const t = try g.named(x.name, x.type_args, e.span, env);
|
||||
if (t.kind != .name) return g.fail("E7005", e.span, "struct constructor requires a named type", x.name);
|
||||
out.kind.struct_lit.name = t.kind.name;
|
||||
out.kind.struct_lit.type_args = &.{};
|
||||
out.kind.struct_lit.fields = try g.walk([]const ast.FieldInit, x.fields, env);
|
||||
out.span.resolved = t.span.resolved;
|
||||
return out;
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
out.kind = try g.walk(ast.Expr.Kind, e.kind, env);
|
||||
return out;
|
||||
}
|
||||
|
||||
fn box(g: *Generator, comptime T: type, value: T) A.Error!*const T {
|
||||
const out = try g.arena.create(T);
|
||||
out.* = value;
|
||||
return out;
|
||||
}
|
||||
|
||||
fn walk(g: *Generator, comptime T: type, value: T, env: Env) Error!T {
|
||||
if (T == ast.Type) return g.ty(value, env);
|
||||
if (T == ast.Expr) return g.expression(value, env);
|
||||
if (T == ast.Pattern) {
|
||||
var out = value;
|
||||
if (value.kind == .ctor) if (value.kind.ctor.qualifier) |q| {
|
||||
const t = try g.named(q, value.kind.ctor.type_args, value.span, env);
|
||||
if (t.kind != .name) return g.fail("E7005", value.span, "enum pattern requires a named type", q);
|
||||
out.kind.ctor.qualifier = t.kind.name;
|
||||
out.kind.ctor.type_args = &.{};
|
||||
out.span.resolved = t.span.resolved;
|
||||
};
|
||||
return out;
|
||||
}
|
||||
if (T == ast.Span) return value;
|
||||
switch (@typeInfo(T)) {
|
||||
.@"struct" => |info| {
|
||||
var out = value;
|
||||
inline for (info.field_names, info.field_types) |name, FieldType| @field(out, name) = try g.walk(FieldType, @field(value, name), env);
|
||||
return out;
|
||||
},
|
||||
.@"union" => switch (value) {
|
||||
inline else => |payload, tag| return @unionInit(T, @tagName(tag), try g.walk(@TypeOf(payload), payload, env)),
|
||||
},
|
||||
.optional => |info| return if (value) |v| try g.walk(info.child, v, env) else null,
|
||||
.pointer => |info| {
|
||||
if (info.child == u8) return value;
|
||||
if (info.size == .slice) {
|
||||
const out = try g.arena.alloc(info.child, value.len);
|
||||
for (value, out) |v, *target| target.* = try g.walk(info.child, v, env);
|
||||
return out;
|
||||
}
|
||||
return try g.box(info.child, try g.walk(info.child, value.*, env));
|
||||
},
|
||||
else => return value,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
pub const Property = enum { Copy, Send, Share, Freeze, Local };
|
||||
fn local(full: []const u8, owner: []const u8, short: []const u8) bool {
|
||||
return full.len == owner.len + short.len + 1 and std.mem.startsWith(u8, full, owner) and full[owner.len] == '.' and std.mem.eql(u8, full[owner.len + 1 ..], short);
|
||||
}
|
||||
fn builtin(name: []const u8) bool {
|
||||
const names = [_][]const u8{ "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "bool", "void", "never", "region", "stream", "listener", "alloc_error", "cap_error", "io_error" };
|
||||
for (names) |n| if (std.mem.eql(u8, n, name)) return true;
|
||||
return false;
|
||||
}
|
||||
fn path(arena: A, e: ast.Expr) A.Error!?[]const u8 {
|
||||
return switch (e.kind) {
|
||||
.name => |name| name,
|
||||
.field => |f| if (try path(arena, f.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, f.name }) else null,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn usesGenerics(comptime T: type, value: T) bool {
|
||||
if (T == ast.Type) if (value.kind == .applied) return true;
|
||||
if (T == ast.Expr) switch (value.kind) {
|
||||
.specialize => return true,
|
||||
.variant => |x| if (x.type_args.len != 0) return true,
|
||||
.struct_lit => |x| if (x.type_args.len != 0) return true,
|
||||
else => {},
|
||||
};
|
||||
if (T == ast.Pattern) if (value.kind == .ctor and value.kind.ctor.type_args.len != 0) return true;
|
||||
switch (@typeInfo(T)) {
|
||||
.@"struct" => |info| {
|
||||
inline for (info.field_names, info.field_types) |name, FT| if (usesGenerics(FT, @field(value, name))) return true;
|
||||
},
|
||||
.@"union" => switch (value) {
|
||||
inline else => |payload| return usesGenerics(@TypeOf(payload), payload),
|
||||
},
|
||||
.optional => |info| return if (value) |v| usesGenerics(info.child, v) else false,
|
||||
.pointer => |info| {
|
||||
if (info.child == u8) return false;
|
||||
if (info.size == .slice) {
|
||||
for (value) |v| if (usesGenerics(info.child, v)) return true;
|
||||
} else return usesGenerics(info.child, value.*);
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
fn shortName(name: []const u8) []const u8 {
|
||||
return if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name;
|
||||
}
|
||||
|
||||
fn usedAir(instances: []const Instance, name: []const u8) bool {
|
||||
for (instances) |instance| if (std.mem.eql(u8, instance.air_name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
+112
-18
@@ -263,7 +263,7 @@ const Rest = struct {
|
||||
|
||||
const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 };
|
||||
|
||||
const FnSig = struct { params: []const Ty, ret: Ty, air_name: []const u8 };
|
||||
const FnSig = struct { params: []const Ty, ret: Ty, air_name: []const u8, display_name: []const u8 };
|
||||
|
||||
const Lowerer = struct {
|
||||
arena: Allocator,
|
||||
@@ -340,7 +340,7 @@ const Lowerer = struct {
|
||||
.bool => "bool",
|
||||
.void => "void",
|
||||
.never => "never",
|
||||
.named => |i| if (source_names and l.m.types[i].air_name != null) l.m.types[i].name else l.typeNames[i],
|
||||
.named => |i| if (source_names and l.m.types[i].air_name != null) (l.m.types[i].display_name orelse l.m.types[i].name) else l.typeNames[i],
|
||||
.array => |a| std.fmt.allocPrint(l.arena, "array<{s}, {d}>", .{ l.typeText(a.elem, source_names), a.len }) catch "array",
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |x| std.fmt.allocPrint(l.arena, "{s}<{s}>", .{ @tagName(t), l.typeText(x.*, source_names) }) catch "borrow",
|
||||
.scope => "scope",
|
||||
@@ -411,7 +411,7 @@ const Lowerer = struct {
|
||||
if (l.sigs.contains(f.name)) return l.fail("E7006", f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
|
||||
const ps = try l.arena.alloc(Ty, f.params.len);
|
||||
for (f.params, ps) |p, *t| t.* = try l.typeOf(p.ty);
|
||||
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret), .air_name = f.air_name orelse f.name });
|
||||
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret), .air_name = f.air_name orelse f.name, .display_name = f.display_name orelse f.name });
|
||||
}
|
||||
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
|
||||
|
||||
@@ -421,6 +421,7 @@ const Lowerer = struct {
|
||||
// closure of what the lowered AIR uses (spec 15 §9).
|
||||
var type_lines: std.ArrayList(Inst) = .empty;
|
||||
for (l.m.types) |t| try type_lines.append(l.arena, .{ .text = try l.typeDeclText(t), .span = t.span });
|
||||
try l.checkRequirements();
|
||||
for (l.m.functions) |f| try l.fns.append(l.arena, try l.function(f));
|
||||
|
||||
var features: std.ArrayList(u8) = .empty;
|
||||
@@ -437,6 +438,80 @@ const Lowerer = struct {
|
||||
for (l.fns.items) |f| try l.emitFunction(f);
|
||||
}
|
||||
|
||||
fn airType(l: *Lowerer, t: Ty) Error!air_module.Type {
|
||||
return switch (t) {
|
||||
.int => |n| .{ .int = std.meta.stringToEnum(air_module.IntType, n).? },
|
||||
.named => |i| .{ .named = i },
|
||||
.cap => |k| .{ .cap = authority.kindIndex(k).? },
|
||||
.builtin => |b| .{ .builtin = b },
|
||||
.resource => |r| .{ .resource = r },
|
||||
.array => |a| blk: {
|
||||
const out = try l.arena.create(air_module.Type.Array);
|
||||
out.* = .{ .elem = try l.airType(a.elem), .len = a.len };
|
||||
break :blk .{ .array = out };
|
||||
},
|
||||
inline .ref, .mut, .slice, .slice_mut, .own, .own_array, .task, .sender, .receiver, .mutex, .guard, .island, .frozen, .arc, .iref, .atomic => |inner, tag| blk: {
|
||||
const out = try l.arena.create(air_module.Type);
|
||||
out.* = try l.airType(inner.*);
|
||||
break :blk @unionInit(air_module.Type, @tagName(tag), out);
|
||||
},
|
||||
.bool => .bool,
|
||||
.void => .void,
|
||||
.never => .never,
|
||||
.region => .region,
|
||||
.scope => .scope,
|
||||
.shield => .shield,
|
||||
};
|
||||
}
|
||||
|
||||
fn checkRequirements(l: *Lowerer) Error!void {
|
||||
if (l.m.requirements.len == 0) return;
|
||||
const types = try l.arena.alloc(air_module.TypeDecl, l.m.types.len);
|
||||
for (l.m.types, types, 0..) |d, *out, index| {
|
||||
out.* = .{ .name = d.air_name orelse d.name, .span = .{ .line = @intCast(index + 1), .col = 1 }, .kind = undefined };
|
||||
switch (d.kind) {
|
||||
.@"struct" => |fs| {
|
||||
const fields = try l.arena.alloc(air_module.Field, fs.len);
|
||||
for (fs, fields) |f, *target| target.* = .{ .name = f.name, .ty = try l.airType(try l.typeOf(f.ty)) };
|
||||
out.kind = .{ .@"struct" = fields };
|
||||
},
|
||||
.@"enum" => |vs| {
|
||||
const variants = try l.arena.alloc(air_module.Variant, vs.len);
|
||||
for (vs, variants) |v, *target| {
|
||||
const payload = try l.arena.alloc(air_module.Type, v.payload.len);
|
||||
for (v.payload, payload) |t, *p| p.* = try l.airType(try l.typeOf(t));
|
||||
target.* = .{ .name = v.name, .payload = payload };
|
||||
}
|
||||
out.kind = .{ .@"enum" = variants };
|
||||
},
|
||||
}
|
||||
}
|
||||
const m: air_module.Module = .{ .name = l.m.name, .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = types, .functions = &.{} };
|
||||
var layout_context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
|
||||
try verifier_types.checkFiniteLayouts(&layout_context);
|
||||
if (layout_context.diags.items.len != 0) {
|
||||
const d = l.m.types[layout_context.diags.items[0].span.?.line - 1];
|
||||
return l.fail("E1003", d.span, "aggregate type contains itself by value", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||||
}
|
||||
for (l.m.requirements) |r| {
|
||||
const ty = try l.typeOf(r.ty);
|
||||
const t = try l.airType(ty);
|
||||
if (!boundedType(m, t, 0)) return l.fail("E7006", r.span, "constraint type traversal is cyclic or exceeds depth 64", &.{});
|
||||
if (r.property.len == 0) {
|
||||
var context: @import("../verifier.zig").Context = .{ .arena = l.arena, .file = "<generic>", .module = m };
|
||||
try verifier_types.checkTypeArgument(&context, .{ .line = 1, .col = 1 }, t);
|
||||
if (context.diags.items.len != 0) return l.fail("E7005", r.span, "generic argument is not a well-formed concrete type", &.{ .{ .name = "parameter", .value = r.parameter }, .{ .name = "found", .value = l.diagnosticTyText(ty) } });
|
||||
continue;
|
||||
}
|
||||
const ok = if (std.mem.eql(u8, r.property, "Copy")) verifier_types.isCopy(m, t) else if (std.mem.eql(u8, r.property, "Send")) verifier_types.isSend(m, t) else if (std.mem.eql(u8, r.property, "Share")) verifier_types.isShare(m, t) else if (std.mem.eql(u8, r.property, "Freeze")) verifier_types.isIslandSafe(m, t) else verifier_types.isLocalType(m, t);
|
||||
if (!ok) return l.fail("E7005", r.span, "generic argument does not satisfy structural constraint", &.{
|
||||
.{ .name = "parameter", .value = r.parameter },
|
||||
.{ .name = "constraint", .value = r.property },
|
||||
.{ .name = "found", .value = l.diagnosticTyText(ty) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The features the lowered AIR uses directly; the header is their
|
||||
/// dependency closure (spec 15 §9). `effects` is always declared.
|
||||
const UseFeature = enum { capabilities, resources, unsafe };
|
||||
@@ -525,6 +600,7 @@ const Lowerer = struct {
|
||||
|
||||
fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty {
|
||||
switch (t.kind) {
|
||||
.applied => return l.fail("E7002", t.span, "unknown generic type", &.{}),
|
||||
.name => |n| {
|
||||
if (isIntName(n)) return .{ .int = n };
|
||||
if (std.mem.eql(u8, n, "bool")) return .bool;
|
||||
@@ -1116,6 +1192,7 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
fn boundName(l: *Lowerer, name: []const u8, span: Span) ?[]const u8 {
|
||||
if (span.resolved) return name;
|
||||
const scope = l.sourceScope(span) orelse return name;
|
||||
if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| {
|
||||
const owner = name[0..at];
|
||||
@@ -1154,6 +1231,7 @@ const Lowerer = struct {
|
||||
|
||||
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
|
||||
return switch (e.kind) {
|
||||
.specialize => null,
|
||||
.int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null,
|
||||
.boolean => .bool,
|
||||
.name => |n| if (l.lookup(n)) |b| b.ty else null,
|
||||
@@ -1285,6 +1363,7 @@ const Lowerer = struct {
|
||||
|
||||
fn expr(l: *Lowerer, e: ast.Expr, want: ?Ty) Error!Value {
|
||||
switch (e.kind) {
|
||||
.specialize => return l.fail("E7006", e.span, "explicit type arguments require a generic function", &.{}),
|
||||
.int => |x| {
|
||||
const ty: Ty = if (parse_mod.intSuffix(x.text)) |s| .{ .int = s } else want orelse
|
||||
return l.fail("E7007", e.span, "the type of this integer literal cannot be determined; add a suffix such as `0u64` or a type annotation", &.{});
|
||||
@@ -1531,7 +1610,7 @@ const Lowerer = struct {
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
const sig = l.functionSig(name, callee.span) orelse return l.unknown(callee.span, name);
|
||||
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
|
||||
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
|
||||
var arg_names: std.ArrayList(u8) = .empty;
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
for (args, sig.params, 0..) |a, pt, i| {
|
||||
@@ -1549,7 +1628,7 @@ const Lowerer = struct {
|
||||
}
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
return l.def(if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
|
||||
return l.def(if (callee.span.resolved) "generic_call" else if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
|
||||
}
|
||||
|
||||
/// `Name { f: e, … }`: every field exactly once; initializers are
|
||||
@@ -1558,20 +1637,20 @@ const Lowerer = struct {
|
||||
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
|
||||
const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||||
const d = l.m.types[t.named];
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = name }});
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = d.display_name orelse name }});
|
||||
const fields = d.kind.@"struct";
|
||||
for (inits, 0..) |fi, i| {
|
||||
for (inits[0..i]) |prev| if (std.mem.eql(u8, prev.name, fi.name)) return l.fail("E7006", fi.span, "field given twice", &.{.{ .name = "field", .value = fi.name }});
|
||||
const known = for (fields) |f| {
|
||||
if (std.mem.eql(u8, f.name, fi.name)) break true;
|
||||
} else false;
|
||||
if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = name }, .{ .name = "field", .value = fi.name } });
|
||||
if (!known) return l.fail("E7002", fi.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = fi.name } });
|
||||
}
|
||||
var args: std.ArrayList(u8) = .empty;
|
||||
for (fields, 0..) |f, i| {
|
||||
const fi = for (inits) |x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = name }, .{ .name = "field", .value = f.name } });
|
||||
} else return l.fail("E7006", e.span, "missing field", &.{ .{ .name = "type", .value = d.display_name orelse name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(f.ty);
|
||||
const v = try l.expr(fi.e, ft);
|
||||
try l.checkTy(fi.e.span, v.ty, ft);
|
||||
@@ -1602,10 +1681,10 @@ const Lowerer = struct {
|
||||
var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
if (bt.isBorrow()) bt = bt.inner().?;
|
||||
const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = l.diagnosticTyText(bt) }});
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.name }});
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||||
const f = for (d.kind.@"struct") |x| {
|
||||
if (std.mem.eql(u8, x.name, name)) break x;
|
||||
} else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.name }, .{ .name = "field", .value = name } });
|
||||
} else return l.fail("E7002", e.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = name } });
|
||||
// Through a borrow: borrow the field and load it.
|
||||
if (l.rootBinding(base)) |rb| if (rb.kind == .borrow) {
|
||||
const p = try l.placeBorrow(e, false, false, e.span);
|
||||
@@ -1671,21 +1750,21 @@ const Lowerer = struct {
|
||||
var ends: std.ArrayList(ArmEnd) = .empty;
|
||||
|
||||
if (l.decl(st)) |d| {
|
||||
if (d.kind != .@"enum") return l.fail("E7005", m.scrutinee.span, "`match` over a struct; use field access", &.{.{ .name = "type", .value = d.name }});
|
||||
if (d.kind != .@"enum") return l.fail("E7005", m.scrutinee.span, "`match` over a struct; use field access", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||||
const vs = d.kind.@"enum";
|
||||
const blocks = try l.arena.alloc(usize, m.arms.len);
|
||||
var head: std.ArrayList(u8) = .empty;
|
||||
try head.appendSlice(l.arena, try l.fmt("enum.switch {s} %{s}", .{ l.tyText(st), sv.name }));
|
||||
for (m.arms, blocks, 0..) |arm, *blk, i| {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
|
||||
return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.name }});
|
||||
return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.display_name orelse d.name }});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
const pattern_type = l.enumType(c.qualifier.?, arm.pattern.span);
|
||||
if (std.mem.indexOfScalar(u8, c.qualifier.?, '.') != null and pattern_type == null) return l.unknown(arm.pattern.span, c.qualifier.?);
|
||||
if (pattern_type == null or !Ty.eql(st, pattern_type.?)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.name }, .{ .name = "found", .value = c.qualifier.? } });
|
||||
if (pattern_type == null or !Ty.eql(st, pattern_type.?)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.display_name orelse d.name }, .{ .name = "found", .value = c.qualifier.? } });
|
||||
const vi = for (vs, 0..) |v, k| {
|
||||
if (std.mem.eql(u8, v.name, c.name)) break k;
|
||||
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.name }, .{ .name = "variant", .value = c.name } });
|
||||
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.display_name orelse d.name }, .{ .name = "variant", .value = c.name } });
|
||||
for (m.arms[0..i]) |prev| if (std.mem.eql(u8, prev.pattern.kind.ctor.name, c.name)) return l.fail("E7006", arm.pattern.span, "variant matched twice", &.{.{ .name = "variant", .value = c.name }});
|
||||
if (c.binds.len != vs[vi].payload.len) return l.fail("E7005", arm.pattern.span, "the pattern binds a different number of payload values", &.{ .{ .name = "variant", .value = c.name }, .{ .name = "expected", .value = try l.fmt("{d}", .{vs[vi].payload.len}) } });
|
||||
blk.* = try l.newBlock(try l.fmt("case_{s}", .{c.name}));
|
||||
@@ -2012,7 +2091,7 @@ const Lowerer = struct {
|
||||
if (d.kind != .@"struct") return l.fail("E7005", place.span, "field of an enum; use `match`", &.{});
|
||||
const fd = for (d.kind.@"struct") |x| {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.name }, .{ .name = "field", .value = f.name } });
|
||||
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.display_name orelse d.name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(fd.ty);
|
||||
const v = try l.def(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), span);
|
||||
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
|
||||
@@ -2383,7 +2462,7 @@ const Lowerer = struct {
|
||||
const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
|
||||
const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname);
|
||||
const fargs = args[2..];
|
||||
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = fname }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
|
||||
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = sig.display_name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
|
||||
var names: std.ArrayList(u8) = .empty;
|
||||
for (fargs, sig.params, 0..) |a, pt, i| {
|
||||
// A borrow is lent to the task until its join, so it is bound
|
||||
@@ -3218,7 +3297,7 @@ fn exprReads(e: ast.Expr, name: []const u8, skip: ?Span) bool {
|
||||
return switch (e.kind) {
|
||||
.name => |n| std.mem.eql(u8, n, name),
|
||||
.move => |n| std.mem.eql(u8, n, name),
|
||||
.int, .boolean, .bytes, .variant => false,
|
||||
.int, .boolean, .bytes, .variant, .specialize => false,
|
||||
.neg, .not, .deref, .or_trap => |x| exprReads(x.*, name, skip),
|
||||
.borrow => |x| exprReads(x.place.*, name, skip),
|
||||
.binary => |x| exprReads(x.l.*, name, skip) or exprReads(x.r.*, name, skip),
|
||||
@@ -3279,7 +3358,7 @@ const After = struct {
|
||||
}
|
||||
return switch (e.kind) {
|
||||
.name, .move => |n| w.seen and std.mem.eql(u8, n, w.name),
|
||||
.int, .boolean, .bytes, .variant => false,
|
||||
.int, .boolean, .bytes, .variant, .specialize => false,
|
||||
.neg, .not, .deref, .or_trap => |x| w.expr(x.*),
|
||||
.borrow => |x| w.expr(x.place.*),
|
||||
.binary => |x| w.expr(x.l.*) or w.expr(x.r.*),
|
||||
@@ -3496,3 +3575,18 @@ fn expressionPath(arena: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 {
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
// Bound property queries before invoking recursive verifier derivations.
|
||||
fn boundedType(m: air_module.Module, t: air_module.Type, depth: usize) bool {
|
||||
if (depth >= 64) return false;
|
||||
if (t == .named) return switch (m.types[t.named].kind) {
|
||||
.@"struct" => |fs| for (fs) |f| {
|
||||
if (!boundedType(m, f.ty, depth + 1)) break false;
|
||||
} else true,
|
||||
.@"enum" => |vs| blk: {
|
||||
for (vs) |v| for (v.payload) |p| if (!boundedType(m, p, depth + 1)) break :blk false;
|
||||
break :blk true;
|
||||
},
|
||||
};
|
||||
return if (t.inner()) |inner| boundedType(m, inner, depth + 1) else true;
|
||||
}
|
||||
+73
-23
@@ -156,6 +156,7 @@ const Parser = struct {
|
||||
const is_struct = p.atWord("struct");
|
||||
_ = p.next();
|
||||
const name = try p.ident("type name");
|
||||
const generics = try p.typeParams();
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
if (is_struct) {
|
||||
var fields: std.ArrayList(ast.Field) = .empty;
|
||||
@@ -169,7 +170,7 @@ const Parser = struct {
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"struct" = fields.items } };
|
||||
return .{ .name = name, .generics = generics, .span = p.span(start), .kind = .{ .@"struct" = fields.items } };
|
||||
}
|
||||
var vs: std.ArrayList(ast.Variant) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
@@ -190,12 +191,13 @@ const Parser = struct {
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .name = name, .span = p.span(start), .kind = .{ .@"enum" = vs.items } };
|
||||
return .{ .name = name, .generics = generics, .span = p.span(start), .kind = .{ .@"enum" = vs.items } };
|
||||
}
|
||||
|
||||
fn fnDecl(p: *Parser) Error!ast.FnDecl {
|
||||
const start = p.next().pos; // `fn`
|
||||
const name = try p.ident("function name");
|
||||
const generics = try p.typeParams();
|
||||
_ = try p.expect(.l_paren, "`(`");
|
||||
var params: std.ArrayList(ast.Param) = .empty;
|
||||
while (p.peek().tag != .r_paren) {
|
||||
@@ -233,7 +235,7 @@ const Parser = struct {
|
||||
trusted = t.text;
|
||||
}
|
||||
const body = try p.block();
|
||||
return .{ .name = name, .span = p.span(start), .params = params.items, .ret = ret, .from = from, .effects = effects.items, .trusted = trusted, .body = body };
|
||||
return .{ .name = name, .generics = generics, .span = p.span(start), .params = params.items, .ret = ret, .from = from, .effects = effects.items, .trusted = trusted, .body = body };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ types
|
||||
@@ -252,25 +254,57 @@ const Parser = struct {
|
||||
const t = p.peek();
|
||||
if (t.tag != .ident) return p.fail(t, "a type");
|
||||
_ = p.next();
|
||||
if (p.peek().tag == .dot) {
|
||||
const name = try p.pathTail(t.text);
|
||||
return .{ .span = p.span(start), .kind = .{ .name = name } };
|
||||
}
|
||||
if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = t.text } };
|
||||
_ = p.next();
|
||||
if (std.mem.eql(u8, t.text, "cap")) {
|
||||
const k = try p.path();
|
||||
const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text;
|
||||
if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = name } };
|
||||
if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) {
|
||||
_ = p.next();
|
||||
const value = try p.path();
|
||||
try p.closeAngle();
|
||||
return .{ .span = p.span(start), .kind = .{ .cap = k } };
|
||||
return .{ .span = p.span(start), .kind = if (std.mem.eql(u8, name, "cap")) .{ .cap = value } else .{ .file = value } };
|
||||
}
|
||||
if (std.mem.eql(u8, t.text, "file")) {
|
||||
const m = try p.ident("`read`, `write` or `append`");
|
||||
try p.closeAngle();
|
||||
return .{ .span = p.span(start), .kind = .{ .file = m } };
|
||||
const args = try p.typeArgs();
|
||||
const wrappers = [_][]const u8{ "ref", "mut", "slice", "slice_mut", "own", "own_array", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "iref", "atomic" };
|
||||
for (wrappers) |wrapper| if (std.mem.eql(u8, name, wrapper)) {
|
||||
if (args.len != 1) return p.fail(t, "one wrapper type argument");
|
||||
return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = name, .inner = try p.box(ast.Type, args[0]) } } };
|
||||
};
|
||||
return .{ .span = p.span(start), .kind = .{ .applied = .{ .name = name, .args = args } } };
|
||||
}
|
||||
|
||||
fn typeArgs(p: *Parser) Error![]const ast.Type {
|
||||
_ = try p.expect(.lt, "`<`");
|
||||
var args: std.ArrayList(ast.Type) = .empty;
|
||||
try args.append(p.arena, try p.typeExpr());
|
||||
while (p.peek().tag == .comma) {
|
||||
_ = p.next();
|
||||
try args.append(p.arena, try p.typeExpr());
|
||||
}
|
||||
const inner = try p.typeExpr();
|
||||
try p.closeAngle();
|
||||
return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = t.text, .inner = try p.box(ast.Type, inner) } } };
|
||||
return args.items;
|
||||
}
|
||||
|
||||
fn typeParams(p: *Parser) Error![]const ast.TypeParam {
|
||||
if (p.peek().tag != .lt) return &.{};
|
||||
_ = p.next();
|
||||
var params: std.ArrayList(ast.TypeParam) = .empty;
|
||||
while (true) {
|
||||
const start = p.peek().pos;
|
||||
const name = try p.ident("a type parameter");
|
||||
var constraints: std.ArrayList([]const u8) = .empty;
|
||||
if (p.peek().tag == .colon) {
|
||||
_ = p.next();
|
||||
try constraints.append(p.arena, try p.ident("a structural property"));
|
||||
while (p.peek().tag == .plus) {
|
||||
_ = p.next();
|
||||
try constraints.append(p.arena, try p.ident("a structural property"));
|
||||
}
|
||||
}
|
||||
try params.append(p.arena, .{ .name = name, .constraints = constraints.items, .span = p.span(start) });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
try p.closeAngle();
|
||||
return params.items;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ statements
|
||||
@@ -504,6 +538,11 @@ const Parser = struct {
|
||||
_ = p.next();
|
||||
var qualifier: ?[]const u8 = null;
|
||||
var name = try p.pathTail(t.text);
|
||||
var type_args: []const ast.Type = &.{};
|
||||
if (p.peek().tag == .colon_colon and p.peekAt(1).tag == .lt) {
|
||||
_ = p.next();
|
||||
type_args = try p.typeArgs();
|
||||
}
|
||||
if (p.peek().tag == .colon_colon) {
|
||||
_ = p.next();
|
||||
qualifier = name;
|
||||
@@ -523,7 +562,7 @@ const Parser = struct {
|
||||
}
|
||||
_ = try p.expect(.r_paren, "`)`");
|
||||
}
|
||||
return .{ .span = p.span(start), .kind = .{ .ctor = .{ .qualifier = qualifier, .name = name, .binds = binds.items } } };
|
||||
return .{ .span = p.span(start), .kind = .{ .ctor = .{ .qualifier = qualifier, .name = name, .binds = binds.items, .type_args = type_args } } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ expressions
|
||||
@@ -637,10 +676,18 @@ const Parser = struct {
|
||||
while (true) {
|
||||
switch (p.peek().tag) {
|
||||
.colon_colon => {
|
||||
const name = try p.exprPath(e) orelse return p.fail(p.peek(), "an enum name before `::`");
|
||||
_ = p.next();
|
||||
if (p.peek().tag == .lt) {
|
||||
const base = try p.box(ast.Expr, e);
|
||||
const args = try p.typeArgs();
|
||||
e = .{ .span = p.span(start), .kind = .{ .specialize = .{ .base = base, .args = args } } };
|
||||
continue;
|
||||
}
|
||||
const base = if (e.kind == .specialize) e.kind.specialize.base.* else e;
|
||||
const name = try p.exprPath(base) orelse return p.fail(p.peek(), "an enum name before `::`");
|
||||
const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{};
|
||||
const variant = try p.ident("a variant name");
|
||||
e = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant } } };
|
||||
e = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant, .type_args = type_args } } };
|
||||
},
|
||||
.dot => {
|
||||
_ = p.next();
|
||||
@@ -662,10 +709,13 @@ const Parser = struct {
|
||||
},
|
||||
.l_brace => {
|
||||
if (p.no_struct) return e;
|
||||
const name = try p.exprPath(e) orelse return e;
|
||||
const base = if (e.kind == .specialize) e.kind.specialize.base.* else e;
|
||||
const name = try p.exprPath(base) orelse return e;
|
||||
const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{};
|
||||
const last = if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name;
|
||||
if (!std.ascii.isUpper(last[0])) return e;
|
||||
e = try p.structLiteral(start, name);
|
||||
e.kind.struct_lit.type_args = type_args;
|
||||
},
|
||||
.l_paren => {
|
||||
const args = try p.callArgs();
|
||||
@@ -805,7 +855,7 @@ const Parser = struct {
|
||||
}
|
||||
if (isKeyword(t.text)) return p.fail(t, "an expression");
|
||||
_ = p.next();
|
||||
if (p.peek().tag == .colon_colon) {
|
||||
if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) {
|
||||
_ = p.next();
|
||||
const v = try p.ident("a variant name");
|
||||
return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } };
|
||||
|
||||
@@ -8,5 +8,7 @@ pub const registry = [_]Source{
|
||||
.{ .name = "std.encoding.hex", .file = "std/encoding/hex.aji", .source = @embedFile("std_encoding_hex_aji") },
|
||||
.{ .name = "std.fmt", .file = "std/fmt.aji", .source = @embedFile("std_fmt_aji") },
|
||||
.{ .name = "std.math", .file = "std/math.aji", .source = @embedFile("std_math_aji") },
|
||||
.{ .name = "std.option", .file = "std/option.aji", .source = @embedFile("std_option_aji") },
|
||||
.{ .name = "std.result", .file = "std/result.aji", .source = @embedFile("std_result_aji") },
|
||||
.{ .name = "std.utf8", .file = "std/utf8.aji", .source = @embedFile("std_utf8_aji") },
|
||||
};
|
||||
+56
-4
@@ -50,13 +50,18 @@ fn checkDeclarations(c: *Context) !void {
|
||||
}
|
||||
}
|
||||
|
||||
// E1003: an aggregate that contains itself by value has no finite size.
|
||||
try checkFiniteLayouts(c);
|
||||
}
|
||||
|
||||
/// E1003 applies through arrays as well as direct nominal members.
|
||||
pub fn checkFiniteLayouts(c: *Context) !void {
|
||||
const m = c.module;
|
||||
const state = try c.arena.alloc(enum { white, grey, black }, m.types.len);
|
||||
@memset(state, .white);
|
||||
for (0..m.types.len) |i| try visitDecl(c, state, @intCast(i));
|
||||
}
|
||||
|
||||
fn visitDecl(c: *Context, state: anytype, i: u32) !void {
|
||||
fn visitDecl(c: *Context, state: anytype, i: u32) std.mem.Allocator.Error!void {
|
||||
if (state[i] == .black) return;
|
||||
if (state[i] == .grey) {
|
||||
const d = c.module.types[i];
|
||||
@@ -66,12 +71,20 @@ fn visitDecl(c: *Context, state: anytype, i: u32) !void {
|
||||
}
|
||||
state[i] = .grey;
|
||||
switch (c.module.types[i].kind) {
|
||||
.@"struct" => |fs| for (fs) |f| if (f.ty == .named) try visitDecl(c, state, f.ty.named),
|
||||
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| if (t == .named) try visitDecl(c, state, t.named),
|
||||
.@"struct" => |fs| for (fs) |f| try visitValue(c, state, f.ty),
|
||||
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try visitValue(c, state, t),
|
||||
}
|
||||
state[i] = .black;
|
||||
}
|
||||
|
||||
fn visitValue(c: *Context, state: anytype, t: Type) std.mem.Allocator.Error!void {
|
||||
switch (t) {
|
||||
.named => |i| try visitDecl(c, state, i),
|
||||
.array => |a| try visitValue(c, state, a.elem),
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
const Position = enum { member, param, ret, block_param, borrowed };
|
||||
|
||||
/// Where a type may appear (spec 07 §8.3, §8.8):
|
||||
@@ -117,6 +130,16 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons
|
||||
}, owner);
|
||||
}
|
||||
|
||||
/// Validate a phantom or used source generic argument by ordinary type rules.
|
||||
pub fn checkTypeArgument(c: *Context, span: air.Span, t: Type) !void {
|
||||
try wellFormed(c, span, t, .param, "generic argument");
|
||||
try argumentLengths(c, span, t);
|
||||
}
|
||||
fn argumentLengths(c: *Context, span: air.Span, t: Type) !void {
|
||||
if (t == .array and (t.array.len == 0 or t.array.len > (1 << 32))) try c.report("E1001", span, "array length outside format-0 range", &.{});
|
||||
if (t.inner()) |inner| try argumentLengths(c, span, inner);
|
||||
}
|
||||
|
||||
/// `local.alloc` results are checked separately: their own type is storage.
|
||||
fn zeroable(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
@@ -338,6 +361,35 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic")
|
||||
}
|
||||
}
|
||||
|
||||
/// Structural Copy query for source constraints; borrows remain second-class.
|
||||
pub fn isCopy(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
.int, .bool, .builtin, .cap, .iref => true,
|
||||
.array => |a| isCopy(m, a.elem),
|
||||
.named => |i| aggregateAll(m, i, isCopy),
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Local is context-bound state, not the complement of Send (spec 15 §15).
|
||||
pub fn isLocalType(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
.local, .task, .scope, .shield, .guard => true,
|
||||
.ref, .mut, .slice, .slice_mut, .own, .own_array, .mutex => |inner| isLocalType(m, inner.*),
|
||||
.array => |a| isLocalType(m, a.elem),
|
||||
.named => |i| switch (m.types[i].kind) {
|
||||
.@"struct" => |fs| for (fs) |f| {
|
||||
if (isLocalType(m, f.ty)) break true;
|
||||
} else false,
|
||||
.@"enum" => |vs| blk: {
|
||||
for (vs) |v| for (v.payload) |p| if (isLocalType(m, p)) break :blk true;
|
||||
break :blk false;
|
||||
},
|
||||
},
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
/// `Send` (spec 04 §35): may move to another task.
|
||||
pub fn isSend(m: air.Module, t: Type) bool {
|
||||
return switch (t) {
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
# Aji standard library
|
||||
|
||||
Implementation in ordinary safe `.aji`: bytes, math, UTF-8, hex, Base64 and integer formatting, with 39 functions and 14 public result enums. They are embedded with the compiler and compiled through the normal frontend/verifier when imported. They are library modules, not standalone `main` programs.
|
||||
Implementation in ordinary safe `.aji`: bytes, math, UTF-8, hex, Base64 and integer formatting, with 39 monomorphic functions, 14 monomorphic result enums and Copy option/result templates with two generic helpers. They are embedded with the compiler and compiled through the normal frontend/verifier when imported. They are library modules, not standalone `main` programs.
|
||||
|
||||
```aji
|
||||
module example
|
||||
@@ -27,8 +27,10 @@ Endian APIs read/write u16/u32/u64 in LE/BE order. Reads return `std.bytes.ReadU
|
||||
|
||||
`std.fmt.write_u64/i64/usize/isize` write decimal ASCII into supplied buffers with `WriteResult::ok(count)` / `short_output`. Counts include a negative sign; short output stays unchanged, suffixes stay unchanged on success and no terminator is written. The [formatting example](../examples/std/format.aji) composes `value=-42 count=7` with explicit offsets and returns 17 without grants.
|
||||
|
||||
The compiler uses its embedded copy, so rebuild after editing these files. An installed compiler needs neither this checkout nor a runtime std search path. Standard enum types use fully qualified names in signatures, constructors and matches. Package imports and imported struct literals use explicit manifest mappings ([example](../examples/modules/aji.toml), spec 15 §14). Generics and owning collections remain future work.
|
||||
The compiler uses its embedded copy, so rebuild after editing these files. An installed compiler needs neither this checkout nor a runtime std search path. Standard enum types use fully qualified names in signatures, constructors and matches. Package imports and imported struct literals use explicit manifest mappings ([example](../examples/modules/aji.toml), spec 15 §14). Explicit generics and Copy option/result templates are implemented; owning collections still require linear_aggregates.
|
||||
|
||||
[API reference](../docs/reference/std.md) · [Specification](../docs/spec/16-standard-library.md) · [Plan](../docs/plan/standard-library.md) · [Import RFC](../docs/rfcs/0016-standard-library-bootstrap.md) · [Endian RFC](../docs/rfcs/0017-standard-endian-results.md) · [Bounded operations RFC](../docs/rfcs/0018-bounded-standard-operations.md) · [Text RFC](../docs/rfcs/0019-standard-text-encodings.md)
|
||||
|
||||
[Formatting RFC](../docs/rfcs/0020-supplied-buffer-integer-formatting.md)
|
||||
|
||||
`std.option.Option<T: Copy>` and `std.result.Result<T: Copy, E: Copy>` use explicit specialization and ordinary exhaustive enum matching. `is_some::<T>`/`is_ok::<T,E>` classify variants without allocation. [Generic example](../examples/std/generics.aji) returns 42; owners/resources/borrows are excluded by the Copy constraint.
|
||||
@@ -0,0 +1,12 @@
|
||||
module std.option
|
||||
|
||||
enum Option<T: Copy> { some(T), none }
|
||||
|
||||
fn is_some<T: Copy>(value: Option<T>) -> bool
|
||||
effects []
|
||||
{
|
||||
match value {
|
||||
Option::<T>::some(payload) => { return true; }
|
||||
Option::<T>::none => { return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
module std.result
|
||||
|
||||
enum Result<T: Copy, E: Copy> { ok(T), err(E) }
|
||||
|
||||
fn is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool
|
||||
effects []
|
||||
{
|
||||
match value {
|
||||
Result::<T, E>::ok(payload) => { return true; }
|
||||
Result::<T, E>::err(error_value) => { return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
; expect: run
|
||||
; result: 42
|
||||
; phase: 1
|
||||
; spec: docs/spec/07-air.md §8.3
|
||||
module demo.layout
|
||||
air 0
|
||||
lang 0.1
|
||||
features [arrays, ownership]
|
||||
type @Leaf = struct { value: u64 }
|
||||
type @Node = struct { child: array<@Leaf, 1> }
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%value = const.u64 42
|
||||
ret %value
|
||||
@@ -0,0 +1,25 @@
|
||||
; expect: run
|
||||
; result: 42
|
||||
; phase: 0
|
||||
; spec: docs/spec/15-source-language.md §15; docs/spec/07a-air-instructions.md
|
||||
module demo.generic
|
||||
air 0
|
||||
lang 0.1
|
||||
features []
|
||||
type @Option_u64 = enum { some(u64), none }
|
||||
fn @identity_u64(%value: u64) -> u64
|
||||
effects []
|
||||
entry:
|
||||
ret %value
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%value = const.u64 42
|
||||
%copied = call @identity_u64(%value)
|
||||
%option = enum.make @Option_u64.some(%copied)
|
||||
enum.switch @Option_u64 %option, some -> @present, none -> @absent
|
||||
present(%payload: u64):
|
||||
ret %payload
|
||||
absent:
|
||||
%zero = const.u64 0
|
||||
ret %zero
|
||||
@@ -0,0 +1,13 @@
|
||||
; expect: reject E1003
|
||||
; phase: 1
|
||||
; spec: docs/spec/07-air.md §8.3
|
||||
module demo.layout
|
||||
air 0
|
||||
lang 0.1
|
||||
features [arrays, ownership]
|
||||
type @Node = struct { child: array<@Node, 1> }
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%value = const.u64 42
|
||||
ret %value
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<u8, u64>(); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn id<T: Copy>(value: T) -> T effects [] { return value; }
|
||||
fn main() -> u64 effects [] { let v = id::<[u64; 2]>([21u64; 2]); return v[0] + v[1]; }
|
||||
@@ -0,0 +1,10 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// equivalent: generics/array_layout.air
|
||||
module demo.generic
|
||||
struct Leaf<T: Copy> { value: T }
|
||||
struct Node<T: Copy> { child: [Leaf<T>; 1] }
|
||||
fn unused(node: Node<u64>) -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<atomic<u128>>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn id<T>(value: T) -> T effects [] { return value; }
|
||||
fn main() -> u64 effects [] { return id<u64>(42); }
|
||||
@@ -0,0 +1,16 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generics
|
||||
struct Pair<T: Copy> { left: T, right: T }
|
||||
enum Maybe<T: Copy> { some(T), none }
|
||||
fn identity<T>(value: T) -> T effects [] { return value; }
|
||||
fn main() -> u64 effects [] {
|
||||
let p: Pair<u64> = Pair::<u64> { left: identity::<u64>(20), right: identity::<u64>(22) };
|
||||
let m = Maybe::<Pair<u64>>::some(p);
|
||||
match m {
|
||||
Maybe::<Pair<u64>>::some(pair) => { return pair.left + pair.right; }
|
||||
Maybe::<Pair<u64>>::none => { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn swap<T: Copy>(left: mut<T>, right: mut<T>) -> void effects [] {
|
||||
let saved = *left;
|
||||
*left = *right;
|
||||
*right = saved;
|
||||
}
|
||||
fn main() -> u64 effects [] { var a: u64 = 20; var b: u64 = 22; swap::<u64>(mut a, mut b); return a + b; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E2101 E2101
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn swap<T: Copy>(a: mut<T>, b: mut<T>) -> void effects [] { let v = *a; *a = *b; *b = v; }
|
||||
fn main() -> u64 effects [] { var a: u64 = 42; swap::<u64>(mut a, mut a); return a; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn read<T: Copy>(value: ref<T>) -> T effects [] { return *value; }
|
||||
fn main() -> u64 effects [] { var value: u64 = 42; return read::<u64>(ref value); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.constraints
|
||||
struct Pair { a: u64, b: u64 }
|
||||
fn plain<T: Copy + Send + Share + Freeze>() -> u64 effects [] { return 40; }
|
||||
fn context<T: Local>() -> u64 effects [] { return 2; }
|
||||
fn main() -> u64 effects [] { return plain::<Pair>() + context::<task<u64>>(); }
|
||||
@@ -0,0 +1,12 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
enum Kind { value }
|
||||
fn copy<T: Copy>() -> u64 effects [] { return 10; }
|
||||
fn send<T: Send>() -> u64 effects [] { return 10; }
|
||||
fn share<T: Share>() -> u64 effects [] { return 10; }
|
||||
fn freeze<T: Freeze>() -> u64 effects [] { return 10; }
|
||||
fn local<T: Local>() -> u64 effects [] { return 2; }
|
||||
fn main() -> u64 effects [] { return copy::<cap<io.write>>() + send::<own<u64>>() + share::<mutex<u64>>() + freeze::<[Kind; 2]>() + local::<task<u64>>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Copy>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<ref<u64>>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.constraint
|
||||
fn marker<T: Copy>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<own<u64>>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Copy + Copy>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct Pair<T> { value: T, value: T }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T, T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// grant: out=io.write
|
||||
// stdout: generic
|
||||
module demo.generic
|
||||
fn emit<T>(out: cap<io.write>) -> u64 effects [io.write] { io.stdout_write(out, b"generic") or trap; return 42; }
|
||||
fn main(out: cap<io.write>) -> u64 effects [io.write] { return emit::<u64>(out); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E3101
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn emit<T>(out: cap<io.write>) -> u64 effects [io.write] { io.stdout_write(out, b"generic") or trap; return 42; }
|
||||
fn main(out: cap<io.write>) -> u64 effects [] { return emit::<u64>(out); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn grow<T>() -> u64 effects [] { return grow::<[T; 2]>(); }
|
||||
fn main() -> u64 effects [] { return grow::<u8>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Freeze>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<cap<io.write>>(); }
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn main<T>() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E1003
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct Node<T> { child: [Node<T>; 1] }
|
||||
fn main() -> u64 effects [] { var node: Node<u64> = zero; return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
module app.lib
|
||||
struct Pair<T: Copy> { value: T }
|
||||
enum Maybe<T: Copy> { some(Pair<T>), none }
|
||||
fn wrap<T: Copy>(value: T) -> Maybe<T> effects [] { return Maybe::<T>::some(Pair::<T> { value: value }); }
|
||||
fn unwrap<T: Copy>(value: Maybe<T>) -> T effects [] { match value { Maybe::<T>::some(pair) => { return pair.value; } Maybe::<T>::none => { trap; } } }
|
||||
fn identity<T: Copy>(value: T) -> T effects [] { return value; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E0006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct Cell<T> { value: T }
|
||||
fn unused(value: Cell<own<u64>>) -> u64 effects [] { return 0; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Local>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<u64>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<t>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7002
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// module: app.lib=source/generics/lib.aji.inc
|
||||
module demo.generic
|
||||
fn main() -> u64 effects [] { return app.lib.identity::<u64>(42); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// module: app.lib=source/generics/lib.aji.inc
|
||||
module demo.generic
|
||||
import app.lib;
|
||||
struct Local { value: u64 }
|
||||
fn main() -> u64 effects [] { let app = 7u8; assert(app == 7); let own = Local { value: 42 }; let wrapped = app.lib.wrap::<Local>(own); return app.lib.unwrap::<Local>(wrapped).value; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<u64>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E1003
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct Node { child: [Node; 1] }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<ref<ref<u64>>>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<own<own<u64>>>(); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct Cell<T: Copy> { value: T }
|
||||
fn read(value: Cell<u64>) -> u64 effects [] { return value.value; }
|
||||
fn main() -> u64 effects [] { return read(Cell::<u8> { value: 42 }); }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// equivalent: generics/option.air
|
||||
module demo.generic
|
||||
import std.option;
|
||||
fn identity<T: Copy>(value: T) -> T effects [] { return value; }
|
||||
fn main() -> u64 effects [] { let v = std.option.Option::<u64>::some(identity::<u64>(42)); match v { std.option.Option::<u64>::some(n) => { return n; } std.option.Option::<u64>::none => { return 0; } } }
|
||||
@@ -0,0 +1,12 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// grant: heap=mem.alloc:64
|
||||
module demo.generic
|
||||
fn identity<T>(value: T) -> T effects [] { return move value; }
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
||||
let value = own.new(42u64, heap) or trap;
|
||||
let returned = identity::<own<u64>>(move value);
|
||||
return own.take(move returned);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7003
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn identity<T>(value: T) -> T effects [] { return move value; }
|
||||
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] { let value = own.new(42u64, heap) or trap; let v = identity::<own<u64>>(value); return own.take(move v); }
|
||||
@@ -0,0 +1,10 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn repeat<T: Copy>(value: T, n: u64) -> T effects [] {
|
||||
if n == 0 { return value; }
|
||||
return repeat::<T>(value, n - 1);
|
||||
}
|
||||
fn main() -> u64 effects [] { return repeat::<u64>(42, 10); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Send>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<task<u64>>(); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct T { x: u64 }
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Share>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<region>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7002
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn bad<T: Copy>(value: T) -> T effects [] { return does_not_exist(value); }
|
||||
fn main() -> u64 effects [] { return bad::<u64>(42); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7004
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
import std.option;
|
||||
fn main() -> u64 effects [] { let v = std.option.Option::<u64>::some(42); match v { std.option.Option::<u64>::some(n) => { return n; } } }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
import std.option;
|
||||
fn unused(value: std.option.Option<own<u64>>) -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,23 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
import std.option;
|
||||
import std.result;
|
||||
fn main() -> u64 effects [] {
|
||||
let absent = std.option.Option::<u8>::none;
|
||||
assert(not std.option.is_some::<u8>(absent));
|
||||
let present: std.option.Option<u64> = std.option.Option::<u64>::some(42);
|
||||
assert(std.option.is_some::<u64>(present));
|
||||
let failure = std.result.Result::<u64, u8>::err(7);
|
||||
assert(not std.result.is_ok::<u64, u8>(failure));
|
||||
match present {
|
||||
std.option.Option::<u64>::some(value) => {
|
||||
let success = std.result.Result::<u64, u8>::ok(value);
|
||||
assert(std.result.is_ok::<u64, u8>(success));
|
||||
match success { std.result.Result::<u64, u8>::ok(n) => { return n; } std.result.Result::<u64, u8>::err(e) => { return e as u64; } }
|
||||
}
|
||||
std.option.Option::<u64>::none => { return 0; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
import std.result;
|
||||
fn unused(value: std.result.Result<u64, ref<u8>>) -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// schedules: 8
|
||||
module demo.generic
|
||||
fn worker<T: Copy + Send>(value: T) -> T effects [] { return value; }
|
||||
fn main() -> u64 effects [task.spawn, task.wait] { var result: u64 = 0; scope s { let t = task.spawn(s, worker::<u64>, 42); result = task.join(move t); } return result; }
|
||||
@@ -0,0 +1,12 @@
|
||||
// expect: run
|
||||
// result: [20,20,22,22]
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
// schedules: 8
|
||||
module demo.generic
|
||||
fn fill<T: Copy + Send>(data: slice_mut<T>, value: T) -> void effects [] { for i in 0..data.len { data[i] = value; } }
|
||||
fn main() -> [u64; 4] effects [task.spawn] {
|
||||
var data: [u64; 4] = zero;
|
||||
{ mut all = data; let (l, r) = all.split_at(2); scope s { let a = task.spawn(s, fill::<u64>, l, 20); let b = task.spawn(s, fill::<u64>, r, 22); task.join(move a); task.join(move b); } }
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E4101
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn fill<T: Copy + Send>(data: slice_mut<T>, value: T) -> void effects [] { data[0] = value; }
|
||||
fn main() -> u64 effects [task.spawn] { var data: [u64; 2] = zero; { mut all = data; scope s { let a = task.spawn(s, fill::<u64>, all, 20); let b = task.spawn(s, fill::<u64>, all, 22); task.join(move a); task.join(move b); } } return data[0]; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
enum Value<T: Copy> { some(T) }
|
||||
fn main() -> u64 effects [] { let v = Value::<own<u64>>::some(0); return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
struct Pair<T: Copy> { value: T }
|
||||
fn main() -> u64 effects [] { let p: Pair = Pair { value: 42 }; return p.value; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T: Unknown>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn unused<T: Copy>(value: T) -> T effects [] { return does_not_exist(value); }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> T effects [] trusted "proof" { trap; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E0006
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> T effects [unknown] { trap; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7002
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>(value: Typo) -> T effects [] { trap; }
|
||||
fn main() -> u64 effects [] { return 42; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<void>(); }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
module demo.generic
|
||||
fn marker<T>() -> u64 effects [] { return 42; }
|
||||
fn main() -> u64 effects [] { return marker::<[u64; 0]>(); }
|
||||
@@ -0,0 +1,16 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §15
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Source generic CLI integration; finite programs use interpreter fuel."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
AJI = REPO / "zig-out/bin/aji"
|
||||
checks = 0
|
||||
|
||||
|
||||
def cli(*args, code=0):
|
||||
global checks
|
||||
run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
|
||||
assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr)
|
||||
checks += 1
|
||||
return run.stdout
|
||||
|
||||
|
||||
example = REPO / "examples/std/generics.aji"
|
||||
assert json.loads(cli("run", "--fuel", "1000000", example))["value"] == 42
|
||||
cli("check", example)
|
||||
cli("report", example)
|
||||
cli("explore", "--max-runs", "8", example)
|
||||
canonical = cli("lower", example)
|
||||
assert cli("lower", example) == canonical
|
||||
with tempfile.TemporaryDirectory(prefix="aji-generics-") as directory:
|
||||
root = Path(directory)
|
||||
air = root / "result.air"
|
||||
air.write_text(canonical)
|
||||
cli("check", air)
|
||||
assert json.loads(cli("run", "--fuel", "1000000", air))["value"] == 42
|
||||
entry = root / "main.aji"
|
||||
lib = root / "lib.aji"
|
||||
manifest = root / "aji.toml"
|
||||
manifest.write_text('[package]\nname = "fixture"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.lib = "lib.aji"\n')
|
||||
lib.write_text("module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return value; }\n")
|
||||
entry.write_text("module app.entry\nimport app.lib;\nstruct Pair { value: u64 }\nfn main() -> u64 effects [] { return app.lib.id::<Pair>(Pair { value: 42 }).value; }\n")
|
||||
assert json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest))["value"] == 42
|
||||
cli("report", "--manifest", manifest)
|
||||
cli("explore", "--max-runs", "8", "--manifest", manifest)
|
||||
assert "__aji_g_" in cli("lower", "--manifest", manifest)
|
||||
lib.write_text("module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { assert(false); return value; }\n")
|
||||
record = json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest, code=4))
|
||||
assert record["source_location"]["file"] == "lib.aji"
|
||||
lib.write_text("module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return missing(value); }\n")
|
||||
error = json.loads(cli("check", "--manifest", manifest, code=1))
|
||||
assert error["code"] == "E7002" and error["file"] == "lib.aji"
|
||||
lib.write_text("module app.lib\nfn id<T: Copy>(value: T) -> T effects [] { return value; }\n")
|
||||
entry.write_text("module app.entry\nimport app.lib;\nfn main() -> u64 effects [] { return app.lib.id::<own<u64>>(0); }\n")
|
||||
for command in ("check", "lower", "report", "run", "explore"):
|
||||
error = json.loads(cli(command, "--manifest", manifest, code=1))
|
||||
assert error["code"] == "E7005" and error["constraint"] == "Copy" and error["parameter"] == "T"
|
||||
entry.write_text("module app.entry\nimport app.lib;\nfn main() -> u64 effects [] { return app.lib.id::<u64>(); }\n")
|
||||
error = json.loads(cli("check", "--manifest", manifest, code=1))
|
||||
assert error["function"] == "app.lib.id<u64>"
|
||||
print(f"source generic CLI integration passed ({checks} checks)")
|
||||
@@ -20,6 +20,12 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source")
|
||||
|
||||
# (area, construct, regex, needs a reject test)
|
||||
CHECKLIST = [
|
||||
("generics", "generic function declaration", r"fn \w+<", True),
|
||||
("generics", "generic struct/enum declaration", r"(?:struct|enum) \w+<", True),
|
||||
("generics", "explicit function/worker application", r"[a-z]\w*::<", True),
|
||||
("generics", "applied generic type", r": (?:[a-z]\w*\.)*[A-Z]\w*<", True),
|
||||
("generics", "generic constructor/pattern", r"[A-Z]\w*::<", True),
|
||||
("generics", "structural property constraint", r"[A-Z]\w*: (?:Copy|Send|Share|Freeze|Local)", True),
|
||||
("modules", "package module import", r"^import app\.", True),
|
||||
("modules", "qualified package call", r"app\.\w+\.[a-z]\w*\(", True),
|
||||
("modules", "qualified struct literal", r"app\.\w+\.[A-Z]\w* \{", True),
|
||||
|
||||
Reference in new issue
Block a user