Phase 1: frame storage, second-class borrows, arrays (P1-3..P1-10)

- air: types local/ref/mut/array/slice/slice_mut, from-returns,
  multi-result binding, 18 new instructions; feature gating reports
  E0006 feature_not_declared; borrow-typed block parameters gated by
  borrow_joins; printer and round-trip tests for all new forms
- verifier: second-class and zeroable type rules (E1001); local.alloc
  only in entry (E5002); frame size accounting (E5101); stages init
  (E1010), borrow (E2101, E2102, E2105-E2108) and bounds facts (E2103);
  value types shared between stages
- interp: frame cells, places, slices, deep copies between storage and
  SSA values, T0008 bounds traps
- features arrays and ownership supported; implemented_phase = 1
- conformance: 5 accept, 18 reject, 11 run tests for Phase 1, including
  the file-copy core exit program; 6000 mutants without a crash
This commit is contained in:
dev committed 2026-10-04 13:24:09 +03:00
1 parent be9dd0e1ed
commit 1ae6b485d8
50 files changed
+2376 -37

No files matched your search

+418
View File
@@ -0,0 +1,418 @@
//! Borrow verification for frame storage (spec 08 §11).
//! Reports E2101, E2102, E2105, E2106, E2107, E2108.
//!
//! Every borrow value has static provenance fixed at its definition (root,
//! path, mode, parent). The only flow-sensitive state is the set of live
//! owned borrows. It must be identical on every edge into a block (§11.4),
//! so one walk over the reverse postorder decides each function. The walk
//! covers blocks reachable from the entry block; other blocks never execute.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const Context = verifier.Context;
const ValueId = air.ValueId;
/// One step of a path from a root (§11.2).
const Seg = union(enum) {
field: u32,
/// One side of a `slice.split`, keyed by the split's left result.
split: struct { key: ValueId, side: u1 },
/// An element or sub-range; overlaps every sibling.
elem,
};
const Mode = enum { shared, exclusive };
const Info = struct {
/// Owned borrows are created in this function; lent ones are parameters.
owned: bool,
mode: Mode,
/// A local (`local.alloc` result) or a lent parameter.
root: ValueId,
path: []const Seg,
/// Owned borrow or lent parameter this borrow was derived from.
parent: ?ValueId,
};
pub fn check(c: *Context) !void {
// Signatures first: a borrow return needs `from` (§11.3).
for (c.module.functions) |f| {
if (f.ret.isBorrow() and f.ret_from == null) {
try c.report("E2102", f.span, "a function returning a borrow must name its source with `from`", &.{
.{ .name = "function", .value = .{ .str = f.name } },
});
}
}
if (c.diags.items.len != 0) return;
for (c.module.functions, c.value_types) |f, types| try checkFunction(c, f, types);
}
const Walker = struct {
c: *Context,
f: air.Function,
types: []const air.Type,
info: []?Info,
/// Live owned borrows in the current block.
live: []bool,
block: u32 = 0,
index: u32 = 0,
span: air.Span = .{ .line = 0, .col = 0 },
fn name(w: *Walker, v: ValueId) ![]const u8 {
return w.c.valueName(w.f, v);
}
fn report(w: *Walker, code: []const u8, message: []const u8, borrow: ValueId, extra: ?struct { []const u8, ValueId }) !void {
if (extra) |e| {
try w.c.report(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "borrow", .value = .{ .str = try w.name(borrow) } },
.{ .name = e[0], .value = .{ .str = try w.name(e[1]) } },
});
} else {
try w.c.report(code, w.span, message, &.{
.{ .name = "function", .value = .{ .str = w.f.name } },
.{ .name = "block", .value = .{ .str = w.f.blocks[w.block].name } },
.{ .name = "inst", .value = .{ .int = w.index } },
.{ .name = "borrow", .value = .{ .str = try w.name(borrow) } },
});
}
}
fn isAncestor(w: *Walker, anc: ValueId, of: ValueId) bool {
var x: ?ValueId = of;
while (x) |v| {
if (v == anc) return true;
x = if (w.info[v]) |i| i.parent else null;
}
return false;
}
/// Checks that `v`, used as a borrow, has not been ended (E2106).
fn usable(w: *Walker, v: ValueId) !bool {
const i = w.info[v].?;
if (!i.owned or w.live[v]) return true;
try w.report("E2106", "borrow used after it was ended", v, null);
return false;
}
/// An access to `path` under `root` with `mode`, performed through
/// `through` (a borrow whose ancestors do not conflict) or directly on a
/// local (`through == null`). Reports the first conflict (E2101).
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].?;
if (ci.root != root) continue;
if (via) |t| if (w.isAncestor(@intCast(cv), t)) continue;
if (mode == .shared and ci.mode == .shared) continue;
if (!overlap(path, ci.path)) continue;
try w.report("E2101", "conflicting borrow or access", who, .{ "conflicts_with", @intCast(cv) });
return;
}
}
/// Records a new owned borrow and checks it against live borrows.
fn create(w: *Walker, v: ValueId, parent: ?ValueId, root: ValueId, path: []const Seg) !void {
const mode: Mode = if (w.types[v].isMutBorrow()) .exclusive else .shared;
w.info[v] = .{ .owned = true, .mode = mode, .root = root, .path = path, .parent = parent };
try w.access(root, path, mode, parent, v);
w.live[v] = true;
}
/// Creates a borrow derived from borrow `p` with an extra path step.
fn derive(w: *Walker, v: ValueId, p: ValueId, seg: ?Seg) !void {
if (!try w.usable(p)) return w.poison(v, p);
const pi = w.info[p].?;
try w.create(v, p, pi.root, try w.extend(pi.path, seg));
}
/// After an error, give `v` provenance so later uses do not cascade.
fn poison(w: *Walker, v: ValueId, p: ValueId) void {
const pi = w.info[p].?;
w.info[v] = .{ .owned = true, .mode = .shared, .root = pi.root, .path = pi.path, .parent = p };
w.live[v] = true;
}
fn extend(w: *Walker, path: []const Seg, seg: ?Seg) ![]const Seg {
const s = seg orelse return path;
const out = try w.c.arena.alloc(Seg, path.len + 1);
@memcpy(out[0..path.len], path);
out[path.len] = s;
return out;
}
/// Read or write through borrow `b` (load, store, slice.copy).
fn useThrough(w: *Walker, b: ValueId, mode: Mode) !void {
if (!try w.usable(b)) return;
const bi = w.info[b].?;
try w.access(bi.root, bi.path, mode, b, b);
}
fn isLocal(w: *Walker, v: ValueId) bool {
return w.types[v] == .local;
}
};
pub fn overlap(a: []const Seg, b: []const Seg) bool {
for (a[0..@min(a.len, b.len)], b[0..@min(a.len, b.len)]) |x, y| {
switch (x) {
.field => |fx| if (y == .field) {
if (fx != y.field) return false;
continue;
},
.split => |sx| if (y == .split and sx.key == y.split.key) {
if (sx.side != y.split.side) return false;
continue;
},
.elem => {},
}
return true;
}
return true; // one path is a prefix of the other
}
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
var w: Walker = .{
.c = c,
.f = f,
.types = types,
.info = try c.arena.alloc(?Info, f.values.len),
.live = try c.arena.alloc(bool, f.values.len),
};
@memset(w.info, null);
@memset(w.live, false);
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,
};
};
const dom = try ssa.dominators(c.arena, f);
const entry_state = try c.arena.alloc(?[]bool, f.blocks.len);
@memset(entry_state, null);
entry_state[0] = try c.arena.dupe(bool, w.live);
var reported_join = try c.arena.alloc(bool, f.blocks.len);
@memset(reported_join, false);
var succ: std.ArrayList(u32) = .empty;
for (dom.rpo) |b| {
@memcpy(w.live, entry_state[b].?);
w.block = b;
const blk = f.blocks[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;
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", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[s].name } },
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, @intCast(v)) } },
});
break;
};
}
} else entry_state[s] = try c.arena.dupe(bool, w.live);
}
}
}
fn step(w: *Walker, inst: air.Inst) !void {
const f = w.f;
switch (inst.op) {
.local_store => |x| try w.access(x.local, &.{}, .exclusive, null, x.local),
.local_zero => |v| try w.access(v, &.{}, .exclusive, null, v),
.local_load => |v| try w.access(v, &.{}, .shared, null, v),
.borrow_ref, .borrow_mut => |x| {
const r = inst.result.?;
if (w.isLocal(x)) {
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 }),
.borrow_index => |x| try w.derive(inst.result.?, x.borrow, .elem),
.slice_make => |v| try w.derive(inst.result.?, v, null),
.slice_sub => |x| try w.derive(inst.result.?, x.slice, .elem),
.slice_split => |x| {
const l = inst.result.?;
try w.derive(l, x.slice, .{ .split = .{ .key = l, .side = 0 } });
try w.derive(inst.result2.?, x.slice, .{ .split = .{ .key = l, .side = 1 } });
},
.slice_len => |v| _ = try w.usable(v), // metadata: no access to elements
.load => |v| try w.useThrough(v, .shared),
.store => |x| try w.useThrough(x.borrow, .exclusive),
.slice_copy => |x| {
try w.useThrough(x.src, .shared);
try w.useThrough(x.dst, .exclusive);
},
.borrow_end => |v| {
const i = w.info[v].?;
if (!i.owned) return w.report("E2107", "a borrow parameter is lent by the caller and cannot be ended", v, null);
if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null);
// 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) {
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),
.ret => |v| try retStep(w, v),
// Values of these instructions are not borrows; any borrow operand
// here was already rejected by the type stage.
else => {},
}
_ = f;
}
fn callStep(w: *Walker, inst: air.Inst, callee_index: u32, args: []const ValueId) !void {
const callee = w.c.module.functions[callee_index];
// 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);
@memset(reported, false);
for (args, 0..) |a, i| {
if (!w.types[a].isBorrow()) continue;
if (!try w.usable(a)) continue;
const ai = w.info[a].?;
// The argument is lent for the call: checked like a use of `a`.
const before = w.c.diags.items.len;
try w.access(ai.root, ai.path, ai.mode, a, a);
if (w.c.diags.items.len != before) {
reported[i] = true;
continue;
}
// Arguments must not alias each other if either is exclusive (§11.2).
for (args[0..i], 0..) |b, j| {
if (reported[j]) continue;
if (!w.types[b].isBorrow()) continue;
const bi = w.info[b].?;
if (bi.root != ai.root) continue;
if (ai.mode == .shared and bi.mode == .shared) continue;
if (overlap(ai.path, bi.path)) {
try w.report("E2101", "call arguments alias and one of them is exclusive", a, .{ "conflicts_with", b });
break;
}
}
}
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 (f.ret_from) |p| {
const pv = f.params[p].value;
const b = value.?;
if (!try w.usable(b)) return;
const bi = w.info[b].?;
if (bi.root != pv) {
if (w.isLocal(bi.root)) {
return w.report("E2108", "borrow of frame storage escapes its function", b, .{ "local", bi.root });
}
return w.report("E2102", "returned borrow does not derive from the `from` parameter", b, .{ "from", pv });
}
transferred = b;
}
// Only the returned borrow and its owned ancestors may remain live.
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);
}
}
// ---------------------------------------------------------------- tests
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n";
fn fun(comptime sig: []const u8, comptime body: []const u8) []const u8 {
return h ++ "fn @f" ++ sig ++ "\neffects []\nentry:\n" ++ body;
}
const local_x = " %x = local.alloc u8\n local.zero %x\n";
test "exclusive XOR shared" {
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.mut %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{"E2101"});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %b = borrow.ref %x\n borrow.end %b\n borrow.end %a\n ret\n"), &.{});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n %one = const.u8 1\n local.store %x, %one\n borrow.end %a\n ret\n"), &.{"E2101"});
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{});
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.mut %x\n %v = local.load %x\n borrow.end %a\n ret %v\n"), &.{"E2101"});
}
test "reborrow freezes the parent" {
// Reading through a mut borrow while a shared child is live is fine;
// writing is not.
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %v = load %m\n borrow.end %r\n borrow.end %m\n ret %v\n"), &.{});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n %z = const.u8 0\n store %m, %z\n borrow.end %r\n borrow.end %m\n ret\n"), &.{"E2101"});
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n borrow.end %m\n borrow.end %r\n ret\n"), &.{"E2102"});
}
test "fields and split halves are disjoint" {
const s = h ++ "type @P = struct { a: u8, b: u8 }\n";
try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.b, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{});
try verifier.expectCodes(s ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc @P\n local.zero %x\n %m = borrow.mut %x\n %fa = borrow.field @P.a, %m\n %fb = borrow.field @P.a, %m\n borrow.end %fa\n borrow.end %fb\n borrow.end %m\n ret\n", &.{"E2101"});
const arr = " %x = local.alloc array<u8, 8>\n local.zero %x\n %m = borrow.mut %x\n %s = slice.make %m\n %k = const.usize 4\n %l, %r = slice.split %s, %k\n";
const ends = " borrow.end %l\n borrow.end %r\n borrow.end %s\n borrow.end %m\n ret\n";
try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %r, %lr\n borrow.end %lr\n" ++ ends), &.{});
// Two element borrows of the same parent overlap.
try verifier.expectCodes(comptime fun("() -> void", arr ++ " %z = const.usize 0\n %e1 = borrow.index %l, %z\n %e2 = borrow.index %l, %z\n borrow.end %e1\n borrow.end %e2\n" ++ ends), &.{"E2101"});
// slice.copy within one slice: source and destination overlap.
try verifier.expectCodes(comptime fun("() -> void", arr ++ " %lr = borrow.ref %l\n slice.copy %l, %lr\n borrow.end %lr\n" ++ ends), &.{"E2101"});
}
test "path linearity" {
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n borrow.end %a\n ret\n"), &.{});
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n ret\nq:\n ret\n"), &.{"E2105"});
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " %a = borrow.ref %x\n cbr %c, @p(), @q()\np:\n borrow.end %a\n br @j()\nq:\n br @j()\nj:\n ret\n"), &.{ "E2105", "E2105" });
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n borrow.end %a\n ret\n"), &.{"E2106"});
try verifier.expectCodes(comptime fun("() -> u8", local_x ++ " %a = borrow.ref %x\n borrow.end %a\n %v = load %a\n ret %v\n"), &.{"E2106"});
// trap paths carry no obligation.
try verifier.expectCodes(comptime fun("() -> void", local_x ++ " %a = borrow.ref %x\n trap\n"), &.{});
}
test "loops end their borrows before the back edge" {
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n borrow.end %a\n cbr %c, @loop(), @out()\nout:\n ret\n"), &.{});
try verifier.expectCodes(comptime fun("(%c: bool) -> void", local_x ++ " br @loop()\nloop:\n %a = borrow.ref %x\n cbr %c, @loop(), @out()\nout:\n borrow.end %a\n ret\n"), &.{"E2105"});
}
test "returning borrows" {
try verifier.expectCodes(h ++ "fn @first(%s: slice<u8>) -> ref<u8> from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{});
try verifier.expectCodes(h ++ "fn @f(%s: slice<u8>) -> ref<u8>\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n", &.{"E2102"});
try verifier.expectCodes(h ++ "fn @f(%p: ref<u8>) -> ref<u8> from %p\neffects []\nentry:\n" ++ local_x ++ " %b = borrow.ref %x\n ret %b\n", &.{"E2108"});
try verifier.expectCodes(h ++ "fn @f(%p: ref<u8>, %q: ref<u8>) -> ref<u8> from %p\neffects []\nentry:\n %b = borrow.ref %q\n ret %b\n", &.{"E2102"});
try verifier.expectCodes(h ++ "fn @f(%p: ref<u8>) -> void\neffects []\nentry:\n borrow.end %p\n ret\n", &.{"E2107"});
}
test "call results keep their source alive; mut arguments do not alias" {
const first = "fn @first(%s: slice<u8>) -> ref<u8> from %s\neffects []\nentry:\n %z = const.usize 0\n %e = borrow.index %s, %z\n ret %e\n";
const caller = "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc array<u8, 4>\n local.zero %x\n %r = borrow.ref %x\n %s = slice.make %r\n %e = call @first(%s)\n";
try verifier.expectCodes(h ++ caller ++ " %v = load %e\n borrow.end %e\n borrow.end %s\n borrow.end %r\n ret %v\n" ++ first, &.{});
try verifier.expectCodes(h ++ caller ++ " borrow.end %s\n %v = load %e\n borrow.end %e\n borrow.end %r\n ret %v\n" ++ first, &.{"E2102"});
const two = "fn @g(%a: mut<u8>, %b: ref<u8>) -> void\neffects []\nentry:\n ret\n";
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n" ++ local_x ++ " %m = borrow.mut %x\n %r = borrow.ref %m\n call @g(%m, %r)\n borrow.end %r\n borrow.end %m\n ret\n" ++ two, &.{"E2101"});
}