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"});
}
+180
View File
@@ -0,0 +1,180 @@
//! Bounds facts for `borrow.index.proven` (spec 08 §12). Reports E2103.
//!
//! The analysis is exactly the fact table of the spec: no arithmetic, no
//! other comparisons, no other types. Accepting more or fewer programs would
//! be a conformance bug.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const init = @import("init.zig");
const Context = verifier.Context;
const Fact = struct { i: air.ValueId, n: air.ValueId };
pub fn check(c: *Context) !void {
for (c.module.functions, c.value_types) |f, types| {
var any = false;
for (f.blocks) |b| for (b.insts) |inst| {
if (inst.op == .borrow_index and inst.op.borrow_index.proven) any = true;
};
if (any) try checkFunction(c, f, types);
}
}
fn defOf(f: air.Function, v: air.ValueId) ?air.Inst {
return switch (f.values[v].def) {
.inst => |d| f.blocks[d.block].insts[d.index],
else => null,
};
}
/// Fact established when `cond` is known to be `truth` (spec 08 §12 table).
fn factFrom(f: air.Function, cond: air.ValueId, truth: bool) ?Fact {
const inst = defOf(f, cond) orelse return null;
if (inst.op != .cmp) return null;
const x = inst.op.cmp;
if (x.ty != .int or x.ty.int != .usize) return null;
if (truth) return switch (x.op) {
.lt => .{ .i = x.a, .n = x.b },
.gt => .{ .i = x.b, .n = x.a },
else => null,
};
return switch (x.op) {
.ge => .{ .i = x.a, .n = x.b },
.le => .{ .i = x.b, .n = x.a },
else => null,
};
}
fn constUsize(f: air.Function, v: air.ValueId) ?u128 {
const inst = defOf(f, v) orelse return null;
if (inst.op != .@"const") return null;
const k = inst.op.@"const";
if (k.ty != .int or k.ty.int != .usize) return null;
return k.bits;
}
fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void {
const dom = try ssa.dominators(c.arena, f);
const preds = try init.predecessors(c.arena, f);
var facts: std.ArrayList(Fact) = .empty;
for (dom.rpo) |b| {
// Facts from cbr edges into b and its dominators.
facts.clearRetainingCapacity();
var d = b;
while (true) {
if (d != 0 and preds[d].len == 1) if (edgeFact(f, preds[d][0], d)) |fact| try facts.append(c.arena, fact);
// Guards anywhere in a strict dominator have executed before b.
if (d != b) for (f.blocks[d].insts) |inst| if (inst.op == .guard) {
if (factFrom(f, inst.op.guard, true)) |fact| try facts.append(c.arena, fact);
};
if (d == 0) break;
d = dom.idom[d];
}
for (f.blocks[b].insts, 0..) |inst, ii| {
switch (inst.op) {
.guard => |g| if (factFrom(f, g, true)) |fact| try facts.append(c.arena, fact),
.borrow_index => |x| if (x.proven and !proven(f, types, facts.items, x.borrow, x.index)) {
try c.report("E2103", inst.span, "element access not proven in bounds", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[b].name } },
.{ .name = "inst", .value = .{ .int = @intCast(ii) } },
.{ .name = "borrow", .value = .{ .str = try c.valueName(f, x.borrow) } },
.{ .name = "index", .value = .{ .str = try c.valueName(f, x.index) } },
});
},
else => {},
}
}
}
}
/// Fact from the edge `from -> to`, if it is the only edge into `to`.
fn edgeFact(f: air.Function, from: u32, to: u32) ?Fact {
const term = f.blocks[from].insts[f.blocks[from].insts.len - 1].op;
if (term != .cbr) return null;
const x = term.cbr;
if (x.then.block == x.@"else".block) return null; // two edges into `to`
return factFrom(f, x.cond, x.then.block == to);
}
fn proven(f: air.Function, types: []const air.Type, facts: []const Fact, b: air.ValueId, i: air.ValueId) bool {
// Static length N when `b` borrows an `array<T, N>`.
const len: ?u64 = switch (types[b]) {
.ref, .mut => |inner| if (inner.* == .array) inner.array.len else null,
else => null,
};
if (len) |n| if (constUsize(f, i)) |k| if (k < n) return true;
for (facts) |fact| {
if (fact.i != i) continue;
if (defOf(f, fact.n)) |nd| if (nd.op == .slice_len and nd.op.slice_len == b) return true;
if (len) |n| if (constUsize(f, fact.n)) |k| if (k <= n) return true;
}
return false;
}
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n";
fn withSlice(comptime body: []const u8) []const u8 {
return h ++ "fn @f(%s: slice<u8>, %i: usize) -> u8\neffects []\nentry:\n %n = slice.len %s\n" ++ body;
}
const use = " %e = borrow.index.proven %s, %i\n %v = load %e\n borrow.end %e\n ret %v\n";
const out = "out:\n trap\n";
test "fact table: each established fact proves the access" {
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = gt.usize %n, %i\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = ge.usize %i, %n\n cbr %c, @out(), @in()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = le.usize %n, %i\n cbr %c, @out(), @in()\nin:\n" ++ use ++ out), &.{});
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n guard %c\n" ++ use), &.{});
}
test "non-facts do not prove the access" {
// i <= n allows i == n.
try verifier.expectCodes(comptime withSlice(" %c = le.usize %i, %n\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{"E2103"});
try verifier.expectCodes(comptime withSlice(" %c = ge.usize %n, %i\n cbr %c, @in(), @out()\nin:\n" ++ use ++ out), &.{"E2103"});
// Wrong edge.
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n cbr %c, @out(), @in()\nin:\n" ++ use ++ out), &.{"E2103"});
// No fact at all.
try verifier.expectCodes(comptime withSlice(use), &.{"E2103"});
// Guard on a false-edge comparison establishes nothing.
try verifier.expectCodes(comptime withSlice(" %c = ge.usize %i, %n\n guard %c\n" ++ use), &.{"E2103"});
}
test "fact applies only to the same slice value" {
try verifier.expectCodes(h ++
\\fn @f(%s: slice<u8>, %t: slice<u8>, %i: usize) -> u8
\\effects []
\\entry:
\\ %n = slice.len %t
\\ %c = lt.usize %i, %n
\\ cbr %c, @in(), @out()
\\in:
\\ %e = borrow.index.proven %s, %i
\\ %v = load %e
\\ borrow.end %e
\\ ret %v
\\out:
\\ trap
\\
, &.{"E2103"});
}
test "constant cases on static arrays" {
const arr = h ++ "fn @f(%a: ref<array<u8, 4>>, %i: usize) -> u8\neffects []\nentry:\n";
const use_a = " %e = borrow.index.proven %a, %i\n %v = load %e\n borrow.end %e\n ret %v\n";
try verifier.expectCodes(arr ++ " %k = const.usize 3\n %e = borrow.index.proven %a, %k\n %v = load %e\n borrow.end %e\n ret %v\n", &.{});
try verifier.expectCodes(arr ++ " %k = const.usize 4\n %e = borrow.index.proven %a, %k\n %v = load %e\n borrow.end %e\n ret %v\n", &.{"E2103"});
try verifier.expectCodes(arr ++ " %k = const.usize 4\n %c = lt.usize %i, %k\n cbr %c, @in(), @out()\nin:\n" ++ use_a ++ out, &.{});
try verifier.expectCodes(arr ++ " %k = const.usize 5\n %c = lt.usize %i, %k\n cbr %c, @in(), @out()\nin:\n" ++ use_a ++ out, &.{"E2103"});
}
test "a cbr edge proves nothing when the target has other predecessors" {
try verifier.expectCodes(comptime withSlice(" %c = lt.usize %i, %n\n cbr %c, @in(), @other()\nother:\n br @in()\nin:\n" ++ use), &.{"E2103"});
}
+49 -1
View File
@@ -15,8 +15,37 @@ pub const Limits = struct {
pub const blocks = 16_384;
pub const insts = 262_144;
pub const cases = 4_096;
pub const local_frame = 1_048_576; // bytes, spec 08 §11.5
};
/// Accounted size in bytes (spec 08 §11.5). A counting rule, not a layout.
/// Recursive aggregates are reported later (E1003); they count as 0 here.
pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) u64 {
if (depth > m.types.len + 1) return 0;
return switch (t) {
.int => |it| it.bits() / 8,
.bool => 1,
.array => |a| std.math.mul(u64, a.len, accountedSize(m, a.elem, depth + 1)) catch std.math.maxInt(u64),
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| blk: {
var sum: u64 = 0;
for (fs) |f| sum +|= accountedSize(m, f.ty, depth + 1);
break :blk sum;
},
.@"enum" => |vs| blk: {
var max: u64 = 0;
for (vs) |v| {
var sum: u64 = 0;
for (v.payload) |p| sum +|= accountedSize(m, p, depth + 1);
max = @max(max, sum);
}
break :blk 4 +| max;
},
},
else => 0,
};
}
pub fn check(c: *verifier.Context) !void {
const m = c.module;
const origin: air.Span = .{ .line = 1, .col = 1 };
@@ -45,10 +74,15 @@ pub fn check(c: *verifier.Context) !void {
};
}
try limit(c, f.span, "instructions per function", Limits.insts, n);
var frame: u64 = 0;
for (f.blocks) |b| for (b.insts) |inst| if (inst.op == .local_alloc) {
frame +|= accountedSize(m, inst.op.local_alloc, 0);
};
try limit(c, f.span, "local frame bytes", Limits.local_frame, frame);
}
}
fn limit(c: *verifier.Context, span: air.Span, name: []const u8, max: usize, found: usize) !void {
fn limit(c: *verifier.Context, span: air.Span, name: []const u8, max: u64, found: u64) !void {
if (found <= max) return;
try c.report("E5101", span, "deterministic verifier resource limit exceeded", &.{
.{ .name = "limit", .value = .{ .str = name } },
@@ -65,3 +99,17 @@ test "too many parameters" {
try src.appendSlice(std.testing.allocator, ") -> void\neffects []\nentry:\n ret\n");
try verifier.expectCodes(src.items, &.{"E5101"});
}
test "local frame limit" {
const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n";
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n %a = local.alloc array<u8, 1048576>\n ret\n", &.{});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n %a = local.alloc array<u8, 1048576>\n %b = local.alloc u8\n ret\n", &.{"E5101"});
try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n %a = local.alloc array<usize, 131073>\n ret\n", &.{"E5101"});
}
test "accounted sizes" {
const m: air.Module = .{ .name = "t", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} };
try std.testing.expectEqual(@as(u64, 8), accountedSize(m, .{ .int = .isize }, 0));
try std.testing.expectEqual(@as(u64, 16), accountedSize(m, .{ .int = .u128 }, 0));
try std.testing.expectEqual(@as(u64, 1), accountedSize(m, .bool, 0));
}
+11
View File
@@ -14,6 +14,11 @@ fn checkFunction(c: *Context, f: air.Function) !void {
if (f.blocks.len == 0) return invalid(c, f, f.span, "function has no blocks", null);
if (f.blocks[0].params.len != 0) try invalid(c, f, f.blocks[0].span, "entry block must not declare parameters", f.blocks[0].name);
for (f.blocks[1..]) |b| for (b.insts) |inst| if (inst.op == .local_alloc) {
// Frame storage is static: allocated once per call (spec 08 §11.5).
try invalid(c, f, inst.span, "local.alloc outside the entry block", b.name);
};
for (f.blocks) |b| {
if (b.insts.len == 0) {
try invalid(c, f, b.span, "block has no terminator", b.name);
@@ -124,3 +129,9 @@ test "switch shapes" {
try verifier.expectCodes(e ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x, B -> @y\nx:\n ret\ny(%v: u8):\n ret\n", &.{});
try verifier.expectCodes(e ++ "fn @f(%e: @E) -> void\neffects []\nentry:\n enum.switch @E %e, A -> @x, default -> @x()\nx:\n ret\n", &.{});
}
test "local.alloc only in the entry block" {
const o = "module t\nair 0\nlang 0.1\nfeatures [ownership]\n";
try verifier.expectCodes(o ++ "fn @f() -> void\neffects []\nentry:\n %x = local.alloc u8\n br @next()\nnext:\n ret\n", &.{});
try verifier.expectCodes(o ++ "fn @f() -> void\neffects []\nentry:\n br @next()\nnext:\n %x = local.alloc u8\n ret\n", &.{"E5002"});
}
+173
View File
@@ -0,0 +1,173 @@
//! Initialization of frame storage (spec 08 §13). Reports E1010.
//!
//! Must-initialized dataflow over reachable blocks: a local is initialized
//! at a point if `local.store` or `local.zero` executed on every path to it.
const std = @import("std");
const air = @import("../air.zig");
const verifier = @import("../verifier.zig");
const ssa = @import("ssa.zig");
const Context = verifier.Context;
pub fn check(c: *Context) !void {
for (c.module.functions) |f| try checkFunction(c, f);
}
fn checkFunction(c: *Context, f: air.Function) !void {
// Number the locals of the function.
const slot = try c.arena.alloc(?u32, f.values.len);
@memset(slot, null);
var n: u32 = 0;
for (f.blocks) |b| for (b.insts) |inst| if (inst.op == .local_alloc) {
slot[inst.result.?] = n;
n += 1;
};
if (n == 0) return;
const dom = try ssa.dominators(c.arena, f);
const preds = try predecessors(c.arena, f);
// in[b]: locals initialized at entry of b; null until computed.
const in = try c.arena.alloc(?[]bool, f.blocks.len);
@memset(in, null);
const out = try c.arena.alloc([]bool, f.blocks.len);
for (out) |*o| {
o.* = try c.arena.alloc(bool, n);
@memset(o.*, true); // top element for the intersection
}
// Iterate to a fixpoint; the lattice is finite and transfer is monotone.
var changed = true;
while (changed) {
changed = false;
for (dom.rpo) |b| {
const state = try c.arena.alloc(bool, n);
if (b == 0) {
@memset(state, false);
} else {
@memset(state, true);
for (preds[b]) |p| if (dom.reachable(p)) {
for (state, out[p]) |*s, o| s.* = s.* and o;
};
}
in[b] = state;
const new = try c.arena.dupe(bool, state);
for (f.blocks[b].insts) |inst| transfer(inst.op, slot, new);
if (!std.mem.eql(bool, new, out[b])) {
out[b] = new;
changed = true;
}
}
}
// Report reads of locals that are not definitely initialized.
for (dom.rpo) |b| {
const state = try c.arena.dupe(bool, in[b].?);
for (f.blocks[b].insts, 0..) |inst, ii| {
const read: ?air.ValueId = switch (inst.op) {
.local_load, .borrow_ref, .borrow_mut => |v| v,
else => null,
};
if (read) |v| if (slot[v]) |s| if (!state[s]) {
try c.report("E1010", inst.span, "local read or borrowed before it is initialized on every path", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "block", .value = .{ .str = f.blocks[b].name } },
.{ .name = "inst", .value = .{ .int = @intCast(ii) } },
.{ .name = "local", .value = .{ .str = try c.valueName(f, v) } },
});
};
transfer(inst.op, slot, state);
}
}
}
fn transfer(op: air.Op, slot: []const ?u32, state: []bool) void {
switch (op) {
.local_store => |x| if (slot[x.local]) |s| {
state[s] = true;
},
.local_zero => |v| if (slot[v]) |s| {
state[s] = true;
},
else => {},
}
}
pub fn predecessors(arena: std.mem.Allocator, f: air.Function) ![]const []const u32 {
var lists = try arena.alloc(std.ArrayList(u32), f.blocks.len);
for (lists) |*l| l.* = .empty;
var succ: std.ArrayList(u32) = .empty;
for (f.blocks, 0..) |b, i| {
succ.clearRetainingCapacity();
try air.successors(b.insts[b.insts.len - 1].op, &succ, arena);
for (succ.items) |s| {
// A block reached twice from the same terminator has one predecessor.
if (std.mem.indexOfScalar(u32, lists[s].items, @intCast(i)) == null) try lists[s].append(arena, @intCast(i));
}
}
const out = try arena.alloc([]const u32, f.blocks.len);
for (lists, out) |l, *o| o.* = l.items;
return out;
}
const h = "module t\nair 0\nlang 0.1\nfeatures [ownership]\n";
test "initialization" {
try verifier.expectCodes(h ++ "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc u8\n %v = local.load %x\n ret %v\n", &.{"E1010"});
try verifier.expectCodes(h ++ "fn @f() -> u8\neffects []\nentry:\n %x = local.alloc u8\n local.zero %x\n %v = local.load %x\n ret %v\n", &.{});
// Initialized on one path only.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ cbr %c, @a(), @b()
\\a:
\\ %one = const.u8 1
\\ local.store %x, %one
\\ br @join()
\\b:
\\ br @join()
\\join:
\\ %v = local.load %x
\\ ret %v
\\
, &.{"E1010"});
// Initialized on both paths.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ cbr %c, @a(), @b()
\\a:
\\ %one = const.u8 1
\\ local.store %x, %one
\\ br @join()
\\b:
\\ local.zero %x
\\ br @join()
\\join:
\\ %r = borrow.ref %x
\\ %v = load %r
\\ borrow.end %r
\\ ret %v
\\
, &.{});
// Initialization inside a loop body does not reach the loop header.
try verifier.expectCodes(h ++
\\fn @f(%c: bool) -> u8
\\effects []
\\entry:
\\ %x = local.alloc u8
\\ br @loop()
\\loop:
\\ %v = local.load %x
\\ local.zero %x
\\ cbr %c, @loop(), @out()
\\out:
\\ ret %v
\\
, &.{"E1010"});
}
+209 -16
View File
@@ -14,7 +14,9 @@ const Type = air.Type;
pub fn check(c: *Context) !void {
try checkDeclarations(c);
if (c.diags.items.len != 0) return;
for (c.module.functions) |f| try checkFunction(c, f);
const all = try c.arena.alloc([]const Type, c.module.functions.len);
for (c.module.functions, all) |f, *out| out.* = try checkFunction(c, f);
c.value_types = all;
}
// ---------------------------------------------------------------- declarations
@@ -22,12 +24,30 @@ pub fn check(c: *Context) !void {
fn checkDeclarations(c: *Context) !void {
const m = c.module;
for (m.types) |d| switch (d.kind) {
.@"struct" => |fs| for (fs) |fld| try valueType(c, d.span, fld.ty, d.name),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try valueType(c, d.span, t, d.name),
.@"struct" => |fs| for (fs) |fld| try wellFormed(c, d.span, fld.ty, .member, d.name),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try wellFormed(c, d.span, t, .member, d.name),
};
for (m.functions) |f| {
for (f.params) |p| try valueType(c, f.span, p.ty, f.name);
for (f.blocks) |b| for (b.params) |p| try valueType(c, b.span, p.ty, f.name);
for (f.params) |p| try wellFormed(c, f.span, p.ty, .param, f.name);
try wellFormed(c, f.span, f.ret, .ret, f.name);
if (f.ret_from) |i| {
const p = f.params[i].ty;
if (!f.ret.isBorrow() or !p.isBorrow() or (f.ret.isMutBorrow() and !p.isMutBorrow())) {
try c.report("E1001", f.span, "`from` requires a borrow return and a borrow parameter whose mode allows the result mode", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "ret", .value = .{ .str = try c.typeName(f.ret) } },
.{ .name = "from", .value = .{ .str = try c.typeName(p) } },
});
}
}
for (f.blocks) |b| {
for (b.params) |p| try wellFormed(c, b.span, p.ty, .block_param, f.name);
for (b.insts) |inst| switch (inst.op) {
.local_alloc => |t| try wellFormed(c, inst.span, t, .member, f.name),
.array_splat => |x| try wellFormed(c, inst.span, x.ty, .member, f.name),
else => {},
};
}
}
// E1003: an aggregate that contains itself by value has no finite size.
@@ -52,13 +72,42 @@ fn visitDecl(c: *Context, state: anytype, i: u32) !void {
state[i] = .black;
}
/// `void` and `never` are only valid as function return types (spec 07 §8.3).
fn valueType(c: *Context, span: air.Span, t: Type, owner: []const u8) !void {
if (t != .void and t != .never) return;
try c.report("E1001", span, "`void` and `never` are only valid as function return types", &.{
const Position = enum { member, param, ret, block_param };
/// Where a type may appear (spec 07 §8.3, §8.8):
/// - `void`/`never` only as return types;
/// - storage (`local<T>`) only as the result of `local.alloc`;
/// - borrows only as parameters, returns and (gated) block parameters,
/// never as members (fields, payloads, elements, locals);
/// - the inner type of every compound type is a value type.
fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []const u8) !void {
const ok = switch (t) {
.void, .never => pos == .ret,
.local => false,
.ref, .mut, .slice, .slice_mut => pos != .member,
else => true,
};
if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{
.{ .name = "in", .value = .{ .str = owner } },
.{ .name = "found", .value = .{ .str = @tagName(t) } },
.{ .name = "position", .value = .{ .str = @tagName(pos) } },
.{ .name = "found", .value = .{ .str = try c.typeName(t) } },
});
if (t.inner()) |inner| try wellFormed(c, span, inner, .member, owner);
}
/// `local.alloc` results are checked separately: their own type is storage.
fn zeroable(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool => true,
.array => |a| zeroable(m, a.elem),
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!zeroable(m, f.ty)) break false;
} else true,
.@"enum" => false,
},
else => false,
};
}
// ---------------------------------------------------------------- functions
@@ -86,6 +135,17 @@ const FnCtx = struct {
});
}
fn kindError(fc: *FnCtx, span: air.Span, v: air.ValueId, expected: []const u8) !void {
try fc.c.report("E1001", span, "operand has the wrong kind of type", &.{
.{ .name = "function", .value = .{ .str = fc.f.name } },
.{ .name = "block", .value = .{ .str = fc.f.blocks[fc.block].name } },
.{ .name = "inst", .value = .{ .int = fc.index } },
.{ .name = "operand", .value = .{ .str = try fc.c.valueName(fc.f, v) } },
.{ .name = "expected", .value = .{ .str = expected } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
});
}
fn expectValue(fc: *FnCtx, span: air.Span, v: air.ValueId, expected: Type) !void {
const found = fc.typeOf(v);
if (!found.eql(expected)) try fc.mismatch(span, try fc.c.valueName(fc.f, v), expected, found);
@@ -121,16 +181,84 @@ fn resultType(m: air.Module, op: air.Op) ?Type {
.struct_get => |x| m.types[x.decl].kind.@"struct"[x.field].ty,
.enum_make => |x| .{ .named = x.decl },
.call => |x| m.functions[x.callee].ret,
.slice_len => .{ .int = .usize },
.array_splat => |x| x.ty,
else => null,
};
}
fn checkFunction(c: *Context, f: air.Function) !void {
fn boxed(arena: std.mem.Allocator, t: Type) !*const Type {
const b = try arena.create(Type);
b.* = t;
return b;
}
/// Result type of an instruction whose result depends on operand types.
/// Returns null while an operand is unresolved, and `.void` (which no later
/// check accepts) if the operand has the wrong kind; `checkInst` reports that.
fn derivedType(fc: *FnCtx, op: air.Op) !?Type {
const a = fc.c.arena;
const m = fc.c.module;
const t = switch (op) {
.copy => |v| return fc.ty[v],
.local_alloc => |inner| return .{ .local = try boxed(a, inner) },
.local_load => |v| fc.ty[v] orelse return null,
.borrow_ref, .borrow_mut, .load, .slice_make => |v| fc.ty[v] orelse return null,
.borrow_field => |x| fc.ty[x.borrow] orelse return null,
.borrow_index => |x| fc.ty[x.borrow] orelse return null,
.slice_sub => |x| fc.ty[x.slice] orelse return null,
.slice_split => |x| fc.ty[x.slice] orelse return null,
else => return null,
};
const invalid: Type = .void;
return switch (op) {
.local_load => if (t == .local) t.local.* else invalid,
.borrow_ref => switch (t) {
.local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) },
.slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) },
else => invalid,
},
.borrow_mut => switch (t) {
.local, .mut => .{ .mut = try boxed(a, t.inner().?) },
.slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) },
else => invalid,
},
.borrow_field => |x| switch (t) {
.ref, .mut => |inner| if (inner.* == .named and inner.named == x.decl) blk: {
const fty = try boxed(a, m.types[x.decl].kind.@"struct"[x.field].ty);
break :blk if (t == .ref) Type{ .ref = fty } else Type{ .mut = fty };
} else invalid,
else => invalid,
},
.load => if (t == .ref or t == .mut) t.inner().? else invalid,
.borrow_index => switch (t) {
.ref, .mut => |inner| if (inner.* == .array) blk: {
const e = try boxed(a, inner.array.elem);
break :blk if (t == .ref) Type{ .ref = e } else Type{ .mut = e };
} else invalid,
.slice => |e| .{ .ref = e },
.slice_mut => |e| .{ .mut = e },
else => invalid,
},
.slice_make => switch (t) {
.ref, .mut => |inner| if (inner.* == .array) blk: {
const e = try boxed(a, inner.array.elem);
break :blk if (t == .ref) Type{ .slice = e } else Type{ .slice_mut = e };
} else invalid,
else => invalid,
},
.slice_sub, .slice_split => if (t.isSlice()) t else invalid,
else => unreachable,
};
}
fn checkFunction(c: *Context, f: air.Function) ![]const Type {
const m = c.module;
var fc: FnCtx = .{ .c = c, .f = f, .ty = try c.arena.alloc(?Type, f.values.len) };
@memset(fc.ty, null);
// Seed types from declarations and opcodes, then resolve `copy` chains.
// Seed types from declarations and opcodes, then resolve types that
// depend on operand types (`copy`, borrows, slices) to a fixpoint.
for (f.params) |p| fc.ty[p.value] = p.ty;
for (f.blocks) |b| {
for (b.params) |p| fc.ty[p.value] = p.ty;
@@ -143,14 +271,15 @@ fn checkFunction(c: *Context, f: air.Function) !void {
progress = false;
for (f.blocks) |b| for (b.insts) |inst| {
const r = inst.result orelse continue;
if (fc.ty[r] != null or inst.op != .copy) continue;
if (fc.ty[inst.op.copy]) |t| {
if (fc.ty[r] != null) continue;
if (try derivedType(&fc, inst.op)) |t| {
fc.ty[r] = t;
if (inst.result2) |r2| fc.ty[r2] = t;
progress = true;
}
};
}
// A `copy` cycle can only occur in unreachable code; give it a type that
// A cycle can only occur in unreachable code; give it a type that
// cannot satisfy any later check rather than leaving it unresolved.
for (fc.ty) |*t| if (t.* == null) {
t.* = .void;
@@ -163,6 +292,9 @@ fn checkFunction(c: *Context, f: air.Function) !void {
try checkInst(&fc, inst);
}
}
const out = try c.arena.alloc(Type, f.values.len);
for (fc.ty, out) |t, *o| o.* = t.?;
return out;
}
fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
@@ -170,7 +302,64 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
const f = fc.f;
const span = inst.span;
switch (inst.op) {
.@"const", .copy, .trap => {},
.@"const", .trap => {},
.copy => |v| if (!fc.typeOf(v).isValue()) try fc.c.report("E1001", span, "only value types can be copied", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(fc.typeOf(v)) } },
}),
.local_alloc, .slice_len => {},
.local_store => |x| {
const t = fc.typeOf(x.local);
if (t != .local) return fc.kindError(span, x.local, "local<T>");
try fc.expectValue(span, x.value, t.local.*);
},
.local_zero => |v| {
const t = fc.typeOf(v);
if (t != .local) return fc.kindError(span, v, "local<T>");
if (!zeroable(m, t.local.*)) try fc.c.report("E1001", span, "type is not zeroable", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(t.local.*) } },
});
},
.local_load => |v| if (fc.typeOf(v) != .local) try fc.kindError(span, v, "local<T>"),
.borrow_ref => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, ref<T>, mut<T>, slice<T> or slice_mut<T>"),
.borrow_mut => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "local<T>, mut<T> or slice_mut<T>"),
.borrow_field => |x| if (resultOf(fc, inst) == .void) try fc.kindError(span, x.borrow, "ref or mut of the named struct"),
.borrow_end => |v| if (!fc.typeOf(v).isBorrow()) try fc.kindError(span, v, "a borrow"),
.load => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref<T> or mut<T>"),
.store => |x| {
const t = fc.typeOf(x.borrow);
if (t != .mut) return fc.kindError(span, x.borrow, "mut<T>");
try fc.expectValue(span, x.value, t.mut.*);
},
.array_splat => |x| {
if (x.ty != .array) return fc.c.report("E1001", span, "array.splat needs an array type", &.{
.{ .name = "function", .value = .{ .str = f.name } },
.{ .name = "found", .value = .{ .str = try fc.c.typeName(x.ty) } },
});
try fc.expectValue(span, x.value, x.ty.array.elem);
},
.borrow_index => |x| {
if (resultOf(fc, inst) == .void) return fc.kindError(span, x.borrow, "a borrow of an array, or a slice");
try fc.expectValue(span, x.index, .{ .int = .usize });
},
.slice_make => |v| if (resultOf(fc, inst) == .void) try fc.kindError(span, v, "ref or mut of an array"),
.slice_sub => |x| {
if (!fc.typeOf(x.slice).isSlice()) return fc.kindError(span, x.slice, "a slice");
try fc.expectValue(span, x.start, .{ .int = .usize });
try fc.expectValue(span, x.len, .{ .int = .usize });
},
.slice_split => |x| {
if (!fc.typeOf(x.slice).isSlice()) return fc.kindError(span, x.slice, "a slice");
try fc.expectValue(span, x.at, .{ .int = .usize });
},
.slice_copy => |x| {
const d = fc.typeOf(x.dst);
if (d != .slice_mut) return fc.kindError(span, x.dst, "slice_mut<T>");
const s = fc.typeOf(x.src);
if (!s.isSlice() or !s.inner().?.eql(d.inner().?)) return fc.kindError(span, x.src, try std.fmt.allocPrint(fc.c.arena, "slice<{s}> or slice_mut<{s}>", .{ try fc.c.typeName(d.inner().?), try fc.c.typeName(d.inner().?) }));
},
.guard => |v| try fc.expectValue(span, v, .bool),
.arith => |x| {
try fc.expectValue(span, x.a, .{ .int = x.ty });
try fc.expectValue(span, x.b, .{ .int = x.ty });
@@ -251,6 +440,10 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void {
}
}
fn resultOf(fc: *FnCtx, inst: air.Inst) Type {
return fc.typeOf(inst.result.?);
}
/// Every value of `from` is representable in `to` (spec 02 §2.1).
pub fn lossless(from: air.IntType, to: air.IntType) bool {
if (from.pointerSized() or to.pointerSized()) return false;