cli: evaluate source nominal properties with continuations

This commit is contained in:
dev committed 2026-10-10 14:18:14 +03:00
1 parent 53907ecf25
commit 4aad95c4a8
4 files changed
+390 -62

No files matched your search

+374 -62
View File
@@ -7,8 +7,7 @@ const Env = struct {
params: []const ast.TypeParam,
known_linear: []const bool = &.{},
};
// Parameter states, rather than argument syntax, distinguish rotations along
// recursive generic edges. Repeated states add no new known linear leaf.
// Pointer paths are used only by the independent shallow test oracle.
const Path = struct { name: []const u8, known_linear: []const bool, parent: ?*const Path };
const Memo = struct {
entries: std.ArrayList(struct { name: []const u8, known_linear: []const bool, value: bool, generation: usize }) = .empty,
@@ -23,7 +22,7 @@ pub fn firstInvalid(annotation: ast.Type, context: anytype, lookup: anytype, par
var memo: Memo = .{};
while (true) {
const generation = memo.generation;
if (try linear(w.inner.*, context, lookup, &.{ .params = params }, null, &memo)) return w.inner.*;
if (try linear(w.inner.*, context, lookup, &.{ .params = params }, &memo)) return w.inner.*;
if (generation == memo.generation) break;
}
}
@@ -36,64 +35,154 @@ pub fn firstInvalid(annotation: ast.Type, context: anytype, lookup: anytype, par
};
}
fn linear(annotation: ast.Type, context: anytype, lookup: anytype, env: *const Env, path: ?*const Path, memo: *Memo) std.mem.Allocator.Error!bool {
var t = annotation;
// Arrays add no environment or nominal path state. Peel only this
// anonymous chain; declaration fixed points retain their original rules.
while (t.kind == .array) t = t.kind.array.elem.*;
switch (t.kind) {
.file => return true,
.wrapped => |w| {
for ([_][]const u8{ "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "atomic" }) |tag| if (std.mem.eql(u8, w.wrapper, tag)) return true;
return false;
},
.array => unreachable,
.name => |name| {
for (env.params, 0..) |p, i| if (std.mem.eql(u8, p.name, name)) {
return i < env.known_linear.len and env.known_linear[i];
};
if (lookup(context, name, t.span)) |d| return declaration(d, &.{}, context, lookup, env, path, memo);
for ([_][]const u8{ "region", "stream", "listener" }) |tag| if (std.mem.eql(u8, name, tag)) return true;
return false;
},
.applied => |a| {
const d = lookup(context, a.name, t.span) orelse return false;
return declaration(d, a.args, context, lookup, env, path, memo);
},
else => return false,
}
}
// Array/payload edges and static argument queries run as continuations.
// Path indices stay valid when either work list grows; memo keys retain their
// caller-arena storage across firstInvalid's fixed-point retries.
const LinearPath = struct { name: []const u8, known_linear: []const bool, parent: ?usize };
const LinearQuery = struct { ty: ast.Type, env: Env, path: ?usize };
const LinearFrame = struct {
declaration: ast.TypeDecl,
args: []const ast.Type,
parent_env: Env,
parent_path: ?usize,
generation: usize,
known: []bool,
phase: enum { arguments, members } = .arguments,
argument: usize = 0,
member: usize = 0,
variant: usize = 0,
path: ?usize = null,
};
fn declaration(d: ast.TypeDecl, args: []const ast.Type, context: anytype, lookup: anytype, env: *const Env, path: ?*const Path, memo: *Memo) std.mem.Allocator.Error!bool {
const generation = memo.generation;
const known = try context.arena.alloc(bool, d.generics.len);
for (known, 0..) |*flag, i| flag.* = i < args.len and try linear(args[i], context, lookup, env, path, memo);
for (memo.entries.items) |entry| if ((entry.value or entry.generation == memo.generation) and std.mem.eql(u8, entry.name, d.name) and std.mem.eql(bool, entry.known_linear, known)) return entry.value;
var previous = path;
while (previous) |p| : (previous = p.parent) {
if (std.mem.eql(u8, p.name, d.name) and std.mem.eql(bool, p.known_linear, known)) {
return false;
}
}
const next: Path = .{ .name = d.name, .known_linear = known, .parent = path };
const bound: Env = .{ .params = d.generics, .known_linear = known };
const value = switch (d.kind) {
.@"struct" => |fs| for (fs) |f| {
if (try linear(f.ty, context, lookup, &bound, &next, memo)) break true;
} else false,
.@"enum" => |vs| result: {
for (vs) |v| for (v.payload) |t| {
if (try linear(t, context, lookup, &bound, &next, memo)) break :result true;
fn linear(annotation: ast.Type, context: anytype, lookup: anytype, env: *const Env, memo: *Memo) std.mem.Allocator.Error!bool {
const arena = context.arena;
var frames: std.ArrayList(LinearFrame) = .empty;
defer frames.deinit(arena);
var paths: std.ArrayList(LinearPath) = .empty;
defer paths.deinit(arena);
var current: ?LinearQuery = .{ .ty = annotation, .env = env.*, .path = null };
var value = false;
while (true) {
if (current) |query| {
current = null;
var t = query.ty;
while (t.kind == .array) t = t.kind.array.elem.*;
var args: []const ast.Type = &.{};
const d = switch (t.kind) {
.file => {
value = true;
continue;
},
.wrapped => |w| {
value = false;
for ([_][]const u8{ "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "atomic" }) |tag| if (std.mem.eql(u8, w.wrapper, tag)) {
value = true;
break;
};
continue;
},
.array => unreachable,
.name => |name| name: {
for (query.env.params, 0..) |p, i| if (std.mem.eql(u8, p.name, name)) {
value = i < query.env.known_linear.len and query.env.known_linear[i];
break :name null;
};
if (lookup(context, name, t.span)) |decl| break :name decl;
value = false;
for ([_][]const u8{ "region", "stream", "listener" }) |tag| if (std.mem.eql(u8, name, tag)) {
value = true;
break;
};
break :name null;
},
.applied => |a| applied: {
args = a.args;
break :applied lookup(context, a.name, t.span);
},
else => {
value = false;
continue;
},
} orelse {
if (t.kind == .applied) value = false;
continue;
};
break :result false;
},
};
// Positive witnesses are final. Learning one invalidates provisional
// negatives, including cycles whose back edge could reach that witness.
// A negative root is queried again until no new positive proof is learned.
if (value) memo.generation += 1;
try memo.entries.append(context.arena, .{ .name = d.name, .known_linear = known, .value = value, .generation = if (value) memo.generation else generation });
return value;
const generation = memo.generation;
const known = try arena.alloc(bool, d.generics.len);
@memset(known, false);
try frames.append(arena, .{ .declaration = d, .args = args, .parent_env = query.env, .parent_path = query.path, .generation = generation, .known = known });
continue;
}
if (frames.items.len == 0) return value;
const f = &frames.items[frames.items.len - 1];
if (f.phase == .arguments) {
if (f.argument != 0) f.known[f.argument - 1] = value;
if (f.argument < f.known.len) {
const i = f.argument;
f.argument += 1;
if (i < f.args.len) {
current = .{ .ty = f.args[i], .env = f.parent_env, .path = f.parent_path };
} else value = false;
continue;
}
var cached: ?bool = null;
for (memo.entries.items) |entry| if ((entry.value or entry.generation == memo.generation) and std.mem.eql(u8, entry.name, f.declaration.name) and std.mem.eql(bool, entry.known_linear, f.known)) {
cached = entry.value;
break;
};
var previous = f.parent_path;
while (cached == null) {
const index = previous orelse break;
const p = paths.items[index];
if (std.mem.eql(u8, p.name, f.declaration.name) and std.mem.eql(bool, p.known_linear, f.known)) {
cached = false;
break;
}
previous = p.parent;
}
if (cached) |result| {
value = result;
_ = frames.pop();
continue;
}
f.path = paths.items.len;
try paths.append(arena, .{ .name = f.declaration.name, .known_linear = f.known, .parent = f.parent_path });
f.phase = .members;
value = false;
}
if (!value) {
const next: ?ast.Type = switch (f.declaration.kind) {
.@"struct" => |fields| member: {
if (f.member == fields.len) break :member null;
const t = fields[f.member].ty;
f.member += 1;
break :member t;
},
.@"enum" => |variants| member: {
while (f.variant < variants.len) {
const payload = variants[f.variant].payload;
if (f.member < payload.len) {
const t = payload[f.member];
f.member += 1;
break :member t;
}
f.variant += 1;
f.member = 0;
}
break :member null;
},
};
if (next) |t| {
current = .{ .ty = t, .env = .{ .params = f.declaration.generics, .known_linear = f.known }, .path = f.path };
continue;
}
}
// Capture the generation before argument evaluation for negatives,
// and retain the original positive-witness invalidation order.
if (value) memo.generation += 1;
try memo.entries.append(arena, .{ .name = f.declaration.name, .known_linear = f.known, .value = value, .generation = if (value) memo.generation else f.generation });
_ = frames.pop();
}
}
test "Copy-content query shares completed diamond branches" {
@@ -154,7 +243,7 @@ test "Copy-content query shares cyclic diamond branches" {
try std.testing.expect(probe.lookups <= 22);
}
// Independent pre-repair anonymous traversal, used only on shallow trees.
// Independent pre-repair syntax and nominal derivation, used only on shallow trees.
const ReferenceAnonymousProperties = struct {
fn firstInvalid(t: ast.Type, context: anytype, lookup: anytype, params: []const ast.TypeParam) std.mem.Allocator.Error!?ast.Type {
switch (t.kind) {
@@ -187,17 +276,48 @@ const ReferenceAnonymousProperties = struct {
for (env.params, 0..) |p, i| if (std.mem.eql(u8, p.name, name)) {
return i < env.known_linear.len and env.known_linear[i];
};
if (lookup(context, name, t.span)) |d| return declaration(d, &.{}, context, lookup, env, path, memo);
if (lookup(context, name, t.span)) |d| return ReferenceAnonymousProperties.declaration(d, &.{}, context, lookup, env, path, memo);
for ([_][]const u8{ "region", "stream", "listener" }) |tag| if (std.mem.eql(u8, name, tag)) return true;
return false;
},
.applied => |a| {
const d = lookup(context, a.name, t.span) orelse return false;
return declaration(d, a.args, context, lookup, env, path, memo);
return ReferenceAnonymousProperties.declaration(d, a.args, context, lookup, env, path, memo);
},
else => return false,
}
}
fn declaration(d: ast.TypeDecl, args: []const ast.Type, context: anytype, lookup: anytype, env: *const Env, path: ?*const Path, memo: *Memo) std.mem.Allocator.Error!bool {
const generation = memo.generation;
const known = try context.arena.alloc(bool, d.generics.len);
for (known, 0..) |*flag, i| flag.* = i < args.len and try ReferenceAnonymousProperties.linear(args[i], context, lookup, env, path, memo);
for (memo.entries.items) |entry| if ((entry.value or entry.generation == memo.generation) and std.mem.eql(u8, entry.name, d.name) and std.mem.eql(bool, entry.known_linear, known)) return entry.value;
var previous = path;
while (previous) |p| : (previous = p.parent) {
if (std.mem.eql(u8, p.name, d.name) and std.mem.eql(bool, p.known_linear, known)) {
return false;
}
}
const next: Path = .{ .name = d.name, .known_linear = known, .parent = path };
const bound: Env = .{ .params = d.generics, .known_linear = known };
const value = switch (d.kind) {
.@"struct" => |fs| for (fs) |f| {
if (try ReferenceAnonymousProperties.linear(f.ty, context, lookup, &bound, &next, memo)) break true;
} else false,
.@"enum" => |vs| result: {
for (vs) |v| for (v.payload) |t| {
if (try ReferenceAnonymousProperties.linear(t, context, lookup, &bound, &next, memo)) break :result true;
};
break :result false;
},
};
// Positive witnesses are final. Learning one invalidates provisional
// negatives, including cycles whose back edge could reach that witness.
// A negative root is queried again until no new positive proof is learned.
if (value) memo.generation += 1;
try memo.entries.append(context.arena, .{ .name = d.name, .known_linear = known, .value = value, .generation = if (value) memo.generation else generation });
return value;
}
};
const PropertyProbe = struct {
@@ -319,3 +439,195 @@ test "anonymous source properties traverse deep types without work allocations"
try std.testing.expect(!failing.has_induced_failure);
try std.testing.expectEqual(@as(usize, 0), failing.allocations);
}
fn expectNominalPropertyMatch(arena: std.mem.Allocator, m: ast.Module, t: ast.Type, env: Env) !void {
var original: PropertyProbe = .{ .arena = arena, .module = m };
var current: PropertyProbe = .{ .arena = arena, .module = m };
var before: Memo = .{};
var after: Memo = .{};
// Keep caches between roots/retries so stale negatives and final positive
// witnesses are compared as well as the first traversal.
for (0..3) |_| {
try std.testing.expectEqual(
try ReferenceAnonymousProperties.linear(t, &original, PropertyProbe.lookup, &env, null, &before),
try linear(t, &current, PropertyProbe.lookup, &env, &after),
);
try std.testing.expectEqual(original.lookups, current.lookups);
try std.testing.expectEqual(before.generation, after.generation);
try std.testing.expectEqualDeep(before.entries.items, after.entries.items);
}
}
test "source nominal continuations match recursive cache generations and argument states" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const span: ast.Span = .{ .start = .{ .line = 3, .col = 5 }, .end = .{ .line = 3, .col = 9 } };
const scalar: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const owner: ast.Type = .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = "own", .inner = &scalar } } };
const t: ast.Type = .{ .span = span, .kind = .{ .name = "T" } };
const u: ast.Type = .{ .span = span, .kind = .{ .name = "U" } };
const params = [_]ast.TypeParam{
.{ .name = "T", .span = span, .constraints = &.{} },
.{ .name = "U", .span = span, .constraints = &.{} },
};
var state: u32 = 0x57b27ac3;
var comparisons: usize = 0;
for (0..128) |graph| {
const decls = try a.alloc(ast.TypeDecl, 6);
const names = try a.alloc([]const u8, decls.len);
for (names, 0..) |*name, i| name.* = try std.fmt.allocPrint(a, "N{d}", .{i});
for (decls, 0..) |*d, i| {
const fields = try a.alloc(ast.Field, 4);
for (fields, 0..) |*f, j| {
state = state *% 1664525 +% 1013904223;
const args = try a.dupe(ast.Type, if (state & 1 == 0) &.{ t, u } else &.{ u, t });
const edge = try a.create(ast.Type);
edge.* = .{ .span = span, .kind = .{ .applied = .{ .name = names[(state >> 8) % names.len], .args = args } } };
const ty: ast.Type = switch ((state >> 16) % 8) {
0 => t,
1 => u,
2 => scalar,
3 => if (graph % 3 == 0) scalar else owner,
4 => edge.*,
5 => .{ .span = span, .kind = .{ .array = .{ .elem = edge, .len = 3 } } },
6 => .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = "iref", .inner = &owner } } },
else => .{ .span = span, .kind = .{ .name = "missing" } },
};
f.* = .{ .span = span, .name = try std.fmt.allocPrint(a, "f{d}", .{j}), .ty = ty };
}
d.* = .{ .name = names[i], .span = span, .generics = &params, .kind = if (i % 2 == 0) .{ .@"struct" = fields } else enum_kind: {
const variants = try a.alloc(ast.Variant, 3);
variants[0] = .{ .span = span, .name = "empty", .payload = &.{} };
variants[1] = .{ .span = span, .name = "first", .payload = try a.dupe(ast.Type, &.{ fields[0].ty, fields[1].ty }) };
variants[2] = .{ .span = span, .name = "last", .payload = try a.dupe(ast.Type, &.{ fields[2].ty, fields[3].ty }) };
break :enum_kind .{ .@"enum" = variants };
} };
}
const m: ast.Module = .{ .name = "properties", .types = decls, .functions = &.{} };
for (decls) |d| for ([_][]const ast.Type{ &.{ scalar, scalar }, &.{ owner, scalar }, &.{ scalar, owner }, &.{ owner, owner }, &.{}, &.{owner} }) |args| {
const root: ast.Type = .{ .span = span, .kind = .{ .applied = .{ .name = d.name, .args = args } } };
try expectNominalPropertyMatch(a, m, root, .{ .params = &.{} });
comparisons += 1;
};
}
// Nested static-argument resolution must finish before a parent tests its
// memo/path state; a positive argument can invalidate a cached negative.
const source =
\\module argument_order
\\struct Plain { x: u8 }
\\struct Linear { x: own<u8> }
\\struct Loop<T, U> { next: Loop<U, T>, value: T }
\\struct Ignore<T, U> { value: u8 }
\\fn main() -> void effects [] {}
;
const m = (try @import("parse.zig").parse(a, source)).ok;
const nested: ast.Type = .{ .span = span, .kind = .{ .applied = .{ .name = "Loop", .args = &.{ .{ .span = span, .kind = .{ .name = "Plain" } }, .{ .span = span, .kind = .{ .name = "Linear" } } } } } };
const root: ast.Type = .{ .span = span, .kind = .{ .applied = .{ .name = "Ignore", .args = &.{ nested, nested } } } };
try expectNominalPropertyMatch(a, m, root, .{ .params = &.{} });
comparisons += 1;
for ([_][]const bool{ &.{}, &.{false}, &.{ true, false }, &.{ false, true } }) |known| {
try expectNominalPropertyMatch(a, m, .{ .span = span, .kind = .{ .applied = .{ .name = "Loop", .args = &.{ t, u } } } }, .{ .params = &params, .known_linear = known });
comparisons += 1;
}
try std.testing.expectEqual(@as(usize, 4613), comparisons);
}
const IndexedPropertyProbe = struct {
arena: std.mem.Allocator,
declarations: []const ast.TypeDecl,
lookups: usize = 0,
fn lookup(p: *@This(), name: []const u8, _: ast.Span) ?ast.TypeDecl {
p.lookups += 1;
if (name.len < 2 or name[0] != 'N') return null;
const i = std.fmt.parseInt(usize, name[1..], 10) catch return null;
return if (i < p.declarations.len) p.declarations[i] else null;
}
};
test "source nominal continuations traverse deep mixed declarations and cyclic witnesses" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const span: ast.Span = .{ .start = .{ .line = 2, .col = 3 }, .end = .{ .line = 2, .col = 9 } };
const scalar: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const count = 16_384;
const decls = try a.alloc(ast.TypeDecl, count);
const fields = try a.alloc(ast.Field, count * 2);
const variants = try a.alloc(ast.Variant, count * 3);
const payloads = try a.alloc(ast.Type, count * 2);
for (decls, 0..) |*d, i| {
const next: ast.Type = if (i + 1 == count) scalar else .{ .span = span, .kind = .{ .name = try std.fmt.allocPrint(a, "N{d}", .{i + 1}) } };
fields[i * 2] = .{ .span = span, .name = "next", .ty = next };
fields[i * 2 + 1] = .{ .span = span, .name = "tail", .ty = scalar };
payloads[i * 2] = next;
payloads[i * 2 + 1] = scalar;
variants[i * 3] = .{ .span = span, .name = "empty", .payload = &.{} };
variants[i * 3 + 1] = .{ .span = span, .name = "next", .payload = payloads[i * 2 ..][0..1] };
variants[i * 3 + 2] = .{ .span = span, .name = "tail", .payload = payloads[i * 2 + 1 ..][0..1] };
d.* = .{ .span = span, .name = try std.fmt.allocPrint(a, "N{d}", .{i}), .kind = if (i % 2 == 0) .{ .@"struct" = fields[i * 2 ..][0..2] } else .{ .@"enum" = variants[i * 3 ..][0..3] } };
}
const root: ast.Type = .{ .span = span, .kind = .{ .name = "N0" } };
for (0..3) |mode| {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
var probe: IndexedPropertyProbe = .{ .arena = arena.allocator(), .declarations = decls };
var memo: Memo = .{};
const leaf: ast.Type = switch (mode) {
0 => scalar,
1 => .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = "own", .inner = &scalar } } },
else => root,
};
payloads[(count - 1) * 2] = leaf;
if (mode == 2) payloads[(count - 1) * 2 + 1] = .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = "own", .inner = &scalar } } };
try std.testing.expectEqual(mode != 0, try linear(root, &probe, IndexedPropertyProbe.lookup, &.{ .params = &.{} }, &memo));
try std.testing.expectEqual(@as(usize, count), memo.entries.items.len);
try std.testing.expectEqual(@as(usize, if (mode == 0) 0 else count), memo.generation);
try std.testing.expectEqual(@as(usize, if (mode == 0) count * 2 + 1 else if (mode == 1) count else count + 1), probe.lookups);
}
}
test "source nominal work metadata OOM propagates with arena cleanup" {
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer scratch.deinit();
const a = scratch.allocator();
const source =
\\module allocation
\\struct Wrap<T> { value: T }
\\struct Cycle<T, U> { next: Cycle<U, T>, value: T }
\\struct Negative<T> { value: u8 }
\\fn main() -> void effects [] {}
;
const m = (try @import("parse.zig").parse(a, source)).ok;
const span: ast.Span = .{ .start = .{ .line = 8, .col = 2 }, .end = .{ .line = 8, .col = 9 } };
const scalar: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
const owner: ast.Type = .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = "own", .inner = &scalar } } };
for ([_]bool{ false, true }) |positive| {
var nested: ast.Type = if (positive) owner else scalar;
for (0..64) |_| {
const args = try a.dupe(ast.Type, &.{nested});
nested = .{ .span = span, .kind = .{ .applied = .{ .name = "Wrap", .args = args } } };
}
const ignored: ast.Type = .{ .span = span, .kind = .{ .applied = .{ .name = "Negative", .args = &.{nested} } } };
for ([_]ast.Type{ nested, ignored, .{ .span = span, .kind = .{ .applied = .{ .name = "Cycle", .args = &.{ nested, scalar } } } } }) |root| {
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 });
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
var probe: PropertyProbe = .{ .arena = arena.allocator(), .module = m };
const owned: ast.Type = .{ .span = span, .kind = .{ .wrapped = .{ .wrapper = "own_array", .inner = &root } } };
const result = firstInvalid(owned, &probe, PropertyProbe.lookup, &.{});
if (failing.has_induced_failure) {
try std.testing.expectError(error.OutOfMemory, result);
} else {
try std.testing.expectEqual(positive and root.kind.applied.name[0] != 'N', (try result) != null);
}
arena.deinit();
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
if (!failing.has_induced_failure) break;
}
}
}
}