Files
aji/src/air/properties.zig
T

775 lines
37 KiB
Zig

//! 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, initial: Type) !void {
var t = initial;
while (t != .named) t = t.inner() orelse return;
try reverse[t.named].append(a, parent);
}
fn accumulate(m: air.Module, out: *air.NominalProperties, t: Type, stats: ?*Stats) void {
if (stats) |s| s.fields += 1;
out.linear = out.linear or prepared.isLinearType(m, t);
out.copy = out.copy and prepared.isCopy(m, t);
out.send = out.send and prepared.isSend(m, t);
out.share = out.share and prepared.isShare(m, t);
out.island_safe = out.island_safe and prepared.isIslandSafe(m, t);
out.local = out.local or prepared.isLocalType(m, t);
out.forbidden = out.forbidden or prepared.contains(m, t, .forbidden);
out.endpoint = out.endpoint or prepared.contains(m, t, .endpoint);
out.zeroable = out.zeroable and prepared.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, initial: Type) u6 {
var t = initial;
var edges: u6 = 0;
while (true) {
const leaf: u6 = switch (t) {
.ref, .mut, .slice, .slice_mut, .scope, .task, .shield, .guard => 0,
.array, .own, .own_array, .buffer, .mutex => {
edges += 1;
if (edges == 34) return 34;
t = t.inner().?;
continue;
},
.named => |i| m.nominal_properties.?[i].source_forbidden_depth,
else => 34,
};
return @intCast(@min(34, @as(u8, edges) + leaf));
}
}
fn height(m: air.Module, initial: Type) u7 {
var t = initial;
var edges: u7 = 0;
while (t != .named) {
const inner = t.inner() orelse return @intCast(@min(65, @as(u8, edges) + 1));
edges += 1;
if (edges == 65) return 65;
t = inner;
}
return @intCast(@min(65, @as(u8, edges) + m.nominal_properties.?[t.named].height));
}
/// 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;
}
/// Structural queries accept resolved declaration indices. Cached reads and
/// anonymous leaves allocate nothing; a cache-free nominal query prepares
/// immutable facts in temporary host storage and propagates allocation errors.
pub const Property = enum { linear, zeroable, copy, local, send, share, island_safe, endpoint, forbidden };
const Named = struct { index: u32, property: Property };
const Leaf = union(enum) { known: bool, named: Named };
fn classify(initial: Type, initial_property: Property) Leaf {
var t = initial;
var property = initial_property;
while (true) switch (property) {
.linear => {
if (t.isLinear()) return .{ .known = true };
switch (t) {
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
else => return .{ .known = false },
}
},
.zeroable => switch (t) {
.int, .bool => return .{ .known = true },
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
else => return .{ .known = false },
},
.copy => switch (t) {
.int, .bool, .builtin, .cap, .iref => return .{ .known = true },
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
else => return .{ .known = false },
},
.local => switch (t) {
.local, .task, .scope, .shield, .guard => return .{ .known = true },
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .mutex => |inner| t = inner.*,
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
else => return .{ .known = false },
},
.send => switch (t) {
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver, .island, .frozen, .arc, .iref, .atomic => return .{ .known = true },
.own, .own_array, .buffer, .mutex, .mut, .slice_mut => |inner| t = inner.*,
.ref, .slice => |inner| {
t = inner.*;
property = .share;
},
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
.scope, .task, .shield, .guard, .local, .void, .never => return .{ .known = false },
},
.share => switch (t) {
.int, .bool, .builtin, .cap, .frozen, .arc, .iref, .atomic => return .{ .known = true },
.own, .own_array, .buffer, .ref, .slice => |inner| t = inner.*,
.mutex => |inner| {
t = inner.*;
property = .send;
},
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never, .island => return .{ .known = false },
},
.island_safe => switch (t) {
.int, .bool, .builtin, .iref => return .{ .known = true },
.array => |a| t = a.elem,
.named => |i| return .{ .named = .{ .index = i, .property = property } },
else => return .{ .known = false },
},
.endpoint, .forbidden => {
const here = if (property == .endpoint) t.isEndpoint() else t.isBorrow() or t.isTaskBound() or t == .guard;
if (here) return .{ .known = true };
// An iref<T> holds no T (spec 03 §22).
if (t == .iref) return .{ .known = false };
if (t.inner()) |inner| if (t != .ref and t != .mut and t != .slice and t != .slice_mut) {
t = inner;
continue;
};
return if (t == .named) .{ .named = .{ .index = t.named, .property = property } } else .{ .known = false };
},
};
}
fn fact(m: air.Module, n: Named) bool {
return switch (n.property) {
inline else => |p| @field(m.nominal_properties.?[n.index], @tagName(p)),
};
}
/// Each uncached nominal query prepares the entire resolved module afresh.
/// For repeated queries, call prepare once and query its returned immutable
/// module; this avoids paying the preparation cost for every named root.
pub fn query(a: std.mem.Allocator, m: air.Module, t: Type, property: Property) std.mem.Allocator.Error!bool {
return switch (classify(t, property)) {
.known => |value| value,
.named => |n| blk: {
if (m.nominal_properties != null) break :blk fact(m, n);
// An enum never has a zero value; its payloads need no query.
if (n.property == .zeroable and m.types[n.index].kind == .@"enum") break :blk false;
var scratch: std.heap.ArenaAllocator = .init(a);
defer scratch.deinit();
break :blk fact(try prepare(scratch.allocator(), m, null), n);
},
};
}
pub fn isLinearType(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .linear);
}
pub fn isZeroable(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .zeroable);
}
pub fn isCopy(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .copy);
}
pub fn isLocalType(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .local);
}
pub fn isSend(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .send);
}
pub fn isShare(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .share);
}
pub fn isIslandSafe(a: std.mem.Allocator, m: air.Module, t: Type) std.mem.Allocator.Error!bool {
return query(a, m, t, .island_safe);
}
pub fn contains(a: std.mem.Allocator, m: air.Module, t: Type, comptime what: enum { endpoint, forbidden }) std.mem.Allocator.Error!bool {
return query(a, m, t, switch (what) {
.endpoint => .endpoint,
.forbidden => .forbidden,
});
}
/// Infallible queries for prepared modules (or anonymous terminal paths).
/// Reaching a named declaration requires valid immutable nominal_properties.
pub const prepared = struct {
fn value(m: air.Module, t: Type, property: Property) bool {
return switch (classify(t, property)) {
.known => |v| v,
.named => |n| fact(m, n),
};
}
pub fn isLinearType(m: air.Module, t: Type) bool {
return value(m, t, .linear);
}
pub fn isZeroable(m: air.Module, t: Type) bool {
return value(m, t, .zeroable);
}
pub fn isCopy(m: air.Module, t: Type) bool {
return value(m, t, .copy);
}
pub fn isLocalType(m: air.Module, t: Type) bool {
return value(m, t, .local);
}
pub fn isSend(m: air.Module, t: Type) bool {
return value(m, t, .send);
}
pub fn isShare(m: air.Module, t: Type) bool {
return value(m, t, .share);
}
pub fn isIslandSafe(m: air.Module, t: Type) bool {
return value(m, t, .island_safe);
}
pub fn contains(m: air.Module, t: Type, comptime what: enum { endpoint, forbidden }) bool {
return value(m, t, switch (what) {
.endpoint => .endpoint,
.forbidden => .forbidden,
});
}
};
// Independent pre-repair derivation for shallow, acyclic test graphs.
const Reference = struct {
/// Whole-value linearity; well-formed nominal ownership graphs are acyclic.
pub fn isLinearType(m: air.Module, initial: Type) bool {
var t = initial;
while (true) {
if (t.isLinear()) return true;
return switch (t) {
.array => |a| {
t = a.elem;
continue;
},
.named => |i| if (m.nominal_properties) |p| p[i].linear else switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (Reference.isLinearType(m, f.ty)) break true;
} else false,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (Reference.isLinearType(m, p)) break :blk true;
break :blk false;
},
},
else => false,
};
}
}
pub fn isZeroable(m: air.Module, initial: Type) bool {
var t = initial;
while (true) {
return switch (t) {
.int, .bool => true,
.array => |a| {
t = a.elem;
continue;
},
.named => |i| if (m.nominal_properties) |p| p[i].zeroable else switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (!Reference.isZeroable(m, f.ty)) break false;
} else true,
.@"enum" => false,
},
else => false,
};
}
}
pub fn isCopy(m: air.Module, initial: Type) bool {
var t = initial;
while (true) {
return switch (t) {
.int, .bool, .builtin, .cap, .iref => true,
.array => |a| {
t = a.elem;
continue;
},
.named => |i| if (m.nominal_properties) |p| p[i].copy else Reference.aggregateAll(m, i, Reference.isCopy),
else => false,
};
}
}
pub fn isLocalType(m: air.Module, initial: Type) bool {
var t = initial;
while (true) {
return switch (t) {
.local, .task, .scope, .shield, .guard => true,
.ref, .mut, .slice, .slice_mut, .own, .own_array, .buffer, .mutex => |inner| {
t = inner.*;
continue;
},
.array => |a| {
t = a.elem;
continue;
},
.named => |i| if (m.nominal_properties) |p| p[i].local else switch (m.types[i].kind) {
.@"struct" => |fs| for (fs) |f| {
if (Reference.isLocalType(m, f.ty)) break true;
} else false,
.@"enum" => |vs| blk: {
for (vs) |v| for (v.payload) |p| if (Reference.isLocalType(m, p)) break :blk true;
break :blk false;
},
},
else => false,
};
}
}
pub fn isSend(m: air.Module, t: Type) bool {
return Reference.sendShare(m, t, .send);
}
pub fn isShare(m: air.Module, t: Type) bool {
return Reference.sendShare(m, t, .share);
}
/// Borrow and mutex edges can change the property being queried. Keep that
/// state explicit so alternating ref/mutex chains do not grow the native stack.
fn sendShare(m: air.Module, initial: Type, initial_mode: enum { send, share }) bool {
var t = initial;
var mode = initial_mode;
while (true) {
if (mode == .send) switch (t) {
.int, .bool, .builtin, .cap, .resource, .region, .sender, .receiver => return true,
// Graph contents are IslandSafe plain data (spec 03 §22–§24).
.island, .frozen, .arc, .iref => return true,
// Every access to a cell is an atomic operation (spec 04 §23).
.atomic => return true,
.own, .own_array, .buffer, .mutex, .mut, .slice_mut => |inner| t = inner.*,
.ref, .slice => |inner| {
t = inner.*;
mode = .share;
},
.array => |a| t = a.elem,
.named => |i| return if (m.nominal_properties) |p| p[i].send else Reference.aggregateAll(m, i, Reference.isSend),
.scope, .task, .shield, .guard, .local, .void, .never => return false,
} else switch (t) {
.int, .bool, .builtin, .cap => return true,
.frozen, .arc, .iref, .atomic => return true,
// Its owner may mutate it: freeze to share (spec 04 §35).
.island => return false,
.resource, .region, .mut, .slice_mut, .scope, .task, .shield, .guard, .sender, .receiver, .local, .void, .never => return false,
.own, .own_array, .buffer, .ref, .slice => |inner| t = inner.*,
// The lock synchronizes access (spec 04 §35, §40).
.mutex => |inner| {
t = inner.*;
mode = .send;
},
.array => |a| t = a.elem,
.named => |i| return if (m.nominal_properties) |p| p[i].share else Reference.aggregateAll(m, i, Reference.isShare),
}
}
}
pub fn isIslandSafe(m: air.Module, initial: Type) bool {
var t = initial;
while (true) {
return switch (t) {
.int, .bool, .builtin, .iref => true,
.array => |a| {
t = a.elem;
continue;
},
.named => |i| if (m.nominal_properties) |p| p[i].island_safe else Reference.aggregateAll(m, i, Reference.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, initial: Type, comptime what: enum { endpoint, forbidden }) bool {
var t = initial;
while (true) {
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) {
t = inner;
continue;
};
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 (Reference.contains(m, f.ty, what)) break true;
} else false,
.@"enum" => |vs| for (vs) |v| {
for (v.payload) |p| if (Reference.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(!try cached.isLinearType(a, t));
try std.testing.expect(try isCopy(a, cached, t) and try isSend(a, cached, t) and try isShare(a, cached, t) and try isIslandSafe(a, cached, t) and try isZeroable(a, cached, t));
try std.testing.expect(!try isLocalType(a, cached, t) and !try contains(a, cached, t, .endpoint) and !try contains(a, 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 "cache-free nominal property queries handle deep records and independent terminal facts" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const byte: Type = .{ .int = .u8 };
const leaves = [_]Type{ byte, .scope, .{ .sender = &byte } };
// Property order: linear, zeroable, Copy, Local, Send, Share,
// IslandSafe, endpoint and forbidden content.
const expected = [_][9]bool{
.{ false, true, true, false, true, true, true, false, false },
.{ true, false, false, true, false, false, false, false, true },
.{ true, false, false, false, true, false, false, true, false },
};
const ds = try a.alloc(air.TypeDecl, 32768);
const fields = try a.alloc(air.Field, ds.len * 2);
for (ds, 0..) |*d, i| {
fields[2 * i] = .{ .name = "child", .ty = if (i + 1 == ds.len) byte else .{ .named = @intCast(i + 1) } };
fields[2 * i + 1] = .{ .name = "flag", .ty = .bool };
d.* = .{ .name = "N", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = fields[2 * i ..][0..2] } };
}
const m: air.Module = .{ .name = "deep", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds, .functions = &.{} };
const ty: Type = .{ .named = 0 };
for (leaves, expected) |leaf, row| {
fields[fields.len - 2].ty = leaf;
inline for (std.meta.tags(Property), 0..) |property, column|
try std.testing.expectEqual(row[column], try query(std.testing.allocator, m, ty, property));
try std.testing.expect(m.nominal_properties == null);
}
}
test "nominal query metadata failures are host errors and prepared or terminal reads allocate nothing" {
const byte: Type = .{ .int = .u8 };
const ds = [_]air.TypeDecl{
.{ .name = "Outer", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "inner", .ty = .{ .named = 1 } }} } },
.{ .name = "Inner", .span = .{ .line = 2, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "owner", .ty = .{ .own = &byte } }} } },
.{ .name = "Choice", .span = .{ .line = 3, .col = 1 }, .kind = .{ .@"enum" = &.{.{ .name = "empty", .payload = &.{} }} } },
};
const m: air.Module = .{ .name = "fail", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &ds, .functions = &.{} };
const ty: Type = .{ .named = 0 };
inline for (std.meta.tags(Property)) |property| {
var fail_index: usize = 0;
while (true) : (fail_index += 1) {
try std.testing.expect(fail_index < 100);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
const result = query(failing.allocator(), m, ty, property);
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
} else _ = try result;
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const cached = try prepare(scratch.allocator(), m, null);
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
inline for (std.meta.tags(Property)) |property| {
try std.testing.expectEqual(try query(std.testing.allocator, m, ty, property), try query(failing.allocator(), cached, ty, property));
try std.testing.expectEqual(try query(std.testing.allocator, m, byte, property), try query(failing.allocator(), m, byte, property));
}
// Zeroable rejects an enum without inspecting its payload graph.
try std.testing.expect(!try isZeroable(failing.allocator(), m, .{ .named = 2 }));
try std.testing.expect(!failing.has_induced_failure);
}
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(try isCopy(a, cached, self) and try isIslandSafe(a, cached, self));
try std.testing.expect(!try cached.isLinearType(a, self) and !try contains(a, 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) };
for ([_]air.Module{ m, cached }) |module| {
try std.testing.expectEqual(Reference.isLinearType(m, t), try module.isLinearType(a, t));
inline for (.{ .{ Reference.isCopy, isCopy }, .{ Reference.isSend, isSend }, .{ Reference.isShare, isShare }, .{ Reference.isIslandSafe, isIslandSafe }, .{ Reference.isLocalType, isLocalType }, .{ Reference.isZeroable, isZeroable } }) |pred| try std.testing.expectEqual(pred[0](m, t), try pred[1](a, module, t));
inline for (.{ .endpoint, .forbidden }) |what| try std.testing.expectEqual(Reference.contains(m, t, what), try contains(a, module, 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(try @import("../verifier/budget.zig").accountedSize(a, 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(try cached.isLinearType(a, t) and try contains(a, cached, t, .forbidden));
try std.testing.expect(!try isCopy(a, cached, t) and !try isShare(a, cached, t));
}
}
fn deepArrays(a: std.mem.Allocator, leaf: Type) !Type {
const rows = try a.alloc(Type.Array, 32_768);
var t = leaf;
for (rows) |*row| {
row.* = .{ .elem = t, .len = 1 };
t = .{ .array = row };
}
return t;
}
test "deep anonymous property queries and nominal preparation avoid recursion" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const u: Type = .{ .int = .u8 };
const plain = try deepArrays(a, u);
const task = try deepArrays(a, .{ .task = &u });
const endpoint = try deepArrays(a, .{ .sender = &u });
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{
.{ .name = "Plain", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "x", .ty = plain }} } },
.{ .name = "Task", .span = .{ .line = 2, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "x", .ty = task }} } },
.{ .name = "Endpoint", .span = .{ .line = 3, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "x", .ty = endpoint }} } },
}, .functions = &.{} };
const cached = try prepare(a, m, null);
for ([_]air.Module{ m, cached }) |module| {
try std.testing.expect(!try module.isLinearType(a, plain));
inline for (.{ isCopy, isSend, isShare, isIslandSafe, isZeroable }) |pred| try std.testing.expect(try pred(a, module, plain));
try std.testing.expect(!try isLocalType(a, module, plain) and !try contains(a, module, plain, .forbidden) and !try contains(a, module, plain, .endpoint));
try std.testing.expect(try module.isLinearType(a, task) and try isLocalType(a, module, task) and try contains(a, module, task, .forbidden));
inline for (.{ isCopy, isSend, isShare, isIslandSafe, isZeroable }) |pred| try std.testing.expect(!try pred(a, module, task));
try std.testing.expect(try module.isLinearType(a, endpoint) and try isSend(a, module, endpoint) and try contains(a, module, endpoint, .endpoint));
try std.testing.expect(!try isLocalType(a, module, endpoint) and !try isShare(a, module, endpoint) and !try contains(a, module, endpoint, .forbidden));
}
for ([_]Type{ plain, task, endpoint }) |t| {
try std.testing.expectEqual(@as(u7, 65), height(cached, t));
try std.testing.expectEqual(@as(u6, 34), sourceForbiddenDepth(cached, t));
}
const p = cached.nominal_properties.?;
try std.testing.expect(p[0].copy and p[0].zeroable and p[0].send and p[0].share and p[0].island_safe and !p[0].linear);
try std.testing.expect(p[1].linear and p[1].local and p[1].forbidden and !p[1].send and !p[1].copy);
try std.testing.expect(p[2].endpoint and p[2].linear and p[2].send and !p[2].share);
}
test "deep nominal dependency through phantom anonymous handles is retained" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const nodes = try a.alloc(Type, 32_768);
var t: Type = .{ .named = 0 };
for (nodes) |*node| {
node.* = t;
t = .{ .iref = node };
}
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 = t }} } }}, .functions = &.{} };
const cached = try prepare(a, m, null);
const p = cached.nominal_properties.?[0];
try std.testing.expect(p.copy and p.send and p.share and p.island_safe and !p.linear and !p.endpoint and !p.forbidden);
try std.testing.expectEqual(@as(u7, 65), p.height);
}
test "deep Send Share transitions preserve ref and mutex modes" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} };
for ([_]bool{ false, true }) |outer_ref| {
const nodes = try a.alloc(Type, 65_536);
var t: Type = .region;
for (nodes, 0..) |*node, i| {
node.* = t;
t = if ((i % 2 == 1) == outer_ref) .{ .ref = node } else .{ .mutex = node };
}
try std.testing.expectEqual(outer_ref, try isSend(a, m, t));
try std.testing.expectEqual(outer_ref, try isShare(a, m, t));
}
}
test "height and source witness distance retain saturation boundaries" {
var scratch = std.heap.ArenaAllocator.init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const rows = try a.alloc(Type.Array, 66);
const properties = [_]air.NominalProperties{.{}};
const m: air.Module = .{ .name = "test", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{}, .nominal_properties = &properties };
var named: Type = .{ .named = 0 };
for (rows, 1..) |*row, edges| {
row.* = .{ .elem = named, .len = 1 };
named = .{ .array = row };
try std.testing.expectEqual(@as(u7, @intCast(@min(65, edges + 1))), height(m, named));
}
const u: Type = .{ .int = .u8 };
var forbidden: Type = .{ .ref = &u };
for (rows, 1..) |*row, edges| {
row.* = .{ .elem = forbidden, .len = 1 };
forbidden = .{ .array = row };
try std.testing.expectEqual(@as(u6, @intCast(@min(34, edges))), sourceForbiddenDepth(m, forbidden));
}
}