From 4aad95c4a89db16fd2e8b360048353eac8909d72 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 14:18:14 +0300 Subject: [PATCH] cli: evaluate source nominal properties with continuations --- docs/design/air-type-depth-audit.md | 8 + docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 6 + src/frontend/type_properties.zig | 436 +++++++++++++++++++++++---- 4 files changed, 390 insertions(+), 62 deletions(-) diff --git a/docs/design/air-type-depth-audit.md b/docs/design/air-type-depth-audit.md index bc52229..4703508 100644 --- a/docs/design/air-type-depth-audit.md +++ b/docs/design/air-type-depth-audit.md @@ -148,3 +148,11 @@ At b23f3e6, the ordinary 16,384-array source aborts in type_properties.firstInva Tests compare 2,160 shallow cases against the independent pre-repair anonymous traversal, including nominal/generic content, cycles with a positive witness, unknown parameters, parameter shadowing, nested own_array and graph stops; the nominal declaration algorithm is shared, not an independent nominal oracle. Deep array/mixed-wrapper queries cover 32,768 levels, positive/negative content and original failure spans, while an allocator failing at its first request verifies zero work allocations on these anonymous paths. Existing diamond/cycle tests, all units and format checks pass. Copy-content/generic CLI integration passes 119/32 checks; all 1,421 public source checks and 506 accepted lowerings retain exact old/new exit/stdout/stderr. All 1,791 conformance cases pass with exact corpus coverage. Both previously aborting complete 16,384-level checks now accept without output, as does the 4,096-array input. Non-Copy content behind the deep own_array returns exactly one E7005 at 2:19, with constraint Copy and type_constructor own_array. Core capture alone is disabled and no timeout ends a probe. These process outcomes establish repairs for these inputs, not arbitrary-depth source acceptance. A separate 8,192-declaration source probe confirms remaining native recursion through named source types: before this repair, 3,326 linear and 3,325 declaration frames; afterward, 3,306 and 3,305, both exit -6 without diagnostic JSON. Source Ty equality/text/AIR conversion and other closing call paths also remain to audit. Q-059 and Phase 6 gates remain open; Q-060's full per-step validation remains separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule or acceptance limit changes. No fresh Claude review is claimed. + +## Source nominal property continuations + +The independently reproduced 8,192-declaration linear/declaration failure is repaired by an explicit query/argument/member continuation machine. Static arguments finish in their parent environment/path before cache and cycle checks. Struct fields and enum payloads retain source order and positive short-circuiting. Cycle state remains the declaration name plus known-linear parameter flags; indexed path entries survive work-list growth. Negative entries retain the generation captured before argument evaluation, while positive completions invalidate provisional negatives in the original order. Memo keys remain in caller-arena storage across retries; temporary frame/path buffers are released on success, early result or OOM. Metadata allocation errors propagate, never become false or a diagnostic. Anonymous terminal paths still allocate no work storage. + +The old recursive nominal declaration algorithm is now copied into the shallow oracle as well, removing the shared-nominal limitation of the preceding tests. Tests compare 4,613 roots over 128 generated six-declaration graphs and targeted nested-argument/parameter states, each queried three times with retained caches: results, lookup counts, complete entry order/keys/values/generations and final generation all agree. The existing 2,160 shallow syntax comparisons now use this independent nominal derivation too. Three 16,384-declaration mixed struct/enum queries cover negative content, positive leaves and a deep cyclic back-edge with a later positive witness. Six argument/cycle/result shapes fail every underlying arena allocation request in turn, checking OOM and full arena cleanup. Units/format checks, nominal/Copy-content/static-function CLI integration (110/119/25) and all 1,791 conformance cases pass with exact corpus coverage; all 1,421 source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. + +The complete formerly failing Copy chain accepts with no output. Replacing its final field with own returns exactly one E7005 at 8194:19, with constraint Copy and type_constructor own_array. No timeout ends these probes; only child core capture is disabled. A separate 65,536-array invalid-atomic source now confirms source typeText native-stack exhaustion (10,001 frames, exit -6, no JSON), before any diagnostic is emitted. Source Ty equality/text/AIR conversion and closing query paths keep Q-059 open; Q-060 validation and Phase 6/contract gates remain separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule, generic traversal guard or accepted-depth limit changes. No fresh Claude review is claimed. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 71f6b9a..ccfeaf1 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -483,6 +483,8 @@ The [source annotation resolution increment](air-type-depth-audit.md#source-anno The [source anonymous property increment](air-type-depth-audit.md#source-anonymous-property-scans) removes confirmed recursion from firstInvalid and the array-chain portion of known linearity. Both 16,384-array and own_array checks now accept, while non-Copy content retains E7005 at its original span. A separate 8,192-declaration probe confirms remaining linear/declaration native-stack exhaustion before and after this increment. Named-declaration repair and source Ty/query closing checks remain open; no acceptance limit or semantic rule changes. +The [source nominal property increment](air-type-depth-audit.md#source-nominal-property-continuations) repairs the confirmed linear/declaration failure with explicit argument/member continuations, retaining cache generations and known-parameter cycle states. An independent recursive nominal oracle checks ordered cache records; complete checking accepts the 8,192-Copy chain and rejects linear content with E7005. A separate 65,536-array invalid-atomic source confirms typeText native-stack exhaustion. Source Ty text/equality/AIR conversion and closing call-path work keep Q-059 open; no semantic limit or rule changes. + ## Q-060 — Native recursion while materializing runtime values The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. At that baseline, recursive copying, value sizing, collection and serialization were additional audit candidates with unverified failure paths; the increment below records subsequent executed failures. Compiler type repairs in Q-059 do not resolve Q-060. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index a375af1..7e1d07c 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -472,3 +472,9 @@ The complete 4,096-array check still accepts; 16,384 now reaches the next confir The [Q-059 source-property increment](../design/air-type-depth-audit.md#source-anonymous-property-scans) makes syntax scanning and anonymous-array linearity iterative, retaining own_array priority, graph stops and nominal fixed points. The two complete 16,384-level source checks that previously aborted now accept; deep non-Copy content returns the original E7005. Tests cover 2,160 independent shallow anonymous comparisons, 32,768-level queries and zero work allocations on anonymous paths. Units/format checks, Copy-content/generic CLI integration (119/32) and byte-identical old/new checks/lowerings (1,421/506) pass; all 1,791 conformance cases pass with exact corpus coverage. A separate 8,192-declaration source confirms the remaining linear/declaration stack failure before and after this increment. Named-source repair, source Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed. + +## Source nominal property continuations (2026-10-10) + +The [Q-059 nominal-source increment](../design/air-type-depth-audit.md#source-nominal-property-continuations) replaces native argument/declaration recursion with explicit continuations, retaining environment/path binding, ordered fields/payloads and cache generation rules. The previously crashing 8,192-Copy declaration check accepts; linear content returns E7005. Independent ordered-cache comparisons cover 4,613 roots (three queries each), while deep mixed/cyclic graphs and allocation-failure cleanup pass. + +Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact coverage and byte-identical old/new checks/lowerings (1,421/506) pass. A separate invalid-atomic source confirms typeText stack failure at 65,536 array levels. Source Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed. diff --git a/src/frontend/type_properties.zig b/src/frontend/type_properties.zig index 4c74f81..9c1b0de 100644 --- a/src/frontend/type_properties.zig +++ b/src/frontend/type_properties.zig @@ -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, ¤t, 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 = ¶ms, .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 } + \\struct Loop { next: Loop, value: T } + \\struct Ignore { 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 = ¶ms, .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 { value: T } + \\struct Cycle { next: Cycle, value: T } + \\struct Negative { 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; + } + } + } +}