Phase 2: I/O intrinsics, linear resources, deterministic profile (RFC 0007)

- air: resource types file<read|write|append>, listener, stream; io_error;
  intrinsic registry (19 intrinsics) synced with reference/intrinsics.md;
  fallible intrinsics as ok/err terminators; fs prefix narrowing;
  linear_aggregates gating
- verifier: intrinsic form, operand, result and capability-kind checks
  (E1001, E3201, E5002); intrinsic effects (E3101); resource linearity
  in the borrow walker with per-edge moves: E3002 leaks and join
  mismatches, E3001, E2001, E2002, E2101 for close while borrowed;
  resources as borrow roots
- interp: deterministic world (captured console, VFS, loopback TCP,
  instruction clock, pinned xoshiro256 PRNG), blocked outcome, run
  record with stdout/stderr/files
- CLI: --stdin, --vfs, --seed, --result-file, --profile (hosted: exit 3),
  exit code 7; runner: stdin/vfs/seed/stdout/stderr/file/blocked headers
- conformance: hello, file copy and TCP echo exit programs; 37 new tests;
  4000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 14:02:17 +03:00
1 parent 571cc6e362
commit d405d4ea50
49 files changed
+2325 -81

No files matched your search

+120 -2
View File
@@ -45,8 +45,8 @@ pub const Kind = struct {
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 = "fs.read", .scope = .path_prefix, .forms = &.{"prefix"} },
.{ .name = "fs.write", .scope = .path_prefix, .forms = &.{"prefix"} },
.{ .name = "io.read", .scope = .none, .forms = &.{} },
.{ .name = "io.write", .scope = .none, .forms = &.{} },
.{ .name = "mem.alloc", .scope = .byte_budget, .forms = &.{} },
@@ -63,10 +63,20 @@ pub const kinds = [_]Kind{
/// Built-in enums: spelled without `@`, fixed variants, no payloads.
pub const Builtin = enum {
cap_error,
io_error,
pub fn variants(b: Builtin) []const []const u8 {
return switch (b) {
.cap_error => &.{ "invalid_restriction", "not_subset", "unsupported_restriction" },
.io_error => &.{ "not_found", "permission_denied", "already_exists", "invalid_input", "no_space", "broken_pipe", "connection_refused", "connection_reset", "address_in_use", "address_unavailable", "timed_out", "other" },
};
}
/// Feature a built-in enum belongs to.
pub fn feature(b: Builtin) []const u8 {
return switch (b) {
.cap_error => "capabilities",
.io_error => "resources",
};
}
@@ -111,6 +121,94 @@ pub fn validScope(kind: u16, scope: ?[]const u8) bool {
};
}
// ---------------------------------------------------------------- intrinsics (reference/intrinsics.md)
/// Linear resource types (spec 06 §6).
pub const Resource = enum {
file_read,
file_write,
file_append,
listener,
stream,
pub fn text(r: Resource) []const u8 {
return switch (r) {
.file_read => "file<read>",
.file_write => "file<write>",
.file_append => "file<append>",
.listener => "listener",
.stream => "stream",
};
}
};
/// Shape of an intrinsic operand.
pub const Operand = union(enum) {
/// `cap<kind>`.
cap: []const u8,
/// `slice<u8>` (read).
bytes,
/// `slice_mut<u8>` (written).
buffer,
/// `mut<R>` for one of the listed resources; not consumed.
borrowed: []const Resource,
/// A resource of one of the listed types, consumed on both edges.
consumed: []const Resource,
};
pub const ResultType = union(enum) {
usize,
u64,
resource: Resource,
};
pub const Intrinsic = struct {
name: []const u8,
operands: []const Operand,
/// Fallible: results are `@ok` parameters and `@err` gets an `io_error`.
/// Infallible: at most one result, bound with `%r =`.
fallible: bool,
results: []const ResultType,
effect: ?[]const u8,
};
const files_w = &[_]Resource{ .file_write, .file_append };
const files_any = &[_]Resource{ .file_read, .file_write, .file_append };
pub const intrinsics = [_]Intrinsic{
.{ .name = "clock.monotonic", .operands = &.{.{ .cap = "clock.read" }}, .fallible = false, .results = &.{.u64}, .effect = "clock.read" },
.{ .name = "fs.close", .operands = &.{.{ .consumed = files_any }}, .fallible = true, .results = &.{}, .effect = null },
.{ .name = "fs.create", .operands = &.{ .{ .cap = "fs.write" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_write }}, .effect = "fs.write" },
.{ .name = "fs.open_append", .operands = &.{ .{ .cap = "fs.write" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_append }}, .effect = "fs.write" },
.{ .name = "fs.open_read", .operands = &.{ .{ .cap = "fs.read" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .file_read }}, .effect = "fs.read" },
.{ .name = "fs.read", .operands = &.{ .{ .borrowed = &.{.file_read} }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "fs.read" },
.{ .name = "fs.sync", .operands = &.{.{ .borrowed = files_w }}, .fallible = true, .results = &.{}, .effect = "fs.write" },
.{ .name = "fs.write_all", .operands = &.{ .{ .borrowed = files_w }, .bytes }, .fallible = true, .results = &.{}, .effect = "fs.write" },
.{ .name = "io.stderr_write", .operands = &.{ .{ .cap = "io.write" }, .bytes }, .fallible = true, .results = &.{}, .effect = "io.write" },
.{ .name = "io.stdin_read", .operands = &.{ .{ .cap = "io.read" }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "io.read" },
.{ .name = "io.stdout_write", .operands = &.{ .{ .cap = "io.write" }, .bytes }, .fallible = true, .results = &.{}, .effect = "io.write" },
.{ .name = "net.accept", .operands = &.{.{ .borrowed = &.{.listener} }}, .fallible = true, .results = &.{.{ .resource = .stream }}, .effect = "net.listen" },
.{ .name = "net.close_listener", .operands = &.{.{ .consumed = &.{.listener} }}, .fallible = true, .results = &.{}, .effect = null },
.{ .name = "net.close_stream", .operands = &.{.{ .consumed = &.{.stream} }}, .fallible = true, .results = &.{}, .effect = null },
.{ .name = "net.connect", .operands = &.{ .{ .cap = "net.connect" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .stream }}, .effect = "net.connect" },
.{ .name = "net.listen", .operands = &.{ .{ .cap = "net.listen" }, .bytes }, .fallible = true, .results = &.{.{ .resource = .listener }}, .effect = "net.listen" },
.{ .name = "net.recv", .operands = &.{ .{ .borrowed = &.{.stream} }, .buffer }, .fallible = true, .results = &.{.usize}, .effect = "net.read" },
.{ .name = "net.send_all", .operands = &.{ .{ .borrowed = &.{.stream} }, .bytes }, .fallible = true, .results = &.{}, .effect = "net.write" },
.{ .name = "random.fill", .operands = &.{ .{ .cap = "random.read" }, .buffer }, .fallible = false, .results = &.{}, .effect = "random.read" },
};
pub fn intrinsicIndex(name: []const u8) ?u16 {
for (intrinsics, 0..) |x, i| if (std.mem.eql(u8, x.name, name)) return @intCast(i);
return null;
}
/// Whether an intrinsic mentions resource types (needs feature `resources`).
pub fn usesResources(x: Intrinsic) bool {
for (x.operands) |o| if (o == .borrowed or o == .consumed) return true;
for (x.results) |r| if (r == .resource) return true;
return false;
}
/// 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 {
@@ -151,3 +249,23 @@ test "instantiation scopes" {
try std.testing.expect(!validScope(kindIndex("io.write").?, "/x"));
try std.testing.expect(validScope(kindIndex("mem.alloc").?, "1048576"));
}
test "intrinsic registry mirrors reference/intrinsics.md" {
const md = @embedFile("intrinsics_md");
var n: usize = 0;
var lines = std.mem.splitScalar(u8, md, '\n');
while (lines.next()) |line| {
if (!std.mem.startsWith(u8, line, "| `")) continue;
var cols = std.mem.tokenizeScalar(u8, line, '|');
const name = std.mem.trim(u8, cols.next().?, " `");
// Only intrinsic rows: a single dotted name (the narrowing table lists kinds).
if (std.mem.indexOfScalar(u8, name, '.') == null or std.mem.indexOfScalar(u8, name, ',') != null) continue;
if (intrinsicIndex(name) == null) {
std.debug.print("intrinsic {s} is documented but not registered\n", .{name});
return error.RegistryOutOfSync;
}
n += 1;
}
try std.testing.expectEqual(intrinsics.len, n);
for (intrinsics, 0..) |x, i| if (i > 0) try std.testing.expect(std.mem.lessThan(u8, intrinsics[i - 1].name, x.name));
}
+3 -1
View File
@@ -30,14 +30,16 @@ pub const registry = [_]Feature{
.{ .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 = "linear_aggregates", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null },
.{ .name = "ownership", .depends = &.{}, .status = .published, .phase = 1 },
.{ .name = "regions", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .reserved, .phase = 2 },
.{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 },
.{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
.{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 },
};
/// Features implemented by this toolchain, sorted.
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership" };
pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "ownership", "resources" };
pub const Reason = enum {
unknown_feature,
+15 -1
View File
@@ -77,6 +77,8 @@ pub const Type = union(enum) {
/// Index into `authority.kinds`.
cap: u16,
builtin: authority.Builtin,
// Feature `resources` (spec 06 §6).
resource: authority.Resource,
pub const Array = struct { elem: Type, len: u64 };
@@ -89,6 +91,7 @@ pub const Type = union(enum) {
.array => |x| x.len == b.array.len and x.elem.eql(b.array.elem),
.cap => |k| b.cap == k,
.builtin => |e| b.builtin == e,
.resource => |r| b.resource == r,
.bool, .void, .never => true,
};
}
@@ -119,9 +122,11 @@ pub const Type = union(enum) {
}
/// Value types may be stored in fields, payloads, elements and locals.
/// (A borrowed resource `mut<file<read>>` has a resource as its inner type.)
/// Linear resources are neither values nor borrows: they are moved.
pub fn isValue(t: Type) bool {
return switch (t) {
.void, .never, .local, .ref, .mut, .slice, .slice_mut => false,
.void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource => false,
else => true,
};
}
@@ -232,6 +237,9 @@ pub const Op = union(enum) {
/// 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 },
/// Intrinsic call (spec 05 §11). With `ok`/`err` it is the fallible
/// terminator form; without, the infallible form.
intrinsic: struct { index: u16, args: []const ValueId, ok: ?u32 = null, err: ?u32 = null },
ret: ?ValueId,
trap,
@@ -241,6 +249,7 @@ pub const Op = union(enum) {
pub fn isTerminator(op: Op) bool {
return switch (op) {
.br, .cbr, .@"switch", .enum_switch, .cap_narrow, .ret, .trap => true,
.intrinsic => |x| x.ok != null,
else => false,
};
}
@@ -366,6 +375,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v
f(ctx, x.cap);
for (x.args) |v| f(ctx, v);
},
.intrinsic => |x| for (x.args) |v| f(ctx, v),
.ret => |v| if (v) |x| f(ctx, x),
.local_alloc => {},
.local_store => |x| {
@@ -419,6 +429,10 @@ pub fn successors(op: Op, buf: *std.ArrayList(u32), gpa: std.mem.Allocator) !voi
try buf.append(gpa, x.ok);
try buf.append(gpa, x.err);
},
.intrinsic => |x| if (x.ok) |ok| {
try buf.append(gpa, ok);
try buf.append(gpa, x.err.?);
},
else => {},
}
}
+49 -8
View File
@@ -423,7 +423,9 @@ const Parser = struct {
while (p.peek().tag != .r_brace) {
const fname = try p.expect(.word, "field name");
_ = try p.expect(.colon, "`:`");
const ty_span = p.peek().span;
const ty = try p.parseType();
try p.gateLinearMember(ty, ty_span);
for (fields.items) |f| if (std.mem.eql(u8, f.name, fname.text))
try p.report("E0003", fname.span, "duplicate field", &.{.{ .name = "name", .value = .{ .str = fname.text } }});
try fields.append(p.arena, .{ .name = fname.text, .ty = ty });
@@ -442,7 +444,10 @@ const Parser = struct {
if (p.peek().tag == .l_paren) {
_ = p.next();
while (p.peek().tag != .r_paren) {
try payload.append(p.arena, try p.parseType());
const ty_span = p.peek().span;
const ty = try p.parseType();
try p.gateLinearMember(ty, ty_span);
try payload.append(p.arena, ty);
if (p.peek().tag != .comma) break;
_ = p.next();
}
@@ -477,9 +482,13 @@ 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.meta.stringToEnum(authority.Builtin, t.text)) |b| {
try p.requireFeature("capabilities", t.span, t.text);
try p.requireFeature(b.feature(), t.span, t.text);
return .{ .builtin = b };
}
if (eql(t.text, "listener") or eql(t.text, "stream")) {
try p.requireFeature("resources", t.span, t.text);
return .{ .resource = if (eql(t.text, "listener")) .listener else .stream };
}
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" } },
@@ -496,6 +505,18 @@ 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, "file")) {
try p.requireFeature("resources", t.span, "file");
_ = try p.expect(.lt, "`<`");
const mode = try p.expect(.word, "`read`, `write` or `append`");
_ = try p.expect(.gt, "`>`");
const Mode = enum { read, write, append };
return .{ .resource = switch (std.meta.stringToEnum(Mode, mode.text) orelse return p.fail(mode, "`read`, `write` or `append`")) {
.read => .file_read,
.write => .file_write,
.append => .file_append,
} };
}
if (eql(t.text, "cap")) {
try p.requireFeature("capabilities", t.span, "cap");
_ = try p.expect(.lt, "`<`");
@@ -517,8 +538,10 @@ const Parser = struct {
.slice, .slice_mut, .array => "arrays",
}, t.span, t.text);
_ = try p.expect(.lt, "`<`");
const inner_span = p.peek().span;
const inner = try p.parseType();
if (kind == .array) {
try p.gateLinearMember(inner, inner_span);
_ = try p.expect(.comma, "`,`");
const n_tok = try p.expect(.number, "array length");
const n = std.fmt.parseInt(u64, n_tok.text, 0) catch 0;
@@ -543,6 +566,11 @@ const Parser = struct {
};
}
/// Resources inside aggregates need the reserved feature `linear_aggregates`.
fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void {
if (t == .resource) try p.requireFeature("linear_aggregates", span, "resource as a member");
}
fn declares(p: *Parser, feature: []const u8) bool {
for (p.declared) |d| if (eql(d, feature)) return true;
return false;
@@ -842,7 +870,7 @@ const Parser = struct {
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);
try p.requireFeature(b.feature(), t.span, t.text);
break :blk .{ .builtin = b };
} else .{ .named = try p.typeRef(.@"enum") };
const value = try p.useValue();
@@ -890,10 +918,23 @@ const Parser = struct {
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;
const which = authority.intrinsicIndex(name.text) orelse {
try p.report("E0004", name.span, "unknown intrinsic", &.{.{ .name = "name", .value = .{ .str = name.text } }});
while (p.peek().tag != .nl) _ = p.next();
return null;
};
if (authority.usesResources(authority.intrinsics[which])) try p.requireFeature("resources", name.span, name.text);
const args = try p.valueList();
if (p.peek().tag != .comma) break :op .{ .intrinsic = .{ .index = which, .args = args } };
_ = p.next();
_ = try p.expectWord("ok");
_ = 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 .{ .intrinsic = .{ .index = which, .args = args, .ok = ok, .err = err } };
}
return p.unknownOpcode(op_tok);
};
@@ -905,7 +946,7 @@ const Parser = struct {
.array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true,
else => false,
};
const may_bind = produces_value or op == .call;
const may_bind = produces_value or op == .call or op == .intrinsic;
if (result_tok) |rt| {
if (!may_bind) return p.fail(rt, "instruction without result binding");
} else if (produces_value) {
+6
View File
@@ -104,6 +104,7 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void {
},
.cap => |k| try w.print("cap<{s}>", .{air.authority.kinds[k].name}),
.builtin => |b| try w.writeAll(@tagName(b)),
.resource => |r| try w.writeAll(r.text()),
.bool, .void, .never => try w.writeAll(@tagName(t)),
}
}
@@ -280,6 +281,11 @@ 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),
.intrinsic => |x| {
try w.print("intrinsic {s}", .{air.authority.intrinsics[x.index].name});
try values(f, x.args, w);
if (x.ok) |ok| try w.print(", ok -> @{s}, err -> @{s}", .{ f.blocks[ok].name, f.blocks[x.err.?].name });
},
.cap_narrow => |x| {
try w.print("cap.narrow.{s} ", .{x.form});
try value(f, x.cap, w);