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

+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 });
},
}
}