air: feature negotiation for AIR format 0 (DD-014)

- reference/air-features.md: normative feature registry (arrays,
  atomics, capabilities, channels, effects, islands, ownership, regions,
  sync, tasks; all reserved), dependency closures, reasons for E0006
- spec 07 §8.1/§8.5/§8.7: features are mandatory, validated before the
  body, full dependency closure declared, sorted canonically; every
  extension belongs to a feature; published feature semantics immutable
- spec 05 §8: features vs effects vs capabilities
- src/air/features.zig: registry, validation, sync test with the docs
- parser validates features first; E0006 carries `reason`
- `aji features` prints supported AIR format, language and features
- conformance: unknown, reserved and duplicate feature tests
- plan: feature publication tasks in phases 1-5
This commit is contained in:
dev committed 2026-10-04 12:49:29 +03:00
1 parent 03dda1245a
commit 19dff5dd52
24 files changed
+366 -17

No files matched your search

+2 -2
View File
@@ -68,7 +68,7 @@ The specification is the single normative source. When documents disagree, use t
RFCs are architectural decision records with rationale, not a normative layer. Accepting an RFC means its rule changes are integrated into `docs/spec/` (and `docs/reference/`) in the same change; from then on the spec, not the RFC, is authoritative. If an accepted RFC and the spec disagree, the spec wins and the RFC is out of date.
AIR format 0 is a frozen semantic baseline (spec 07 §8.7): do not change the meaning of existing format-0 constructs; extend only as §8.7 allows, otherwise introduce a new format version through an RFC.
AIR format 0 is a frozen semantic baseline (spec 07 §8.7): do not change the meaning of existing format-0 constructs; extend only as §8.7 allows, otherwise introduce a new format version through an RFC. Every extension belongs to a registered feature (`docs/reference/air-features.md`); modules declare features and their full dependency closure in the `features [...]` header. Keep three concepts apart: features (what the implementation must understand), effects (what code does), capabilities (what code may do).
## Normative language
@@ -131,7 +131,7 @@ zig fmt --check build.zig build.zig.zon src tools
Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing.
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded. `aji run [--fuel N]` prints one JSON run record. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded. `aji run [--fuel N]` prints one JSON run record. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
## Testing policy
+3 -2
View File
@@ -49,8 +49,9 @@ Everything under `src/` except `main.zig` is part of the trusted computing base
2. **Spec first.** If the behavior is not specified, change the spec (or write an RFC for major changes) before code. Never let the implementation define semantics silently.
3. **Tests first.** Add conformance tests (`accept` and `reject`) for every verifier rule touched.
4. **Implement.**
5. **Diagnostics.** A new rejection needs a code in `docs/reference/error-codes.md` *and* `src/diag.zig`; the unit test fails if they drift.
6. **Run** `zig fmt`, `zig build test`, `zig build conformance`.
5. **Features.** A new AIR construct belongs to a feature in `docs/reference/air-features.md`; publishing a feature means specifying it fully, changing its status to `published` in the registry and `src/air/features.zig`, and adding it to `supported`.
6. **Diagnostics.** A new rejection needs a code in `docs/reference/error-codes.md` *and* `src/diag.zig`; the unit test fails if they drift.
7. **Run** `zig fmt`, `zig build test`, `zig build conformance`.
## Definition of done
+3
View File
@@ -15,6 +15,9 @@ pub fn build(b: *std.Build) void {
mod.addAnonymousImport("error_codes_md", .{
.root_source_file = b.path("docs/reference/error-codes.md"),
});
mod.addAnonymousImport("air_features_md", .{
.root_source_file = b.path("docs/reference/air-features.md"),
});
// CLI: `aji`.
const exe = b.addExecutable(.{
+1
View File
@@ -10,5 +10,6 @@
"src",
"tools",
"docs/reference/error-codes.md",
"docs/reference/air-features.md",
},
}
+1
View File
@@ -31,6 +31,7 @@ RFCs are not in this list: accepting an RFC integrates its rules into `spec/` in
| a MUST/SHOULD rule | the matching `spec/NN-*.md` |
| a major change to memory, concurrency, effects, AIR or unsafe | `rfcs/NNNN-title.md` from `rfcs/0000-template.md` |
| a new error code, intrinsic or grammar rule | `reference/` (and `src/diag.zig` for codes) |
| a new AIR feature bundle | `reference/air-features.md` (and `src/air/features.zig`) |
| a small decision with a one-paragraph reason | `design/decisions.md` as the next `DD-NNN` |
| a gap or ambiguity you found but cannot resolve now | `design/open-questions.md` as the next `Q-NNN` |
| tasks, milestones, sequencing | `plan/` |
+6
View File
@@ -75,3 +75,9 @@ Reason: a stable foundation lets generated code, tests and tools rely on format
Runs are bounded by fuel (executed AIR instructions), never by wall-clock time. Exhaustion is the outcome `limit_exceeded` (exit code 5), not a trap.
Reason: timeouts make test outcomes depend on machine speed; a trap code for exhaustion would make the test harness part of the language semantics.
## DD-014 — AIR feature negotiation
AIR format 0 uses the mandatory `features [...]` header as an explicit semantic compatibility contract. Every post-baseline AIR 0 extension belongs to a registered feature (`reference/air-features.md`). Modules MUST declare every feature they use and its dependency closure. Implementations MUST validate the feature set before validating the module body. Unknown, unsupported, undeclared, duplicated or dependency-incomplete features are reported as `E0006` with a structured `reason`. Feature semantics are immutable once published. `aji features` reports what a toolchain supports.
Reason: format 0 is frozen; features make it an extensible protocol without an older implementation half-parsing a module it cannot understand. One code with a reason keeps the §8.7 exception for `E0006` intact.
+1
View File
@@ -80,6 +80,7 @@ These run through all phases rather than belonging to one.
| Diagnostics | New codes are added to `../reference/error-codes.md` and `src/diag.zig` together; structured fields per code are documented in the spec section that defines the rule. |
| Determinism | Every run test is executed twice and compared from P0-12 on; concurrency tests add schedule stress from P3. |
| Audit reports | Each phase that adds an auditable fact (unsafe sites, effects, capabilities, weak atomics, eliminated checks) extends the report in `src/report/` (spec 10 §6, spec 13 §5). |
| Features | Every phase from P1 publishes its feature bundles (`../reference/air-features.md`) when their semantics are specified, and adds them to `supported` when implemented. `aji features` is the discovery interface for agents. |
| Packages | Minimal `aji.toml` reading for capabilities in P2; dependencies, lockfile and sandboxed build extensions in P8 (spec 12). |
## Task conventions
+2 -1
View File
@@ -21,7 +21,8 @@ Out: islands, `Arc`, `Pin`, raw addresses (beyond rejecting them in safe code).
| ID | Status | Task | Depends | Output | Done when |
|---|---|---|---|---|---|
| P1-1 | todo | Resolve Q-009 and Q-010; propose RFC 0001 memory sections for acceptance | — | spec 03, 07, RFC 0001 | questions resolved; RFC ready for the owner, rules integrated on acceptance |
| P1-2 | todo | Contract tables for Phase 1 opcodes | P1-1 | spec 07 appendix | every in-scope opcode has all spec 07 §4 fields, including verifier transfer function |
| P1-2 | todo | Contract tables for Phase 1 opcodes, grouped by feature (`arrays`, `ownership`, `regions`) | P1-1 | spec 07a | every in-scope opcode has all spec 07 §4 fields, including verifier transfer function, and names its feature |
| P1-2a | todo | Feature gating in the parser: constructs of an undeclared feature report `E0006` reason `feature_not_declared`; publish `arrays`, `ownership`, `regions` in the registry and add them to `supported` once implemented | P1-2 | `src/air/features.zig`, `src/air/parse.zig`, `reference/air-features.md` | reject test per feature for `feature_not_declared` and `missing_dependency`; `aji features` lists the three |
| P1-3 | todo | Interpreter memory: allocations, provenance, bounds, region generations, uninitialized bytes | P1-2 | `src/interp/memory.zig` | unit tests: every access checks provenance; reading uninitialized bytes is detected in interpreter debug checks |
| P1-4 | todo | Initialization verifier | P1-2 | `src/verifier/init.zig` | E1010 accept/reject (scalar, struct field, array prefix) |
| P1-5 | todo | Ownership state machine | P1-2 | `src/verifier/ownership.zig` | E2001, E2002 accept/reject, including across branches and loops |
@@ -22,6 +22,7 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
|---|---|---|---|---|---|
| P2-1 | todo | Resolve Q-011, Q-012, Q-018 | — | spec 05, 07, 10 | questions resolved; runtime record format defined |
| P2-2 | todo | Formal signatures for fs, io, net, clock, random intrinsics | P2-1 | `reference/intrinsics.md` | each intrinsic lists types, effects, capabilities, ownership, failure, blocking (spec 09 §2) |
| P2-2a | todo | Publish features `effects` and `capabilities` (spec text, registry status, `supported`); effect checking applies to modules declaring `effects` | P2-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests; baseline modules unaffected |
| P2-3 | todo | Contract tables for `intrinsic.call`, `resource.consume`, `call.indirect` | P2-1 | spec 07 appendix | all spec 07 §4 fields present |
| P2-4 | todo | Effect verifier | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees |
| P2-5 | todo | Capability verifier: unforgeability, narrowing, transfer rules | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject |
@@ -24,6 +24,7 @@ Non-normative. Part of the [implementation plan](README.md).
|---|---|---|---|---|---|
| P3-1 | todo | Resolve Q-013, Q-014; propose RFC 0002 for acceptance | — | spec 04, 11 | questions resolved |
| P3-2 | todo | Contract tables: `task.*`, `thread.*`, `channel.*`, `mutex.*`, `rwlock.*`, select | P3-1 | spec 07 appendix | all spec 07 §4 fields including synchronization effects |
| P3-2a | todo | Publish features `tasks`, `channels`, `sync` | P3-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P3-3 | todo | Deterministic scheduler: seeds, choice points, choice log; global fuel across tasks and a separate `quantum` (spec 11 §7.2) | P3-2 | `src/interp/sched.zig` | same seed ⇒ identical trace; choice log replays a run; fuel is the sum over all tasks |
| P3-4 | todo | Send/Share/Local derivation | P3-1 | `src/verifier/send_share.zig` | E4001, E4002 accept/reject |
| P3-5 | todo | Task-scope verifier and scoped borrows | P3-2 | `src/verifier/tasks.zig` | E4301, E4302 accept/reject |
+1
View File
@@ -23,6 +23,7 @@ Non-normative. Part of the [implementation plan](README.md).
| ID | Status | Task | Depends | Output | Done when |
|---|---|---|---|---|---|
| P4-1 | todo | Contract tables: `island.create`, `island.alloc`, `island.freeze`, `iref` access, `arc.clone`, `arc.release` | — | spec 07 appendix | all spec 07 §4 fields present |
| P4-1a | todo | Publish feature `islands` | P4-1 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P4-2 | todo | Island allocator in the interpreter (private regions, O(1) transfer) | P4-1 | `src/interp/memory.zig` | transfer cost independent of graph size (unit benchmark with fixed bound) |
| P4-3 | todo | `iref` verifier and closure checks | P4-1 | `src/verifier/island.zig` | E2110, E2111 accept/reject |
| P4-4 | todo | Island transfer through channels and task spawn; sender invalidation | P4-3 | verifier + interpreter | sender use after send rejected (E2001) |
@@ -23,6 +23,7 @@ Non-normative. Part of the [implementation plan](README.md).
|---|---|---|---|---|---|
| P5-1 | todo | Resolve Q-015, Q-017; propose RFC 0003 for acceptance | — | spec 04, 11 | questions resolved |
| P5-2 | todo | Contract tables: `atomic.load`, `atomic.store`, `atomic.rmw`, `atomic.cmpxchg`, `atomic.fence` | P5-1 | spec 07 appendix | all fields present, including allowed orderings per op |
| P5-2a | todo | Publish feature `atomics` | P5-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P5-3 | todo | Atomic types and ordering validation | P5-2 | `src/verifier/atomics.zig` | E4201 accept/reject for every op, including cmpxchg failure order |
| P5-4 | todo | `atomic` / `atomic.weak` effect marking | P5-3 | verifier + report | relaxed use without `atomic.weak` rejected per Q-011 outcome; weak sites listed in report |
| P5-5 | todo | Weak-memory model in the interpreter | P5-1 | `src/interp/weak.zig` | SB weak outcome reachable; MP forbidden outcome unreachable |
+63
View File
@@ -0,0 +1,63 @@
# AIR Feature Registry
Normative registry for the `features [...]` header of AIR format 0 (spec 07 §8.1, §8.7). `src/air/features.zig` mirrors this table; a unit test fails if they drift.
## What a feature is
A feature is a coherent block of AIR semantics added to format 0 after the Phase 0 baseline: its types, instructions, verifier rules, diagnostics and interpreter behavior. A module that declares a feature tells the implementation: *to verify and execute this module you must understand these semantics.*
Features are not build options. Three concepts stay separate:
| Concept | Question it answers | Where |
|---|---|---|
| feature | what the AIR implementation must understand | module header `features [...]` |
| effect | what a function does | function `effects [...]` (spec 05) |
| capability | what an invocation is allowed to do | `cap<…>` values (spec 05) |
Declaring `features [capabilities, effects, ownership]` grants no authority. It only states that the module uses capability semantics.
## Rules
- `features []` is the Phase 0 baseline.
- Every post-baseline construct belongs to exactly one feature. A feature is a whole semantic block, not one instruction.
- A module MUST declare every feature whose constructs it uses, plus the full dependency closure; nothing is implied.
- Canonical form: names sorted lexicographically, no duplicates.
- Status `reserved`: the name and dependencies are fixed, semantics are not yet specified; modules MUST NOT use it (`unsupported_feature`).
- Status `published`: semantics are specified in spec 07a and the relevant spec files, and are immutable. Incompatible evolution needs a new feature name or a new AIR format version.
- A dependency is listed only when the feature's semantics cannot be stated without it.
## Registry
| Feature | Status | Phase | Depends on | Semantic block |
|---|---|---|---|---|
| `arrays` | reserved | 1 | — | fixed-size arrays `[T; N]`, checked indexing |
| `atomics` | reserved | 5 | `ownership` | atomic types, the five orderings, fences, `atomic.*` instructions |
| `capabilities` | reserved | 2 | `effects`, `ownership` | `cap<…>` values, narrowing, delegation, capability-gated intrinsics |
| `channels` | reserved | 3 | `ownership` | bounded and rendezvous channels with ownership transfer |
| `effects` | reserved | 2 | — | effect checking of `effects [...]` lists (E3101) |
| `islands` | reserved | 4 | `ownership`, `regions` | `Island<T>`, `iref<T>`, transfer, freeze, `Frozen<T>` |
| `ownership` | reserved | 1 | — | `Own<T>`, `move`, `ref<T>`/`mut<T>` borrows, slices, initialization, linearity |
| `regions` | reserved | 1 | `ownership` | `Region`, generations, region allocation, reset and destroy |
| `sync` | reserved | 3 | `ownership` | `Mutex<T>`, `RwLock<T>`, linear guards |
| `tasks` | reserved | 3 | `ownership` | structured task scopes, spawn/join/cancel, `Send`/`Share` |
`capabilities` depends on `effects` so that every module that can perform an external operation is also effect-checked.
`effects` in the baseline: format-0 modules already carry `effects [...]` lines. Without the `effects` feature these lists are recorded but not checked; there is no effectful operation in the baseline, so nothing can escape checking.
## Diagnostics
Feature problems are reported as `E0006` (`module.unsupported_feature`) with a `reason` field, before the module body is examined:
| `reason` | Meaning | Extra fields |
|---|---|---|
| `unknown_feature` | name not in this registry | `feature` |
| `unsupported_feature` | registered but reserved, or not implemented by this toolchain | `feature` |
| `missing_dependency` | a dependency of a declared feature is not declared | `feature`, `requires` |
| `duplicate_feature` | the same name is declared twice | `feature` |
| `feature_not_declared` | the body uses a construct of an undeclared feature | `feature`, `construct` |
| `reserved_type` | the body uses a reserved type such as `f32` (spec 07 §8.4) | `type` |
## Discovery
`aji features` prints the toolchain's AIR format, language version and supported features as one JSON object, e.g. `{"air":0,"lang":"0.1","features":[]}`. Agents query it before generating AIR.
+1 -1
View File
@@ -11,7 +11,7 @@ Draft registry. Codes are stable once released in a tagged compiler version.
| E0003 | parse.duplicate_name | Function, type, block, field or variant name defined twice |
| E0004 | parse.unknown_name | Unknown opcode, type, function, field or variant |
| E0005 | module.unsupported_version | AIR format or language version not implemented |
| E0006 | module.unsupported_feature | Required feature or reserved type not implemented |
| E0006 | module.unsupported_feature | Feature unknown, unsupported, undeclared or dependency-incomplete, or reserved type used; field `reason` (reference/air-features.md) |
## E1xxx — Types and values
+4
View File
@@ -99,3 +99,7 @@ The toolchain should be able to emit:
- capability requirements per entry point;
- effective transitive authority;
- unsafe/FFI authority boundaries.
## 8. Relation to AIR features
AIR features (spec 07 §8.1) are a third, separate concept. A feature says which semantics the implementation must understand; it grants no authority and adds no effect. Declaring `features [capabilities, effects, ownership]` does not let a program read a file: the function still needs `effects [fs.read]` and a `cap<fs.read>` value.
+16 -4
View File
@@ -198,7 +198,17 @@ lang 0.1
features []
```
An implementation MUST reject a module whose `air` format version or `lang` version it does not implement (`E0005`), and a module that lists a feature it does not implement (`E0006`). Format version 0 defines no features.
An implementation MUST reject a module whose `air` format version or `lang` version it does not implement (`E0005`).
The `features` line is the semantic compatibility contract of the module: it lists the feature bundles ([`../reference/air-features.md`](../reference/air-features.md)) an implementation MUST understand to verify and execute the module. `features []` is the Phase 0 baseline.
- A module MUST declare every feature whose constructs it uses, together with the full dependency closure of those features; a feature never implies another.
- The same name MUST NOT appear twice.
- An implementation MUST validate the feature list before examining the module body, and MUST NOT examine the body if any feature is unknown, unsupported, duplicated or missing a declared dependency.
- A construct belonging to a feature that the module does not declare is rejected.
- All of these are reported as `E0006` with a `reason` field (`unknown_feature`, `unsupported_feature`, `duplicate_feature`, `missing_dependency`, `feature_not_declared`); see the registry for the fields of each reason.
Features describe what the implementation must understand. They grant no authority and declare no effects: effects (spec 05 §2) say what a function does and capabilities (spec 05 §3) say what an invocation may do.
### 8.2 Functions and blocks
@@ -217,11 +227,11 @@ An implementation MUST reject a module whose `air` format version or `lang` vers
### 8.4 Reserved
`f32` and `f64` are reserved until floating-point determinism is specified (open question Q-016). A module that uses them MUST be rejected with `E0006`.
`f32` and `f64` are reserved until floating-point determinism is specified (open question Q-016). A module that uses them MUST be rejected with `E0006`, reason `reserved_type`.
### 8.5 Canonical form
The canonical serialization of a module is: the four header lines; one blank line; type declarations in declaration order, one per line; for each function, a blank line, the signature line, the `effects` line, then each block label at column 0 followed by its instructions indented by four spaces. Separators are `", "` between list items and single spaces elsewhere. Comments are not preserved. Value, block, function and type names are preserved.
The canonical serialization of a module is: the four header lines, with feature names sorted lexicographically; one blank line; type declarations in declaration order, one per line; for each function, a blank line, the signature line, the `effects` line, then each block label at column 0 followed by its instructions indented by four spaces. Separators are `", "` between list items and single spaces elsewhere. Comments are not preserved. Value, block, function and type names are preserved.
Serializing a parsed module and parsing the result MUST yield an equal module.
@@ -237,7 +247,9 @@ A change is permitted under `air 0` only if all of the following hold:
1. every module accepted before the change is still accepted and produces the same run record (spec 07a "Run result") or the same trap record;
2. every module rejected before the change is still rejected with the same codes, **except** where the rejection was `E0004` (unknown opcode or type name) or `E0006` (reserved type or unsupported feature) and the change gives that name a meaning;
3. the change adds instructions, types, header features, diagnostic codes or trap codes, and specifies each new instruction in spec 07a before it is implemented;
3. the change adds instructions, types, diagnostic codes or trap codes; every added construct belongs to a feature registered in [`../reference/air-features.md`](../reference/air-features.md), and the feature's semantics are specified (spec 07a and the relevant spec files) before the feature is published and implemented;
4. the canonical form (§8.5) of existing constructs is unchanged.
A published feature's semantics are immutable. Extending a feature with new semantics is not permitted; register a new feature instead.
Any other change to format 0 — a different meaning, typing rule, trap behavior, diagnostic code or canonical spelling for an existing construct — requires a new format version (`air 1`) introduced by an RFC. An implementation that supports several format versions selects the semantics by the module's `air` line; it never mixes them.
+2
View File
@@ -30,9 +30,11 @@ pub const successors = module.successors;
pub const parse = @import("air/parse.zig");
pub const print = @import("air/print.zig");
pub const features = @import("air/features.zig");
test {
_ = module;
_ = parse;
_ = print;
_ = features;
}
+178
View File
@@ -0,0 +1,178 @@
//! AIR feature negotiation (spec 07 §8.1, §8.7; reference/air-features.md).
//!
//! `registry` MUST mirror docs/reference/air-features.md (enforced by a test).
//! `supported` lists the features this toolchain implements.
const std = @import("std");
pub const Status = enum {
/// Name and dependencies are fixed; semantics are specified in the phase
/// that publishes the feature. Modules may not use it yet.
reserved,
/// Semantics are specified and immutable.
published,
};
pub const Feature = struct {
name: []const u8,
depends: []const []const u8,
status: Status,
/// Plan phase that publishes the feature.
phase: u8,
};
pub const registry = [_]Feature{
.{ .name = "arrays", .depends = &.{}, .status = .reserved, .phase = 1 },
.{ .name = "atomics", .depends = &.{"ownership"}, .status = .reserved, .phase = 5 },
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .reserved, .phase = 2 },
.{ .name = "channels", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "effects", .depends = &.{}, .status = .reserved, .phase = 2 },
.{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .reserved, .phase = 4 },
.{ .name = "ownership", .depends = &.{}, .status = .reserved, .phase = 1 },
.{ .name = "regions", .depends = &.{"ownership"}, .status = .reserved, .phase = 1 },
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
};
/// Features implemented by this toolchain, sorted. Empty: Phase 0 baseline.
pub const supported = [_][]const u8{};
pub const Reason = enum {
unknown_feature,
unsupported_feature,
feature_not_declared,
missing_dependency,
duplicate_feature,
reserved_type,
};
pub const Problem = struct {
reason: Reason,
feature: []const u8,
/// For `missing_dependency`: the dependency that is not declared.
requires: ?[]const u8 = null,
/// Index into the declared list, for locating the diagnostic.
index: usize,
};
pub fn find(reg: []const Feature, name: []const u8) ?Feature {
for (reg) |f| if (std.mem.eql(u8, f.name, name)) return f;
return null;
}
fn contains(list: []const []const u8, name: []const u8) bool {
for (list) |x| if (std.mem.eql(u8, x, name)) return true;
return false;
}
/// Validates a declared feature set before the module body is examined.
/// Problems are reported in declaration order; for one feature at most one
/// problem is reported, checked in the order duplicate, unknown,
/// unsupported, missing dependency.
pub fn validate(
arena: std.mem.Allocator,
declared: []const []const u8,
reg: []const Feature,
sup: []const []const u8,
) std.mem.Allocator.Error![]const Problem {
var problems: std.ArrayList(Problem) = .empty;
for (declared, 0..) |name, i| {
if (contains(declared[0..i], name)) {
try problems.append(arena, .{ .reason = .duplicate_feature, .feature = name, .index = i });
continue;
}
const f = find(reg, name) orelse {
try problems.append(arena, .{ .reason = .unknown_feature, .feature = name, .index = i });
continue;
};
if (f.status != .published or !contains(sup, name)) {
try problems.append(arena, .{ .reason = .unsupported_feature, .feature = name, .index = i });
continue;
}
for (f.depends) |dep| if (!contains(declared, dep)) {
try problems.append(arena, .{ .reason = .missing_dependency, .feature = name, .requires = dep, .index = i });
break;
};
}
return problems.items;
}
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
return std.mem.lessThan(u8, a, b);
}
/// Canonical order of a feature list (spec 07 §8.5).
pub fn sort(list: [][]const u8) void {
std.mem.sort([]const u8, list, {}, lessThan);
}
// ---------------------------------------------------------------- tests
const test_registry = [_]Feature{
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
.{ .name = "regions", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
.{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .published, .phase = 4 },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
};
fn expectProblems(declared: []const []const u8, sup: []const []const u8, want: []const Reason) !void {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const ps = try validate(arena_state.allocator(), declared, &test_registry, sup);
try std.testing.expectEqual(want.len, ps.len);
for (want, ps) |w, p| try std.testing.expectEqual(w, p.reason);
}
test "feature validation" {
const all = [_][]const u8{ "islands", "ownership", "regions", "tasks" };
try expectProblems(&.{}, &all, &.{});
try expectProblems(&.{ "islands", "ownership", "regions" }, &all, &.{});
try expectProblems(&.{ "islands", "ownership" }, &all, &.{.missing_dependency});
try expectProblems(&.{"regions"}, &all, &.{.missing_dependency});
try expectProblems(&.{"magic"}, &all, &.{.unknown_feature});
try expectProblems(&.{ "ownership", "ownership" }, &all, &.{.duplicate_feature});
try expectProblems(&.{ "ownership", "tasks" }, &all, &.{.unsupported_feature}); // reserved
try expectProblems(&.{"ownership"}, &.{}, &.{.unsupported_feature}); // not implemented here
}
test "registry is sorted, closed under dependencies and acyclic" {
for (registry, 0..) |f, i| {
if (i > 0) try std.testing.expect(std.mem.lessThan(u8, registry[i - 1].name, f.name));
for (f.depends) |d| {
const dep = find(&registry, d) orelse return error.UnknownDependency;
// Dependencies are themselves closed: a feature lists its full closure.
for (dep.depends) |dd| try std.testing.expect(contains(f.depends, dd));
try std.testing.expect(dep.phase <= f.phase);
try std.testing.expect(!contains(dep.depends, f.name));
}
}
}
test "registry mirrors docs/reference/air-features.md" {
const md = @embedFile("air_features_md");
var seen: usize = 0;
var lines = std.mem.splitScalar(u8, md, '\n');
var in_registry = false;
while (lines.next()) |line| {
if (std.mem.startsWith(u8, line, "## ")) in_registry = std.mem.eql(u8, line, "## Registry");
// Table rows look like: | `name` | reserved | 1 | `dep`, `dep` | description |
if (!in_registry or !std.mem.startsWith(u8, line, "| `")) continue;
var cols = std.mem.tokenizeScalar(u8, line, '|');
const name = std.mem.trim(u8, cols.next().?, " `");
const status = std.mem.trim(u8, cols.next().?, " ");
const phase = try std.fmt.parseInt(u8, std.mem.trim(u8, cols.next().?, " "), 10);
const deps_text = std.mem.trim(u8, cols.next().?, " ");
const f = find(&registry, name) orelse {
std.debug.print("feature {s} is in air-features.md but not in the registry\n", .{name});
return error.RegistryOutOfSync;
};
try std.testing.expectEqualStrings(@tagName(f.status), status);
try std.testing.expectEqual(f.phase, phase);
var n: usize = 0;
var deps = std.mem.tokenizeAny(u8, deps_text, "`, —");
while (deps.next()) |d| : (n += 1) try std.testing.expect(contains(f.depends, d));
try std.testing.expectEqual(f.depends.len, n);
seen += 1;
}
try std.testing.expectEqual(registry.len, seen);
}
+28 -6
View File
@@ -9,6 +9,7 @@
const std = @import("std");
const diag = @import("../diag.zig");
const air = @import("module.zig");
const features_mod = @import("features.zig");
const Allocator = std.mem.Allocator;
const Span = air.Span;
@@ -272,13 +273,30 @@ const Parser = struct {
});
_ = try p.expect(.nl, "end of line");
_ = try p.expectWord("features");
const features = try p.parsePathList();
for (features) |f| try p.report("E0006", lang_tok.span, "unsupported feature", &.{
.{ .name = "feature", .value = .{ .str = f } },
});
const features_tok = try p.expectWord("features");
const features = try p.arena.dupe([]const u8, try p.parsePathList());
_ = try p.expect(.nl, "end of line");
// Features are validated before the body (spec 07 §8.1). If any is
// unusable the body is not examined: its constructs may belong to it.
const problems = try features_mod.validate(p.arena, features, &features_mod.registry, &features_mod.supported);
for (problems) |pr| {
if (pr.requires) |req| {
try p.report("E0006", features_tok.span, "feature dependency not declared", &.{
.{ .name = "reason", .value = .{ .str = @tagName(pr.reason) } },
.{ .name = "feature", .value = .{ .str = pr.feature } },
.{ .name = "requires", .value = .{ .str = req } },
});
} else {
try p.report("E0006", features_tok.span, "feature cannot be used", &.{
.{ .name = "reason", .value = .{ .str = @tagName(pr.reason) } },
.{ .name = "feature", .value = .{ .str = pr.feature } },
});
}
}
if (problems.len != 0) return error.SyntaxError;
features_mod.sort(features);
try p.prescanDeclarations();
var types: std.ArrayList(air.TypeDecl) = .empty;
@@ -444,7 +462,10 @@ const Parser = struct {
if (std.mem.eql(u8, t.text, "void")) return .void;
if (std.mem.eql(u8, t.text, "never")) return .never;
if (std.mem.eql(u8, t.text, "f32") or std.mem.eql(u8, t.text, "f64")) {
try p.report("E0006", t.span, "floating-point types are reserved (spec 07 §8.4)", &.{.{ .name = "type", .value = .{ .str = t.text } }});
try p.report("E0006", t.span, "floating-point types are reserved (spec 07 §8.4)", &.{
.{ .name = "reason", .value = .{ .str = "reserved_type" } },
.{ .name = "type", .value = .{ .str = t.text } },
});
return .void;
}
try p.report("E0004", t.span, "unknown type", &.{.{ .name = "name", .value = .{ .str = t.text } }});
@@ -967,6 +988,7 @@ test "resolution diagnostics" {
try expectCodes(header ++ "fn @f() -> f32\neffects []\nentry:\n trap\n", &.{"E0006"});
try expectCodes(header ++ "fn @f() -> u8\neffects []\nentry:\n trap\nfn @f() -> u8\neffects []\nentry:\n trap\n", &.{"E0003"});
try expectCodes("module t\nair 1\nlang 0.1\nfeatures []\n", &.{"E0005"});
try expectCodes("module t\nair 0\nlang 0.1\nfeatures [magic, ownership, ownership]\nfn @f( -> broken\n", &.{ "E0006", "E0006", "E0006" });
try expectCodes(header ++ "fn @f( -> u8\n", &.{"E0001"});
try expectCodes(header ++ "type\n", &.{"E0001"}); // found by fuzzing
}
+1 -1
View File
@@ -22,7 +22,7 @@ pub const registry = [_]Code{
.{ .id = "E0003", .kind = "parse.duplicate_name", .meaning = "Function, type, block, field or variant name defined twice" },
.{ .id = "E0004", .kind = "parse.unknown_name", .meaning = "Unknown opcode, type, function, field or variant" },
.{ .id = "E0005", .kind = "module.unsupported_version", .meaning = "AIR format or language version not implemented" },
.{ .id = "E0006", .kind = "module.unsupported_feature", .meaning = "Required feature or reserved type not implemented" },
.{ .id = "E0006", .kind = "module.unsupported_feature", .meaning = "Feature unknown, unsupported, undeclared or dependency-incomplete, or reserved type used" },
// E1xxx — Types and values
.{ .id = "E1001", .kind = "type.mismatch", .meaning = "Operand/result type mismatch" },
.{ .id = "E1002", .kind = "type.invalid_cast", .meaning = "Cast not permitted by safe semantics" },
+11
View File
@@ -20,6 +20,7 @@ const usage =
\\ verify, then run @main and print the run record;
\\ --fuel stops after N executed instructions
\\ codes list diagnostic codes as JSON Lines
\\ features print supported AIR format, language version and features
\\ explain <code> show one diagnostic code
\\ version print toolchain version
\\
@@ -54,6 +55,16 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
try out.print("aji {s} (air format {d})\n", .{ aji.version, aji.air.format_version });
return .accepted;
}
if (std.mem.eql(u8, cmd, "features")) {
var s: std.json.Stringify = .{ .writer = out };
try s.write(.{
.air = aji.air.format_version,
.lang = std.fmt.comptimePrint("{d}.{d}", .{ aji.air.lang_version[0], aji.air.lang_version[1] }),
.features = &aji.air.features.supported,
});
try out.writeByte('\n');
return .accepted;
}
if (std.mem.eql(u8, cmd, "codes")) {
for (aji.diag.registry) |c| try writeCode(out, c);
return .accepted;
@@ -0,0 +1,13 @@
; The same feature is declared twice: reasons unsupported_feature (arrays is reserved) and duplicate_feature.
; expect: reject E0006 E0006
; phase: 0
; spec: docs/spec/07-air.md
module test.duplicate_feature
air 0
lang 0.1
features [arrays, arrays]
fn @f() -> void
effects []
entry:
ret
@@ -0,0 +1,13 @@
; ownership is registered but reserved until Phase 1 publishes it.
; expect: reject E0006
; phase: 0
; spec: docs/spec/07-air.md
module test.reserved_feature
air 0
lang 0.1
features [ownership]
fn @f() -> void
effects []
entry:
ret
@@ -0,0 +1,13 @@
; Feature name not in the registry.
; expect: reject E0006
; phase: 0
; spec: docs/spec/07-air.md
module test.unknown_feature
air 0
lang 0.1
features [teleport]
fn @f() -> void
effects []
entry:
ret