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

+133 -29
View File
@@ -26,6 +26,9 @@ const Seg = union(enum) {
const Mode = enum { shared, exclusive };
/// Why a resource is no longer live (spec 06 §6.3).
const Dead = enum { none, closed, moved };
const Info = struct {
/// Owned borrows are created in this function; lent ones are parameters.
owned: bool,
@@ -55,8 +58,10 @@ const Walker = struct {
f: air.Function,
types: []const air.Type,
info: []?Info,
/// Live owned borrows in the current block.
/// Live owned borrows and live owned resources at the current point.
live: []bool,
/// How a resource stopped being live, for diagnostics.
dead: []Dead,
block: u32 = 0,
index: u32 = 0,
span: air.Span = .{ .line = 0, .col = 0 },
@@ -107,7 +112,7 @@ const Walker = struct {
fn access(w: *Walker, root: ValueId, path: []const Seg, mode: Mode, via: ?ValueId, who: ValueId) !void {
for (w.live, 0..) |is_live, cv| {
if (!is_live) continue;
const ci = w.info[cv].?;
const ci = w.info[cv] orelse continue; // live resources are not borrows
if (ci.root != root) continue;
if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue;
if (mode == .shared and ci.mode == .shared) continue;
@@ -157,6 +162,32 @@ const Walker = struct {
fn isLocal(w: *Walker, v: ValueId) bool {
return w.types[v] == .local;
}
fn isResource(w: *Walker, v: ValueId) bool {
return w.types[v] == .resource;
}
/// A non-consuming use of resource `v` (a borrow of it).
fn resourceUsable(w: *Walker, v: ValueId) !bool {
if (w.live[v]) return true;
switch (w.dead[v]) {
.closed => try w.report("E3001", "resource used after it was closed", v, null),
.moved => try w.report("E2001", "resource used after its ownership was transferred", v, null),
.none => try w.report("E3001", "resource used before it is owned", v, null),
}
return false;
}
/// Consumes resource `v` by closing or by transfer (spec 06 §6.2).
fn consume(w: *Walker, v: ValueId, how: Dead) !void {
if (!w.live[v]) {
return w.report("E2002", "resource consumed twice", v, null);
}
// Consumption is an exclusive access to the whole resource.
try w.access(v, &.{}, .exclusive, null, v);
w.live[v] = false;
w.dead[v] = how;
}
};
pub fn overlap(a: []const Seg, b: []const Seg) bool {
@@ -177,6 +208,35 @@ pub fn overlap(a: []const Seg, b: []const Seg) bool {
return true; // one path is a prefix of the other
}
const Edge = struct { target: u32, args: []const ValueId };
fn edges(op: air.Op, out: *std.ArrayList(Edge), arena: std.mem.Allocator) !void {
switch (op) {
.br => |t| try out.append(arena, .{ .target = t.block, .args = t.args }),
.cbr => |x| {
try out.append(arena, .{ .target = x.then.block, .args = x.then.args });
try out.append(arena, .{ .target = x.@"else".block, .args = x.@"else".args });
},
.@"switch" => |x| {
for (x.cases) |c| try out.append(arena, .{ .target = c.target.block, .args = c.target.args });
try out.append(arena, .{ .target = x.default.block, .args = x.default.args });
},
.enum_switch => |x| {
for (x.arms) |a| try out.append(arena, .{ .target = a.block, .args = &.{} });
if (x.default) |d| try out.append(arena, .{ .target = d.block, .args = d.args });
},
.cap_narrow => |x| {
try out.append(arena, .{ .target = x.ok, .args = &.{} });
try out.append(arena, .{ .target = x.err, .args = &.{} });
},
.intrinsic => |x| if (x.ok) |ok| {
try out.append(arena, .{ .target = ok, .args = &.{} });
try out.append(arena, .{ .target = x.err.?, .args = &.{} });
},
else => {},
}
}
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
var w: Walker = .{
.c = c,
@@ -184,18 +244,22 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
.types = types,
.info = try c.arena.alloc(?Info, f.values.len),
.live = try c.arena.alloc(bool, f.values.len),
.dead = try c.arena.alloc(Dead, f.values.len),
};
@memset(w.info, null);
@memset(w.live, false);
for (f.params) |p| if (p.ty.isBorrow()) {
w.info[p.value] = .{
@memset(w.dead, .none);
for (f.params) |p| {
if (p.ty.isBorrow()) w.info[p.value] = .{
.owned = false,
.mode = if (p.ty.isMutBorrow()) .exclusive else .shared,
.root = p.value,
.path = &.{},
.parent = null,
};
};
// Resource parameters were moved in: the function owns them (spec 06 §6.3).
if (p.ty == .resource) w.live[p.value] = true;
}
const dom = try ssa.dominators(c.arena, f);
const entry_state = try c.arena.alloc(?[]bool, f.blocks.len);
@@ -204,33 +268,51 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
var reported_join = try c.arena.alloc(bool, f.blocks.len);
@memset(reported_join, false);
var succ: std.ArrayList(u32) = .empty;
var out: std.ArrayList(Edge) = .empty;
for (dom.rpo) |b| {
@memcpy(w.live, entry_state[b].?);
w.block = b;
const blk = f.blocks[b];
// Resource block parameters own their argument from here on.
for (blk.params) |p| if (p.ty == .resource) {
w.live[p.value] = true;
w.dead[p.value] = .none;
};
w.block = b;
for (blk.insts, 0..) |inst, ii| {
w.index = @intCast(ii);
w.span = inst.span;
try step(&w, inst);
}
// Propagate the exit state along every edge (§11.4).
succ.clearRetainingCapacity();
try air.successors(blk.insts[blk.insts.len - 1].op, &succ, c.arena);
for (succ.items) |s| {
if (entry_state[s]) |expected| {
if (!std.mem.eql(bool, expected, w.live) and !reported_join[s]) {
reported_join[s] = true;
// Propagate along every edge; branch arguments of resource type are
// moved on their own edge only (§11.4, spec 06 §6.2).
out.clearRetainingCapacity();
try edges(blk.insts[blk.insts.len - 1].op, &out, c.arena);
const base = try c.arena.dupe(bool, w.live);
const base_dead = try c.arena.dupe(Dead, w.dead);
for (out.items) |e| {
@memcpy(w.live, base);
@memcpy(w.dead, base_dead);
for (e.args) |a| if (types[a] == .resource) try w.consume(a, .moved);
// A resource parameter of the target that is still live on this
// edge would be overwritten: that instance leaks.
for (f.blocks[e.target].params) |p| if (p.ty == .resource) {
if (w.live[p.value]) try w.report("E3002", "resource not consumed before it is redefined", p.value, null);
w.live[p.value] = false;
};
if (entry_state[e.target]) |expected| {
if (!std.mem.eql(bool, expected, w.live) and !reported_join[e.target]) {
reported_join[e.target] = true;
for (expected, w.live, 0..) |a, x, v| if (a != x) {
try c.report("E2105", f.blocks[s].span, "borrow state differs between edges into this block", &.{
const is_res = types[v] == .resource;
try c.report(if (is_res) "E3002" else "E2105", f.blocks[e.target].span, if (is_res) "resource state differs between edges into this block" else "borrow state differs between edges into this block", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[s].name } },
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
.{ .name = "block", .value = .{ .str = f.blocks[e.target].name } },
.{ .name = if (is_res) "resource" else "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
});
break;
};
}
} else entry_state[s] = try c.arena.dupe(bool, w.live);
} else entry_state[e.target] = try c.arena.dupe(bool, w.live);
}
}
}
@@ -245,6 +327,13 @@ fn step(w: *Walker, inst: air.Inst) !void {
const r = inst.result.?;
if (w.isLocal(x)) {
try w.create(r, null, x, &.{});
} else if (w.isResource(x)) {
if (!try w.resourceUsable(x)) {
w.info[r] = .{ .owned = true, .mode = .shared, .root = x, .path = &.{}, .parent = null };
w.live[r] = true;
return;
}
try w.create(r, null, x, &.{});
} else try w.derive(r, x, null);
},
.borrow_field => |x| try w.derive(inst.result.?, x.borrow, .{ .field = x.field }),
@@ -270,12 +359,29 @@ fn step(w: *Walker, inst: air.Inst) !void {
// Ended even when rejected, so one mistake yields one diagnostic.
defer w.live[v] = false;
for (w.live, 0..) |is_live, cv| {
if (is_live and w.info[cv].?.parent == v) {
if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) {
return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) });
}
}
},
.call => |x| try callStep(w, inst, x.callee, x.args),
.call => |x| {
try lendArgs(w, x.args);
const callee = w.c.module.functions[x.callee];
for (x.args) |a| if (w.isResource(a)) try w.consume(a, .moved);
if (callee.ret_from) |p| {
// The result borrows from the argument passed for `from` (§11.3).
const a = x.args[p];
if (w.types[a].isBorrow() and w.info[a] != null) try w.derive(inst.result.?, a, .elem);
}
if (inst.result) |r| if (w.isResource(r)) {
w.live[r] = true;
};
},
.intrinsic => |x| {
try lendArgs(w, x.args);
// Closing intrinsics consume on both edges, so before propagation.
for (x.args, air.authority.intrinsics[x.index].operands) |a, o| if (o == .consumed) try w.consume(a, .closed);
},
.ret => |v| try retStep(w, v),
// Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage.
@@ -284,8 +390,9 @@ fn step(w: *Walker, inst: air.Inst) !void {
_ = f;
}
fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId) !void {
const callee = w.c.module.functions[callee_index];
/// Borrow arguments of a call or intrinsic are lent for its duration and
/// must not alias each other when one is exclusive (§11.2).
fn lendArgs(w: *Walker, args: []const ValueId) !void {
// Arguments already reported; a conflict involving one of them is the
// same mistake and is not reported again.
const reported = try w.c.arena.alloc(bool, args.len);
@@ -314,17 +421,12 @@ fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId
}
}
}
if (callee.ret_from) |p| {
// The result borrows from the argument passed for `from` (§11.3).
const a = args[p];
if (!w.types[a].isBorrow() or w.info[a] == null) return;
try w.derive(inst.result.?, a, .elem);
}
}
fn retStep(w: *Walker, value: ?ValueId) !void {
const f = w.f;
var transferred: ?ValueId = null;
if (value) |v| if (w.isResource(v)) try w.consume(v, .moved);
if (f.ret_from) |p| {
const pv = f.params[p].value;
const b = value.?;
@@ -342,7 +444,9 @@ fn retStep(w: *Walker, value: ?ValueId) !void {
for (w.live, 0..) |is_live, v| {
if (!is_live) continue;
if (transferred) |t| if (w.isAncestor(@intCast(v), t)) continue;
try w.report("E2105", "borrow not ended before return", @intCast(v), null);
if (w.isResource(@intCast(v))) {
try w.report("E3002", "resource not consumed before return", @intCast(v), null);
} else try w.report("E2105", "borrow not ended before return", @intCast(v), null);
}
}