Phase 2: effects and capabilities (RFC 0006)

- air: cap<K> and built-in enums (cap_error) as types; enum.switch over
  built-in enums; cap.narrow terminator with ok/err targets; intrinsic
  syntax (registry still empty: E0004); registries for effects,
  capability kinds and built-in enums, synced with reference docs
- verifier: effect stage (E3101, flat, direct callees); cap.narrow form
  check (E3202) and ok/err parameter rules (E5002, E1001); capabilities
  are copyable, not zeroable, not comparable; sizes cap 8, built-in tag
- interp: host authority table; @main instantiation from grants by
  parameter name with not_instantiated reasons; capabilities render as
  opaque
- CLI: --grant P=KIND[:SCOPE], exit code 6; runner: grant: and
  not_instantiated: headers, pending only for unsupported features
- conformance: 18 Phase 2 tests; 4000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 13:42:35 +03:00
1 parent fb4338cea6
commit 9c29a80b72
41 files changed
+908 -58

No files matched your search

+1 -1
View File
@@ -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. `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).
`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, 6 not instantiated. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]…` prints one JSON run record; capabilities reach a program only as named `@main` parameters. `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
+6
View File
@@ -18,6 +18,12 @@ pub fn build(b: *std.Build) void {
mod.addAnonymousImport("air_features_md", .{
.root_source_file = b.path("docs/reference/air-features.md"),
});
mod.addAnonymousImport("effects_md", .{
.root_source_file = b.path("docs/reference/effects.md"),
});
mod.addAnonymousImport("capabilities_md", .{
.root_source_file = b.path("docs/reference/capabilities.md"),
});
// CLI: `aji`.
const exe = b.addExecutable(.{
+2
View File
@@ -11,5 +11,7 @@
"tools",
"docs/reference/error-codes.md",
"docs/reference/air-features.md",
"docs/reference/effects.md",
"docs/reference/capabilities.md",
},
}
+1 -1
View File
@@ -48,7 +48,7 @@ Reason: Zig's standard library changes between minor versions; an unpinned toolc
## DD-009 — CLI diagnostics are JSON Lines on stdout
`aji` writes one JSON diagnostic per line on stdout, human notes on stderr, and uses fixed exit codes (0 accepted or returned, 1 rejected, 2 usage/I/O, 3 not yet implemented, 4 trapped, 5 execution limit exceeded).
`aji` writes one JSON diagnostic per line on stdout, human notes on stderr, and uses fixed exit codes (0 accepted or returned, 1 rejected, 2 usage/I/O, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated).
Reason: agents consume diagnostics programmatically (spec 10); mixing prose into the machine channel breaks repair loops.
+1
View File
@@ -32,6 +32,7 @@ Planned header extensions (added by the phase that needs them):
|---|---|---|
| `expect: run` + `result:` / `trap:` | P0 (implemented) | module must verify; run record must match |
| `stdout:` | P2 | expected output, `\n`-escaped (needs `io.write`) |
| `grant:` / `not_instantiated:` | P2 (implemented) | capability grants for `@main`; expected instantiation failure |
| `fuel:` | P0 (implemented) | instruction limit; default 1 000 000 (spec 11 §7.1) |
| `seed:` / `schedules:` / `quantum:` | P3 | scheduler seed / schedule budget / instructions per forced scheduling point (spec 11 §7.2) |
| `profile:` | P2 | runtime profile (`hosted`, `deterministic`, …) |
+1 -1
View File
@@ -99,5 +99,5 @@ These run through all phases rather than belonging to one.
|---|---|
| P0 | done; AIR format 0 frozen as the semantic baseline (spec 07 §8.7) |
| P1 | done (exit review in the phase file) |
| P2 | next |
| P2 | in progress: RFC 0006 (effects, capabilities) accepted and implemented; next RFC 0007 (I/O) and RFC 0008 (heap, regions) |
| P3–P8 | not started |
@@ -20,20 +20,20 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
| ID | Status | Task | Depends | Output | Done when |
|---|---|---|---|---|---|
| P2-1 | todo | Resolve Q-011, Q-012, Q-018 | — | spec 05, 07, 10 | questions resolved; runtime record format defined |
| P2-1 | done | Resolve Q-011, Q-012, Q-018 (RFC 0006; Q-018 resolved in P0) | — | 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-2a | done | 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-2b | todo | Specify and publish `heap` (`Own<T>`, `own.alloc`, `own.free`, move-only values) and `regions` (static generations per Q-010); contracts in spec 07a | P2-2a | spec 03, 07a, 08; registry | features published |
| P2-2c | todo | Ownership verifier for move-only values: use after move, double consume | P2-2b | `src/verifier/ownership.zig` | E2001, E2002 accept/reject (incl. `phase2/reject/use_after_move.air`) |
| P2-2d | todo | Region verifier: reset/destroy with live borrows, prior-generation use; region-derived borrows as an escapable `from` source | P2-2b | `src/verifier/region.zig` | E2104 accept/reject |
| P2-2e | todo | Interpreter heap and regions | P2-2b | `src/interp/memory.zig` | run tests; file-copy with a heap-backed region buffer |
| 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 |
| P2-4 | doing | Effect verifier (calls done; intrinsics with RFC 0007) | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees |
| P2-5 | doing | Capability verifier: unforgeability, narrowing, transfer rules (types, E3202, instantiation done; E3201 with intrinsics) | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject |
| P2-6 | todo | Linear resource and typestate verifier | P2-3 | `src/verifier/resource.zig` | E3001, E3002 accept/reject; leak on an error path detected |
| P2-7 | todo | Unsafe boundary verifier | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject |
| P2-8 | todo | Runtime intrinsics in the interpreter; virtual filesystem and loopback network for the `deterministic` profile | P2-2 | `src/runtime/` | intrinsic unit tests pass under both profiles; deterministic profile output identical across runs |
| P2-9 | todo | Entry-point capability instantiation from `aji.toml` `[capabilities]` | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) |
| P2-9 | doing | Entry-point capability instantiation (`--grant` done; `aji.toml` `[capabilities]` pending) | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) |
| P2-10 | todo | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test |
| P2-11 | todo | Reference programs: hello (real `io.write` if deferred from P0), file-copy, tcp-echo (single task) | P2-8 | `tests/programs/` | all three run; cleanup on every error path verified |
| P2-12 | todo | Phase exit review | all | plan status | exit criterion passes |
+2
View File
@@ -31,10 +31,12 @@ 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");
pub const authority = module.authority;
test {
_ = module;
_ = parse;
_ = print;
_ = features;
_ = authority;
}
+153
View File
@@ -0,0 +1,153 @@
//! Registries for effects, capability kinds and built-in enums
//! (spec 05 §9–§10; reference/effects.md, reference/capabilities.md).
//! Each registry mirrors its reference file; unit tests fail on drift.
const std = @import("std");
pub const Effect = struct {
name: []const u8,
/// Capability kind that grants the authority, or null if none is needed.
authority: ?[]const u8,
};
pub const effects = [_]Effect{
.{ .name = "atomic", .authority = null },
.{ .name = "atomic.weak", .authority = null },
.{ .name = "clock.read", .authority = "clock.read" },
.{ .name = "ffi", .authority = null },
.{ .name = "fs.read", .authority = "fs.read" },
.{ .name = "fs.write", .authority = "fs.write" },
.{ .name = "io.read", .authority = "io.read" },
.{ .name = "io.write", .authority = "io.write" },
.{ .name = "mem.alloc", .authority = "mem.alloc" },
.{ .name = "mem.map", .authority = "mem.map" },
.{ .name = "net.connect", .authority = "net.connect" },
.{ .name = "net.listen", .authority = "net.listen" },
.{ .name = "net.read", .authority = "net.read" },
.{ .name = "net.write", .authority = "net.write" },
.{ .name = "process.env", .authority = "process.env" },
.{ .name = "process.spawn", .authority = "process.spawn" },
.{ .name = "random.read", .authority = "random.read" },
.{ .name = "task.spawn", .authority = null },
.{ .name = "thread.block", .authority = null },
.{ .name = "thread.spawn", .authority = null },
.{ .name = "unsafe", .authority = null },
};
pub const Scope = enum { none, path_prefix, byte_budget };
pub const Kind = struct {
name: []const u8,
scope: Scope,
/// Registered narrowing forms; empty until RFC 0007/0008 register them.
forms: []const []const u8,
};
pub const kinds = [_]Kind{
.{ .name = "clock.read", .scope = .none, .forms = &.{} },
.{ .name = "fs.read", .scope = .path_prefix, .forms = &.{} },
.{ .name = "fs.write", .scope = .path_prefix, .forms = &.{} },
.{ .name = "io.read", .scope = .none, .forms = &.{} },
.{ .name = "io.write", .scope = .none, .forms = &.{} },
.{ .name = "mem.alloc", .scope = .byte_budget, .forms = &.{} },
.{ .name = "mem.map", .scope = .none, .forms = &.{} },
.{ .name = "net.connect", .scope = .none, .forms = &.{} },
.{ .name = "net.listen", .scope = .none, .forms = &.{} },
.{ .name = "net.read", .scope = .none, .forms = &.{} },
.{ .name = "net.write", .scope = .none, .forms = &.{} },
.{ .name = "process.env", .scope = .none, .forms = &.{} },
.{ .name = "process.spawn", .scope = .none, .forms = &.{} },
.{ .name = "random.read", .scope = .none, .forms = &.{} },
};
/// Built-in enums: spelled without `@`, fixed variants, no payloads.
pub const Builtin = enum {
cap_error,
pub fn variants(b: Builtin) []const []const u8 {
return switch (b) {
.cap_error => &.{ "invalid_restriction", "not_subset", "unsupported_restriction" },
};
}
pub fn variantIndex(b: Builtin, name: []const u8) ?u32 {
for (b.variants(), 0..) |v, i| if (std.mem.eql(u8, v, name)) return @intCast(i);
return null;
}
};
pub fn effectIndex(name: []const u8) ?usize {
for (effects, 0..) |e, i| if (std.mem.eql(u8, e.name, name)) return i;
return null;
}
pub fn kindIndex(name: []const u8) ?u16 {
for (kinds, 0..) |k, i| if (std.mem.eql(u8, k.name, name)) return @intCast(i);
return null;
}
pub fn hasForm(kind: u16, form: []const u8) bool {
for (kinds[kind].forms) |f| if (std.mem.eql(u8, f, form)) return true;
return false;
}
/// Validates a scope given at instantiation (reference/capabilities.md).
pub fn validScope(kind: u16, scope: ?[]const u8) bool {
const s = scope orelse return true;
return switch (kinds[kind].scope) {
.none => false,
.byte_budget => blk: {
_ = std.fmt.parseInt(u64, s, 10) catch break :blk false;
break :blk true;
},
.path_prefix => blk: {
if (s.len == 0 or s[0] != '/') break :blk false;
var it = std.mem.splitScalar(u8, s[1..], '/');
while (it.next()) |part| {
if (std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) break :blk false;
}
break :blk true;
},
};
}
/// Names in the first column of the first table of a reference file whose
/// rows start with "| `".
fn tableNames(comptime md: []const u8, buf: [][]const u8) usize {
var n: usize = 0;
var lines = std.mem.splitScalar(u8, md, '\n');
while (lines.next()) |line| {
if (std.mem.startsWith(u8, line, "## ")) break; // first table only
if (!std.mem.startsWith(u8, line, "| `")) continue;
var cols = std.mem.tokenizeScalar(u8, line, '|');
buf[n] = std.mem.trim(u8, cols.next().?, " `");
n += 1;
}
return n;
}
test "effect registry mirrors reference/effects.md" {
var buf: [64][]const u8 = undefined;
const n = tableNames(@embedFile("effects_md"), &buf);
try std.testing.expectEqual(effects.len, n);
for (buf[0..n], effects) |name, e| try std.testing.expectEqualStrings(e.name, name);
}
test "capability registry mirrors reference/capabilities.md" {
var buf: [64][]const u8 = undefined;
const n = tableNames(@embedFile("capabilities_md"), &buf);
try std.testing.expectEqual(kinds.len, n);
for (buf[0..n], kinds) |name, k| try std.testing.expectEqualStrings(k.name, name);
// Every kind authorizes the effect of the same name, and every effect
// that needs authority names a registered kind.
for (effects) |e| if (e.authority) |a| try std.testing.expect(kindIndex(a) != null);
}
test "instantiation scopes" {
const fs = kindIndex("fs.read").?;
try std.testing.expect(validScope(fs, "/var/data"));
try std.testing.expect(!validScope(fs, "var/data"));
try std.testing.expect(!validScope(fs, "/var/../etc"));
try std.testing.expect(!validScope(kindIndex("io.write").?, "/x"));
try std.testing.expect(validScope(kindIndex("mem.alloc").?, "1048576"));
}
+3 -3
View File
@@ -25,9 +25,9 @@ pub const registry = [_]Feature{
.{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
.{ .name = "atomics", .depends = &.{"ownership"}, .status = .reserved, .phase = 5 },
.{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null },
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .reserved, .phase = 2 },
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 2 },
.{ .name = "channels", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "effects", .depends = &.{}, .status = .reserved, .phase = 2 },
.{ .name = "effects", .depends = &.{}, .status = .published, .phase = 2 },
.{ .name = "heap", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 },
.{ .name = "islands", .depends = &.{ "capabilities", "effects", "ownership", "regions" }, .status = .reserved, .phase = 4 },
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
@@ -37,7 +37,7 @@ pub const registry = [_]Feature{
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "ownership" };
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership" };
pub const Reason = enum {
unknown_feature,
+58 -2
View File
@@ -4,6 +4,7 @@
//! Every slice is owned by the arena the module was parsed into.
const std = @import("std");
pub const authority = @import("authority.zig");
pub const format_version: u32 = 0;
pub const lang_version: [2]u32 = .{ 0, 1 };
@@ -72,6 +73,10 @@ pub const Type = union(enum) {
array: *const Array,
slice: *const Type,
slice_mut: *const Type,
// Feature `capabilities` (spec 05 §10).
/// Index into `authority.kinds`.
cap: u16,
builtin: authority.Builtin,
pub const Array = struct { elem: Type, len: u64 };
@@ -82,6 +87,8 @@ pub const Type = union(enum) {
.named => |x| b.named == x,
.local, .ref, .mut, .slice, .slice_mut => |x| x.eql(b.inner().?),
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k,
.builtin => |e| b.builtin == e,
.bool, .void, .never => true,
};
}
@@ -220,7 +227,11 @@ pub const Op = union(enum) {
br: Target,
cbr: struct { cond: ValueId, then: Target, @"else": Target },
@"switch": struct { ty: IntType, value: ValueId, cases: []const Case, default: Target },
enum_switch: struct { decl: u32, value: ValueId, arms: []const Arm, default: ?Target },
/// `ty` is a declared enum (`.named`) or a built-in enum (`.builtin`).
enum_switch: struct { ty: Type, value: ValueId, arms: []const Arm, default: ?Target },
/// Fallible narrowing (spec 05 §10.4): continues at `ok` with the new
/// capability or at `err` with a `cap_error`, as block parameters.
cap_narrow: struct { form: []const u8, cap: ValueId, args: []const ValueId, ok: u32, err: u32 },
ret: ?ValueId,
trap,
@@ -229,7 +240,7 @@ pub const Op = union(enum) {
pub fn isTerminator(op: Op) bool {
return switch (op) {
.br, .cbr, .@"switch", .enum_switch, .ret, .trap => true,
.br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true,
else => false,
};
}
@@ -270,6 +281,43 @@ pub const Module = struct {
types: []const TypeDecl,
functions: []const Function,
pub fn declares(m: Module, feature: []const u8) bool {
for (m.features) |f| if (std.mem.eql(u8, f, feature)) return true;
return false;
}
/// Variant names and payloads of a declared or built-in enum type.
pub fn variantCount(m: Module, t: Type) usize {
return switch (t) {
.named => |i| m.types[i].kind.@"enum".len,
.builtin => |b| b.variants().len,
else => 0,
};
}
pub fn variantName(m: Module, t: Type, i: usize) []const u8 {
return switch (t) {
.named => |d| m.types[d].kind.@"enum"[i].name,
.builtin => |b| b.variants()[i],
else => unreachable,
};
}
pub fn variantPayload(m: Module, t: Type, i: usize) []const Type {
return switch (t) {
.named => |d| m.types[d].kind.@"enum"[i].payload,
else => &.{},
};
}
pub fn typeName(m: Module, t: Type) []const u8 {
return switch (t) {
.named => |i| m.types[i].name,
.builtin => |b| @tagName(b),
else => unreachable,
};
}
pub fn functionIndex(m: Module, name: []const u8) ?u32 {
for (m.functions, 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return @intCast(i);
return null;
@@ -314,6 +362,10 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
f(ctx, x.value);
if (x.default) |d| for (d.args) |v| f(ctx, v);
},
.cap_narrow => |x| {
f(ctx, x.cap);
for (x.args) |v| f(ctx, v);
},
.ret => |v| if (v) |x| f(ctx, x),
.local_alloc => {},
.local_store => |x| {
@@ -363,6 +415,10 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !voi
for (x.arms) |a| try buf.append(gpa, a.block);
if (x.default) |d| try buf.append(gpa, d.block);
},
.cap_narrow => |x| {
try buf.append(gpa, x.ok);
try buf.append(gpa, x.err);
},
else => {},
}
}
+79 -4
View File
@@ -10,6 +10,7 @@ const std = @import("std");
const diag = @import("../diag.zig");
const air = @import("module.zig");
const features_mod = @import("features.zig");
const authority = air.authority;
const Allocator = std.mem.Allocator;
const Span = air.Span;
@@ -475,6 +476,10 @@ const Parser = struct {
if (std.mem.eql(u8, t.text, "bool")) return .bool;
if (std.mem.eql(u8, t.text, "void")) return .void;
if (std.mem.eql(u8, t.text, "never")) return .never;
if (std.meta.stringToEnum(authority.Builtin, t.text)) |b| {
try p.requireFeature("capabilities", t.span, t.text);
return .{ .builtin = b };
}
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 = "reason", .value = .{ .str = "reserved_type" } },
@@ -491,6 +496,17 @@ const Parser = struct {
/// `local<T>`, `ref<T>`, `mut<T>`, `slice<T>`, `slice_mut<T>`, `array<T, N>` (spec 07 §8.8).
fn parseCompoundType(p: *Parser, t: Token) Error!air.Type {
if (eql(t.text, "cap")) {
try p.requireFeature("capabilities", t.span, "cap");
_ = try p.expect(.lt, "`<`");
const k = try p.expect(.word, "capability kind");
_ = try p.expect(.gt, "`>`");
const idx = authority.kindIndex(k.text) orelse blk: {
try p.report("E0004", k.span, "unknown capability kind", &.{.{ .name = "name", .value = .{ .str = k.text } }});
break :blk 0;
};
return .{ .cap = idx };
}
const Kind = enum { local, ref, mut, slice, slice_mut, array };
const kind = std.meta.stringToEnum(Kind, t.text) orelse {
try p.report("E0004", t.span, "unknown type", &.{.{ .name = "name", .value = .{ .str = t.text } }});
@@ -527,6 +543,11 @@ const Parser = struct {
};
}
fn declares(p: *Parser, feature: []const u8) bool {
for (p.declared) |d| if (eql(d, feature)) return true;
return false;
}
/// Reports `E0006 feature_not_declared` if `feature` is not in the header (spec 07 §8.1).
fn requireFeature(p: *Parser, feature: []const u8, span: Span, construct: []const u8) Error!void {
for (p.declared) |d| if (eql(d, feature)) return;
@@ -573,9 +594,14 @@ const Parser = struct {
}
_ = try p.expect(.nl, "end of line");
p.skipNewlines();
_ = try p.expectWord("effects");
const effects_tok = try p.expectWord("effects");
const effects = try p.parsePathList();
_ = try p.expect(.nl, "end of line");
// Effect names are checked against the registry when the module
// declares `effects` (spec 05 §9.1).
if (p.declares("effects")) for (effects) |e| {
if (authority.effectIndex(e) == null) try p.report("E0004", effects_tok.span, "unknown effect", &.{.{ .name = "name", .value = .{ .str = e } }});
};
try p.prescanBlocks();
@@ -809,7 +835,16 @@ const Parser = struct {
break :op .{ .@"switch" = .{ .ty = it, .value = value, .cases = cases.items, .default = try p.target() } };
}
if (eql(op_tok.text, "enum.switch")) {
const decl = try p.typeRef(.@"enum");
// A declared enum (`@E`) or a built-in enum (`cap_error`).
const ety: air.Type = if (p.peek().tag == .word) blk: {
const t = p.next();
const b = std.meta.stringToEnum(authority.Builtin, t.text) orelse {
try p.report("E0004", t.span, "unknown enum", &.{.{ .name = "name", .value = .{ .str = t.text } }});
return error.SyntaxError;
};
try p.requireFeature("capabilities", t.span, t.text);
break :blk .{ .builtin = b };
} else .{ .named = try p.typeRef(.@"enum") };
const value = try p.useValue();
var arms: std.ArrayList(air.Op.Arm) = .empty;
var default: ?air.Target = null;
@@ -822,18 +857,44 @@ const Parser = struct {
break;
}
const span = p.peek().span;
const variant = try p.variantRef(decl);
const variant = try p.enumVariantRef(ety);
_ = try p.expect(.arrow, "`->`");
const blk = try p.blockRef();
try arms.append(p.arena, .{ .variant = variant, .block = blk, .span = span });
}
break :op .{ .enum_switch = .{ .decl = decl, .value = value, .arms = arms.items, .default = default } };
break :op .{ .enum_switch = .{ .ty = ety, .value = value, .arms = arms.items, .default = default } };
}
if (eql(op_tok.text, "ret")) {
break :op .{ .ret = if (p.peek().tag == .local) try p.useValue() else null };
}
if (eql(op_tok.text, "trap")) break :op .trap;
if (try p.parseMemoryOp(op_tok)) |mop| break :op mop;
if (parts.len == 3 and eql(parts[0], "cap") and eql(parts[1], "narrow")) {
try p.requireFeature("capabilities", op_tok.span, op_tok.text);
const c = try p.useValue();
var args: std.ArrayList(air.ValueId) = .empty;
while (true) {
_ = try p.expect(.comma, "`,`");
if (p.atWord("ok")) break;
try args.append(p.arena, try p.useValue());
}
_ = p.next();
_ = try p.expect(.arrow, "`->`");
const ok = try p.blockRef();
_ = try p.expect(.comma, "`,`");
_ = try p.expectWord("err");
_ = try p.expect(.arrow, "`->`");
const err = try p.blockRef();
break :op .{ .cap_narrow = .{ .form = parts[2], .cap = c, .args = args.items, .ok = ok, .err = err } };
}
if (eql(op_tok.text, "intrinsic")) {
try p.requireFeature("capabilities", op_tok.span, "intrinsic");
const name = try p.expect(.word, "intrinsic name");
// No intrinsic is registered yet (RFC 0007), so every name is unknown.
try p.report("E0004", name.span, "unknown intrinsic", &.{.{ .name = "name", .value = .{ .str = name.text } }});
while (p.peek().tag != .nl) _ = p.next();
return null;
}
return p.unknownOpcode(op_tok);
};
_ = try p.expect(.nl, "end of line");
@@ -992,6 +1053,20 @@ const Parser = struct {
return error.SyntaxError;
}
fn enumVariantRef(p: *Parser, t: air.Type) Error!u32 {
return switch (t) {
.named => |d| p.variantRef(d),
.builtin => |b| blk: {
const tok = try p.expect(.word, "variant name");
break :blk b.variantIndex(tok.text) orelse {
try p.report("E0004", tok.span, "unknown variant", &.{.{ .name = "name", .value = .{ .str = tok.text } }});
break :blk 0;
};
},
else => unreachable,
};
}
fn variantRef(p: *Parser, decl: u32) Error!u32 {
const t = try p.expect(.word, "variant name");
if (p.types[decl].variantIndex(t.text)) |i| return i;
+15 -3
View File
@@ -102,6 +102,8 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
try printType(m, a.elem, w);
try w.print(", {d}>", .{a.len});
},
.cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}),
.builtin => |b| try w.writeAll(@tagName(b)),
.bool, .void, .never => try w.writeAll(@tagName(t)),
}
}
@@ -226,10 +228,11 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
try target(f, x.default, w);
},
.enum_switch => |x| {
const d = m.types[x.decl];
try w.print("enum.switch @{s} ", .{d.name});
try w.writeAll("enum.switch ");
try printType(m, x.ty, w);
try w.writeByte(' ');
try value(f, x.value, w);
for (x.arms) |a| try w.print(", {s} -> @{s}", .{ d.kind.@"enum"[a.variant].name, f.blocks[a.block].name });
for (x.arms) |a| try w.print(", {s} -> @{s}", .{ m.variantName(x.ty, a.variant), f.blocks[a.block].name });
if (x.default) |dt| {
try w.writeAll(", default -> ");
try target(f, dt, w);
@@ -277,6 +280,15 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error!
.slice_split => |x| try two(f, w, "slice.split", x.slice, x.at),
.slice_copy => |x| try two(f, w, "slice.copy", x.dst, x.src),
.guard => |v| try one(f, w, "guard", v),
.cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form});
try value(f, x.cap, w);
for (x.args) |a| {
try w.writeAll(", ");
try value(f, a, w);
}
try w.print(", ok -> @{s}, err -> @{s}", .{ f.blocks[x.ok].name, f.blocks[x.err].name });
},
}
}
+1
View File
@@ -6,6 +6,7 @@ pub const Value = machine.Value;
pub const Trap = machine.Trap;
pub const Outcome = machine.Outcome;
pub const Options = machine.Options;
pub const Grant = machine.Grant;
pub const run = machine.run;
pub const writeOutcome = machine.writeOutcome;
pub const writeValue = machine.writeValue;
+103 -6
View File
@@ -27,6 +27,11 @@ pub const Value = union(enum) {
place: Place,
/// `slice<T>` / `slice_mut<T>`.
slice: Slice,
/// `cap<K>`: index into the host's authority table. Never observable
/// by the program (spec 05 §10.1).
cap: u32,
/// Value of a built-in enum such as `cap_error`.
builtin: struct { which: air.authority.Builtin, variant: u32 },
pub const Aggregate = struct {
decl: u32,
@@ -57,22 +62,70 @@ pub const Outcome = union(enum) {
trapped: Trap,
/// The runner's fuel ran out (spec 11 §7). Not a trap.
limit_exceeded: struct { limit: u64, steps: u64 },
/// The host did not start the program (spec 05 §10.2). Not a trap.
not_instantiated: NotInstantiated,
};
pub const NotInstantiated = struct {
reason: []const u8,
parameter: []const u8,
kind: ?[]const u8 = null,
granted: ?[]const u8 = null,
scope: ?[]const u8 = null,
};
/// One `--grant <parameter>=<kind>[:<scope>]`.
pub const Grant = struct {
parameter: []const u8,
kind: []const u8,
scope: ?[]const u8 = null,
};
/// An authority object held by the host: copies of a capability share it.
pub const Authority = struct { kind: u16, scope: ?[]const u8 };
pub const Options = struct {
/// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited.
fuel: ?u64 = null,
/// Capability grants for the parameters of the entry function.
grants: []const Grant = &.{},
};
pub const Error = std.mem.Allocator.Error || error{EntryNotFound};
pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant };
/// Runs `entry`, which must take no parameters. `module` must have passed
/// verification.
pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, options: Options) Error!Outcome {
const idx = module.functionIndex(entry) orelse return error.EntryNotFound;
if (module.functions[idx].params.len != 0) return error.EntryNotFound;
const f = module.functions[idx];
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel };
return switch (try m.call(idx, &.{})) {
// Instantiation (spec 05 §10.2): every capability parameter gets exactly
// one grant of its kind, and every grant names a parameter.
for (options.grants, 0..) |g, i| {
for (options.grants[0..i]) |prev| if (std.mem.eql(u8, prev.parameter, g.parameter)) return error.DuplicateGrant;
}
const args = try arena.alloc(Value, f.params.len);
for (f.params, args) |p, *arg| {
const pname = f.values[p.value].name;
const kind = air.authority.kinds[p.ty.cap].name;
const g = for (options.grants) |g| {
if (std.mem.eql(u8, g.parameter, pname)) break g;
} else return .{ .not_instantiated = .{ .reason = "missing_capability", .parameter = pname, .kind = kind } };
if (!std.mem.eql(u8, g.kind, kind)) return .{ .not_instantiated = .{ .reason = "kind_mismatch", .parameter = pname, .kind = kind, .granted = g.kind } };
if (!air.authority.validScope(p.ty.cap, g.scope)) return .{ .not_instantiated = .{ .reason = "invalid_scope", .parameter = pname, .kind = kind, .scope = g.scope } };
try m.authorities.append(arena, .{ .kind = p.ty.cap, .scope = g.scope });
arg.* = .{ .cap = @intCast(m.authorities.items.len - 1) };
}
for (options.grants) |g| {
const known = for (f.params) |p| {
if (std.mem.eql(u8, f.values[p.value].name, g.parameter)) break true;
} else false;
if (!known) return .{ .not_instantiated = .{ .reason = "unknown_parameter", .parameter = g.parameter } };
}
return switch (try m.call(idx, args)) {
.value => |v| .{ .returned = v },
.trap => |t| .{ .trapped = t },
.limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } },
@@ -122,6 +175,8 @@ const Machine = struct {
module: air.Module,
depth: u32 = 0,
fuel: ?u64,
/// Host authority table; capabilities index into it.
authorities: std.ArrayList(Authority) = .empty,
/// Instructions executed so far.
steps: u64 = 0,
@@ -246,13 +301,20 @@ const Machine = struct {
return m.jump(f, vals, x.default);
},
.enum_switch => |x| {
const agg = vals[x.value].aggregate;
for (x.arms) |arm| if (arm.variant == agg.variant) {
for (f.blocks[arm.block].params, agg.fields) |p, fv| vals[p.value] = fv;
const variant: u32, const fields: []const Value = switch (vals[x.value]) {
.aggregate => |agg| .{ agg.variant, agg.fields },
.builtin => |b| .{ b.variant, &.{} },
else => unreachable,
};
for (x.arms) |arm| if (arm.variant == variant) {
for (f.blocks[arm.block].params, fields) |p, fv| vals[p.value] = fv;
return .{ .jump = arm.block };
};
return m.jump(f, vals, x.default.?);
},
// No narrowing form is registered yet, so verified AIR contains
// no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008).
.cap_narrow => unreachable,
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
.local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst),
@@ -549,6 +611,22 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W
},
// Storage and borrows cannot be returned from `@main` (spec 08 §11.3).
.local, .place, .slice => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
try s.objectField("capability");
try s.write("opaque");
try s.endObject();
},
.builtin => |b| {
try s.beginObject();
try s.objectField("variant");
try s.write(b.which.variants()[b.variant]);
try s.objectField("payload");
try s.beginArray();
try s.endArray();
try s.endObject();
},
.aggregate => |agg| {
const d = module.types[agg.decl];
switch (d.kind) {
@@ -599,6 +677,25 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, w: *std.Io.Writer) std
try s.objectField("inst");
try s.write(t.inst);
},
.not_instantiated => |n| {
try s.write("not_instantiated");
try s.objectField("reason");
try s.write(n.reason);
try s.objectField("parameter");
try s.write(n.parameter);
if (n.kind) |k| {
try s.objectField("kind");
try s.write(k);
}
if (n.granted) |g| {
try s.objectField("granted");
try s.write(g);
}
if (n.scope) |sc| {
try s.objectField("scope");
try s.write(sc);
}
},
.limit_exceeded => |l| {
try s.write("limit_exceeded");
try s.objectField("kind");
+40 -7
View File
@@ -6,7 +6,8 @@
//! - `aji run` writes one run record (spec 07a "Run result") to stdout;
//! - exit codes: 0 accepted / returned, 1 rejected, 2 usage or I/O error,
//! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped,
//! 5 execution limit exceeded (`--fuel`, spec 11 §7).
//! 5 execution limit exceeded (`--fuel`, spec 11 §7),
//! 6 not instantiated (missing or invalid `--grant`, spec 05 §10.2).
const std = @import("std");
const aji = @import("aji");
@@ -16,9 +17,10 @@ const usage =
\\
\\commands:
\\ check <file.air> parse and verify a text AIR module
\\ run [--fuel N] <file.air>
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air>
\\ verify, then run @main and print the run record;
\\ --fuel stops after N executed instructions
\\ --fuel stops after N executed instructions;
\\ --grant binds capability parameter P of @main
\\ codes list diagnostic codes as JSON Lines
\\ features print supported AIR format, language version and features
\\ explain <code> show one diagnostic code
@@ -26,7 +28,7 @@ const usage =
\\
;
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5 };
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5, not_instantiated = 6 };
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
@@ -77,11 +79,17 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
}
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
var options: aji.interp.Options = .{};
var grants: std.ArrayList(aji.interp.Grant) = .empty;
var rest = args[2..];
if (std.mem.eql(u8, cmd, "run") and rest.len == 3 and std.mem.eql(u8, rest[0], "--fuel")) {
options.fuel = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--fuel takes a non-negative integer");
while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) {
if (std.mem.eql(u8, rest[0], "--fuel")) {
options.fuel = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--fuel takes a non-negative integer");
} else if (std.mem.eql(u8, rest[0], "--grant")) {
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
} else break;
rest = rest[2..];
}
options.grants = grants.items;
if (rest.len != 1) return usageError("check and run take exactly one file");
const path = rest[0];
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
@@ -96,7 +104,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
const module = report.module.?;
const outcome = aji.interp.run(arena, module, "main", options) catch |err| switch (err) {
error.EntryNotFound => return usageError("module has no parameterless @main"),
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
else => |e| return e,
};
try aji.interp.writeOutcome(module, outcome, out);
@@ -105,6 +114,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
.returned => .accepted,
.trapped => .trapped,
.limit_exceeded => .limit_exceeded,
.not_instantiated => .not_instantiated,
};
}
return switch (report.status) {
@@ -129,3 +139,26 @@ fn usageError(msg: []const u8) ExitCode {
std.debug.print("aji: {s}\n\n{s}", .{ msg, usage });
return .usage;
}
/// `<parameter>=<kind>[:<scope>]` (reference/capabilities.md).
pub fn parseGrant(text: []const u8) ?aji.interp.Grant {
const eq = std.mem.indexOfScalar(u8, text, '=') orelse return null;
const rest = text[eq + 1 ..];
const colon = std.mem.indexOfScalar(u8, rest, ':');
const g: aji.interp.Grant = .{
.parameter = text[0..eq],
.kind = if (colon) |c| rest[0..c] else rest,
.scope = if (colon) |c| rest[c + 1 ..] else null,
};
if (g.parameter.len == 0 or g.kind.len == 0) return null;
return g;
}
test parseGrant {
const g = parseGrant("data=fs.read:/var/data").?;
try std.testing.expectEqualStrings("data", g.parameter);
try std.testing.expectEqualStrings("fs.read", g.kind);
try std.testing.expectEqualStrings("/var/data", g.scope.?);
try std.testing.expect(parseGrant("out=io.write").?.scope == null);
try std.testing.expect(parseGrant("io.write") == null);
}
+3 -1
View File
@@ -16,6 +16,7 @@ pub const budget = @import("verifier/budget.zig");
pub const cfg = @import("verifier/cfg.zig");
pub const ssa = @import("verifier/ssa.zig");
pub const types = @import("verifier/types.zig");
pub const effects = @import("verifier/effects.zig");
pub const init = @import("verifier/init.zig");
pub const borrow = @import("verifier/borrow.zig");
pub const bounds = @import("verifier/bounds.zig");
@@ -60,7 +61,7 @@ pub const Context = struct {
/// stage, or an empty slice if the module verifies.
pub fn verify(arena: std.mem.Allocator, file: []const u8, module: air.Module) std.mem.Allocator.Error![]const diag.Diagnostic {
var c: Context = .{ .arena = arena, .file = file, .module = module };
const stages = .{ budget.check, cfg.check, ssa.check, types.check, init.check, borrow.check, bounds.check };
const stages = .{ budget.check, cfg.check, ssa.check, types.check, effects.check, init.check, borrow.check, bounds.check };
inline for (stages) |stage| {
try stage(&c);
if (c.diags.items.len != 0) {
@@ -84,6 +85,7 @@ test {
_ = cfg;
_ = ssa;
_ = types;
_ = effects;
_ = init;
_ = borrow;
_ = bounds;
+2 -1
View File
@@ -28,8 +28,9 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
return switch (t) {
.int => |it| it.bits() / 8,
.bool => 1,
.ref, .mut => 8,
.ref, .mut, .cap => 8,
.slice, .slice_mut => 16,
.builtin => |b| tagSize(b.variants().len),
.array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1) orelse return null) catch null,
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| blk: {
+20 -12
View File
@@ -52,39 +52,47 @@ fn checkTerminator(c: *Context, f: air.Function, inst: air.Inst) !void {
try arity(c, f, inst.span, x.default);
},
.enum_switch => |x| {
const variants = c.module.types[x.decl].kind.@"enum";
const m = c.module;
for (x.arms, 0..) |arm, i| {
for (x.arms[0..i]) |prev| if (prev.variant == arm.variant)
try invalid(c, f, arm.span, "duplicate enum.switch arm", null);
const blk = f.blocks[arm.block];
if (blk.params.len != variants[arm.variant].payload.len) {
try c.report("E5002", arm.span, "arm target parameters do not match the variant payload", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = blk.name } },
.{ .name = "expected", .value = .{ .int = @intCast(variants[arm.variant].payload.len) } },
.{ .name = "found", .value = .{ .int = @intCast(blk.params.len) } },
});
}
try paramCount(c, f, arm.span, arm.block, m.variantPayload(x.ty, arm.variant).len, "arm target parameters do not match the variant payload");
}
if (x.default) |d| {
try arity(c, f, inst.span, d);
} else {
for (variants, 0..) |v, vi| {
for (0..m.variantCount(x.ty)) |vi| {
const covered = for (x.arms) |arm| {
if (arm.variant == vi) break true;
} else false;
if (!covered) try c.report("E5002", inst.span, "enum.switch is not exhaustive and has no default", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "missing_variant", .value = .{ .str = v.name } },
.{ .name = "missing_variant", .value = .{ .str = m.variantName(x.ty, vi) } },
});
}
}
},
// `ok` receives the narrowed capability, `err` the `cap_error` (spec 05 §10.4).
.cap_narrow => |x| {
try paramCount(c, f, inst.span, x.ok, 1, "cap.narrow `ok` target takes exactly one parameter");
try paramCount(c, f, inst.span, x.err, 1, "cap.narrow `err` target takes exactly one parameter");
},
.ret, .trap => {},
else => unreachable,
}
}
fn paramCount(c: *Context, f: air.Function, span: air.Span, block: u32, expected: usize, message: []const u8) !void {
const blk = f.blocks[block];
if (blk.params.len == expected) return;
try c.report("E5002", span, message, &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = blk.name } },
.{ .name = "expected", .value = .{ .int = @intCast(expected) } },
.{ .name = "found", .value = .{ .int = @intCast(blk.params.len) } },
});
}
fn arity(c: *Context, f: air.Function, span: air.Span, t: air.Target) !void {
const blk = f.blocks[t.block];
if (blk.params.len == t.args.len) return;
+49
View File
@@ -0,0 +1,49 @@
//! Effect checking (spec 05 §9.3). Reports E3101.
//!
//! Applies to modules that declare the feature `effects`. Effects are flat
//! atoms: a call needs every effect of its callee in the caller's list.
//! Checking each function against its direct callees makes the rule hold
//! transitively, including through recursion.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const Context = verifier.Context;
pub fn check(c: *Context) !void {
const m = c.module;
if (!m.declares("effects")) return;
for (m.functions) |f| {
for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) {
.call => |x| {
const callee = m.functions[x.callee];
for (callee.effects) |e| if (!contains(f.effects, e)) {
try c.report("E3101", inst.span, "callee effect not declared by the caller", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "callee", .value = .{ .str = callee.name } },
.{ .name = "effect", .value = .{ .str = e } },
});
};
},
else => {},
};
}
}
fn contains(list: []const []const u8, name: []const u8) bool {
for (list) |x| if (std.mem.eql(u8, x, name)) return true;
return false;
}
const h = "module t\nair 0\nlang 0.1\nfeatures [effects]\n";
test "callee effects must be declared" {
const g = "fn @g() -> void\neffects [io.write]\nentry:\n ret\n";
try verifier.expectCodes(h ++ "fn @f() -> void\neffects [io.write]\nentry:\n call @g()\n ret\n" ++ g, &.{});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n call @g()\n ret\n" ++ g, &.{"E3101"});
// Flat: atomic does not cover atomic.weak.
try verifier.expectCodes(h ++ "fn @f() -> void\neffects [atomic]\nentry:\n call @w()\n ret\nfn @w() -> void\neffects [atomic.weak]\nentry:\n ret\n", &.{"E3101"});
// Without the feature, lists are recorded but not checked.
try verifier.expectCodes("module t\nair 0\nlang 0.1\nfeatures []\nfn @f() -> void\neffects []\nentry:\n call @g()\n ret\n" ++ g, &.{});
}
+17 -3
View File
@@ -418,16 +418,30 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
try fc.expectTarget(span, x.default);
},
.enum_switch => |x| {
try fc.expectValue(span, x.value, .{ .named = x.decl });
const variants = m.types[x.decl].kind.@"enum";
try fc.expectValue(span, x.value, x.ty);
for (x.arms) |arm| {
const params = f.blocks[arm.block].params;
for (params, variants[arm.variant].payload) |p, t| {
for (params, m.variantPayload(x.ty, arm.variant)) |p, t| {
if (!p.ty.eql(t)) try fc.mismatch(arm.span, try fc.c.valueName(f, p.value), t, p.ty);
}
}
if (x.default) |d| try fc.expectTarget(span, d);
},
.cap_narrow => |x| {
const t = fc.typeOf(x.cap);
if (t != .cap) return fc.kindError(span, x.cap, "cap<K>");
// No form of any kind widens; an unregistered form is reported as
// an attempt to widen (spec 05 §10.4).
if (!air.authority.hasForm(t.cap, x.form)) try fc.c.report("E3202", span, "narrowing form not defined for this capability kind", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "kind", .value = .{ .str = air.authority.kinds[t.cap].name } },
.{ .name = "form", .value = .{ .str = x.form } },
});
const ok = f.blocks[x.ok].params[0];
if (!ok.ty.eql(t)) try fc.mismatch(span, try fc.c.valueName(f, ok.value), t, ok.ty);
const err = f.blocks[x.err].params[0];
if (!err.ty.eql(.{ .builtin = .cap_error })) try fc.mismatch(span, try fc.c.valueName(f, err.value), .{ .builtin = .cap_error }, err.ty);
},
.ret => |v| switch (f.ret) {
.never => try fc.c.report("E1001", span, "`ret` in a function returning never", &.{
.{ .name = "function", .value = .{ .str = f.name } },
+3 -1
View File
@@ -22,6 +22,8 @@ Every test starts with a block of `;` lines. Keys:
| `expect` | yes | `accept`; `reject` followed by one or more codes from `docs/reference/error-codes.md`; or `run` |
| `result` | with `run` | expected `value` of the run record as canonical JSON, e.g. `42` or `{"x":1}` |
| `trap` | with `run` | expected trap code, e.g. `T0003` |
| `not_instantiated` | with `run` | expected `reason` of a `not_instantiated` record (spec 05 §10.2) |
| `grant` | no, repeatable | `<parameter>=<kind>[:<scope>]` binding for a capability parameter of `@main` |
| `fuel` | no | instruction limit for `run` tests (spec 11 §7.1); default 1 000 000. Running out is a `FAIL`, never a pass |
| `phase` | yes | implementation phase number |
| `spec` | yes | spec section that justifies the expectation |
@@ -38,7 +40,7 @@ A key is a single lowercase word; header lines without a `key:` prefix are free-
|---|---|
| `PASS` | result matches `expect` |
| `FAIL` | result differs, or the header is malformed; the run exits 1 |
| `PENDING` | the test's `phase` is later than `aji.implemented_phase`, or the pipeline stage it needs is not implemented yet |
| `PENDING` | the test's `phase` is later than `aji.implemented_phase` and its module declares a feature the toolchain does not support yet |
## Rules
@@ -0,0 +1,23 @@
; Capabilities are copyable values: passed, copied and stored in a struct.
; expect: accept
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.capability_values
air 0
lang 0.1
features [capabilities, effects, ownership]
type @Logger = struct { out: cap<io.write> }
fn @make(%out: cap<io.write>) -> @Logger
effects []
entry:
%c = copy %out
%l = struct.make @Logger(%c)
ret %l
fn @use(%l: @Logger) -> cap<io.write>
effects []
entry:
%o = struct.get @Logger.out, %l
ret %o
@@ -0,0 +1,20 @@
; Effects declared along a call chain, including recursion.
; expect: accept
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.transitive_effects
air 0
lang 0.1
features [effects]
fn @a() -> void
effects [io.write]
entry:
call @b()
ret
fn @b() -> void
effects [io.write]
entry:
call @b()
ret
@@ -0,0 +1,13 @@
; cap<K> belongs to the feature capabilities, which is not declared.
; expect: reject E0006
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.cap_without_feature
air 0
lang 0.1
features [effects]
fn @f(%c: cap<io.write>) -> void
effects []
entry:
ret
@@ -0,0 +1,17 @@
; A struct holding a capability is authority-bearing and cannot be zeroed.
; expect: reject E1001
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.capability_not_zeroable
air 0
lang 0.1
features [capabilities, effects, ownership]
type @Logger = struct { out: cap<io.write> }
fn @f() -> void
effects []
entry:
%x = local.alloc @Logger
local.zero %x
ret
@@ -0,0 +1,19 @@
; atomic does not imply atomic.weak.
; expect: reject E3101
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.flat_effects
air 0
lang 0.1
features [effects]
fn @f() -> void
effects [atomic]
entry:
call @g()
ret
fn @g() -> void
effects [atomic.weak]
entry:
ret
@@ -0,0 +1,17 @@
; The ok target of cap.narrow takes exactly one parameter.
; expect: reject E5002
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.narrow_ok_arity
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @f(%c: cap<io.write>, %n: usize) -> void
effects []
entry:
cap.narrow.budget %c, %n, ok -> @ok, err -> @err
ok:
ret
err(%e: cap_error):
ret
@@ -0,0 +1,14 @@
; Capabilities cannot be compared: there is no eq.cap.
; expect: reject E0004 E5001
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.no_capability_comparison
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @f(%a: cap<io.write>, %b: cap<io.write>) -> bool
effects []
entry:
%r = eq.cap %a, %b
ret %r
@@ -0,0 +1,19 @@
; The caller does not declare the effect of its callee.
; expect: reject E3101
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.undeclared_effect
air 0
lang 0.1
features [effects]
fn @f() -> void
effects []
entry:
call @g()
ret
fn @g() -> void
effects [io.write]
entry:
ret
@@ -0,0 +1,13 @@
; cap<root> is not a registered capability kind.
; expect: reject E0004
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.unknown_capability_kind
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @f(%c: cap<root>) -> void
effects []
entry:
ret
@@ -0,0 +1,13 @@
; teleport is not a registered effect.
; expect: reject E0004
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.unknown_effect
air 0
lang 0.1
features [effects]
fn @f() -> void
effects [teleport]
entry:
ret
@@ -0,0 +1,14 @@
; No intrinsic is registered yet; unknown names are E0004.
; expect: reject E0004
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.unknown_intrinsic
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @f(%c: cap<io.write>) -> void
effects [io.write]
entry:
intrinsic io.teleport(%c)
ret
@@ -0,0 +1,17 @@
; io.write has no narrowing forms; any form is reported as widening.
; expect: reject E3202
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.unknown_narrowing_form
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @f(%c: cap<io.write>, %n: usize) -> void
effects []
entry:
cap.narrow.budget %c, %n, ok -> @ok, err -> @err
ok(%d: cap<io.write>):
ret
err(%e: cap_error):
ret
@@ -0,0 +1,16 @@
; A granted capability parameter instantiates @main.
; expect: run
; grant: out=io.write
; result: 1
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.instantiate
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @main(%out: cap<io.write>) -> u8
effects [io.write]
entry:
%v = const.u8 1
ret %v
@@ -0,0 +1,16 @@
; A path scope with .. cannot be granted.
; expect: run
; grant: data=fs.read:/var/../etc
; not_instantiated: invalid_scope
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.invalid_scope
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @main(%data: cap<fs.read>) -> u8
effects [fs.read]
entry:
%v = const.u8 1
ret %v
@@ -0,0 +1,16 @@
; The grant is of a different kind than the parameter.
; expect: run
; grant: out=fs.read:/tmp
; not_instantiated: kind_mismatch
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.kind_mismatch
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @main(%out: cap<io.write>) -> u8
effects [io.write]
entry:
%v = const.u8 1
ret %v
@@ -0,0 +1,15 @@
; No grant for the parameter: the program does not start.
; expect: run
; not_instantiated: missing_capability
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.missing_capability
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @main(%out: cap<io.write>) -> u8
effects [io.write]
entry:
%v = const.u8 1
ret %v
@@ -0,0 +1,17 @@
; Two parameters of the same kind get different scopes by name.
; expect: run
; grant: config=fs.read:/etc/app
; grant: data=fs.read:/var/data
; result: 1
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.two_scopes
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @main(%config: cap<fs.read>, %data: cap<fs.read>) -> u8
effects [fs.read]
entry:
%v = const.u8 1
ret %v
@@ -0,0 +1,17 @@
; A grant naming no parameter is an error, so typos are not ignored.
; expect: run
; grant: out=io.write
; grant: ouy=io.write
; not_instantiated: unknown_parameter
; phase: 2
; spec: docs/spec/05-effects-and-capabilities.md
module test.unknown_parameter
air 0
lang 0.1
features [capabilities, effects, ownership]
fn @main(%out: cap<io.write>) -> u8
effects [io.write]
entry:
%v = const.u8 1
ret %v
+47 -7
View File
@@ -20,6 +20,8 @@ const Expect = union(enum) {
result: []const u8,
/// Expected trap code.
trap: []const u8,
/// Expected `reason` of a `not_instantiated` record.
not_instantiated: []const u8,
};
};
@@ -32,6 +34,7 @@ const default_fuel: u64 = 1_000_000;
const Header = struct {
expect: Expect,
fuel: u64,
grants: []const aji.interp.Grant,
phase: u8,
spec: []const u8,
};
@@ -121,8 +124,10 @@ fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Resul
const header = parseHeader(arena, source) catch |err|
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "bad header: {t}", .{err}) };
if (header.phase > aji.implemented_phase)
return .{ .outcome = .pending, .detail = try std.fmt.allocPrint(arena, "phase {d} not implemented", .{header.phase}) };
// A test is pending only while its phase is unfinished and it needs a
// feature this toolchain does not support yet.
if (header.phase > aji.implemented_phase) if (unsupportedFeature(source)) |name|
return .{ .outcome = .pending, .detail = try std.fmt.allocPrint(arena, "phase {d}: feature {s} not implemented", .{ header.phase, name }) };
// Blank header lines (keeping newlines) so spans in diagnostics stay accurate
// and the AIR grammar does not have to know about test metadata.
@@ -147,7 +152,7 @@ fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Resul
switch (header.expect) {
.accept => if (report.status == .accepted) return .{ .outcome = .pass },
.reject => |want| if (report.status == .rejected and eqlCodes(want, got.items)) return .{ .outcome = .pass },
.run => |want| if (report.status == .accepted) return runModule(arena, report.module.?, want, header.fuel),
.run => |want| if (report.status == .accepted) return runModule(arena, report.module.?, want, header),
}
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "expected {f}, got {t} {s}", .{
fmtExpect(header.expect), report.status, try std.mem.join(arena, " ", got.items),
@@ -156,12 +161,13 @@ fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Resul
/// Runs the module twice and requires byte-identical run records (spec 11)
/// before comparing against the expectation.
fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, fuel: u64) !Result {
fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, header: Header) !Result {
var records: [2][]const u8 = undefined;
var outcome: aji.interp.Outcome = undefined;
for (&records) |*rec| {
outcome = aji.interp.run(arena, module, "main", .{ .fuel = fuel }) catch |err| switch (err) {
error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no parameterless @main" },
outcome = aji.interp.run(arena, module, "main", .{ .fuel = header.fuel, .grants = header.grants }) catch |err| switch (err) {
error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" },
error.DuplicateGrant => return .{ .outcome = .fail, .detail = "a parameter is granted more than once" },
else => |e| return e,
};
var w: std.Io.Writer.Allocating = .init(arena);
@@ -174,6 +180,7 @@ fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run,
const ok = switch (want) {
.trap => |code| outcome == .trapped and std.mem.eql(u8, outcome.trapped.code.id, code),
.result => |json| outcome == .returned and std.mem.eql(u8, json, try valueJson(arena, module, outcome.returned)),
.not_instantiated => |reason| outcome == .not_instantiated and std.mem.eql(u8, outcome.not_instantiated.reason, reason),
};
if (ok) return .{ .outcome = .pass };
return .{ .outcome = .fail, .detail = try std.fmt.allocPrint(arena, "got {s}", .{records[0]}) };
@@ -186,6 +193,24 @@ fn valueJson(arena: std.mem.Allocator, module: aji.air.Module, v: aji.interp.Val
return w.written();
}
/// First feature of the module header that this toolchain does not support.
fn unsupportedFeature(source: []const u8) ?[]const u8 {
var lines = std.mem.splitScalar(u8, source, '\n');
while (lines.next()) |line| {
if (!std.mem.startsWith(u8, line, "features [")) continue;
const close = std.mem.indexOfScalar(u8, line, ']') orelse return null;
var names = std.mem.tokenizeAny(u8, line["features [".len..close], ", ");
while (names.next()) |name| {
const known = for (aji.air.features.supported) |s| {
if (std.mem.eql(u8, s, name)) break true;
} else false;
if (!known) return name;
}
return null;
}
return null;
}
fn isKey(s: []const u8) bool {
if (s.len == 0) return false;
for (s) |ch| if (!std.ascii.isLower(ch) and ch != '_') return false;
@@ -212,17 +237,19 @@ fn formatExpect(e: Expect, w: *std.Io.Writer) std.Io.Writer.Error!void {
.run => |r| switch (r) {
.result => |j| try w.print("run returning {s}", .{j}),
.trap => |c| try w.print("run trapping {s}", .{c}),
.not_instantiated => |reason| try w.print("not_instantiated ({s})", .{reason}),
},
}
}
const HeaderError = error{ MissingExpect, MissingPhase, MissingSpec, MissingRunResult, UnknownKey, UnknownCode, BadExpect, OutOfMemory, InvalidCharacter, Overflow };
const HeaderError = error{ 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;
var run_result: ?Expect.Run = null;
var phase: ?u8 = null;
var fuel: u64 = default_fuel;
var grants: std.ArrayList(aji.interp.Grant) = .empty;
var spec: ?[]const u8 = null;
var lines = std.mem.splitScalar(u8, source, '\n');
@@ -260,6 +287,18 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
const code = aji.diag.lookup(value) orelse return error.UnknownCode;
if (code.id[0] != 'T') return error.UnknownCode;
run_result = .{ .trap = value };
} else if (std.mem.eql(u8, key, "not_instantiated")) {
if (run_result != null) return error.BadExpect;
run_result = .{ .not_instantiated = value };
} else if (std.mem.eql(u8, key, "grant")) {
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return error.BadGrant;
const rest = value[eq + 1 ..];
const sep = std.mem.indexOfScalar(u8, rest, ':');
try grants.append(arena, .{
.parameter = value[0..eq],
.kind = if (sep) |c| rest[0..c] else rest,
.scope = if (sep) |c| rest[c + 1 ..] else null,
});
} else if (std.mem.eql(u8, key, "fuel")) {
fuel = try std.fmt.parseInt(u64, value, 10);
} else if (std.mem.eql(u8, key, "phase")) {
@@ -275,6 +314,7 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header
return .{
.expect = expect orelse return error.MissingExpect,
.fuel = fuel,
.grants = grants.items,
.phase = phase orelse return error.MissingPhase,
.spec = spec orelse return error.MissingSpec,
};