From c96199e7eca1225b08cd35ac6220dc75b5a2dcf3 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Tue, 6 Oct 2026 18:51:54 +0300 Subject: [PATCH] cli: add explicit package source modules Link manifest-selected source graphs with module-local names, qualified structs/enums/functions and task workers through ordinary AIR verification. Keep source inputs bounded, reject source symlinks and preserve explicit grants, diagnostics and deterministic canonical lowering. Integrate spec 12/15, RFC 0021, source reference budgets, roadmap, examples and CI coverage. Validate 579 conformance tests, unit tests, 76 source constructs, hosted smoke, 36 package CLI checks and task schedule stress. --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 1 + docs/agent/README.md | 2 + docs/agent/quick-reference.md | 27 ++++ docs/agent/source-bundle.txt | 6 +- docs/agent/source-notes.md | 3 +- docs/design/open-questions.md | 6 + docs/plan/phase-6-source-language.md | 4 +- docs/plan/standard-library.md | 10 +- docs/reference/grammar.ebnf | 6 +- docs/rfcs/0021-package-source-modules.md | 117 ++++++++++++++ docs/spec/12-packages-and-build.md | 25 ++- docs/spec/15-source-language.md | 45 +++++- examples/modules/aji.toml | 7 + examples/modules/main.aji | 9 ++ examples/modules/model.aji | 7 + src/check.zig | 71 +++++++- src/frontend.zig | 7 +- src/frontend/ast.zig | 10 +- src/frontend/lower.zig | 108 +++++++++---- src/frontend/modules.zig | 152 ++++++++++++++++++ src/frontend/parse.zig | 41 +++-- src/frontend/stdlib.zig | 96 +---------- src/main.zig | 140 ++++++++-------- src/manifest.zig | 63 +++++++- src/root.zig | 1 + src/source_package.zig | 91 +++++++++++ std/README.md | 2 +- tests/conformance/README.md | 1 + tests/conformance/modules/nominal_call.air | 21 +++ tests/conformance/modules/record.air | 24 +++ tests/conformance/source/modules/alias.aji | 7 + .../source/modules/bad_member.aji.inc | 2 + .../source/modules/bad_syntax.aji.inc | 2 + tests/conformance/source/modules/borrow.aji | 8 + .../conformance/source/modules/borrow.aji.inc | 2 + .../conformance/source/modules/collision.aji | 14 ++ tests/conformance/source/modules/cycle.aji | 8 + .../source/modules/cycle_a.aji.inc | 3 + .../source/modules/cycle_b.aji.inc | 2 + .../source/modules/duplicate_binding.aji | 8 + .../source/modules/duplicate_import.aji | 8 + .../source/modules/duplicate_member.aji | 7 + .../source/modules/duplicate_member.aji.inc | 3 + .../conformance/source/modules/effect.aji.inc | 2 + tests/conformance/source/modules/effects.aji | 10 ++ .../source/modules/error_in_unused_member.aji | 7 + tests/conformance/source/modules/example.aji | 14 ++ .../source/modules/example_model.aji.inc | 7 + tests/conformance/source/modules/fields.aji | 14 ++ .../conformance/source/modules/fields.aji.inc | 6 + .../source/modules/mismatched_module.aji | 7 + .../source/modules/missing_effect.aji | 7 + .../source/modules/missing_field.aji | 7 + .../source/modules/missing_module.aji | 6 + .../source/modules/missing_move.aji | 7 + .../conformance/source/modules/model.aji.inc | 9 ++ .../source/modules/no_short_import.aji | 7 + tests/conformance/source/modules/nominal.aji | 9 ++ .../conformance/source/modules/other.aji.inc | 3 + tests/conformance/source/modules/owner.aji | 9 ++ .../conformance/source/modules/owner.aji.inc | 2 + tests/conformance/source/modules/record.aji | 22 +++ .../conformance/source/modules/root_self.aji | 8 + .../source/modules/self_import.aji | 6 + .../source/modules/syntax_in_module.aji | 7 + tests/conformance/source/modules/task.aji | 9 ++ .../conformance/source/modules/task_lend.aji | 31 ++++ .../source/modules/task_lend_twice.aji | 23 +++ .../source/modules/task_missing_import.aji | 13 ++ .../source/modules/transitive_call.aji | 8 + .../source/modules/transitive_enum.aji | 8 + .../source/modules/transitive_type.aji | 8 + .../source/modules/unknown_member.aji | 7 + .../source/modules/unreachable.aji | 7 + tests/conformance/source/modules/work.aji.inc | 5 + .../source/modules/workers.aji.inc | 3 + tests/conformance/source/quickref/modules.aji | 14 ++ tests/hosted/source_modules.py | 139 ++++++++++++++++ tools/conformance.zig | 20 ++- tools/source_coverage.py | 4 + 81 files changed, 1419 insertions(+), 234 deletions(-) create mode 100644 docs/rfcs/0021-package-source-modules.md create mode 100644 examples/modules/aji.toml create mode 100644 examples/modules/main.aji create mode 100644 examples/modules/model.aji create mode 100644 src/frontend/modules.zig create mode 100644 src/source_package.zig create mode 100644 tests/conformance/modules/nominal_call.air create mode 100644 tests/conformance/modules/record.air create mode 100644 tests/conformance/source/modules/alias.aji create mode 100644 tests/conformance/source/modules/bad_member.aji.inc create mode 100644 tests/conformance/source/modules/bad_syntax.aji.inc create mode 100644 tests/conformance/source/modules/borrow.aji create mode 100644 tests/conformance/source/modules/borrow.aji.inc create mode 100644 tests/conformance/source/modules/collision.aji create mode 100644 tests/conformance/source/modules/cycle.aji create mode 100644 tests/conformance/source/modules/cycle_a.aji.inc create mode 100644 tests/conformance/source/modules/cycle_b.aji.inc create mode 100644 tests/conformance/source/modules/duplicate_binding.aji create mode 100644 tests/conformance/source/modules/duplicate_import.aji create mode 100644 tests/conformance/source/modules/duplicate_member.aji create mode 100644 tests/conformance/source/modules/duplicate_member.aji.inc create mode 100644 tests/conformance/source/modules/effect.aji.inc create mode 100644 tests/conformance/source/modules/effects.aji create mode 100644 tests/conformance/source/modules/error_in_unused_member.aji create mode 100644 tests/conformance/source/modules/example.aji create mode 100644 tests/conformance/source/modules/example_model.aji.inc create mode 100644 tests/conformance/source/modules/fields.aji create mode 100644 tests/conformance/source/modules/fields.aji.inc create mode 100644 tests/conformance/source/modules/mismatched_module.aji create mode 100644 tests/conformance/source/modules/missing_effect.aji create mode 100644 tests/conformance/source/modules/missing_field.aji create mode 100644 tests/conformance/source/modules/missing_module.aji create mode 100644 tests/conformance/source/modules/missing_move.aji create mode 100644 tests/conformance/source/modules/model.aji.inc create mode 100644 tests/conformance/source/modules/no_short_import.aji create mode 100644 tests/conformance/source/modules/nominal.aji create mode 100644 tests/conformance/source/modules/other.aji.inc create mode 100644 tests/conformance/source/modules/owner.aji create mode 100644 tests/conformance/source/modules/owner.aji.inc create mode 100644 tests/conformance/source/modules/record.aji create mode 100644 tests/conformance/source/modules/root_self.aji create mode 100644 tests/conformance/source/modules/self_import.aji create mode 100644 tests/conformance/source/modules/syntax_in_module.aji create mode 100644 tests/conformance/source/modules/task.aji create mode 100644 tests/conformance/source/modules/task_lend.aji create mode 100644 tests/conformance/source/modules/task_lend_twice.aji create mode 100644 tests/conformance/source/modules/task_missing_import.aji create mode 100644 tests/conformance/source/modules/transitive_call.aji create mode 100644 tests/conformance/source/modules/transitive_enum.aji create mode 100644 tests/conformance/source/modules/transitive_type.aji create mode 100644 tests/conformance/source/modules/unknown_member.aji create mode 100644 tests/conformance/source/modules/unreachable.aji create mode 100644 tests/conformance/source/modules/work.aji.inc create mode 100644 tests/conformance/source/modules/workers.aji.inc create mode 100644 tests/conformance/source/quickref/modules.aji create mode 100644 tests/hosted/source_modules.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e1894d..5ee75b9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,7 @@ jobs: - run: zig build conformance - run: zig build conformance -- --stress 200 - run: zig build && python3 tests/hosted/smoke.py + - run: python3 tests/hosted/source_modules.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) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a14175b..6ff74f9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,7 @@ zig build conformance # conformance suite, see tests/conformance/README.m 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 (cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests zig fmt --check build.zig src tools ``` diff --git a/docs/agent/README.md b/docs/agent/README.md index 148ac65..a36de82 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -100,3 +100,5 @@ RFC 0018 bounded operations (cl100k, relative to endian): Quick Reference 6,000 RFC 0019 text/encodings (cl100k, relative to bounded): Quick Reference 6,082 → 6,163 (+1.3%); other source docs 33,628 → 36,042 (+7.2%); full source docs excluding AIR 39,710 → 42,205 (+6.3%). The library page is 6,644 tokens. AIR remains unchanged. UTF-8, hex and canonical Base64 use existing primitives and fixed frame tables. Cumulative full source growth since the pre-stdlib baseline is +24.2%, above the 20% review line; RFC 0019 records the justification and owner-review scope. Future API references should be split/read selectively instead of expanding the front-door catalog. 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. diff --git a/docs/agent/quick-reference.md b/docs/agent/quick-reference.md index 4536fe1..8e1f75b 100644 --- a/docs/agent/quick-reference.md +++ b/docs/agent/quick-reference.md @@ -360,3 +360,30 @@ The usual enum rules apply: missing arm `E7004`, wrong enum/payload `E7005`, unk `std.utf8` validates bytes and decodes the next scalar with an explicit consumed count. `std.encoding.hex` and `std.encoding.base64` encode/decode into `mut` output slices; ordinary enum results expose malformed input and short capacity, leaving output unchanged on errors. Base64 accepts canonical padded standard encoding. Signatures and a checked example are in `/docs/library/std.md`. `std.fmt.write_u64/i64/usize/isize` write decimal integers into supplied output slices; `WriteResult::ok(count)` / `short_output` expose capacity, with unchanged output on failure. Composition and signatures are in `/docs/library/std.md`. + +## 11. Package modules + +Declare package inputs explicitly in `aji.toml`: + +```toml +[package] +entry = "main.aji" +[modules] +app.model = "model.aji" +``` + +`model.aji` declares `module app.model`. Import it directly; functions, structs and enums use full names. Short names stay local to their defining module; imports grant no authority or transitive name visibility. + +```aji +module app.entry +import app.model; + +fn main() -> u64 +effects [] +{ + let pair = app.model.Pair { left: 20, right: 22 }; + return app.model.total(pair); +} +``` + +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. diff --git a/docs/agent/source-bundle.txt b/docs/agent/source-bundle.txt index 1a22854..5b00ad9 100644 --- a/docs/agent/source-bundle.txt +++ b/docs/agent/source-bundle.txt @@ -9,7 +9,7 @@ > QUICK.md docs/agent/quick-reference.md -docs/agent/source-notes.md :: ## 11. Where to read more +docs/agent/source-notes.md :: ## 12. Where to read more > language/syntax.md docs/reference/grammar.ebnf @@ -21,6 +21,10 @@ docs/spec/15-source-language.md :: ## 6. Fallible operations and `match` docs/spec/15-source-language.md :: ## 13. Built-in standard modules +> 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 + > library/std.md docs/spec/16-standard-library.md docs/reference/std.md diff --git a/docs/agent/source-notes.md b/docs/agent/source-notes.md index 3bf213e..87a950f 100644 --- a/docs/agent/source-notes.md +++ b/docs/agent/source-notes.md @@ -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. -## 11. Where to read more +## 12. 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` | +| 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` | | borrows, scopes, frame storage, slices, initialization | `/docs/language/ownership.md` | diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index d476418..a1cd5c7 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -236,3 +236,9 @@ UTF-8 needs a scalar-level iteration contract without an owning iterator. Hex/Ba Formatting needs a defined byte representation, insufficient-capacity state and signed-minimum behavior before a library promises arbitrary integer output. A format-string parser or growable writer would add contracts beyond the supplied-buffer milestone. **Resolved in the STD-2b branch:** spec 16 §2.8 defines decimal writers for u64/i64 and target-width usize/isize with one ordinary result enum. Complete capacity is checked before mutation, successful counts include the sign, suffixes stay unchanged and no terminator is emitted. Signed minimum is supported without negating it directly. RFC 0020 records the proposal. General formatting, other widths, floats and parsing remain separate work; explicit caller offsets compose records with existing byte copy. + +## Q-032 — Package module resolution and namespace boundaries + +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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 87001e3..3a624dd 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -132,7 +132,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 | todo | Modules, imports, name resolution | P6-2 | `src/frontend/resolve.zig` | unresolved names produce 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-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 | @@ -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 std bootstrap and endian increment implement a closed two-module import subset and qualified standard enum types/constructors/patterns (`STD-0/1a`, [plan](standard-library.md)). P6-3 remains open for general user modules, imported struct literals and dependency resolution. P6-4 remains open for generics. No full Phase 6 task is marked complete by that subset. +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. diff --git a/docs/plan/standard-library.md b/docs/plan/standard-library.md index 2babf62..6445311 100644 --- a/docs/plan/standard-library.md +++ b/docs/plan/standard-library.md @@ -21,7 +21,7 @@ Without external source dependencies, Aji should support ordinary CLI tools, sto | Scalars, structs/enums, slices/arrays, explicit borrows | implemented | pure fixed-storage algorithms can start now | | Heap/regions, I/O, files, TCP, clock/random, structured tasks/channels/mutex | implemented primitives | wrappers can reuse them, but their presence does not imply the complete APIs below | | Built-in standard imports and enum types | STD-0/1a/2a/2b branch implementation | compiler-pinned, closed registry; six modules; qualified enum types/constructors/patterns; no package lookup | -| General modules/imported struct literals | P6-3 pending | needed before publishing owning collection types | +| 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`, `HashMap`, 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 | @@ -51,7 +51,7 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob | STD-1b | done (branch implementation; RFC Proposed) | bounded copy/search, split composition and recoverable arithmetic for u64/usize | STD-1a | contracts define capacity/overflow failure, no partial mutation, empty inputs and aliasing; independent fixtures pass | | STD-2a | done (branch implementation; RFC Proposed) | UTF-8 next/validate and supplied-buffer hex/base64 | STD-1a/1b | malformed text and insufficient capacity are explicit, output unchanged on returned errors; independent vectors and boundary cases pass | | STD-2b | done (branch implementation; RFC Proposed) | decimal u64/i64/usize/isize formatting into supplied buffers | STD-2a | minimal explicit format contract, no implicit heap, capacity/empty/maximal scalar tests and caller example | -| STD-3 | todo | general modules and imported type names (P6-3) | STD-0 | deterministic resolution, collisions/cycles and diagnostics specified and covered | +| 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-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 | @@ -102,3 +102,9 @@ All algorithms are safe source using existing verifier/runtime rules, fixed fram Four safe decimal writers and one ordinary result enum complete the supplied-buffer formatting increment. No heap, retained cursor, format-string language, runtime primitive or syntax is added. Counts include a negative sign, suffixes remain unchanged and insufficient capacity preserves the complete destination. Counting precedes mutation; signed magnitude uses `-(value + 1)` then an unsigned increment, avoiding signed-minimum negation. Explicit caller offsets and `std.bytes.copy` compose a record; failure preserves the individual call's destination, not earlier successful calls. Spec 16 §2.8 and RFC 0020 specify the invariant, existing verifier/runtime rules, valid/rejected examples, diagnostic impact, deterministic execution and unchanged AIR format 0. Independent Python decimal vectors exercise zero, all small values, decimal/binary transitions, seeded scalar inputs, both 64-bit limits and every capacity from zero through 22, checking all guard/suffix bytes. Target-width fixtures guard conversions against the target limits; the current interpreter executes at air64. Source/AIR result equivalence, explicit record composition, disjoint borrows, qualified types/collisions and rejection of conflicting borrows (including short output), missing imports, invalid payloads/types and incomplete matches cover the public boundary. RFC 0020 records required checks and source/AIR documentation budgets. Next semantic prerequisites for owning buffers and containers remain STD-3/4/5; a decimal writer does not complete general formatting or owning strings. + +## STD-3 verification + +P6-3 now links explicit package sources through the same frontend as compiler-pinned std. Manifest mappings supply source bytes; pure linking checks an acyclic graph, module identity and direct-import visibility, then emits collision-free deterministic AIR. Imported functions, structs, enums and qualified task workers use existing ownership, lifetime, effect and scheduler rules. Check/lower/report instantiate no grants; run/explore use explicit manifest grants and overrides. Package sources have portable bounded paths, no symlink traversal and a 64 MiB aggregate source budget; file-only commands never discover manifests. + +RFC 0021 records invariants, diagnostics, compatibility, complete validation and documentation growth. General modules and imported struct literals are implemented on this branch; dependencies and external package resolution are separate work. The next semantic step is STD-4/P6-4 generics and structural constraints, followed by the independent linear-aggregate gate. Owning collections still require both gates. diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf index 2011904..0aa6d58 100644 --- a/docs/reference/grammar.ebnf +++ b/docs/reference/grammar.ebnf @@ -12,8 +12,8 @@ - Every construct has one canonical spelling (spec 15 §1). *) -module = "module" path { std_import } { item } ; -std_import = "import" path ";" ; (* contextual word, spec 15 §13 *) +module = "module" path { module_import } { item } ; +module_import = "import" path ";" ; (* contextual word, spec 15 §13/§14 *) item = type_decl | fn_decl ; path = ident { "." ident } ; @@ -88,7 +88,7 @@ postfix = primary { "." 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 [ "{" field_init { "," field_init } [ "," ] "}" ] (* struct literal *) + | ident | path "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *) | path "::" ident (* enum variant; applied by a call *) | "[" expr ";" int_lit "]" | "(" expr ")" diff --git a/docs/rfcs/0021-package-source-modules.md b/docs/rfcs/0021-package-source-modules.md new file mode 100644 index 0000000..547d7f9 --- /dev/null +++ b/docs/rfcs/0021-package-source-modules.md @@ -0,0 +1,117 @@ +# RFC 0021: Explicit package source modules + +Status: Proposed +Scope: STD-3 / P6-3; source language 0.1, AIR format 0 unchanged + +The branch contains the proposed normative text, implementation and tests. Only the language owner changes RFC acceptance status. + +## Motivation and decision + +Reusable library types need module identity, local name binding and explicit compiler inputs before generics or owning collections can have stable contracts. Extend the existing compiler-pinned standard import mechanism to an explicit source provider. The CLI obtains this provider solely from a selected manifest's `[modules]` map; the frontend accepts source bytes and diagnostic paths, without filesystem access. General package dependency resolution is separate work. + +Spec 12 §1.3 defines the manifest and loading contract; spec 15 §14 defines the graph and namespace rules. The standard registry remains compiler-pinned and cannot be shadowed. Every declaration and field is available through a direct import. All reachable declarations, including unused helpers, lower and verify. There are no aliases, re-exports, visibility modifiers or executable module initialization. + +Imports form an acyclic graph. Header mismatch, duplicate imports/mappings and cycles reject; unreachable mapped files must be readable explicit inputs but are not parsed. Fixed limits are 1,024 mapped modules, graph depth 256, 1 MiB manifest and 64 MiB aggregate source snapshot. Cached graph heights count shared tails toward the depth limit. Modules append in lexicographic order, declarations in source order, using existing collision-free AIR mangling. Entry AIR names remain unchanged; only its unqualified `main` is the entry. + +Each module sees its own short names and directly imported full names. Linked transitive declarations do not become name-visible. A function can return a type inferred by its caller without the caller importing that type's module, but explicitly naming/constructing it requires a direct import. Qualified names resolve independently of local values with the same prefix. Module identity is carried separately from diagnostic filenames, so identical file labels cannot alter binding. Imported function `main` is an ordinary qualified function. + +Qualified struct literals use `app.model.Pair { left: 20, right: 22 }`, retaining the existing uppercase-final-component and condition-brace grammar rules. `task.spawn(s, app.work.run, args)` resolves a static function and emits the existing `task.spawn` instruction with its actual mangled AIR name. Built-in namespaces remain reserved for provider bindings; legacy entry names and built-in precedence stay compatible. + +## Memory, ownership and concurrency invariant + +Importing does not create authority, allocate program heap, retain borrows, share mutable storage, change resource consumption or introduce implicit cleanup. Every cross-module call has the same explicit signature and ownership/effect obligations as a local call. Named linear arguments still require `move`; mutable borrows remain exclusive and within lifetime; task lends remain unavailable until join; all linear values/resources are consumed on every path. + +## Verifier rule + +The frontend binds nominal types and static functions, then submits one combined ordinary AIR module. The existing type, call, initialization, alias, lifetime, resource, effect, Send/Share and task transfer functions apply unchanged. Imported code is never trusted simply because it is imported. Every reachable function is checked even if unused. No new verifier state, transfer function, AIR instruction or feature is introduced; the combined module declares existing feature dependency closure. Format-0 meaning is unchanged. + +## Runtime rule and deterministic behavior + +No runtime module loader, dispatch, initialization or new primitive exists. The interpreter executes ordinary mangled function calls, struct/enum operations and structured tasks. The same explicit source bytes and bindings produce identical canonical AIR across mapping/import orders, directories, diagnostic filenames and execution profiles. First graph errors follow source import order. Imported diagnostics and traps name the supplied source file. Existing interpreter fuel, deterministic scheduler and hosted profiles remain unchanged. + +The CLI snapshots explicit package input files relative to the selected manifest directory. Portable `.aji` paths reject absolute paths, empty/dot/parent components, backslashes, colons and NUL. Descent keeps directory handles open and uses no-follow opens; source leaves must be regular files, checked before open and again on their handles. Symlinks, directories and static pipes reject rather than execute or block on input. These checks do not promise an atomic filesystem snapshot under concurrent writes; compilation is deterministic from the bytes actually read. Legacy manifests without `[modules]` retain their loading contract. + +Check/lower/report select source inputs without instantiating grants. Run/explore merge only explicitly selected manifest grants and command-line overrides. A file-only command never discovers a manifest. `lower --stats` compares entry source bytes against the combined AIR; it is explicitly not a whole-package compression metric. + +## Valid examples + +`examples/modules/aji.toml` maps `app.model` to `model.aji`. The model defines a plain Copy struct and an ordinary function: + +```aji +module app.model +struct Pair { left: u64, right: u64 } +fn total(pair: Pair) -> u64 effects [] { return pair.left + pair.right; } +``` + +```aji +module app.entry +import app.model; +fn main() -> u64 effects [] { + let pair = app.model.Pair { left: 20, right: 22 }; + return app.model.total(pair); +} +``` + +`aji run --fuel 1000000 --manifest examples/modules/aji.toml` returns 42 without grants. Source conformance also passes an owner with explicit `move` to an imported disposal function and lends disjoint slices to two qualified task workers. The latter has a hand-written AIR twin and deterministic/stress schedule coverage. + +## Rejected examples and diagnostics + +With the same mapping, constructing `app.model.Pair` without a direct `import app.model;` is `E7002`; linking it through another module does not grant name visibility. Repeatedly lending one mutable buffer to qualified workers rejects with the existing race code: + +```aji +module app.entry +import app.workers; +fn main() -> u64 effects [task.spawn] { + var buf: [u64; 2] = zero; + { + mut s = buf; + scope sc { + let a = task.spawn(sc, app.workers.bump, s); + let b = task.spawn(sc, app.workers.bump, s); + task.join(move a); + task.join(move b); + } + } + return buf[0]; +} +``` + +The independently checked fixture rejects `E4101`. Borrow conflicts reject `E2101`; omitted owner moves use `E7003`; absent declared effects use `E3101`. Names/imports use `E7002`; graph/header/duplicate/input-depth errors use `E7006`; source syntax uses `E7001` with expected/found fields at the imported source. Type mismatch remains `E7005`/`E1001`. CLI manifest/path/I/O/budget errors use stderr and exit 2 before verification; source rejection uses JSON Lines and exit 1. No new diagnostic code or envelope is added. + +## Compatibility and integration + +Spec 15 §2, §5, §7, §11, §13–§14 and spec 12 §1 integrate the rules. Reference grammar, Quick Reference, source bundle, Q-032 and both implementation plans track the increment. The six standard modules still expose 39 functions and 14 ordinary enums, with no API change. Existing file-only, AIR-only, standard-only and legacy-manifest programs preserve meaning and lowering. Previously unknown package names become valid only with explicit inputs. Short names remain local; distinct module types are nominally different. No migration or semantics-changing flag is needed. + +## Agent complexity impact + +- New concepts: explicit module-to-file inputs, module-local short names, direct qualified visibility and an acyclic source graph. All declarations are available; there is no separate export list or privacy state. +- Source forms: existing `import path;`, qualified calls/types/enum variants extend to package modules; qualified struct literals and a qualified static worker are supported. Manifest adds one `[modules]` map. No new source keyword, lifetime/ownership syntax, AIR syntax, effect, capability or diagnostic code. +- Frontend state: module identity on spans, direct-import scope table, graph visit/cache/depth state and existing nominal type/static signature binding. Verifier/runtime state: none. +- Interactions: structs/enums/arrays, local functions, std imports, collision handling, borrow projections, owner moves, effectful calls, task return types and lent buffers. Imported files remain explicit untrusted source inputs through the ordinary verifier. +- Repairability: missing imports, cycles, header mismatch and inaccessible members have stable diagnostics; imported source locations point to the actual repair file. No ambient resolution, transitive namespace effects, initialization order or privileged library magic must be reasoned about. +- Existing AIR primitives suffice. Textual source concatenation would lose scope and nominal identity; a runtime loader or a new AIR module instruction would add trusted complexity without improving this contract. Generics and linear aggregates remain independent prerequisites for owning containers. + +The source bundle adds an on-demand `language/modules.md` containing the two normative contracts; Quick Reference gives the manifest, one checked source example and navigation. No additional AIR documentation is needed. Measurements and final checks are recorded below. + +## Alternatives and remaining work + +Convention-based file lookup, parent manifest search and environment paths hide compiler inputs. Transitive visibility or import aliases add ambiguous bindings; private/public modifiers and re-exports add concepts before the minimal library need demands them. Lazy runtime loading adds authority and initialization ordering. Dependency fetching and lockfiles require their own package tooling contract. STD-4/P6-4 next addresses deterministic generics and structural constraints; owning collections also require a separate vertical linear-aggregates feature. + +## Documentation measurements + +Measured against STD-2b with `zig build agent-reference` and `HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source`: + +| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after | +|---|---|---|---| +| Quick Reference | 6,220 → 6,501 (+4.5%) | 6,241 → 6,522 (+4.5%) | 6,415 → 6,704 (+4.5%) | +| Other source docs | 37,128 → 38,822 (+4.6%) | 37,248 → 38,940 (+4.5%) | 38,154 → 39,889 (+4.5%) | +| Full source docs without AIR | 43,348 → 45,323 (+4.6%) | 43,489 → 45,462 (+4.5%) | 44,569 → 46,593 (+4.5%) | +| AIR docs in source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 | + +Standalone AIR remains 160,797 bytes, 48 sections and 19 files. The new module page is 1,566/1,567/1,599 tokens; library/std.md remains 7,730/7,766/7,955. Front-door growth is 281/281/289 tokens. The precise graph, type binding, input bounds and package loading contracts live on demand. Cumulative cl100k growth since pre-stdlib is 33,981 → 45,323 (+33.4%) for full source docs and 5,511 → 6,501 (+18.0%) for Quick Reference. The existing 20% source-doc review crossing remains explicit for owner review. The additional cost buys deterministic modules and nominal types for reusable libraries; it does not establish empirical Model Capability Compression. API-reference splitting and selective reading remain necessary as std grows. + +## Branch validation + +`zig build`, `zig build test`, full conformance (579 passed, zero failed/pending), `zig fmt --check build.zig build.zig.zon src tools tests/extended`, source coverage (76/76), agent-reference, hosted file/stdin/TCP smoke and package CLI integration (36 checks) pass. The module example returns 42. The 35 added conformance cases include source runs/rejections, two hand-written AIR tests and the checked Quick Reference example. All source runs check canonical repeat lowering and deterministic repeat execution. Qualified workers additionally pass 32 schedule-stress seeds across quanta 1, 2 and 7; mutable lends, explicit joins and repeated-lend rejection use existing rules. + +Unit checks cover provider/import-order independence, nominal types when diagnostic file labels coincide, imported syntax/unused-function verifier provenance, bounded shared-tail graphs and names longer than the built-in path buffer. Conformance covers local binding collisions, imported `main`, qualified types/struct fields/enums, lack of short/transitive names, effect/owner/alias/race rejection, header mismatch, duplicate maps/imports/members, cycles, syntax, absent inputs and unreachable malformed sources. CLI checks cover all five commands, grants and overrides, hosted result/output behavior, source trap locations, no ambient manifest discovery, forbidden path components, leaf/ancestor/entry symlinks, nonregular files and aggregate source limits. The integration script is included in CI. No private held-out evaluation material was consulted or changed. diff --git a/docs/spec/12-packages-and-build.md b/docs/spec/12-packages-and-build.md index 4f608cc..82bf1c6 100644 --- a/docs/spec/12-packages-and-build.md +++ b/docs/spec/12-packages-and-build.md @@ -4,7 +4,7 @@ A package contains an `aji.toml` manifest. Decision record for capability grants: RFC 0010. -1. **A manifest requests; the operator grants.** The author of a package writes `[capabilities]`. Authority is granted only when someone explicitly runs the program with that manifest (`aji run --manifest`). Building, verifying or installing never grants anything (spec 05 §6). +1. **A manifest requests; the operator grants.** The author of a package writes `[capabilities]`. Authority is granted only when someone explicitly runs the program with that manifest (`aji run --manifest` or `aji explore --manifest`). Building, verifying or installing never grants anything (spec 05 §6). 2. **Same model as `--grant`.** One entry per `@main` capability parameter: `parameter = "kind[:scope]"`. All instantiation rules apply unchanged (missing, mismatched, unknown, invalid scope; mandatory `mem.alloc` budget in the deterministic profile). 3. **The operator has the last word.** A command-line `--grant P=…` replaces the manifest entry for `P`, for example to point a scope at another directory. It never silently adds parameters: an unknown parameter is still `unknown_parameter`. 4. **Strict parsing.** Unknown sections, unknown keys and duplicate keys are errors, so a typo cannot silently drop or misplace authority. @@ -42,10 +42,31 @@ aji run --manifest aji.toml [--grant P=KIND[:SCOPE]]... [other run options] - The module is the manifest's `entry`; a file argument is not allowed together with `--manifest`. - Grants are the manifest's `[capabilities]` entries, each replaced by a `--grant` for the same parameter if given. -- `aji check` and `aji report` do not read manifests. +- `aji check`, `aji lower` and `aji report` read a manifest only with explicit `--manifest PATH`, selecting its entry and module inputs without granting program authority. `aji explore --manifest PATH` uses its entry/module inputs and grants with the same override rules as run. Manifest errors (unreadable file, syntax, unknown section or key, duplicate key, missing `name`/`version`/`entry`, malformed grant string) are reported before verification as a usage error (exit code 2) with a message naming the line. Structured manifest diagnostics belong to the package tooling of Phase 8. +### 1.3 Package source mapping + +An optional `[modules]` table maps dotted source module names to manifest-relative `.aji` file paths: + +```toml +[package] +name = "record-tool" +version = "0.1.0" +entry = "src/main.aji" + +[modules] +app.model = "src/model.aji" +app.work = "src/work.aji" +``` + +Mapping keys MUST be ASCII identifier components separated by dots and MUST NOT occupy standard/built-in namespaces (spec 15 §14). Duplicate keys remain manifest errors. With this section present, `entry` is required and MUST name `.aji` source; entry/mapped paths MUST be nonempty portable relative paths with `/` separators and no empty, `.` or `..` component, backslash, colon or NUL. They MUST end in `.aji`. Every directory component and source file MUST be opened without following symlinks, relative to the selected manifest directory; that directory is the operator-selected root. Directory/file handles stay open while descending/reading to avoid substituting an ancestor with a symlink. Nonregular sources MUST be rejected. Unsupported safe no-follow behavior MUST fail rather than silently read outside the package. + +The loader MUST read entry first, then mapped files in lexicographic module-name order into fixed compilation inputs. All mapped files are explicit build inputs and MUST be readable even if unreachable; only the reachable graph is parsed/linked (spec 15 §14). No source is executed during loading. The manifest is limited to 1 MiB, at most 1,024 mapped modules and the total source snapshot to 64 MiB. Invalid bindings/paths, unavailable files, symlinks, input limits and other I/O errors use the existing usage/I/O error contract (exit 2 before verification); source graph/name/type errors are verification rejection (exit 1, JSON diagnostics). Manifests without `[modules]` retain their entry-loading contract. + +Commands accept one file or `--manifest PATH`, never both. Check/lower/report never grant program authority; run/explore instantiate only with explicitly selected manifest grants and command-line overrides. No implicit manifest discovery is allowed. + ## 2. Reproducibility Given the same: diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index be59a5e..29a0834 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -29,7 +29,7 @@ It MUST NOT hide: Rules: -1. Lowering is a pure function of the source: the same module gives byte-identical canonical AIR (spec 07 §8.5). +1. Lowering is a pure function of its explicit source inputs: the same module graph gives byte-identical canonical AIR (spec 07 §8.5). 2. No source construct admits a program whose AIR the verifier rejects. Errors the verifier would find are reported with the verifier's code (§9). 3. `.aji` 0.1 covers the published features of Phases 0–3 and nothing else. 4. Every construct has **one canonical spelling**. There are no alternative forms of the same operation. @@ -58,7 +58,7 @@ effects [io.read, io.write] ``` - A file holds one module: `module `, then type and function declarations in any order. -- Between the module header and declarations, `import ;` imports a built-in standard module (§13). `import` is contextual at this position; it remains an ordinary identifier elsewhere. +- Between the module header and declarations, `import ;` imports a standard (§13) or explicitly supplied package module (§14). `import` is contextual at this position; it remains an ordinary identifier elsewhere. - `//` starts a line comment. - Function `f` lowers to `@f`; type `T` to `@T`. - **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then the body block. @@ -159,7 +159,7 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass 6A has no destructuring: no `let Point { x, y } = p`, no nested patterns, guards or or-patterns. -**Calls.** `f(args)` calls a function of the module. Built-in operations are called by their AIR names (§7, §8). Arguments are evaluated left to right. +**Calls.** `f(args)` calls a local function; a directly imported function uses its full path (§13–§14). Built-in operations are called by their AIR names (§7, §8). Arguments are evaluated left to right. **Borrows and places.** A place is: @@ -254,7 +254,7 @@ scope s { **`scope s { … }`** is `task.scope.begin` and `task.scope.end`, at every normal exit of the block. Inside it: -- `task.spawn(s, f, args)` spawns `f` (a function of the module) into the scope `s`. Arguments are passed like call arguments: a named linear value is `move`d (`E7003`). A borrow argument is lent until the join (spec 04 §34), so it is a borrow binding passed by name (`mut part = buf;` … `task.spawn(s, f, part)`). A borrow or byte string written inline is `E7006`, because a temporary would have to end right after the spawn. The first operand must be the scope (`E7005`); +- `task.spawn(s, f, args)` spawns `f` (a local or directly imported qualified function, §14) into the scope `s`. Arguments are passed like call arguments: a named linear value is `move`d (`E7003`). A borrow argument is lent until the join (spec 04 §34), so it is a borrow binding passed by name (`mut part = buf;` … `task.spawn(s, f, part)`). A borrow or byte string written inline is `E7006`, because a temporary would have to end right after the spawn. The first operand must be the scope (`E7005`); - `task.join(move t)` joins; its value is the task's result (`task` gives `T`); - a task that is not joined at an exit is `E4301`. @@ -426,10 +426,13 @@ Its diagnostics keep their AIR codes, reported at the source location. | `aji lower --stats file.aji` | source and AIR size, expansion ratios and the two `mechanical_air_eliminated` metrics below | | `aji lower --annotate file.aji` | the same with `; line:col-line:col` source spans before each instruction (not canonical; for debugging) | -Lowering is deterministic: the same source and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test. +`check`, `lower`, `report`, `run` and `explore` also accept `--manifest PATH` for explicit package inputs (§14, spec 12 §1.3). Check/lower/report do not instantiate grants. + +Lowering is deterministic: the same source inputs and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test. **Size metrics** (`--stats`, non-normative tooling with a fixed definition): +- With `--manifest`, source sizes count the entry file only; AIR sizes count the combined module. These ratios MUST NOT be interpreted as whole-package compression. - Sizes count code only: non-empty lines that are not comments (`//` in source, `;` in AIR), each with its newline. - `mechanical_air_eliminated_raw` = 1 − `source_bytes` / `air_bytes`: how much of the AIR text the author did not write. This is the main engineering metric. - `mechanical_air_eliminated_normalized` = 1 − `source_bytes` / `air_bytes_normalized`: the same against AIR in which every byte-string materialization counts as one logical constant operation. Such a materialization is the instructions from the string's `local.zero` to its final `borrow.end`, a store per non-zero byte, because format 0 has no byte-array constant. It is replaced by the single notional line ` const.bytes %, `, where `` is the canonical spelling: printable ASCII as is, otherwise the escapes `\n \r \t \0 \\ \" \xNN`. The storage's `local.alloc` is real frame storage and stays. No other instruction is normalized. The rule is the same for every program, and `byte_string_constants` reports how many were replaced. @@ -470,9 +473,9 @@ Other rules: ## 13. Built-in standard modules -The compiler MUST provide the standard modules listed in spec 16 §2, pinned to its own version. An import MUST resolve only against that closed registry: no file-system search, environment variable, network fetch, package manifest, or build extension participates. Unknown modules are `E7002`; duplicate imports are `E7006`. Imports MUST precede declarations; a misplaced import or missing semicolon is `E7001`. +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 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 outside the grammar (`E7001`). 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. @@ -484,4 +487,30 @@ 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, general user modules, dependency resolution, aliases, imported struct literals or generics; those require separate specifications. +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. + +## 14. Package source modules + +### 14.1 Explicit inputs and graph + +The frontend MUST take an entry source and an explicit mapping of module names to source bytes and diagnostic file paths. Its compilation MUST be a pure function of those inputs and compiler version. The CLI supplies the mapping only from an explicitly selected manifest's `[modules]` (spec 12 §1.3); a file-only invocation has no package mapping and MUST NOT discover a manifest. No parent search, directory scan, environment search path, network access, dependency fetch or build script participates. Standard imports continue to use §13's compiler-pinned registry and MUST NOT be shadowed by the package mapping. + +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. + +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. + +### 14.2 Names and types + +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` 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. + +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. + +### 14.3 AIR, safety and compatibility + +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. diff --git a/examples/modules/aji.toml b/examples/modules/aji.toml new file mode 100644 index 0000000..9265c04 --- /dev/null +++ b/examples/modules/aji.toml @@ -0,0 +1,7 @@ +[package] +name = "module-example" +version = "0.1.0" +entry = "main.aji" + +[modules] +app.model = "model.aji" diff --git a/examples/modules/main.aji b/examples/modules/main.aji new file mode 100644 index 0000000..68f4d69 --- /dev/null +++ b/examples/modules/main.aji @@ -0,0 +1,9 @@ +module app.entry +import app.model; + +fn main() -> u64 +effects [] +{ + let pair = app.model.Pair { left: 20, right: 22 }; + return app.model.total(pair); +} diff --git a/examples/modules/model.aji b/examples/modules/model.aji new file mode 100644 index 0000000..b794fcd --- /dev/null +++ b/examples/modules/model.aji @@ -0,0 +1,7 @@ +module app.model + +struct Pair { left: u64, right: u64 } + +fn total(pair: Pair) -> u64 +effects [] +{ return pair.left + pair.right; } diff --git a/src/check.zig b/src/check.zig index 4edc588..a38a2ec 100644 --- a/src/check.zig +++ b/src/check.zig @@ -30,8 +30,12 @@ pub const Report = struct { /// Checks a `.aji` module (frontend, then the AIR pipeline, with every /// diagnostic at its source location) or a text AIR module. pub fn checkFile(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report { + return checkWithModules(arena, file_name, source, &.{}); +} + +pub fn checkWithModules(arena: std.mem.Allocator, file_name: []const u8, source: []const u8, sources: []const frontend.modules.Source) !Report { if (!std.mem.endsWith(u8, file_name, ".aji")) return checkAir(arena, file_name, source); - const lowered = switch (try frontend.compile(arena, file_name, source)) { + const lowered = switch (try frontend.compileWithModules(arena, file_name, source, sources)) { .ok => |o| o, .err => |d| return .{ .status = .rejected, .diagnostics = try arena.dupe(diag.Diagnostic, &.{d}) }, .unimplemented => |what| return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = what }, @@ -168,3 +172,68 @@ test "standard type diagnostics use the public source name" { try std.testing.expectEqualStrings(case.found, found); } } + +test "package module order, nominal names and diagnostic paths are independent" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const a: frontend.modules.Source = .{ .name = "app.a", .file = "same.aji", .source = "module app.a\nstruct Pair { value: u64 }\nfn value(p: Pair) -> u64 effects [] { return p.value; }\n" }; + const b: frontend.modules.Source = .{ .name = "app.b", .file = "same.aji", .source = "module app.b\nimport app.a;\nfn value() -> u64 effects [] { return app.a.value(app.a.Pair { value: 42 }); }\n" }; + const body = "fn main() -> u64 effects [] { return app.b.value(); }\n"; + const first = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.a;\nimport app.b;\n" ++ body, &.{ a, b }); + const second = try checkWithModules(arena, "/elsewhere/root.aji", "module app.entry\nimport app.b;\nimport app.a;\n" ++ body, &.{ b, a }); + 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.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; same.aji:") != null); + const bad = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.b;\nfn main() -> u64 effects [] { let p: app.a.Pair = app.a.Pair { value: 42 }; return 0; }", &.{ a, b }); + try std.testing.expectEqualStrings("E7002", bad.diagnostics[0].code.id); +} + +test "module syntax and verifier errors retain imported source provenance" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const root = "module app.entry\nimport app.lib;\nfn main() -> u64 effects [] { return 42; }"; + const syntax = try checkWithModules(arena, "entry.aji", root, &.{.{ .name = "app.lib", .file = "src/lib.aji", .source = "module app.lib\nfn broken(" }}); + try std.testing.expectEqualStrings("E7001", syntax.diagnostics[0].code.id); + try std.testing.expectEqualStrings("src/lib.aji", syntax.diagnostics[0].span.?.file); + try std.testing.expectEqualStrings("expected", syntax.diagnostics[0].fields[0].name); + const alias = try checkWithModules(arena, "entry.aji", root, &.{.{ .name = "app.lib", .file = "src/lib.aji", .source = "module app.lib\nfn broken() -> u8 effects [] { var b: [u8; 4] = zero; ref held = b; b[0] = 1; return held[0]; }" }}); + try std.testing.expectEqualStrings("E2101", alias.diagnostics[0].code.id); + try std.testing.expectEqualStrings("src/lib.aji", alias.diagnostics[0].span.?.file); +} + +test "module graph depth is bounded even with a cached shared tail" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var sources: std.ArrayList(frontend.modules.Source) = .empty; + for (0..257) |i| { + const name = try std.fmt.allocPrint(arena, "app.m{d}", .{i}); + const source = if (i == 256) try std.fmt.allocPrint(arena, "module {s}\n", .{name}) else try std.fmt.allocPrint(arena, "module {s}\nimport app.m{d};\n", .{ name, i + 1 }); + try sources.append(arena, .{ .name = name, .file = name, .source = source }); + } + const prefix = "module app.entry\nimport app.m200;\nimport app.m0;\nfn main() -> u64 effects [] { return 42; }"; + const excessive = try checkWithModules(arena, "root.aji", prefix, sources.items); + try std.testing.expectEqualStrings("E7006", excessive.diagnostics[0].code.id); + const valid = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.m1;\nfn main() -> u64 effects [] { return 42; }", sources.items); + try std.testing.expectEqual(Status.accepted, valid.status); + const many = try arena.alloc(frontend.modules.Source, 1025); + @memset(many, sources.items[0]); + const limited = try checkWithModules(arena, "root.aji", prefix, many); + try std.testing.expectEqualStrings("E7006", limited.diagnostics[0].code.id); +} + +test "qualified module names are not limited by builtin path storage" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const component = try arena.alloc(u8, 300); + @memset(component, 'a'); + const name = try std.fmt.allocPrint(arena, "app.{s}", .{component}); + const source = try std.fmt.allocPrint(arena, "module {s}\nstruct Pair {{ value: u64 }}\nfn total(p: Pair) -> u64 effects [] {{ return p.value; }}", .{name}); + const entry = try std.fmt.allocPrint(arena, "module app.entry\nimport {s};\nfn main() -> u64 effects [] {{ return {s}.total({s}.Pair {{ value: 42 }}); }}", .{ name, name, name }); + const checked = try checkWithModules(arena, "root.aji", entry, &.{.{ .name = name, .file = "lib.aji", .source = source }}); + try std.testing.expectEqual(Status.accepted, checked.status); +} diff --git a/src/frontend.zig b/src/frontend.zig index c7bd0f1..a3a0c8e 100644 --- a/src/frontend.zig +++ b/src/frontend.zig @@ -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 modules = @import("frontend/modules.zig"); pub const stdlib = @import("frontend/stdlib.zig"); pub const Span = ast.Span; @@ -21,6 +22,10 @@ pub const Compiled = union(enum) { }; pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) std.mem.Allocator.Error!Compiled { + return compileWithModules(arena, file, source, &.{}); +} + +pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []const u8, sources: []const modules.Source) std.mem.Allocator.Error!Compiled { const parsed = try parse.parse(arena, source); const m = switch (parsed) { .ok => |m| m, @@ -34,7 +39,7 @@ pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) s }), } }, }; - const linked = try stdlib.link(arena, m); + const linked = try modules.link(arena, m, sources); const result = switch (linked) { .ok => |combined| try lower_mod.lower(arena, combined), .err => |p| lower_mod.Result{ .err = p }, diff --git a/src/frontend/ast.zig b/src/frontend/ast.zig index fac2134..4f4c8ac 100644 --- a/src/frontend/ast.zig +++ b/src/frontend/ast.zig @@ -6,7 +6,7 @@ const lex = @import("lex.zig"); pub const Pos = lex.Pos; -pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null }; +pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null, namespace: ?[]const u8 = null }; pub const Type = struct { span: Span, @@ -168,7 +168,7 @@ pub const Variant = struct { name: []const u8, payload: []const Type, span: Span pub const TypeDecl = struct { name: []const u8, - /// Linker-chosen AIR identifier for a qualified standard type. + /// Linker-chosen AIR identifier for a qualified imported type. air_name: ?[]const u8 = null, span: Span, kind: union(enum) { @"struct": []const Field, @"enum": []const Variant }, @@ -178,7 +178,7 @@ pub const Param = struct { name: []const u8, ty: Type, span: Span }; pub const FnDecl = struct { name: []const u8, - /// Linker-chosen AIR identifier for a qualified standard function. + /// Linker-chosen AIR identifier for a qualified imported function. air_name: ?[]const u8 = null, span: Span, params: []const Param, @@ -192,8 +192,12 @@ pub const FnDecl = struct { pub const Module = struct { name: []const u8, imports: []const Import = &.{}, + scopes: []const ModuleScope = &.{}, types: []const TypeDecl, functions: []const FnDecl, }; pub const Import = struct { path: []const u8, span: Span }; + +/// Source name resolution stays separate from diagnostic file paths. +pub const ModuleScope = struct { name: []const u8, entry: bool, qualified_self: bool = true, imports: []const Import }; diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index a352e59..8e895c3 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -530,7 +530,7 @@ const Lowerer = struct { if (std.mem.eql(u8, n, "bool")) return .bool; if (std.mem.eql(u8, n, "void")) return .void; if (std.mem.eql(u8, n, "never")) return .never; - for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) }; + if (l.enumOrStruct(n, t.span)) |ty| return ty; if (std.mem.eql(u8, n, "region")) return .region; if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b }; if (std.mem.eql(u8, n, "stream")) return .{ .resource = .stream }; @@ -1109,12 +1109,47 @@ const Lowerer = struct { /// The type of an expression without lowering it, where it follows /// from names, suffixes, casts and calls; null otherwise. + fn sourceScope(l: *Lowerer, span: Span) ?ast.ModuleScope { + const name = span.namespace orelse l.m.name; + for (l.m.scopes) |scope| if (std.mem.eql(u8, scope.name, name)) return scope; + return null; + } + + fn boundName(l: *Lowerer, name: []const u8, span: Span) ?[]const u8 { + const scope = l.sourceScope(span) orelse return name; + if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| { + const owner = name[0..at]; + if (std.mem.eql(u8, owner, scope.name)) 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 (l.m.types) |t| if (localName(t.name, scope.name, name)) return t.name; + for (l.m.functions) |f| if (localName(f.name, scope.name, name)) return f.name; + return null; + } + + fn functionSig(l: *Lowerer, name: []const u8, span: Span) ?FnSig { + return l.sigs.get(l.boundName(name, span) orelse return null); + } + fn calleeSig(l: *Lowerer, e: ast.Expr) ?FnSig { - if (e.kind == .name) return l.sigs.get(e.kind.name); - var buf: [256]u8 = undefined; - const name = dotted(e, &buf) orelse return null; - if (!std.mem.startsWith(u8, name, "std.")) return null; - return l.sigs.get(name); + const name = expressionPath(l.arena, e) catch return null; + return l.functionSig(name orelse return null, e.span); + } + + fn moduleCall(l: *Lowerer, e: ast.Expr) Error!?[]const u8 { + if (e.kind != .field) return null; + const name = try expressionPath(l.arena, e) orelse return null; + if (standardPath(e)) return name; + if (pathOf(e) != null) return null; + const owner = name[0..std.mem.lastIndexOfScalar(u8, name, '.').?]; + for (l.m.scopes) |scope| if (std.mem.eql(u8, owner, scope.name)) return name; + if (l.sourceScope(e.span)) |scope| for (scope.imports) |imp| if (std.mem.eql(u8, owner, imp.path)) return name; + var root = e; + while (root.kind == .field) root = root.kind.field.e.*; + if (root.kind == .name and l.lookup(root.kind.name) == null) return name; + return null; } fn peekType(l: *Lowerer, e: ast.Expr) ?Ty { @@ -1134,13 +1169,13 @@ const Lowerer = struct { else => l.peekType(x.l.*) orelse l.peekType(x.r.*), }, .call => |x| switch (x.callee.kind) { - .name => |n| if (l.sigs.get(n)) |sig| sig.ret else null, - .variant => |v| l.enumType(v.@"enum"), + .name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null, + .variant => |v| l.enumType(v.@"enum", e.span), else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null, }, .move => |n| if (l.lookup(n)) |b| b.ty else null, - .variant => |v| l.enumType(v.@"enum"), - .struct_lit => |x| l.enumOrStruct(x.name), + .variant => |v| l.enumType(v.@"enum", e.span), + .struct_lit => |x| l.enumOrStruct(x.name, e.span), .field => |x| blk: { if (std.mem.eql(u8, x.name, "len")) break :blk Ty{ .int = "usize" }; var base = l.peekType(x.e.*) orelse break :blk null; @@ -1232,18 +1267,19 @@ const Lowerer = struct { fn typeOfNoFail(l: *Lowerer, t: ast.Type) ?Ty { return switch (t.kind) { - .name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else l.enumOrStruct(n), + .name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else l.enumOrStruct(n, t.span), else => null, }; } - fn enumOrStruct(l: *Lowerer, n: []const u8) ?Ty { + fn enumOrStruct(l: *Lowerer, name: []const u8, span: Span) ?Ty { + const n = l.boundName(name, span) orelse return null; for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) }; return null; } - fn enumType(l: *Lowerer, n: []const u8) ?Ty { - const t = l.enumOrStruct(n) orelse return null; + fn enumType(l: *Lowerer, n: []const u8, span: Span) ?Ty { + const t = l.enumOrStruct(n, span) orelse return null; return if (l.m.types[t.named].kind == .@"enum") t else null; } @@ -1429,9 +1465,7 @@ const Lowerer = struct { fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value { if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args); - var buf: [256]u8 = undefined; - if (standardPath(callee)) { - const name = dotted(callee, &buf) orelse return l.unknown(callee.span, callee.kind.field.name); + if (try l.moduleCall(callee)) |name| { // Reuse ordinary call typing/borrowing/lowering, including E7002. const owned_name = try l.arena.dupe(u8, name); return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args); @@ -1496,7 +1530,7 @@ const Lowerer = struct { try l.emit(try l.fmt("assume %{s}", .{v.name}), e.span); return .{ .name = "", .ty = .void }; } - const sig = l.sigs.get(name) orelse return l.unknown(callee.span, name); + 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}) } }); var arg_names: std.ArrayList(u8) = .empty; var temps: std.ArrayList([]const u8) = .empty; @@ -1515,14 +1549,14 @@ const Lowerer = struct { } return .{ .name = "", .ty = .void }; } - return l.def(if (std.mem.startsWith(u8, name, "std.")) "std_call" else name, sig.ret, text, e.span); + 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); } /// `Name { f: e, … }`: every field exactly once; initializers are /// evaluated in declaration order, so the AIR does not depend on the /// order the fields are written in (spec 15 §5). fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value { - const t = l.enumOrStruct(name) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }}); + 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 }}); const fields = d.kind.@"struct"; @@ -1547,7 +1581,7 @@ const Lowerer = struct { } fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value { - const t = l.enumType(enum_name) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }}); + const t = l.enumType(enum_name, e.span) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }}); const vs = l.m.types[t.named].kind.@"enum"; const v = for (vs) |x| { if (std.mem.eql(u8, x.name, variant)) break x; @@ -1580,7 +1614,7 @@ const Lowerer = struct { return v; }; const v = try l.expr(base, bt); - return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.name, name, v.name }), e.span); + return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span); } /// One branch of a conditional or `match`: where it ended (null if it @@ -1646,8 +1680,9 @@ const Lowerer = struct { 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 }}); const c = arm.pattern.kind.ctor; - if (std.mem.startsWith(u8, c.qualifier.?, "std.") and l.enumType(c.qualifier.?) == null) return l.unknown(arm.pattern.span, c.qualifier.?); - if (!std.mem.eql(u8, c.qualifier.?, d.name)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.name }, .{ .name = "found", .value = c.qualifier.? } }); + 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.? } }); 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 } }); @@ -1781,8 +1816,8 @@ const Lowerer = struct { if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null; if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null; if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null; - if (eq(u8, p, "task.spawn") and args.len >= 2 and args[1].kind == .name) { - const sig = l.sigs.get(args[1].kind.name) orelse return null; + if (eq(u8, p, "task.spawn") and args.len >= 2) { + const sig = l.calleeSig(args[1]) orelse return null; return l.wrap(.task, sig.ret) catch null; } return null; @@ -1979,7 +2014,7 @@ const Lowerer = struct { 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 } }); 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.name, f.name, base.v.name }), span); + 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) }; }, .index => |x| { @@ -2345,9 +2380,8 @@ const Lowerer = struct { const sb = try l.bindingOf(args[0], "a task scope"); if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.diagnosticTyText(sb.ty) }}); const scope_name = sb.value; - if (args[1].kind != .name) return l.fail("E7005", args[1].span, "the function to spawn is named", &.{}); - const fname = args[1].kind.name; - const sig = l.sigs.get(fname) orelse return l.unknown(args[1].span, fname); + 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}) } }); var names: std.ArrayList(u8) = .empty; @@ -2359,7 +2393,7 @@ const Lowerer = struct { try l.checkTy(a.span, v.ty, pt); try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name })); } - return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, fname, names.items }), e.span); + return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, sig.air_name, names.items }), e.span); } if (eq(p, "task.join")) { if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{}); @@ -3450,3 +3484,15 @@ fn selectAssigns(x: ast.Select, name: []const u8) bool { for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true; return exprAssigns(x.cancelled, name); } + +fn localName(full: []const u8, module: []const u8, short: []const u8) bool { + return full.len == module.len + 1 + short.len and std.mem.startsWith(u8, full, module) and full[module.len] == '.' and std.mem.eql(u8, full[module.len + 1 ..], short); +} + +fn expressionPath(arena: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 { + return switch (e.kind) { + .name => |name| name, + .field => |field| if (try expressionPath(arena, field.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, field.name }) else null, + else => null, + }; +} diff --git a/src/frontend/modules.zig b/src/frontend/modules.zig new file mode 100644 index 0000000..faae3fa --- /dev/null +++ b/src/frontend/modules.zig @@ -0,0 +1,152 @@ +//! Pure linking of explicit source inputs; no filesystem or authority. +const std = @import("std"); +const ast = @import("ast.zig"); +const parse = @import("parse.zig"); +const lower = @import("lower.zig"); +const stdlib = @import("stdlib.zig"); +const authority = @import("../air/authority.zig"); + +pub const Source = stdlib.Source; +pub const Result = union(enum) { ok: ast.Module, err: lower.Problem }; +const Error = error{ OutOfMemory, InvalidSource }; +const Node = struct { module: ast.Module, active: bool, height: usize = 0 }; + +pub fn reserved(name: []const u8) bool { + const first = if (std.mem.indexOfScalar(u8, name, '.')) |at| name[0..at] else name; + for ([_][]const u8{ "std", "slice", "own", "region", "cap", "task", "channel", "mutex", "island", "frozen", "arc", "atomic" }) |word| { + if (std.mem.eql(u8, first, word)) return true; + } + for (authority.intrinsics) |intrinsic| { + const at = std.mem.indexOfScalar(u8, intrinsic.name, '.').?; + if (std.mem.eql(u8, first, intrinsic.name[0..at])) return true; + } + return false; +} + +pub fn link(arena: std.mem.Allocator, entry: ast.Module, sources: []const Source) std.mem.Allocator.Error!Result { + var g: Graph = .{ .arena = arena, .sources = sources }; + const span: ast.Span = if (entry.functions.len != 0) entry.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }; + const combined = g.run(entry, span) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + error.InvalidSource => return .{ .err = g.problem.? }, + }; + return .{ .ok = combined }; +} + +const Graph = struct { + arena: std.mem.Allocator, + sources: []const Source, + nodes: std.ArrayList(Node) = .empty, + problem: ?lower.Problem = null, + + fn fail(g: *Graph, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error { + g.problem = .{ .code = code, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory }; + return error.InvalidSource; + } + + fn run(g: *Graph, entry: ast.Module, span: ast.Span) Error!ast.Module { + if (g.sources.len > 1024) return g.fail("E7006", span, "more than 1024 mapped modules", entry.name); + for (g.sources, 0..) |source, i| { + if (reserved(source.name)) return g.fail("E7006", span, "package mapping uses a reserved namespace", source.name); + for (g.sources[0..i]) |previous| if (std.mem.eql(u8, previous.name, source.name)) return g.fail("E7006", span, "module mapped twice", source.name); + } + try g.nodes.append(g.arena, .{ .module = entry, .active = true }); + const root_height = try g.imports(entry, 0); + g.nodes.items[0].height = root_height; + g.nodes.items[0].active = false; + std.mem.sort(Node, g.nodes.items[1..], {}, struct { + fn less(_: void, a: Node, b: Node) bool { + return std.mem.lessThan(u8, a.module.name, b.module.name); + } + }.less); + var types: std.ArrayList(ast.TypeDecl) = .empty; + var functions: std.ArrayList(ast.FnDecl) = .empty; + var scopes: std.ArrayList(ast.ModuleScope) = .empty; + try types.appendSlice(g.arena, entry.types); + try functions.appendSlice(g.arena, entry.functions); + for (g.nodes.items, 0..) |node, i| { + const m = node.module; + try scopes.append(g.arena, .{ .name = m.name, .entry = i == 0, .qualified_self = i != 0 or !reserved(m.name), .imports = m.imports }); + if (i == 0) continue; + for (m.types) |t| { + var qualified = t; + qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, t.name }); + qualified.air_name = try airName(g.arena, m.name, t.name, types.items, functions.items); + try types.append(g.arena, qualified); + } + for (m.functions) |f| { + var qualified = f; + qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, f.name }); + qualified.air_name = try airName(g.arena, m.name, f.name, types.items, functions.items); + try functions.append(g.arena, qualified); + } + } + var result = entry; + result.types = types.items; + result.functions = functions.items; + result.scopes = scopes.items; + return result; + } + + fn imports(g: *Graph, m: ast.Module, depth: usize) Error!usize { + var height: usize = 0; + for (m.imports, 0..) |imp, i| { + for (m.imports[0..i]) |previous| if (std.mem.eql(u8, imp.path, previous.path)) return g.fail("E7006", imp.span, "module imported twice", imp.path); + height = @max(height, 1 + try g.visit(imp, depth + 1)); + } + return height; + } + + fn visit(g: *Graph, imp: ast.Import, depth: usize) Error!usize { + for (g.nodes.items) |node| if (std.mem.eql(u8, node.module.name, imp.path)) { + if (node.active) return g.fail("E7006", imp.span, "cyclic module import", imp.path); + if (depth + node.height > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path); + return node.height; + }; + if (depth > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path); + const source = for (stdlib.registry) |source| { + if (std.mem.eql(u8, source.name, imp.path)) break source; + } else for (g.sources) |source| { + if (std.mem.eql(u8, source.name, imp.path)) break source; + } else return g.fail("E7002", imp.span, "unknown module in explicit source mapping", imp.path); + const m = switch (try parse.parseWithFile(g.arena, source.source, source.file)) { + .ok => |m| m, + .err => |failure| { + g.problem = .{ + .code = if (std.mem.startsWith(u8, source.name, "std.")) "E7900" else "E7001", + .span = .{ .start = failure.pos, .end = failure.pos, .file = source.file, .namespace = source.name }, + .message = try std.fmt.allocPrint(g.arena, "expected {s}", .{failure.expected}), + .fields = try g.arena.dupe(lower.Problem.Field, &.{ .{ .name = "expected", .value = failure.expected }, .{ .name = "found", .value = failure.found } }), + }; + return error.InvalidSource; + }, + }; + if (!std.mem.eql(u8, m.name, source.name)) return g.fail("E7006", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name); + const index = g.nodes.items.len; + try g.nodes.append(g.arena, .{ .module = m, .active = true }); + const height = try g.imports(m, depth); + g.nodes.items[index].height = height; + g.nodes.items[index].active = false; + return g.nodes.items[index].height; + } +}; + +fn airName(arena: std.mem.Allocator, module: []const u8, name: []const u8, types: []const ast.TypeDecl, functions: []const ast.FnDecl) std.mem.Allocator.Error![]const u8 { + const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ module, name }); + for (base) |*c| if (c.* == '.') { + c.* = '_'; + }; + var candidate: []const u8 = base; + var suffix: usize = 0; + while (used(types, functions, candidate)) { + suffix += 1; + candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix }); + } + return candidate; +} + +fn used(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool { + for (types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true; + for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true; + return false; +} diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index cec4e14..88a9a84 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -36,6 +36,7 @@ const Parser = struct { pos: usize = 0, failure: ?Failure = null, file: ?[]const u8 = null, + module_name: ?[]const u8 = null, /// Struct literals are not allowed where a `{` starts a block (conditions). no_struct: bool = false, @@ -104,7 +105,7 @@ const Parser = struct { } fn span(p: *Parser, start: lex.Pos) ast.Span { - return .{ .start = start, .end = p.prevEnd(), .file = p.file }; + return .{ .start = start, .end = p.prevEnd(), .file = p.file, .namespace = p.module_name }; } fn box(p: *Parser, comptime T: type, v: T) Error!*const T { @@ -118,6 +119,7 @@ const Parser = struct { fn module(p: *Parser) Error!ast.Module { _ = try p.expectWord("module"); const name = try p.path(); + p.module_name = name; var imports: std.ArrayList(ast.Import) = .empty; while (p.atWord("import")) { const start = p.next().pos; @@ -658,6 +660,13 @@ const Parser = struct { e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } }; } }, + .l_brace => { + if (p.no_struct) return e; + const name = try p.exprPath(e) orelse return e; + 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); + }, .l_paren => { const args = try p.callArgs(); const callee = try p.box(ast.Expr, e); @@ -722,6 +731,22 @@ const Parser = struct { }; } + fn structLiteral(p: *Parser, start: lex.Pos, name: []const u8) Error!ast.Expr { + _ = try p.expect(.l_brace, "`{`"); + var fields: std.ArrayList(ast.FieldInit) = .empty; + while (p.peek().tag != .r_brace) { + const fs = p.peek().pos; + const fname = try p.ident("a field name"); + _ = try p.expect(.colon, "`:`"); + const fe = try p.expr(); + try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe }); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_brace, "`}`"); + return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = name, .fields = fields.items } } }; + } + fn primary(p: *Parser) Error!ast.Expr { const start = p.peek().pos; const t = p.peek(); @@ -786,19 +811,7 @@ const Parser = struct { return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } }; } if (p.peek().tag == .l_brace and !p.no_struct and std.ascii.isUpper(t.text[0])) { - _ = p.next(); - var fields: std.ArrayList(ast.FieldInit) = .empty; - while (p.peek().tag != .r_brace) { - const fs = p.peek().pos; - const fname = try p.ident("a field name"); - _ = try p.expect(.colon, "`:`"); - const fe = try p.expr(); - try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe }); - if (p.peek().tag != .comma) break; - _ = p.next(); - } - _ = try p.expect(.r_brace, "`}`"); - return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = t.text, .fields = fields.items } } }; + return p.structLiteral(start, t.text); } return .{ .span = p.span(start), .kind = .{ .name = t.text } }; }, diff --git a/src/frontend/stdlib.zig b/src/frontend/stdlib.zig index 36f3d0a..4aa8fbe 100644 --- a/src/frontend/stdlib.zig +++ b/src/frontend/stdlib.zig @@ -1,13 +1,8 @@ -//! Closed, compiler-pinned registry of safe `.aji` standard modules. -//! No host file lookup, runtime initialization or verifier privilege. +//! Compiler-pinned safe source modules. General linking lives in modules.zig. -const std = @import("std"); -const ast = @import("ast.zig"); -const parse = @import("parse.zig"); -const lower = @import("lower.zig"); +pub const Source = struct { name: []const u8, file: []const u8, source: []const u8 }; -const Entry = struct { name: []const u8, file: []const u8, source: []const u8 }; -const registry = [_]Entry{ +pub const registry = [_]Source{ .{ .name = "std.bytes", .file = "std/bytes.aji", .source = @embedFile("std_bytes_aji") }, .{ .name = "std.encoding.base64", .file = "std/encoding/base64.aji", .source = @embedFile("std_encoding_base64_aji") }, .{ .name = "std.encoding.hex", .file = "std/encoding/hex.aji", .source = @embedFile("std_encoding_hex_aji") }, @@ -15,88 +10,3 @@ const registry = [_]Entry{ .{ .name = "std.math", .file = "std/math.aji", .source = @embedFile("std_math_aji") }, .{ .name = "std.utf8", .file = "std/utf8.aji", .source = @embedFile("std_utf8_aji") }, }; - -pub const Result = union(enum) { ok: ast.Module, err: lower.Problem }; - -pub fn link(arena: std.mem.Allocator, module: ast.Module) std.mem.Allocator.Error!Result { - // Validate in source order, before lowering, so the first error is stable. - for (module.imports, 0..) |imp, i| { - for (module.imports[0..i]) |prev| { - if (std.mem.eql(u8, imp.path, prev.path)) return problem(arena, "E7006", imp, "module imported twice"); - } - const known = for (registry) |entry| { - if (std.mem.eql(u8, entry.name, imp.path)) break true; - } else false; - if (!known) return problem(arena, "E7002", imp, "unknown built-in standard module"); - } - if (module.imports.len == 0) return .{ .ok = module }; - - var functions: std.ArrayList(ast.FnDecl) = .empty; - try functions.appendSlice(arena, module.functions); - var types: std.ArrayList(ast.TypeDecl) = .empty; - try types.appendSlice(arena, module.types); - // Registry order is lexicographic; import declaration order never affects AIR. - for (registry) |entry| { - const imported = for (module.imports) |imp| { - if (std.mem.eql(u8, imp.path, entry.name)) break true; - } else false; - if (!imported) continue; - const library = switch (try parse.parseWithFile(arena, entry.source, entry.file)) { - .ok => |m| m, - .err => |failure| return .{ .err = .{ - .code = "E7900", - .span = .{ .start = failure.pos, .end = failure.pos, .file = entry.file }, - .message = "malformed bundled standard source: a compiler bug", - } }, - }; - // Bundled source spells standard type references by their full path. - std.debug.assert(std.mem.eql(u8, library.name, entry.name)); - std.debug.assert(library.imports.len == 0); - for (library.types) |t| { - std.debug.assert(t.kind == .@"enum"); - var qualified = t; - qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, t.name }); - qualified.air_name = try airName(arena, entry.name, t.name, types.items, functions.items); - try types.append(arena, qualified); - } - for (library.functions) |f| { - var qualified = f; - qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, f.name }); - qualified.air_name = try airName(arena, entry.name, f.name, types.items, functions.items); - try functions.append(arena, qualified); - } - } - var combined = module; - combined.types = types.items; - combined.functions = functions.items; - return .{ .ok = combined }; -} - -fn airName(arena: std.mem.Allocator, module: []const u8, name: []const u8, types: []const ast.TypeDecl, functions: []const ast.FnDecl) std.mem.Allocator.Error![]const u8 { - const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ module, name }); - for (base) |*c| if (c.* == '.') { - c.* = '_'; - }; - var candidate: []const u8 = base; - var suffix: usize = 0; - while (airNameUsed(types, functions, candidate)) { - suffix += 1; - candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix }); - } - return candidate; -} - -fn airNameUsed(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool { - for (types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true; - for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true; - return false; -} - -fn problem(arena: std.mem.Allocator, code: []const u8, imp: ast.Import, message: []const u8) std.mem.Allocator.Error!Result { - return .{ .err = .{ - .code = code, - .span = imp.span, - .message = message, - .fields = try arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = imp.path }}), - } }; -} diff --git a/src/main.zig b/src/main.zig index 91433c9..e78d7d3 100644 --- a/src/main.zig +++ b/src/main.zig @@ -17,10 +17,10 @@ const usage = \\usage: aji [args] \\ \\commands: - \\ check [--report unsafe] + \\ check [--report unsafe] \\ parse and verify a text AIR module; the unsafe report \\ lists trusted boundaries and unsafe operations - \\ run [--fuel N] [--grant P=KIND[:SCOPE]]... + \\ run [--fuel N] [--grant P=KIND[:SCOPE]]... \\ verify, then run @main and print the run record; \\ --fuel stops after N executed instructions; \\ --grant binds capability parameter P of @main @@ -29,16 +29,16 @@ const usage = \\ --seed N; scheduler: --quantum N, --task-limit N, \\ --schedule-seed N; --profile hosted uses the real OS and \\ writes the record only to --result-file PATH - \\ lower [--annotate | --stats] + \\ lower [--annotate | --stats] \\ print the canonical AIR a source module lowers to; \\ --annotate adds source spans as comments (not canonical); \\ --stats prints source/AIR size and expansion ratio - \\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... + \\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... \\ run @main under every schedule and weak-memory choice \\ (depth first, up to N runs, default 100000) and print the \\ distinct outcomes; "complete" is true when the whole \\ choice tree was explored (spec 04 §20.5) - \\ report verify, then print the audit report (spec 10 §6.1) + \\ report verify, then print the audit report (spec 10 §6.1) \\ codes list diagnostic codes as JSON Lines \\ features print supported AIR format, language version and features \\ explain show one diagnostic code @@ -76,32 +76,43 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s return .accepted; } if (std.mem.eql(u8, cmd, "report")) { - if (args.len != 3) return usageError("report takes exactly one file"); - const path = args[2]; - const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| { - std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err }); - return .usage; - }; - const result = try aji.check.checkAir(arena, path, source); + const from_manifest = args.len == 4 and std.mem.eql(u8, args[2], "--manifest"); + if (args.len != 3 and !from_manifest) return usageError("report takes a file or --manifest PATH"); + const input = try readInput(arena, io, args[args.len - 1], from_manifest) orelse return .usage; + const result = try aji.check.checkWithModules(arena, input.path, input.source, input.modules); for (result.diagnostics) |d| { try d.writeJson(out); try out.writeByte('\n'); } + if (result.status == .unimplemented) return .unimplemented; const module = result.module orelse return .rejected; try aji.report.write(arena, module, out); try out.writeByte('\n'); return .accepted; } if (std.mem.eql(u8, cmd, "lower")) { - const annotate = args.len == 4 and std.mem.eql(u8, args[2], "--annotate"); - const stats = args.len == 4 and std.mem.eql(u8, args[2], "--stats"); - if (args.len != 3 and !annotate and !stats) return usageError("lower takes [--annotate | --stats] and one .aji file"); - const path = args[args.len - 1]; - const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| { - std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err }); - return .usage; - }; - switch (try aji.frontend.compile(arena, path, source)) { + var annotate = false; + var stats = false; + var manifest_path: ?[]const u8 = null; + var rest = args[2..]; + while (rest.len != 0) { + if (std.mem.eql(u8, rest[0], "--annotate") and !annotate and !stats) { + annotate = true; + rest = rest[1..]; + } else if (std.mem.eql(u8, rest[0], "--stats") and !annotate and !stats) { + stats = true; + rest = rest[1..]; + } else if (std.mem.eql(u8, rest[0], "--manifest") and rest.len >= 2 and manifest_path == null) { + manifest_path = rest[1]; + rest = rest[2..]; + } else break; + } + if ((manifest_path != null and rest.len != 0) or (manifest_path == null and rest.len != 1)) return usageError("lower takes [--annotate | --stats] and a file or --manifest PATH"); + const input = try readInput(arena, io, manifest_path orelse rest[0], manifest_path != null) orelse return .usage; + const path = input.path; + const source = input.source; + if (manifest_path != null and !std.mem.endsWith(u8, path, ".aji")) return usageError("lower requires a .aji entry"); + switch (try aji.frontend.compileWithModules(arena, path, source, input.modules)) { .ok => |o| { if (stats) { // How much mechanical work the frontend took over. @@ -190,12 +201,16 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s var result_file: ?[]const u8 = null; var rest = args[2..]; var unsafe_report = false; - if (std.mem.eql(u8, cmd, "check") and rest.len == 3 and std.mem.eql(u8, rest[0], "--report")) { + if (std.mem.eql(u8, cmd, "check") and rest.len >= 3 and std.mem.eql(u8, rest[0], "--report")) { if (!std.mem.eql(u8, rest[1], "unsafe")) return usageError("--report takes unsafe"); unsafe_report = true; rest = rest[2..]; } var manifest_path: ?[]const u8 = null; + if (std.mem.eql(u8, cmd, "check") and rest.len >= 2 and std.mem.eql(u8, rest[0], "--manifest")) { + manifest_path = rest[1]; + rest = rest[2..]; + } while (std.mem.eql(u8, cmd, "run") and rest.len >= 2) { const flag = rest[0]; const value = rest[1]; @@ -229,46 +244,18 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s rest = rest[2..]; } options.world.files = files.items; - var path: []const u8 = undefined; + var input: aji.source_package.Input = undefined; if (manifest_path) |mp| { - // spec 12 §1.2: the module is the manifest's entry; its grants - // are applied, each replaced by a --grant for the same parameter. if (rest.len != 0) return usageError("a file argument cannot be combined with --manifest"); - const text = std.Io.Dir.cwd().readFileAlloc(io, mp, arena, .limited(1 << 20)) catch |err| { - std.debug.print("aji: cannot read {s}: {t}\n", .{ mp, err }); - return .usage; - }; - const m = switch (try aji.manifest.parse(arena, text)) { - .ok => |m| m, - .err => |e| { - std.debug.print("aji: manifest {s}:{d}: {s}\n", .{ mp, e.line, e.message }); - return .usage; - }, - }; - const entry = m.entry orelse { - std.debug.print("aji: manifest {s}: [package] entry is required for aji run\n", .{mp}); - return .usage; - }; - path = try std.fs.path.join(arena, &.{ std.fs.path.dirname(mp) orelse ".", entry }); - var merged: std.ArrayList(aji.interp.Grant) = .empty; - for (m.grants) |g| { - const overridden = for (grants.items) |cg| { - if (std.mem.eql(u8, cg.parameter, g.parameter)) break true; - } else false; - if (!overridden) try merged.append(arena, .{ .parameter = g.parameter, .kind = g.kind, .scope = g.scope }); - } - try merged.appendSlice(arena, grants.items); - options.grants = merged.items; + input = try readInput(arena, io, mp, true) orelse return .usage; + options.grants = try mergeGrants(arena, input.grants, grants.items); } else { - if (rest.len != 1) return usageError("check and run take exactly one file"); - path = rest[0]; + if (rest.len != 1) return usageError("check and run take a file or --manifest PATH"); + input = try readInput(arena, io, rest[0], false) orelse return .usage; options.grants = grants.items; } - const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| { - std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err }); - return .usage; - }; - const report = try aji.check.checkFile(arena, path, source); + const path = input.path; + const report = try aji.check.checkWithModules(arena, path, input.source, input.modules); for (report.diagnostics) |d| { try d.writeJson(out); try out.writeByte('\n'); @@ -335,21 +322,22 @@ fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out: var max_runs: u64 = 100_000; var grants: std.ArrayList(aji.interp.Grant) = .empty; var rest = argv; + var manifest_path: ?[]const u8 = null; while (rest.len >= 2) { if (std.mem.eql(u8, rest[0], "--max-runs")) { max_runs = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--max-runs takes a positive integer"); } else if (std.mem.eql(u8, rest[0], "--grant")) { try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes =[:]")); + } else if (std.mem.eql(u8, rest[0], "--manifest") and manifest_path == null) { + manifest_path = rest[1]; } else break; rest = rest[2..]; } - if (rest.len != 1) return usageError("explore takes exactly one file"); - const path = rest[0]; - const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| { - std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err }); - return .usage; - }; - const report = try aji.check.checkFile(arena, path, source); + if ((manifest_path != null and rest.len != 0) or (manifest_path == null and rest.len != 1)) return usageError("explore takes a file or --manifest PATH"); + const input = try readInput(arena, io, manifest_path orelse rest[0], manifest_path != null) orelse return .usage; + const all_grants = try mergeGrants(arena, input.grants, grants.items); + const path = input.path; + const report = try aji.check.checkWithModules(arena, path, input.source, input.modules); for (report.diagnostics) |d| { try d.writeJson(out); try out.writeByte('\n'); @@ -366,7 +354,7 @@ fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out: defer run_arena.deinit(); var ex: aji.interp.Explore = .{ .prefix = prefix.items }; const outcome = aji.interp.run(run_arena.allocator(), module, "main", .{ - .grants = grants.items, + .grants = all_grants, .quantum = std.math.maxInt(u64), .explore = &ex, }) catch |err| switch (err) { @@ -496,3 +484,25 @@ test "standard library trap record identifies the bundled source" { try std.testing.expectEqualStrings("std/math.aji", location.get("file").?.string); try std.testing.expectEqual(@as(i64, 20), location.get("line").?.integer); } + +fn readInput(arena: std.mem.Allocator, io: std.Io, path: []const u8, from_manifest: bool) !?aji.source_package.Input { + return switch (if (from_manifest) try aji.source_package.load(arena, io, path) else try aji.source_package.single(arena, io, path)) { + .ok => |input| input, + .err => |err| blk: { + std.debug.print("aji: {s}:{d}: {s}\n", .{ err.path, err.line, err.message }); + break :blk null; + }, + }; +} + +fn mergeGrants(arena: std.mem.Allocator, baseline: []const aji.manifest.Grant, overrides: []const aji.interp.Grant) ![]const aji.interp.Grant { + var result: std.ArrayList(aji.interp.Grant) = .empty; + for (baseline) |grant| { + const replaced = for (overrides) |override| { + if (std.mem.eql(u8, grant.parameter, override.parameter)) break true; + } else false; + if (!replaced) try result.append(arena, .{ .parameter = grant.parameter, .kind = grant.kind, .scope = grant.scope }); + } + try result.appendSlice(arena, overrides); + return result.items; +} diff --git a/src/manifest.zig b/src/manifest.zig index b2ea80d..60fda01 100644 --- a/src/manifest.zig +++ b/src/manifest.zig @@ -6,13 +6,18 @@ //! drop or misplace authority. const std = @import("std"); +const modules = @import("frontend/modules.zig"); pub const Grant = struct { parameter: []const u8, kind: []const u8, scope: ?[]const u8 }; +pub const ModuleBinding = struct { name: []const u8, file: []const u8, line: u32 }; + pub const Manifest = struct { name: []const u8, version: []const u8, entry: ?[]const u8, + modules: []const ModuleBinding = &.{}, + has_modules: bool = false, /// `[capabilities]` in file order. grants: []const Grant, }; @@ -46,14 +51,32 @@ fn isKey(s: []const u8) bool { return true; } +fn isModuleName(name: []const u8) bool { + var parts = std.mem.splitScalar(u8, name, '.'); + while (parts.next()) |part| { + if (part.len == 0 or !(std.ascii.isAlphabetic(part[0]) or part[0] == '_')) return false; + for (part[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_')) return false; + } + return name.len != 0; +} + +pub fn sourcePath(path: []const u8) bool { + if (!std.mem.endsWith(u8, path, ".aji") or std.mem.indexOfAny(u8, path, "\\:\x00") != null) return false; + var parts = std.mem.splitScalar(u8, path, '/'); + while (parts.next()) |part| if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false; + return true; +} + pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result { - const Section = enum { none, package, capabilities, metadata }; + const Section = enum { none, package, capabilities, metadata, modules }; var section: Section = .none; - var seen_sections: [3]bool = .{ false, false, false }; + var seen_sections: [4]bool = @splat(false); var name: ?[]const u8 = null; var version: ?[]const u8 = null; var entry: ?[]const u8 = null; var grants: std.ArrayList(Grant) = .empty; + var bindings: std.ArrayList(ModuleBinding) = .empty; + var entry_line: u32 = 0; var keys: std.StringHashMapUnmanaged(void) = .empty; var lines = std.mem.splitScalar(u8, text, '\n'); @@ -74,7 +97,7 @@ pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result { } const eq = std.mem.indexOfScalar(u8, line, '=') orelse return fail(arena, line_no, "expected key = \"value\"", .{}); const key = std.mem.trim(u8, line[0..eq], " \t"); - if (!isKey(key)) return fail(arena, line_no, "malformed key", .{}); + if (!(if (section == .modules) isModuleName(key) else isKey(key))) return fail(arena, line_no, "malformed key", .{}); const value = (try parseString(arena, std.mem.trim(u8, line[eq + 1 ..], " \t"))) orelse return fail(arena, line_no, "value of {s} must be a string \"...\" (escapes \\\", \\\\, \\n), optionally followed by a # comment", .{key}); if (section == .none) return fail(arena, line_no, "key {s} outside a section", .{key}); @@ -89,15 +112,29 @@ pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result { version = value; } else if (std.mem.eql(u8, key, "entry")) { entry = value; + entry_line = line_no; } else return fail(arena, line_no, "unknown key {s} in [package]", .{key}); }, .capabilities => try grants.append(arena, parseGrantValue(key, value) orelse return fail(arena, line_no, "grant {s} must be \"kind[:scope]\"", .{key})), + .modules => { + if (modules.reserved(key)) return fail(arena, line_no, "reserved module namespace {s}", .{key}); + if (!sourcePath(value)) return fail(arena, line_no, "module {s} needs a portable relative .aji path", .{key}); + if (bindings.items.len >= 1024) return fail(arena, line_no, "at most 1024 modules are allowed", .{}); + try bindings.append(arena, .{ .name = key, .file = value, .line = line_no }); + }, .metadata => {}, .none => unreachable, } } + const has_modules = seen_sections[3]; + if (has_modules) { + const source_entry = entry orelse return fail(arena, line_no, "[modules] requires an entry .aji source", .{}); + if (!sourcePath(source_entry)) return fail(arena, entry_line, "[modules] requires a portable relative entry .aji path", .{}); + } return .{ .ok = .{ + .modules = bindings.items, + .has_modules = has_modules, .name = name orelse return fail(arena, line_no, "[package] name is required", .{}), .version = version orelse return fail(arena, line_no, "[package] version is required", .{}), .entry = entry, @@ -177,3 +214,23 @@ test "strict parsing" { try expectErr("[package]\nname = \"a\"\nversion = \"1\"\n[capabilities]\nout = \":x\"\n", 5); // empty kind try expectErr("[package]\nname = \"a\"\n", 3); // missing version: reported at the end of the file } + +test "explicit package module mapping and portable paths" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const prefix = "[package]\nname = \"a\"\nversion = \"1\"\nentry = \"src/main.aji\"\n[modules]\n"; + const good = try parse(arena, prefix ++ "app.model = \"src/model.aji\"\n"); + try std.testing.expect(good == .ok); + try std.testing.expectEqualStrings("app.model", good.ok.modules[0].name); + try std.testing.expect(good.ok.has_modules); + for ([_][]const u8{ + "app.model = \"../model.aji\"", "app.model = \"/model.aji\"", "app.model = \"src//model.aji\"", + "app.model = \"src/./model.aji\"", "app.model = \"src/model.air\"", "app.model = \"C:/model.aji\"", + "std.bytes = \"model.aji\"", "task.work = \"model.aji\"", "io.work = \"model.aji\"", + "app..model = \"model.aji\"", "app.0model = \"model.aji\"", "app-model = \"model.aji\"", + }) |line| try expectErr(try std.mem.concat(arena, u8, &.{ prefix, line }), 6); + try expectErr(prefix ++ "app.model = \"model.aji\"\napp.model = \"other.aji\"", 7); + try expectErr("[package]\nname = \"a\"\nversion = \"1\"\nentry = \"main.air\"\n[modules]\n", 4); + for ([_][]const u8{ "src\\model.aji", "a\x00.aji", "src/../a.aji", "src/.aji/../b.aji" }) |path| try std.testing.expect(!sourcePath(path)); +} diff --git a/src/root.zig b/src/root.zig index 172b5e9..7db8416 100644 --- a/src/root.zig +++ b/src/root.zig @@ -18,6 +18,7 @@ pub const check = @import("check.zig"); pub const frontend = @import("frontend.zig"); pub const report = @import("report.zig"); pub const manifest = @import("manifest.zig"); +pub const source_package = @import("source_package.zig"); test { @import("std").testing.refAllDecls(@This()); diff --git a/src/source_package.zig b/src/source_package.zig new file mode 100644 index 0000000..af35ea9 --- /dev/null +++ b/src/source_package.zig @@ -0,0 +1,91 @@ +//! Explicit manifest source snapshot. No source is executed here. +const std = @import("std"); +const manifest = @import("manifest.zig"); +const frontend = @import("frontend.zig"); + +pub const Input = struct { + path: []const u8, + source: []const u8, + modules: []const frontend.modules.Source = &.{}, + grants: []const manifest.Grant = &.{}, +}; +pub const Failure = struct { path: []const u8, line: u32 = 0, message: []const u8 }; +pub const Result = union(enum) { ok: Input, err: Failure }; +const source_limit: usize = 64 << 20; + +fn fail(arena: std.mem.Allocator, path: []const u8, err: anyerror) std.mem.Allocator.Error!Result { + if (err == error.OutOfMemory) return error.OutOfMemory; + return .{ .err = .{ .path = path, .message = try std.fmt.allocPrint(arena, "cannot read source: {t}", .{err}) } }; +} + +pub fn single(arena: std.mem.Allocator, io: std.Io, path: []const u8) std.mem.Allocator.Error!Result { + const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(source_limit)) catch |err| return fail(arena, path, err); + return .{ .ok = .{ .path = path, .source = source } }; +} + +pub fn load(arena: std.mem.Allocator, io: std.Io, path: []const u8) std.mem.Allocator.Error!Result { + const text = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| return fail(arena, path, err); + const m = switch (try manifest.parse(arena, text)) { + .ok => |m| m, + .err => |err| return .{ .err = .{ .path = path, .line = err.line, .message = err.message } }, + }; + const entry = m.entry orelse return .{ .err = .{ .path = path, .message = "[package] entry is required" } }; + const parent = std.fs.path.dirname(path) orelse "."; + const entry_path = try std.fs.path.join(arena, &.{ parent, entry }); + if (!m.has_modules) { + var result = try single(arena, io, entry_path); + if (result == .ok) result.ok.grants = m.grants; + return result; + } + const root = std.Io.Dir.cwd().openDir(io, parent, .{}) catch |err| return fail(arena, parent, err); + defer root.close(io); + const source = readSource(arena, io, root, entry, source_limit) catch |err| return fail(arena, entry, err); + var remaining = source_limit - source.len; + const bindings = try arena.dupe(manifest.ModuleBinding, m.modules); + std.mem.sort(manifest.ModuleBinding, bindings, {}, struct { + fn less(_: void, a: manifest.ModuleBinding, b: manifest.ModuleBinding) bool { + return std.mem.lessThan(u8, a.name, b.name); + } + }.less); + var sources: std.ArrayList(frontend.modules.Source) = .empty; + for (bindings) |binding| { + const bytes = readSource(arena, io, root, binding.file, remaining) catch |err| return fail(arena, binding.file, err); + remaining -= bytes.len; + try sources.append(arena, .{ .name = binding.name, .file = binding.file, .source = bytes }); + } + return .{ .ok = .{ .path = entry_path, .source = source, .modules = sources.items, .grants = m.grants } }; +} + +fn readSource(arena: std.mem.Allocator, io: std.Io, root: std.Io.Dir, path: []const u8, limit: usize) ![]const u8 { + std.debug.assert(manifest.sourcePath(path)); + var dirs: std.ArrayList(std.Io.Dir) = .empty; + defer for (dirs.items) |dir| dir.close(io); + var current = root; + var parts = std.mem.splitScalar(u8, path, '/'); + while (parts.next()) |part| { + if (parts.peek() != null) { + const next = try current.openDir(io, part, .{ .follow_symlinks = false }); + dirs.append(arena, next) catch |err| { + next.close(io); + return err; + }; + current = next; + continue; + } + // Avoid opening a static pipe/device; the opened handle is checked too. + if ((try current.statFile(io, part, .{ .follow_symlinks = false })).kind != .file) return error.NotRegularSource; + const file = try current.openFile(io, part, .{ .follow_symlinks = false, .allow_directory = false }); + defer file.close(io); + const stat = try file.stat(io); + if (stat.kind != .file) return error.NotRegularSource; + if (stat.size > limit) return error.StreamTooLong; + var reader = file.reader(io, &.{}); + const bytes = reader.interface.allocRemaining(arena, .limited(limit + 1)) catch |err| switch (err) { + error.ReadFailed => return reader.err.?, + else => return err, + }; + if (bytes.len > limit) return error.StreamTooLong; + return bytes; + } + unreachable; +} diff --git a/std/README.md b/std/README.md index f736327..cb55c73 100644 --- a/std/README.md +++ b/std/README.md @@ -27,7 +27,7 @@ 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. General user imports, imported struct literals, generics and owning collections are still 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). Generics and owning collections remain future work. [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) diff --git a/tests/conformance/README.md b/tests/conformance/README.md index 8b84cdd..47920c0 100644 --- a/tests/conformance/README.md +++ b/tests/conformance/README.md @@ -32,6 +32,7 @@ Every test starts with a block of `;` lines. Keys: | `file` | no, repeatable | `=`: expected contents of a file written by the run | | `fuel` | no | instruction limit for `run` tests (spec 11 §7.1); default 1 000 000. Running out is a `FAIL`, never a pass | | `equivalent` | no, `.aji` `run` tests only | path, relative to `tests/conformance`, of a reference AIR program. Both are run with this test's world and grants; their run records must be byte-identical (for a trap, the trap code must match, since the record carries the AIR location; `schedule.choices` is not compared, since the scheduler's quantum counts AIR instructions and the lowered program may have a different instruction stream). The AIR texts may differ | +| `module` | no, repeatable, `.aji` only | `NAME=PATH`: explicit source provider; path is relative to `tests/conformance`. Reachable sources are linked through the ordinary frontend. Use `.aji.inc` for helper files so they are not standalone tests | | `phase` | yes | implementation phase number | | `spec` | yes | spec section that justifies the expectation | diff --git a/tests/conformance/modules/nominal_call.air b/tests/conformance/modules/nominal_call.air new file mode 100644 index 0000000..a9b3e2a --- /dev/null +++ b/tests/conformance/modules/nominal_call.air @@ -0,0 +1,21 @@ +; expect: reject E1001 +; phase: 0 +; spec: docs/spec/15-source-language.md §14.3; docs/spec/07a-air-instructions.md +module app.entry +air 0 +lang 0.1 +features [] +type @app_a_Pair = struct { value: u64 } +type @app_b_Pair = struct { value: u64 } +fn @app_a_total(%pair: @app_a_Pair) -> u64 +effects [] +entry: + %value = struct.get @app_a_Pair.value, %pair + ret %value +fn @main() -> u64 +effects [] +entry: + %value = const.u64 42 + %pair = struct.make @app_b_Pair(%value) + %result = call @app_a_total(%pair) + ret %result diff --git a/tests/conformance/modules/record.air b/tests/conformance/modules/record.air new file mode 100644 index 0000000..a911f8f --- /dev/null +++ b/tests/conformance/modules/record.air @@ -0,0 +1,24 @@ +; expect: run +; result: 42 +; phase: 0 +; spec: docs/spec/15-source-language.md §14.3; docs/spec/07a-air-instructions.md +module app.entry +air 0 +lang 0.1 +features [] +type @Pair = struct { left: u64, right: u64 } +fn @sum(%pair: @Pair) -> u64 +effects [] +entry: + %left = struct.get @Pair.left, %pair + %right = struct.get @Pair.right, %pair + %total = add.checked.u64 %left, %right + ret %total +fn @main() -> u64 +effects [] +entry: + %left = const.u64 20 + %right = const.u64 22 + %pair = struct.make @Pair(%left, %right) + %result = call @sum(%pair) + ret %result diff --git a/tests/conformance/source/modules/alias.aji b/tests/conformance/source/modules/alias.aji new file mode 100644 index 0000000..b05754c --- /dev/null +++ b/tests/conformance/source/modules/alias.aji @@ -0,0 +1,7 @@ +// expect: reject E2101 E2101 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.borrow=source/modules/borrow.aji.inc +module app.entry +import app.borrow; +fn main() -> u8 effects [] { var data: [u8; 4] = zero; ref held = data; app.borrow.fill(mut data); return held[0]; } diff --git a/tests/conformance/source/modules/bad_member.aji.inc b/tests/conformance/source/modules/bad_member.aji.inc new file mode 100644 index 0000000..c6f8ac3 --- /dev/null +++ b/tests/conformance/source/modules/bad_member.aji.inc @@ -0,0 +1,2 @@ +module app.bad +fn nope() -> u8 effects [] { return missing(); } diff --git a/tests/conformance/source/modules/bad_syntax.aji.inc b/tests/conformance/source/modules/bad_syntax.aji.inc new file mode 100644 index 0000000..ed261bf --- /dev/null +++ b/tests/conformance/source/modules/bad_syntax.aji.inc @@ -0,0 +1,2 @@ +module app.broken +fn nope( diff --git a/tests/conformance/source/modules/borrow.aji b/tests/conformance/source/modules/borrow.aji new file mode 100644 index 0000000..1de4cd3 --- /dev/null +++ b/tests/conformance/source/modules/borrow.aji @@ -0,0 +1,8 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.borrow=source/modules/borrow.aji.inc +module app.entry +import app.borrow; +fn main() -> u8 effects [] { var data: [u8; 4] = zero; app.borrow.fill(mut data); return data[3]; } diff --git a/tests/conformance/source/modules/borrow.aji.inc b/tests/conformance/source/modules/borrow.aji.inc new file mode 100644 index 0000000..18e4ba9 --- /dev/null +++ b/tests/conformance/source/modules/borrow.aji.inc @@ -0,0 +1,2 @@ +module app.borrow +fn fill(dst: slice_mut) -> void effects [] { for i in 0..dst.len { dst[i] = 42; } } diff --git a/tests/conformance/source/modules/collision.aji b/tests/conformance/source/modules/collision.aji new file mode 100644 index 0000000..41ab30d --- /dev/null +++ b/tests/conformance/source/modules/collision.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +struct __aji_app_model_Pair { own_value: u64 } +fn __aji_app_model_total() -> u64 effects [] { return 7; } +fn main() -> u64 effects [] { + assert(__aji_app_model_total() == 7); + let pair = app.model.Pair { right: 22, left: 20 }; + return app.model.total(pair); +} diff --git a/tests/conformance/source/modules/cycle.aji b/tests/conformance/source/modules/cycle.aji new file mode 100644 index 0000000..d9e333a --- /dev/null +++ b/tests/conformance/source/modules/cycle.aji @@ -0,0 +1,8 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.a=source/modules/cycle_a.aji.inc +// module: app.b=source/modules/cycle_b.aji.inc +module app.entry +import app.a; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/cycle_a.aji.inc b/tests/conformance/source/modules/cycle_a.aji.inc new file mode 100644 index 0000000..1f678de --- /dev/null +++ b/tests/conformance/source/modules/cycle_a.aji.inc @@ -0,0 +1,3 @@ +module app.a +import app.b; +fn value() -> u8 effects [] { return 1; } diff --git a/tests/conformance/source/modules/cycle_b.aji.inc b/tests/conformance/source/modules/cycle_b.aji.inc new file mode 100644 index 0000000..cc8748a --- /dev/null +++ b/tests/conformance/source/modules/cycle_b.aji.inc @@ -0,0 +1,2 @@ +module app.b +import app.a; diff --git a/tests/conformance/source/modules/duplicate_binding.aji b/tests/conformance/source/modules/duplicate_binding.aji new file mode 100644 index 0000000..b1b9170 --- /dev/null +++ b/tests/conformance/source/modules/duplicate_binding.aji @@ -0,0 +1,8 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/duplicate_import.aji b/tests/conformance/source/modules/duplicate_import.aji new file mode 100644 index 0000000..d92dee9 --- /dev/null +++ b/tests/conformance/source/modules/duplicate_import.aji @@ -0,0 +1,8 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +import app.model; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/duplicate_member.aji b/tests/conformance/source/modules/duplicate_member.aji new file mode 100644 index 0000000..e230551 --- /dev/null +++ b/tests/conformance/source/modules/duplicate_member.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.duplicate=source/modules/duplicate_member.aji.inc +module app.entry +import app.duplicate; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/duplicate_member.aji.inc b/tests/conformance/source/modules/duplicate_member.aji.inc new file mode 100644 index 0000000..cc3908b --- /dev/null +++ b/tests/conformance/source/modules/duplicate_member.aji.inc @@ -0,0 +1,3 @@ +module app.duplicate +fn member() -> u64 effects [] { return 1; } +fn member() -> u64 effects [] { return 2; } diff --git a/tests/conformance/source/modules/effect.aji.inc b/tests/conformance/source/modules/effect.aji.inc new file mode 100644 index 0000000..36e81ec --- /dev/null +++ b/tests/conformance/source/modules/effect.aji.inc @@ -0,0 +1,2 @@ +module app.effect +fn emit(out: cap) -> void effects [io.write] { io.stdout_write(out, b"module") or trap; } diff --git a/tests/conformance/source/modules/effects.aji b/tests/conformance/source/modules/effects.aji new file mode 100644 index 0000000..b2fed9e --- /dev/null +++ b/tests/conformance/source/modules/effects.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// grant: out=io.write +// stdout: module +// module: app.effect=source/modules/effect.aji.inc +module app.entry +import app.effect; +fn main(out: cap) -> u64 effects [io.write] { app.effect.emit(out); return 42; } diff --git a/tests/conformance/source/modules/error_in_unused_member.aji b/tests/conformance/source/modules/error_in_unused_member.aji new file mode 100644 index 0000000..f604232 --- /dev/null +++ b/tests/conformance/source/modules/error_in_unused_member.aji @@ -0,0 +1,7 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.bad=source/modules/bad_member.aji.inc +module app.entry +import app.bad; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/example.aji b/tests/conformance/source/modules/example.aji new file mode 100644 index 0000000..627e817 --- /dev/null +++ b/tests/conformance/source/modules/example.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/example_model.aji.inc +module app.entry +import app.model; + +fn main() -> u64 +effects [] +{ + let pair = app.model.Pair { left: 20, right: 22 }; + return app.model.total(pair); +} diff --git a/tests/conformance/source/modules/example_model.aji.inc b/tests/conformance/source/modules/example_model.aji.inc new file mode 100644 index 0000000..b794fcd --- /dev/null +++ b/tests/conformance/source/modules/example_model.aji.inc @@ -0,0 +1,7 @@ +module app.model + +struct Pair { left: u64, right: u64 } + +fn total(pair: Pair) -> u64 +effects [] +{ return pair.left + pair.right; } diff --git a/tests/conformance/source/modules/fields.aji b/tests/conformance/source/modules/fields.aji new file mode 100644 index 0000000..e1d8907 --- /dev/null +++ b/tests/conformance/source/modules/fields.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.fields=source/modules/fields.aji.inc +module app.entry +import app.fields; +fn main() -> u64 effects [] { + var pair: app.fields.Pair = app.fields.Pair { left: 19, right: 22 }; + app.fields.increment(mut pair); + let wrapper = app.fields.Wrap { pair: pair }; + let value: app.fields.Pair = app.fields.unwrap(wrapper); + return app.fields.total(ref value); +} diff --git a/tests/conformance/source/modules/fields.aji.inc b/tests/conformance/source/modules/fields.aji.inc new file mode 100644 index 0000000..80bf8ec --- /dev/null +++ b/tests/conformance/source/modules/fields.aji.inc @@ -0,0 +1,6 @@ +module app.fields +struct Pair { left: u64, right: u64 } +struct Wrap { pair: Pair } +fn increment(pair: mut) -> void effects [] { pair.left = pair.left + 1; } +fn total(pair: ref) -> u64 effects [] { return pair.left + pair.right; } +fn unwrap(value: Wrap) -> Pair effects [] { return value.pair; } diff --git a/tests/conformance/source/modules/mismatched_module.aji b/tests/conformance/source/modules/mismatched_module.aji new file mode 100644 index 0000000..7e6b03e --- /dev/null +++ b/tests/conformance/source/modules/mismatched_module.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.other=source/modules/model.aji.inc +module app.entry +import app.other; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/missing_effect.aji b/tests/conformance/source/modules/missing_effect.aji new file mode 100644 index 0000000..e57c352 --- /dev/null +++ b/tests/conformance/source/modules/missing_effect.aji @@ -0,0 +1,7 @@ +// expect: reject E3101 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.effect=source/modules/effect.aji.inc +module app.entry +import app.effect; +fn main(out: cap) -> u64 effects [] { app.effect.emit(out); return 42; } diff --git a/tests/conformance/source/modules/missing_field.aji b/tests/conformance/source/modules/missing_field.aji new file mode 100644 index 0000000..8093eb6 --- /dev/null +++ b/tests/conformance/source/modules/missing_field.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +fn main() -> u64 effects [] { let pair = app.model.Pair { left: 20 }; return pair.left; } diff --git a/tests/conformance/source/modules/missing_module.aji b/tests/conformance/source/modules/missing_module.aji new file mode 100644 index 0000000..0326c41 --- /dev/null +++ b/tests/conformance/source/modules/missing_module.aji @@ -0,0 +1,6 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +module app.entry +import app.unknown; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/missing_move.aji b/tests/conformance/source/modules/missing_move.aji new file mode 100644 index 0000000..5a8a268 --- /dev/null +++ b/tests/conformance/source/modules/missing_move.aji @@ -0,0 +1,7 @@ +// expect: reject E7003 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.owner=source/modules/owner.aji.inc +module app.entry +import app.owner; +fn main(mem: cap) -> u64 effects [mem.alloc] { let value = own.new(42u64, mem) or trap; app.owner.dispose(value); return 42; } diff --git a/tests/conformance/source/modules/model.aji.inc b/tests/conformance/source/modules/model.aji.inc new file mode 100644 index 0000000..b09f97f --- /dev/null +++ b/tests/conformance/source/modules/model.aji.inc @@ -0,0 +1,9 @@ +module app.model +struct Pair { left: u64, right: u64 } +struct Wrap { pair: Pair } +enum State { Done(Pair), Empty } +fn make() -> Pair effects [] { return Pair { left: 20, right: 22 }; } +fn total(pair: Pair) -> u64 effects [] { return pair.left + pair.right; } +fn helper() -> u64 effects [] { return 10; } +fn local() -> u64 effects [] { return helper(); } +fn main() -> u64 effects [] { return 9; } diff --git a/tests/conformance/source/modules/no_short_import.aji b/tests/conformance/source/modules/no_short_import.aji new file mode 100644 index 0000000..a9b7ecd --- /dev/null +++ b/tests/conformance/source/modules/no_short_import.aji @@ -0,0 +1,7 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +fn main() -> u64 effects [] { let pair = Pair { left: 20, right: 22 }; return pair.left; } diff --git a/tests/conformance/source/modules/nominal.aji b/tests/conformance/source/modules/nominal.aji new file mode 100644 index 0000000..a8bac59 --- /dev/null +++ b/tests/conformance/source/modules/nominal.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +// module: app.other=source/modules/other.aji.inc +module app.entry +import app.model; +import app.other; +fn main() -> u64 effects [] { let pair: app.model.Pair = app.other.make(); return pair.left; } diff --git a/tests/conformance/source/modules/other.aji.inc b/tests/conformance/source/modules/other.aji.inc new file mode 100644 index 0000000..83b6764 --- /dev/null +++ b/tests/conformance/source/modules/other.aji.inc @@ -0,0 +1,3 @@ +module app.other +struct Pair { left: u64, right: u64 } +fn make() -> Pair effects [] { return Pair { left: 20, right: 22 }; } diff --git a/tests/conformance/source/modules/owner.aji b/tests/conformance/source/modules/owner.aji new file mode 100644 index 0000000..998767f --- /dev/null +++ b/tests/conformance/source/modules/owner.aji @@ -0,0 +1,9 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// grant: mem=mem.alloc:128 +// module: app.owner=source/modules/owner.aji.inc +module app.entry +import app.owner; +fn main(mem: cap) -> u64 effects [mem.alloc] { let value = own.new(42u64, mem) or trap; app.owner.dispose(move value); return 42; } diff --git a/tests/conformance/source/modules/owner.aji.inc b/tests/conformance/source/modules/owner.aji.inc new file mode 100644 index 0000000..a700cf2 --- /dev/null +++ b/tests/conformance/source/modules/owner.aji.inc @@ -0,0 +1,2 @@ +module app.owner +fn dispose(value: own) -> void effects [] { own.free(move value); } diff --git a/tests/conformance/source/modules/record.aji b/tests/conformance/source/modules/record.aji new file mode 100644 index 0000000..87eab19 --- /dev/null +++ b/tests/conformance/source/modules/record.aji @@ -0,0 +1,22 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// equivalent: modules/record.air +// module: app.work=source/modules/work.aji.inc +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +import app.work; +fn helper() -> u64 effects [] { return 100; } +fn main() -> u64 effects [] { + let app = 7u8; + assert(app == 7); + assert(helper() == 100); + assert(app.model.local() == 10); + assert(app.model.main() == 9); + let p: app.model.Pair = app.work.run(); + let w = app.model.Wrap { pair: p }; + let state = app.model.State::Done(w.pair); + match state { app.model.State::Done(pair) => { return app.model.total(pair); } app.model.State::Empty => { return 0; } } +} diff --git a/tests/conformance/source/modules/root_self.aji b/tests/conformance/source/modules/root_self.aji new file mode 100644 index 0000000..e6651f0 --- /dev/null +++ b/tests/conformance/source/modules/root_self.aji @@ -0,0 +1,8 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +module app.entry +struct Pair { value: u64 } +fn total(pair: Pair) -> u64 effects [] { return pair.value; } +fn main() -> u64 effects [] { return app.entry.total(app.entry.Pair { value: 42 }); } diff --git a/tests/conformance/source/modules/self_import.aji b/tests/conformance/source/modules/self_import.aji new file mode 100644 index 0000000..30d3713 --- /dev/null +++ b/tests/conformance/source/modules/self_import.aji @@ -0,0 +1,6 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +module app.entry +import app.entry; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/syntax_in_module.aji b/tests/conformance/source/modules/syntax_in_module.aji new file mode 100644 index 0000000..0edec80 --- /dev/null +++ b/tests/conformance/source/modules/syntax_in_module.aji @@ -0,0 +1,7 @@ +// expect: reject E7001 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.broken=source/modules/bad_syntax.aji.inc +module app.entry +import app.broken; +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/task.aji b/tests/conformance/source/modules/task.aji new file mode 100644 index 0000000..cd418cc --- /dev/null +++ b/tests/conformance/source/modules/task.aji @@ -0,0 +1,9 @@ +// expect: run +// result: 10 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// schedules: 8 +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +fn main() -> u64 effects [task.spawn, task.wait] { var result: u64 = 0; scope s { let t = task.spawn(s, app.model.local); result = task.join(move t); } return result; } diff --git a/tests/conformance/source/modules/task_lend.aji b/tests/conformance/source/modules/task_lend.aji new file mode 100644 index 0000000..29af0f4 --- /dev/null +++ b/tests/conformance/source/modules/task_lend.aji @@ -0,0 +1,31 @@ +// Two tasks square the two halves of one buffer; the halves are lent until the joins. +// expect: run +// result: [1,4,9,16] +// equivalent: phase3/run/tasks_parallel_square.air +// schedules: 8 +// module: app.workers=source/modules/workers.aji.inc +// phase: 6 +// spec: docs/spec/15-source-language.md +module app.entry +import app.workers; + +fn main() -> [u64; 4] +effects [task.spawn] +{ + var buf: [u64; 4] = zero; + buf[0] = 1; + buf[1] = 2; + buf[2] = 3; + buf[3] = 4; + { + mut s = buf; + let (l, r) = s.split_at(2); + scope sc { + let t1 = task.spawn(sc, app.workers.square, l); + let t2 = task.spawn(sc, app.workers.square, r); + task.join(move t1); + task.join(move t2); + } + } + buf +} diff --git a/tests/conformance/source/modules/task_lend_twice.aji b/tests/conformance/source/modules/task_lend_twice.aji new file mode 100644 index 0000000..05defe3 --- /dev/null +++ b/tests/conformance/source/modules/task_lend_twice.aji @@ -0,0 +1,23 @@ +// The same exclusive borrow lent to two live tasks: a possible data race (E4101). +// expect: reject E4101 +// module: app.workers=source/modules/workers.aji.inc +// phase: 6 +// spec: docs/spec/15-source-language.md +module app.entry +import app.workers; + +fn main() -> u64 +effects [task.spawn] +{ + var buf: [u64; 2] = zero; + { + mut s = buf; + scope sc { + let a = task.spawn(sc, app.workers.bump, s); + let b = task.spawn(sc, app.workers.bump, s); + task.join(move a); + task.join(move b); + } + } + buf[0] +} diff --git a/tests/conformance/source/modules/task_missing_import.aji b/tests/conformance/source/modules/task_missing_import.aji new file mode 100644 index 0000000..f9d4f8b --- /dev/null +++ b/tests/conformance/source/modules/task_missing_import.aji @@ -0,0 +1,13 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +// module: app.work=source/modules/work.aji.inc +module app.entry +import app.work; +fn main() -> u64 effects [task.spawn, task.wait] { + scope s { + let t = task.spawn(s, app.model.local); + return task.join(move t); + } +} diff --git a/tests/conformance/source/modules/transitive_call.aji b/tests/conformance/source/modules/transitive_call.aji new file mode 100644 index 0000000..0468615 --- /dev/null +++ b/tests/conformance/source/modules/transitive_call.aji @@ -0,0 +1,8 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.work=source/modules/work.aji.inc +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.work; +fn main() -> u64 effects [] { return app.model.local(); } diff --git a/tests/conformance/source/modules/transitive_enum.aji b/tests/conformance/source/modules/transitive_enum.aji new file mode 100644 index 0000000..90ee563 --- /dev/null +++ b/tests/conformance/source/modules/transitive_enum.aji @@ -0,0 +1,8 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.work=source/modules/work.aji.inc +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.work; +fn main() -> u64 effects [] { let value = app.model.State::Empty; return 42; } diff --git a/tests/conformance/source/modules/transitive_type.aji b/tests/conformance/source/modules/transitive_type.aji new file mode 100644 index 0000000..e64616e --- /dev/null +++ b/tests/conformance/source/modules/transitive_type.aji @@ -0,0 +1,8 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.work=source/modules/work.aji.inc +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.work; +fn main() -> u64 effects [] { let pair: app.model.Pair = app.work.run(); return pair.left; } diff --git a/tests/conformance/source/modules/unknown_member.aji b/tests/conformance/source/modules/unknown_member.aji new file mode 100644 index 0000000..5853b27 --- /dev/null +++ b/tests/conformance/source/modules/unknown_member.aji @@ -0,0 +1,7 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/model.aji.inc +module app.entry +import app.model; +fn main() -> u64 effects [] { return app.model.nope(); } diff --git a/tests/conformance/source/modules/unreachable.aji b/tests/conformance/source/modules/unreachable.aji new file mode 100644 index 0000000..7eb4322 --- /dev/null +++ b/tests/conformance/source/modules/unreachable.aji @@ -0,0 +1,7 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.broken=source/modules/bad_syntax.aji.inc +module app.entry +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/modules/work.aji.inc b/tests/conformance/source/modules/work.aji.inc new file mode 100644 index 0000000..6e84223 --- /dev/null +++ b/tests/conformance/source/modules/work.aji.inc @@ -0,0 +1,5 @@ +module app.work +import app.model; +import std.math; +fn run() -> app.model.Pair effects [] { return app.model.make(); } +fn bounded(value: u64) -> u64 effects [] { return std.math.min_u64(value, 42); } diff --git a/tests/conformance/source/modules/workers.aji.inc b/tests/conformance/source/modules/workers.aji.inc new file mode 100644 index 0000000..d2b9153 --- /dev/null +++ b/tests/conformance/source/modules/workers.aji.inc @@ -0,0 +1,3 @@ +module app.workers +fn square(s: slice_mut) -> void effects [] { for i in 0..s.len { s[i] = s[i] * s[i]; } } +fn bump(s: slice_mut) -> void effects [] { s[0] = s[0] + 1; } diff --git a/tests/conformance/source/quickref/modules.aji b/tests/conformance/source/quickref/modules.aji new file mode 100644 index 0000000..627e817 --- /dev/null +++ b/tests/conformance/source/quickref/modules.aji @@ -0,0 +1,14 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §14 +// module: app.model=source/modules/example_model.aji.inc +module app.entry +import app.model; + +fn main() -> u64 +effects [] +{ + let pair = app.model.Pair { left: 20, right: 22 }; + return app.model.total(pair); +} diff --git a/tests/hosted/source_modules.py b/tests/hosted/source_modules.py new file mode 100644 index 0000000..ec5741a --- /dev/null +++ b/tests/hosted/source_modules.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Explicit package inputs through the CLI; runs use fuel, never timeouts.""" +import json +import os +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, cwd=None): + global checks + result = subprocess.run([str(AJI), *map(str, args)], cwd=cwd, capture_output=True, text=True) + assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + +def write_manifest(root, mapping='app.model = "src/model.aji"', grants=""): + path = root / "aji.toml" + path.write_text('[package]\nname = "fixture"\nversion = "1"\nentry = "src/main.aji"\n[modules]\n' + mapping + '\n' + grants) + return path + + +with tempfile.TemporaryDirectory(prefix="aji-source-modules-") as directory: + root = Path(directory) + (root / "src").mkdir() + main = root / "src/main.aji" + model = root / "src/model.aji" + main.write_text((REPO / "examples/modules/main.aji").read_text()) + model.write_text((REPO / "examples/modules/model.aji").read_text()) + manifest = write_manifest(root) + cli("check", "--manifest", manifest) + record = cli("run", "--fuel", "1000000", "--manifest", manifest) + assert json.loads(record.stdout) == {"status": "returned", "value": 42} + canonical = cli("lower", "--manifest", manifest).stdout + assert cli("lower", "--manifest", manifest, cwd="/").stdout == canonical + annotation = cli("lower", "--annotate", "--manifest", manifest).stdout + assert "; src/model.aji:" in annotation + cli("lower", "--stats", "--manifest", manifest) + cli("report", "--manifest", manifest) + cli("check", "--report", "unsafe", "--manifest", manifest) + cli("explore", "--max-runs", "8", "--manifest", manifest) + # No ambient lookup, even with an aji.toml next to the entry. + diagnostic = json.loads(cli("check", main, code=1).stdout) + assert diagnostic["code"] == "E7002" + cli("run", "--manifest", manifest, main, code=2) + cli("lower", "--manifest", manifest, main, code=2) + cli("check", "--manifest", manifest, main, code=2) + # Mapping/import order cannot change canonical output. + other = root / "src/other.aji" + other.write_text("module app.other\nstruct Pair { value: u64 }\n") + original = main.read_text() + main.write_text(original.replace("import app.model;", "import app.model;\nimport app.other;")) + write_manifest(root, 'app.other = "src/other.aji"\napp.model = "src/model.aji"') + ordered = cli("lower", "--manifest", manifest).stdout + write_manifest(root, 'app.model = "src/model.aji"\napp.other = "src/other.aji"') + main.write_text(main.read_text().replace("import app.model;\nimport app.other;", "import app.other;\nimport app.model;")) + assert cli("lower", "--manifest", manifest).stdout == ordered + main.write_text(original) + write_manifest(root) + # Errors and traps name the actual imported source. + saved_model = model.read_text() + model.write_text("module app.model\nfn broken(\n") + diagnostic = json.loads(cli("check", "--manifest", manifest, code=1).stdout) + assert diagnostic["code"] == "E7001" and diagnostic["file"] == "src/model.aji" + assert "expected" in diagnostic and "found" in diagnostic + model.write_text("module app.model\nfn total(value: u64) -> u64 effects [] { assert(false); return value; }\n") + main.write_text("module app.entry\nimport app.model;\nfn main() -> u64 effects [] { return app.model.total(42); }\n") + trapped = json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest, code=4).stdout) + assert trapped["source_location"]["file"] == "src/model.aji" + main.write_text(original) + model.write_text(saved_model) + # Imported authority is explicit; checking never instantiates grants. + model.write_text('module app.model\nfn emit(out: cap) -> void effects [io.write] { io.stdout_write(out, b"module") or trap; }\n') + main.write_text("module app.entry\nimport app.model;\nfn main(out: cap) -> u64 effects [io.write] { app.model.emit(out); return 42; }\n") + cli("check", "--manifest", manifest) + missing = cli("run", "--fuel", "1000000", "--manifest", manifest, code=6) + assert json.loads(missing.stdout)["status"] == "not_instantiated" + write_manifest(root, grants='[capabilities]\nout = "io.write"\n') + granted = json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest).stdout) + assert granted["stdout"] == "module" + overridden = cli("run", "--fuel", "1000000", "--manifest", manifest, "--grant", "out=io.read", code=6) + assert json.loads(overridden.stdout)["status"] == "not_instantiated" + cli("explore", "--max-runs", "8", "--manifest", manifest) + result_file = root / "result.json" + hosted = cli("run", "--profile", "hosted", "--fuel", "1000000", "--result-file", result_file, "--manifest", manifest) + assert hosted.stdout == "module" and json.loads(result_file.read_text())["value"] == 42 + main.write_text(original) + model.write_text(saved_model) + write_manifest(root) + # Invalid paths/reserved names reject as manifest errors, without source execution. + for mapping in ('app.model = "../outside.aji"', 'app.model = "/outside.aji"', + 'app.model = "src/./model.aji"', 'std.bytes = "src/model.aji"', + 'app.model = "src/model.aji"\napp.model = "src/other.aji"'): + write_manifest(root, mapping) + assert cli("check", "--manifest", manifest, code=2).stdout == "" + write_manifest(root, 'app.model = "src/missing.aji"') + cli("check", "--manifest", manifest, code=2) + # Reject source symlinks and directory symlinks, including entry links. + outside = root / "outside.aji" + outside.write_text(saved_model) + link = root / "src/link.aji" + link.symlink_to(outside) + write_manifest(root, 'app.model = "src/link.aji"') + cli("check", "--manifest", manifest, code=2) + alias = root / "alias" + alias.symlink_to(root / "src", target_is_directory=True) + write_manifest(root, 'app.model = "alias/model.aji"') + cli("check", "--manifest", manifest, code=2) + entry_link = root / "src/entry-link.aji" + entry_link.symlink_to(main) + write_manifest(root) + manifest.write_text(manifest.read_text().replace('entry = "src/main.aji"', 'entry = "src/entry-link.aji"')) + cli("check", "--manifest", manifest, code=2) + # Static pipes/directories are rejected without a blocking read. + pipe = root / "src/pipe.aji" + os.mkfifo(pipe) + write_manifest(root, 'app.model = "src/pipe.aji"') + cli("check", "--manifest", manifest, code=2) + (root / "src/directory.aji").mkdir() + write_manifest(root, 'app.model = "src/directory.aji"') + cli("check", "--manifest", manifest, code=2) + large = root / "src/large.aji" + with large.open("wb") as stream: + stream.truncate((64 << 20) + 1) + write_manifest(root, 'app.model = "src/large.aji"') + cli("check", "--manifest", manifest, code=2) + # Aggregate budget is enforced before parsing even if each input fits alone. + with main.open("wb") as stream: + stream.truncate(63 << 20) + with large.open("wb") as stream: + stream.truncate(2 << 20) + cli("check", "--manifest", manifest, code=2) + +print(f"source module CLI integration passed ({checks} checks)") diff --git a/tools/conformance.zig b/tools/conformance.zig index 1eb9951..246c7a1 100644 --- a/tools/conformance.zig +++ b/tools/conformance.zig @@ -39,6 +39,8 @@ const Outcome = enum { pass, fail, pending }; /// runs always use a limit). const default_fuel: u64 = 1_000_000; +const ModuleBinding = struct { name: []const u8, path: []const u8 }; + const Header = struct { expect: Expect, fuel: u64, @@ -57,6 +59,7 @@ const Header = struct { /// `.aji` only: a reference AIR program (relative to the conformance /// root) whose observable run must equal this one's. equivalent: ?[]const u8 = null, + modules: []const ModuleBinding = &.{}, }; pub fn main(init: std.process.Init) !void { @@ -151,10 +154,15 @@ const stress_quanta = [_]u64{ 1, 2, 7 }; fn runSource(arena: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, rel: []const u8, path: []const u8, source: []const u8) !Result { const header = parseHeader(arena, source) catch |err| return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) }; - const report = try aji.check.checkFile(arena, path, source); + var modules: std.ArrayList(aji.frontend.modules.Source) = .empty; + for (header.modules) |binding| { + const text = dir.readFileAlloc(io, binding.path, arena, .limited(64 << 20)) catch |err| return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "module {s}: {t}", .{ binding.path, err }) }; + try modules.append(arena, .{ .name = binding.name, .file = binding.path, .source = text }); + } + const report = try aji.check.checkWithModules(arena, path, source, modules.items); if (report.status == .unimplemented) return .{ .outcome = .pending, .detail = report.missing_stage }; if (report.lowered) |lowered| { - const again = try aji.frontend.compile(arena, path, source); + const again = try aji.frontend.compileWithModules(arena, path, source, modules.items); if (again != .ok or !std.mem.eql(u8, again.ok.air, lowered.air)) return .{ .outcome = .fail, .detail = "lowering is not deterministic" }; const parsed = try aji.air.parse.parse(arena, path, lowered.air); if (parsed.module) |m| { @@ -452,7 +460,7 @@ fn formatExpect(e: Expect, w: *std.Io.Writer) std.Io.Writer.Error!void { } } -const HeaderError = error{ BadGrant, MissingExpect, MissingPhase, MissingSpec, MissingRunResult, UnknownKey, UnknownCode, BadExpect, OutOfMemory, InvalidCharacter, Overflow }; +const HeaderError = error{ BadModule, BadGrant, MissingExpect, MissingPhase, MissingSpec, MissingRunResult, UnknownKey, UnknownCode, BadExpect, OutOfMemory, InvalidCharacter, Overflow }; fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header { var expect: ?Expect = null; @@ -470,6 +478,7 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header var want_stderr: ?[]const u8 = null; var spec: ?[]const u8 = null; var equivalent: ?[]const u8 = null; + var modules: std.ArrayList(ModuleBinding) = .empty; var lines = std.mem.splitScalar(u8, source, '\n'); while (lines.next()) |line| { @@ -549,6 +558,10 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header phase = try std.fmt.parseInt(u8, value, 10); } else if (std.mem.eql(u8, key, "spec")) { spec = value; + } else if (std.mem.eql(u8, key, "module")) { + const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadModule; + if (eq == 0 or eq + 1 == value.len) return error.BadModule; + try modules.append(arena, .{ .name = value[0..eq], .path = value[eq + 1 ..] }); } else if (std.mem.eql(u8, key, "equivalent")) { equivalent = value; } else return error.UnknownKey; @@ -574,6 +587,7 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header .phase = phase orelse return error.MissingPhase, .spec = spec orelse return error.MissingSpec, .equivalent = equivalent, + .modules = modules.items, }; } diff --git a/tools/source_coverage.py b/tools/source_coverage.py index 3fd5912..0cca406 100644 --- a/tools/source_coverage.py +++ b/tools/source_coverage.py @@ -20,6 +20,10 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source") # (area, construct, regex, needs a reject test) CHECKLIST = [ + ("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), + ("modules", "qualified task worker", r"task\.spawn\(\w+, app\.", True), ("stdlib", "qualified standard enum type", r": std\.(?:bytes|fmt|math|utf8|encoding\.(?:hex|base64))\.[A-Z]\w*\b", True), ("stdlib", "qualified standard enum constructor", r"std\.(?:bytes|fmt|math|utf8|encoding\.(?:hex|base64))\.[A-Z]\w*::\w+(?:\(|;)", True), ("stdlib", "qualified standard enum match", r"std\.(?:bytes|fmt|math|utf8|encoding\.(?:hex|base64))\.[A-Z]\w*::\w+(?:\([^)]*\))? =>", True),