verifier: cache structural properties and nominal size queries

This commit is contained in:
dev committed 2026-10-08 13:33:24 +03:00
1 parent 41f3afbf05
commit 48b9b42fed
31 files changed
+1399 -166

No files matched your search

+347
View File
@@ -0,0 +1,347 @@
//! Cached structural properties of resolved AIR declarations (spec 02/03/04).
const std = @import("std");
const air = @import("module.zig");
const Type = air.Type;
pub const Stats = struct { evaluations: usize = 0, fields: usize = 0 };
/// Resolve shared nominal subgraphs once per changed fact, including cycles.
/// All predicates are monotone: existential facts grow from false, universal
/// facts shrink from true. Height grows to 65, preserving the depth-64 guard.
/// No caller-supplied cache is trusted. Declarations are immutable thereafter.
pub fn prepare(a: std.mem.Allocator, input: air.Module, stats: ?*Stats) !air.Module {
const entries = try a.alloc(air.NominalProperties, input.types.len);
@memset(entries, .{});
var m = input;
m.nominal_properties = entries;
const reverse = try a.alloc(std.ArrayList(u32), input.types.len);
@memset(reverse, .empty);
for (m.types, 0..) |d, i| switch (d.kind) {
.@"struct" => |fs| for (fs) |f| try dependencies(a, reverse, @intCast(i), f.ty),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try dependencies(a, reverse, @intCast(i), t),
};
const queue = try a.alloc(u32, m.types.len);
const queued = try a.alloc(bool, m.types.len);
@memset(queued, true);
for (queue, 0..) |*slot, i| slot.* = @intCast(queue.len - 1 - i);
var head: usize = 0;
var tail: usize = 0;
var count = queue.len;
while (count != 0) {
const i = queue[head];
head = (head + 1) % queue.len;
count -= 1;
queued[i] = false;
if (stats) |s| s.evaluations += 1;
var next: air.NominalProperties = .{};
switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| accumulate(m, &next, f.ty, stats),
.@"enum" => |vs| {
next.zeroable = false;
for (vs) |v| for (v.payload) |t| accumulate(m, &next, t, stats);
},
}
if (entries[i] == next) continue;
entries[i] = next;
for (reverse[i].items) |parent| {
if (queued[parent]) continue;
queue[tail] = parent;
tail = (tail + 1) % queue.len;
count += 1;
queued[parent] = true;
}
}
return m;
}
// Include phantom edges for height. This is a dependency superset for the
// boolean predicates, whose unchanged tag rules decide which inners matter.
fn dependencies(a: std.mem.Allocator, reverse: []std.ArrayList(u32), parent: u32, t: Type) !void {
if (t == .named) {
try reverse[t.named].append(a, parent);
} else if (t.inner()) |inner| try dependencies(a, reverse, parent, inner);
}
fn accumulate(m: air.Module, out: *air.NominalProperties, t: Type, stats: ?*Stats) void {
if (stats) |s| s.fields += 1;
out.linear = out.linear or m.isLinearType(t);
out.copy = out.copy and isCopy(m, t);
out.send = out.send and isSend(m, t);
out.share = out.share and isShare(m, t);
out.island_safe = out.island_safe and isIslandSafe(m, t);
out.local = out.local or isLocalType(m, t);
out.forbidden = out.forbidden or contains(m, t, .forbidden);
out.endpoint = out.endpoint or contains(m, t, .endpoint);
out.zeroable = out.zeroable and isZeroable(m, t);
out.height = @max(out.height, @min(65, @as(u8, height(m, t)) + 1));
out.source_forbidden_depth = @min(out.source_forbidden_depth, @min(34, @as(u8, sourceForbiddenDepth(m, t)) + 1));
}
/// Match the frontend's existing element edges and depth-32 witness guard.
/// A nearest-leaf distance permits pruning without changing field order.
pub fn sourceForbiddenDepth(m: air.Module, t: Type) u6 {
return switch (t) {
.ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => 0,
.array, .own, .own_array, .buffer, .mutex => @intCast(@min(34, @as(u8, sourceForbiddenDepth(m, t.inner().?)) + 1)),
.named => |i| m.nominal_properties.?[i].source_forbidden_depth,
else => 34,
};
}
fn height(m: air.Module, t: Type) u7 {
if (t == .named) return m.nominal_properties.?[t.named].height;
return if (t.inner()) |inner| @intCast(@min(65, @as(u8, height(m, inner)) + 1)) else 1;
}
/// The preceding depth guard, with cached nominal height and identical edges.
pub fn bounded(m: air.Module, t: Type, depth: usize) bool {
if (depth >= 64) return false;
if (t == .named) {
if (m.nominal_properties) |_| return height(m, t) <= 64 - depth;
return switch (m.types[t.named].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!bounded(m, f.ty, depth + 1)) break false;
} else true,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (!bounded(m, p, depth + 1)) break :blk false;
break :blk true;
},
};
}
return if (t.inner()) |inner| bounded(m, inner, depth + 1) else true;
}
pub fn isZeroable(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool => true,
.array => |a| isZeroable(m, a.elem),
.named => |i| if (m.nominal_properties) |p| p[i].zeroable else switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!isZeroable(m, f.ty)) break false;
} else true,
.@"enum" => false,
},
else => false,
};
}
pub fn isCopy(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap, .iref => true,
.array => |a| isCopy(m, a.elem),
.named => |i| if (m.nominal_properties) |p| p[i].copy else aggregateAll(m, i, isCopy),
else => false,
};
}
pub fn isLocalType(m: air.Module, t: Type) bool {
return switch (t) {
.local, .task, .scope, .shield, .guard => true,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .mutex => |inner| isLocalType(m, inner.*),
.array => |a| isLocalType(m, a.elem),
.named => |i| if (m.nominal_properties) |p| p[i].local else switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (isLocalType(m, f.ty)) break true;
} else false,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (isLocalType(m, p)) break :blk true;
break :blk false;
},
},
else => false,
};
}
pub fn isSend(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => true,
// Graph contents are IslandSafe plain data (spec 03 §22–§24).
.island, .frozen, .arc, .iref => true,
// Every access to a cell is an atomic operation (spec 04 §23).
.atomic => true,
.own, .own_array, .buffer, .mutex => |inner| isSend(m, inner.*),
.ref, .slice => |inner| isShare(m, inner.*),
.mut, .slice_mut => |inner| isSend(m, inner.*),
.array => |a| isSend(m, a.elem),
.named => |i| if (m.nominal_properties) |p| p[i].send else aggregateAll(m, i, isSend),
.scope, .task, .shield, .guard, .local, .void, .never => false,
};
}
pub fn isShare(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .cap => true,
.frozen, .arc, .iref, .atomic => true,
// Its owner may mutate it: freeze to share (spec 04 §35).
.island => false,
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => false,
.own, .own_array, .buffer, .ref, .slice => |inner| isShare(m, inner.*),
// The lock synchronizes access (spec 04 §35, §40).
.mutex => |inner| isSend(m, inner.*),
.array => |a| isShare(m, a.elem),
.named => |i| if (m.nominal_properties) |p| p[i].share else aggregateAll(m, i, isShare),
};
}
pub fn isIslandSafe(m: air.Module, t: Type) bool {
return switch (t) {
.int, .bool, .builtin, .iref => true,
.array => |a| isIslandSafe(m, a.elem),
.named => |i| if (m.nominal_properties) |p| p[i].island_safe else aggregateAll(m, i, isIslandSafe),
else => false,
};
}
pub fn aggregateAll(m: air.Module, i: u32, comptime pred: fn (air.Module, Type) bool) bool {
return switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!pred(m, f.ty)) break false;
} else true,
.@"enum" => |vs| {
for (vs) |v| for (v.payload) |p| if (!pred(m, p)) return false;
return true;
},
};
}
pub fn contains(m: air.Module, t: Type, comptime what: enum { endpoint, forbidden }) bool {
const here = switch (what) {
.endpoint => t.isEndpoint(),
.forbidden => t.isBorrow() or t.isTaskBound() or t == .guard,
};
if (here) return true;
// An `iref<T>` holds no `T`: types may recurse through it (spec 03 §22).
if (t == .iref) return false;
if (t.inner()) |inner| if (t != .ref and t != .mut and t != .slice and t != .slice_mut) return contains(m, inner, what);
return switch (t) {
.named => |i| if (m.nominal_properties) |p| @field(p[i], @tagName(what)) else switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (contains(m, f.ty, what)) break true;
} else false,
.@"enum" => |vs| for (vs) |v| {
for (v.payload) |p| if (contains(m, p, what)) return true;
} else false,
},
else => false,
};
}
test "shared nominal diamonds have counted bounded property queries" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const ds = try a.alloc(air.TypeDecl, 65);
for (ds, 0..) |*d, i| {
const fields = try a.alloc(air.Field, if (i == 64) 1 else 2);
for (fields) |*f| f.* = .{ .name = "x", .ty = if (i == 64) .{ .int = .u64 } else .{ .named = @intCast(i + 1) } };
d.* = .{ .name = "N", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = fields } };
}
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds, .functions = &.{} };
var stats: Stats = .{};
const cached = try prepare(a, m, &stats);
try std.testing.expectEqual(@as(usize, 65), stats.evaluations);
try std.testing.expectEqual(@as(usize, 129), stats.fields);
for (0..65) |i| {
const t: Type = .{ .named = @intCast(i) };
try std.testing.expect(!cached.isLinearType(t));
try std.testing.expect(isCopy(cached, t) and isSend(cached, t) and isShare(cached, t) and isIslandSafe(cached, t) and isZeroable(cached, t));
try std.testing.expect(!isLocalType(cached, t) and !contains(cached, t, .endpoint) and !contains(cached, t, .forbidden));
}
try std.testing.expect(!bounded(cached, .{ .named = 0 }, 0));
try std.testing.expect(!bounded(cached, .{ .named = 1 }, 0));
try std.testing.expect(bounded(cached, .{ .named = 2 }, 0));
}
test "cyclic property work terminates and phantom handles stay Copy" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const self: Type = .{ .named = 0 };
const phantom: Type = .{ .iref = &self };
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{.{ .name = "Node", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "next", .ty = phantom }} } }}, .functions = &.{} };
var stats: Stats = .{};
const cached = try prepare(a, m, &stats);
try std.testing.expect(stats.evaluations <= 65);
try std.testing.expect(isCopy(cached, self) and isIslandSafe(cached, self));
try std.testing.expect(!cached.isLinearType(self) and !contains(cached, self, .forbidden));
try std.testing.expect(!bounded(cached, self, 0));
}
test "cached predicates match uncached derivations on mixed acyclic graphs" {
for (0..256) |seed| {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const ds = try a.alloc(air.TypeDecl, 4);
for (ds, 0..) |*d, i| {
const child = try a.create(Type);
child.* = if (i == 3) .{ .int = .u64 } else .{ .named = @intCast(i + 1) };
const array = try a.create(Type.Array);
array.* = .{ .elem = child.*, .len = 2 };
const choices = [_]Type{ child.*, .bool, .void, .region, .scope, .{ .own = child }, .{ .mut = child }, .{ .ref = child }, .{ .mutex = child }, .{ .iref = child }, .{ .task = child }, .{ .sender = child }, .{ .array = array }, .{ .island = child }, .{ .arc = child }, .{ .buffer = child } };
const x = choices[(seed + i * 7) % choices.len];
const y = choices[(seed / choices.len + i * 3) % choices.len];
const fields = try a.dupe(air.Field, &.{ .{ .name = "a", .ty = x }, .{ .name = "b", .ty = y } });
const vs = try a.alloc(air.Variant, 2);
vs[0] = .{ .name = "A", .payload = try a.dupe(Type, &.{x}) };
vs[1] = .{ .name = "B", .payload = try a.dupe(Type, &.{y}) };
d.* = .{ .name = "N", .span = .{ .line = 1, .col = 1 }, .kind = if ((seed + i) % 3 == 0) .{ .@"enum" = vs } else .{ .@"struct" = fields } };
}
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds, .functions = &.{} };
const cached = try prepare(a, m, null);
for (0..4) |i| {
const t: Type = .{ .named = @intCast(i) };
try std.testing.expectEqual(m.isLinearType(t), cached.isLinearType(t));
inline for (.{ isCopy, isSend, isShare, isIslandSafe, isLocalType, isZeroable }) |pred| try std.testing.expectEqual(pred(m, t), pred(cached, t));
inline for (.{ .endpoint, .forbidden }) |what| try std.testing.expectEqual(contains(m, t, what), contains(cached, t, what));
for ([_]usize{ 0, 31, 63, 64 }) |depth| try std.testing.expectEqual(bounded(m, t, depth), bounded(cached, t, depth));
for ([_]u32{ 0, 30, 31, 32, 33 }) |depth| {
const before = witness(m, t, depth, false);
const after = witness(cached, t, depth, true);
try std.testing.expectEqual(before == null, after == null);
if (before) |b| try std.testing.expect(b.eql(after.?));
}
var memo: @import("../verifier/budget.zig").SizeMemo = .{ .arena = a };
for ([_]usize{ 0, 1, 5, 6 }) |depth| try std.testing.expectEqual(@import("../verifier/budget.zig").accountedSize(m, t, depth), try memo.size(m, t, depth));
}
}
}
// The preceding frontend witness rule, independently applied to AIR types.
fn witness(m: air.Module, t: Type, depth: u32, cached: bool) ?Type {
if (depth > 32) return null;
if (cached and t == .named and sourceForbiddenDepth(m, t) > 32 - depth) return null;
return switch (t) {
.ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => t,
.array, .own, .own_array, .buffer, .mutex => witness(m, t.inner().?, depth + 1, cached),
.named => |i| switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (witness(m, f.ty, depth + 1, cached)) |bad| break bad;
} else null,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (witness(m, p, depth + 1, cached)) |bad| break :blk bad;
break :blk null;
},
},
else => null,
};
}
test "cyclic existential facts reach all predecessors without a false cache" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const u: Type = .{ .int = .u64 };
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{
.{ .name = "A", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "b", .ty = .{ .named = 1 } }} } },
.{ .name = "B", .span = .{ .line = 2, .col = 1 }, .kind = .{ .@"struct" = &.{ .{ .name = "a", .ty = .{ .named = 0 } }, .{ .name = "owner", .ty = .{ .own = &u } }, .{ .name = "borrow", .ty = .{ .mut = &u } } } } },
}, .functions = &.{} };
var stats: Stats = .{};
const cached = try prepare(a, m, &stats);
try std.testing.expect(stats.evaluations < 150);
for (0..2) |i| {
const t: Type = .{ .named = @intCast(i) };
try std.testing.expect(cached.isLinearType(t) and contains(cached, t, .forbidden));
try std.testing.expect(!isCopy(cached, t) and !isShare(cached, t));
}
}