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.
This commit is contained in:
dev committed 2026-10-06 18:51:54 +03:00
1 parent 618b4b95c1
commit c96199e7ec
81 files changed
+1419 -234

No files matched your search

+23 -2
View File
@@ -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:
+37 -8
View File
@@ -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 <dotted.path>`, then type and function declarations in any order.
- Between the module header and declarations, `import <dotted.path>;` imports a built-in standard module (§13). `import` is contextual at this position; it remains an ordinary identifier elsewhere.
- Between the module header and declarations, `import <dotted.path>;` 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<T>` 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 %<storage>, <literal>`, where `<literal>` 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<app.model.Pair>` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals remain forbidden in unparenthesized conditions, where `{` starts a block. This adds no methods, reflection, generic arguments or permission to store forbidden linear/borrowed values in aggregates.
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.