From 24a38760030875486abf4f8b6d78fec838fc1f7a Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 13:04:58 +0300 Subject: [PATCH] cli: inspect generic uses with an explicit worklist --- docs/design/air-type-depth-audit.md | 10 ++ docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 6 + src/frontend/generics.zig | 172 +++++++++++++++++++++++++-- 4 files changed, 183 insertions(+), 7 deletions(-) diff --git a/docs/design/air-type-depth-audit.md b/docs/design/air-type-depth-audit.md index ca5e2fc..babeab8 100644 --- a/docs/design/air-type-depth-audit.md +++ b/docs/design/air-type-depth-audit.md @@ -122,3 +122,13 @@ The source type parser now suspends array suffixes and argument lists in explici Unit tests inspect 32,768 mixed array/wrapper/applied-type levels with sibling arguments, 16,384 nested static function argument pairs and split-closer spans. Deep malformed input retains its leaf and wrapper-name failure positions. Failing each underlying parser arena allocation checks OutOfMemory and cleanup. All units, format checks and all 1,791 conformance cases pass, with exact corpus coverage. Hosted grammar and repair-advice suites pass 288 and 299 checks. Formatter integration passes 6,072 checks over 1,467 public files (1,412 parsed, 55 syntax errors and 782 identical AIR outputs). All 1,421 old/new source checks and 506 accepted lowerings are byte-identical; 156 additional constructor/argument/error probes retain exact outputs. The formerly failing array input now formats successfully, producing 82,019 bytes; a second formatting pass is byte-identical. Full checking reaches a separate confirmed failure in `generics.usesGenerics` (20,002 symbolized frames, exit -6), without `typeExpr` frames. A second deep input, invalid `mut slice<…>`, previously aborts while speculative repair-advice parsing recurses; it now returns one E7001 at the original primary position with the exact `slice_mut_type` candidate. Passing parsing/formatting or this diagnostic does not establish complete checking for arbitrary source depth. Q-059 remains open for source AST traversal and closing call-path work. No fresh Claude review was available. + +## Source generic-use detection + +The preceding 16,384-array source reproduces the `usesGenerics` failure again at cef944d (10,001 frames before the traceback limit, exit -6). The query now visits immutable AST storage through explicit work entries. Typed callbacks enqueue pointers to original struct fields, active union payloads, optional contents and slice/pointer children; no pointer to a copied temporary payload escapes. Reversed enqueue order retains the original depth-first field/element order. String bytes and scalar fields remain leaves. Temporary work storage is released on completion, early positive detection or allocation error. + +The original generic-use markers are unchanged: applied/static-function types, explicit expression specialization, enum/struct expressions with type arguments and constructor patterns with type arguments. Generic declarations still take their preceding specialization path; monomorphic input is not assigned a new depth limit. OutOfMemory propagates as a host error rather than false or a source diagnostic. Syntax, nominal identity, effects, verifier acceptance, ownership/runtime/fuel rules and bundles are unchanged. The private host query gains an allocator/error result; no AIR feature, public diagnostic or semantic flag is introduced. + +Unit tests compare 387 shallow type/expression/pattern/block/module queries against the independent pre-repair derivation, including empty arguments and optional fields. Positive and negative queries traverse 32,768 type, expression and nested-block levels. Every work-allocation request is failed in turn for both outcomes, checking error propagation and cleanup. All units and format checks pass; generic and static-function CLI integration passes 32 and 25 checks. All 1,791 conformance cases pass with exact corpus coverage. All 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr. + +The complete 4,096-array check still accepts before and after. The 16,384-array check now reaches a separate confirmed native-stack failure in lowering's resolveType (10,883 frames, exit -6), with no usesGenerics frames or diagnostic JSON. No timeout terminates these probes; only child core capture is disabled. This is progress through the pipeline, not full deep-source acceptance. Q-059's source lowering/remaining traversals and Phase 6 gates remain open. The earlier full per-step collection suite is still in progress. Claude's preceding property review does not cover this change. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 50ad79d..97c3c82 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -477,6 +477,8 @@ The [cache-free nominal property increment](air-type-depth-audit.md#cache-free-n The [source parser increment](air-type-depth-audit.md#source-type-syntax-parser) repairs a confirmed `typeExpr` failure at 16,384 source-array levels, preserving syntax, argument order, split-angle spans and existing shallow diagnostic envelopes. Deep speculative slice-advice parsing also returns its original E7001 instead of aborting. The same monomorphic file now formats but full checking reaches a confirmed recursive `usesGenerics` failure; that remaining source AST traversal keeps Q-059 open. The generic depth-64 guard is not silently extended to ordinary parsed annotations. +The [source generic-use increment](air-type-depth-audit.md#source-generic-use-detection) replaces the confirmed recursive AST scan with explicit borrowed work entries. Generic-use markers, field order and the specialization path are unchanged; independent shallow comparisons, deep positive/negative ASTs and failed-allocation cleanup cover the query. The repeated 16,384-array check now passes this stage and confirms the next native-stack failure in lower.resolveType. Source lowering/remaining traversals and the closing audit keep Q-059 open; no generic guard is imposed on monomorphic parsing. + ## 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 1b6a7f8..6a6ab71 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -454,3 +454,9 @@ A subsequent read-only Claude review against the property base 897f538 found no The [Q-059 source parser increment](../design/air-type-depth-audit.md#source-type-syntax-parser) replaces recursive type/argument parsing with explicit array and argument-list frames, preserving static function arguments, sibling order, split angle positions, syntax failures and slice repair candidates. Unit tests inspect deep mixed types and static arguments and fail parser metadata allocations. The old 16,384-array source crashes in parsing; the new parser allows formatting, while full checking confirms the next failure in `usesGenerics`. A deep invalid slice annotation now returns its original E7001 candidate instead of crashing. The existing generic guard is not imposed on monomorphic syntax. Units/format checks and all 1,791 conformance cases pass with exact corpus coverage. Hosted grammar/advice suites pass 288/299 checks; formatter integration passes 6,072 checks over 1,467 public files. All 1,421 source checks and 506 accepted lowerings preserve exact old/new outputs, as do 156 targeted syntax/argument/error probes; deep formatting is idempotent. No normative/bundle/feature/code change or new acceptance limit is introduced. Q-059's source AST/closing audit, Q-060's closing validation and Phase 6/contract gates remain open. No fresh Claude review was available. + +## Source generic-use detection (2026-10-10) + +The [Q-059 generic-use increment](../design/air-type-depth-audit.md#source-generic-use-detection) visits immutable AST fields/payloads through explicit work entries, retaining the original markers and field/element order. Metadata OOM propagates and pending entries are released; monomorphic syntax gains no new depth limit. Independent shallow comparisons (387), deep positive/negative types/expressions/blocks and work-allocation failure tests pass. The earlier failing source now passes usesGenerics and confirms the next failure in lower.resolveType at 16,384 array levels; complete checking at 4,096 still accepts. + +Units/format checks and generic/static-function CLI integration (32/25) pass. All 1,791 conformance cases pass with exact corpus coverage; all 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr. No normative/bundle/feature/code change or semantic flag is introduced. Q-059's source lowering/closing audit, Q-060's closing validation and Phase 6/contract gates remain open. Claude's property review does not cover this increment. diff --git a/src/frontend/generics.zig b/src/frontend/generics.zig index d4f184b..e7cc635 100644 --- a/src/frontend/generics.zig +++ b/src/frontend/generics.zig @@ -320,7 +320,7 @@ const Generator = struct { } generic = generic or f.generics.len != 0; } - if (!generic and !usesGenerics(ast.Module, g.m)) return g.m; + if (!generic and !try usesGenerics(g.arena, ast.Module, &g.m)) return g.m; var types: std.ArrayList(ast.TypeDecl) = .empty; var functions: std.ArrayList(ast.FnDecl) = .empty; for (g.m.types) |t| if (t.generics.len == 0) try types.append(g.arena, try g.walk(ast.TypeDecl, t, .{})); @@ -661,7 +661,72 @@ fn path(arena: A, e: ast.Expr) A.Error!?[]const u8 { }; } -fn usesGenerics(comptime T: type, value: T) bool { +// Each entry borrows immutable AST storage. Reflective children point into +// that storage, never into a copied union payload or a queue entry. +const GenericUseWork = struct { + pointer: *const anyopaque, + visit: *const fn (A, *std.ArrayList(GenericUseWork), *const anyopaque) A.Error!bool, +}; + +fn queueGenericUse(arena: A, queue: *std.ArrayList(GenericUseWork), comptime T: type, value: *const T) A.Error!void { + switch (@typeInfo(T)) { + .@"struct", .@"union", .optional => {}, + .pointer => |info| if (info.child == u8) return, + else => return, + } + try queue.append(arena, .{ .pointer = @ptrCast(value), .visit = GenericUseVisitor(T).visit }); +} + +fn GenericUseVisitor(comptime T: type) type { + return struct { + fn visit(arena: A, queue: *std.ArrayList(GenericUseWork), raw: *const anyopaque) A.Error!bool { + const value: *const T = @ptrCast(@alignCast(raw)); + if (T == ast.Type) if (value.kind == .applied or value.kind == .function_ref) return true; + if (T == ast.Expr) switch (value.kind) { + .specialize => return true, + .variant => |x| if (x.type_args.len != 0) return true, + .struct_lit => |x| if (x.type_args.len != 0) return true, + else => {}, + }; + if (T == ast.Pattern) if (value.kind == .ctor and value.kind.ctor.type_args.len != 0) return true; + switch (@typeInfo(T)) { + .@"struct" => |info| { + inline for (0..info.field_names.len) |offset| { + const i = info.field_names.len - 1 - offset; + try queueGenericUse(arena, queue, info.field_types[i], &@field(value.*, info.field_names[i])); + } + }, + .@"union" => switch (value.*) { + inline else => |*payload| try queueGenericUse(arena, queue, @TypeOf(payload.*), payload), + }, + .optional => |info| if (value.*) |*child| try queueGenericUse(arena, queue, info.child, child), + .pointer => |info| { + if (info.child == u8) return false; + if (info.size == .slice) { + var i = value.*.len; + while (i != 0) { + i -= 1; + try queueGenericUse(arena, queue, info.child, &value.*[i]); + } + } else try queueGenericUse(arena, queue, info.child, value.*); + }, + else => {}, + } + return false; + } + }; +} + +fn usesGenerics(arena: A, comptime T: type, value: *const T) A.Error!bool { + var queue: std.ArrayList(GenericUseWork) = .empty; + defer queue.deinit(arena); + try queueGenericUse(arena, &queue, T, value); + while (queue.pop()) |work| if (try work.visit(arena, &queue, work.pointer)) return true; + return false; +} + +// Independent pre-repair derivation for shallow, finite test ASTs. +fn referenceUsesGenerics(comptime T: type, value: T) bool { if (T == ast.Type) if (value.kind == .applied or value.kind == .function_ref) return true; if (T == ast.Expr) switch (value.kind) { .specialize => return true, @@ -672,17 +737,17 @@ fn usesGenerics(comptime T: type, value: T) bool { if (T == ast.Pattern) if (value.kind == .ctor and value.kind.ctor.type_args.len != 0) return true; switch (@typeInfo(T)) { .@"struct" => |info| { - inline for (info.field_names, info.field_types) |name, FT| if (usesGenerics(FT, @field(value, name))) return true; + inline for (info.field_names, info.field_types) |name, FT| if (referenceUsesGenerics(FT, @field(value, name))) return true; }, .@"union" => switch (value) { - inline else => |payload| return usesGenerics(@TypeOf(payload), payload), + inline else => |payload| return referenceUsesGenerics(@TypeOf(payload), payload), }, - .optional => |info| return if (value) |v| usesGenerics(info.child, v) else false, + .optional => |info| return if (value) |v| referenceUsesGenerics(info.child, v) else false, .pointer => |info| { if (info.child == u8) return false; if (info.size == .slice) { - for (value) |v| if (usesGenerics(info.child, v)) return true; - } else return usesGenerics(info.child, value.*); + for (value) |v| if (referenceUsesGenerics(info.child, v)) return true; + } else return referenceUsesGenerics(info.child, value.*); }, else => {}, } @@ -704,3 +769,96 @@ fn usedAir(instances: []const Instance, name: []const u8) bool { for (instances) |instance| if (std.mem.eql(u8, instance.air_name, name)) return true; return false; } + +test "generic use worklist matches the independent shallow AST derivation" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const span: ast.Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 }, .file = "Box", .namespace = "generic.name" }; + const byte: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } }; + const application: ast.Type = .{ .span = span, .kind = .{ .applied = .{ .name = "Box", .args = &.{byte} } } }; + const static_arg: ast.Type = .{ .span = span, .kind = .{ .function_ref = .{ .name = "operation" } } }; + const plain: ast.Expr = .{ .span = span, .kind = .{ .name = "value" } }; + const types = [_]ast.Type{ byte, application, static_arg }; + for (&types) |*ty| { + try std.testing.expectEqual(referenceUsesGenerics(ast.Type, ty.*), try usesGenerics(a, ast.Type, ty)); + for (0..8) |mode| { + const argument_types: []const ast.Type = if (mode % 2 == 0) &.{} else &.{ty.*}; + const expressions = [_]ast.Expr{ + .{ .span = span, .kind = .{ .variant = .{ .@"enum" = "E", .name = "A", .type_args = argument_types } } }, + .{ .span = span, .kind = .{ .struct_lit = .{ .name = "S", .fields = &.{.{ .name = "x", .span = span, .e = plain }}, .type_args = argument_types } } }, + .{ .span = span, .kind = .{ .cast = .{ .mode = .widen, .e = &plain, .ty = ty.* } } }, + .{ .span = span, .kind = .{ .call = .{ .callee = &plain, .type_arg = if (mode % 3 == 0) null else ty.*, .args = &.{plain} } } }, + .{ .span = span, .kind = .{ .specialize = .{ .base = &plain, .args = argument_types } } }, + }; + const pattern: ast.Pattern = .{ .span = span, .kind = .{ .ctor = .{ .qualifier = null, .name = "ok", .binds = &.{"x"}, .type_args = argument_types } } }; + try std.testing.expectEqual(referenceUsesGenerics(ast.Pattern, pattern), try usesGenerics(a, ast.Pattern, &pattern)); + for (&expressions) |*expression| { + try std.testing.expectEqual(referenceUsesGenerics(ast.Expr, expression.*), try usesGenerics(a, ast.Expr, expression)); + const arm: ast.Arm = .{ .pattern = pattern, .body = expression.* }; + const match: ast.Match = .{ .span = span, .scrutinee = plain, .arms = &.{arm}, .kind = .outcome }; + const matched: ast.Expr = .{ .span = span, .kind = .{ .match_expr = &match } }; + const statements = [_]ast.Stmt{ .{ .span = span, .kind = .{ .@"var" = .{ .name = "v", .ty = ty.*, .init = expression.* } } }, .{ .span = span, .kind = .{ .expr = matched } } }; + const block: ast.Block = .{ .span = span, .stmts = &statements, .tail = if (mode % 4 == 0) null else expression }; + const module: ast.Module = .{ .name = "m", .types = &.{.{ .name = "S", .span = span, .kind = .{ .@"enum" = &.{.{ .name = "A", .span = span, .payload = &.{ty.*} }} } }}, .functions = &.{.{ .name = "f", .span = span, .params = &.{.{ .name = "p", .span = span, .ty = byte }}, .ret = byte, .from = null, .effects = &.{}, .trusted = null, .body = block }} }; + try std.testing.expectEqual(referenceUsesGenerics(ast.Block, block), try usesGenerics(a, ast.Block, &block)); + try std.testing.expectEqual(referenceUsesGenerics(ast.Module, module), try usesGenerics(a, ast.Module, &module)); + } + } + } +} + +test "generic use detection visits deep types expressions and statement blocks iteratively" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const span: ast.Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } }; + const types = try a.alloc(ast.Type, 32_769); + for (types[0 .. types.len - 1], 0..) |*t, i| t.* = .{ .span = span, .kind = if (i % 2 == 0) .{ .array = .{ .elem = &types[i + 1], .len = 1 } } else .{ .wrapped = .{ .wrapper = "ref", .inner = &types[i + 1] } } }; + types[types.len - 1] = .{ .span = span, .kind = .{ .name = "u8" } }; + try std.testing.expect(!try usesGenerics(a, ast.Type, &types[0])); + types[types.len - 1].kind = .{ .applied = .{ .name = "Box", .args = &.{} } }; + try std.testing.expect(try usesGenerics(a, ast.Type, &types[0])); + const expressions = try a.alloc(ast.Expr, 32_769); + for (expressions[0 .. expressions.len - 1], 0..) |*e, i| e.* = .{ .span = span, .kind = .{ .field = .{ .name = "x", .e = &expressions[i + 1] } } }; + expressions[expressions.len - 1] = .{ .span = span, .kind = .{ .name = "value" } }; + try std.testing.expect(!try usesGenerics(a, ast.Expr, &expressions[0])); + expressions[expressions.len - 1].kind = .{ .variant = .{ .@"enum" = "E", .name = "A", .type_args = types[types.len - 1 ..] } }; + try std.testing.expect(try usesGenerics(a, ast.Expr, &expressions[0])); + const blocks = try a.alloc(ast.Block, 32_769); + const statements = try a.alloc(ast.Stmt, blocks.len - 1); + blocks[blocks.len - 1] = .{ .span = span, .stmts = &.{}, .tail = null }; + var i = statements.len; + while (i != 0) { + i -= 1; + statements[i] = .{ .span = span, .kind = .{ .loop = blocks[i + 1] } }; + blocks[i] = .{ .span = span, .stmts = statements[i .. i + 1], .tail = null }; + } + try std.testing.expect(!try usesGenerics(a, ast.Block, &blocks[0])); + blocks[0].tail = &expressions[0]; + try std.testing.expect(try usesGenerics(a, ast.Block, &blocks[0])); +} + +test "generic use work metadata errors propagate and temporary entries are released" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const span: ast.Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } }; + const fields = try a.alloc(ast.Field, 256); + for (fields) |*f| f.* = .{ .span = span, .name = "x", .ty = .{ .span = span, .kind = .{ .name = "u8" } } }; + var declaration: ast.TypeDecl = .{ .span = span, .name = "S", .kind = .{ .@"struct" = fields } }; + for ([_]bool{ false, true }) |generic| { + if (generic) fields[fields.len - 1].ty.kind = .{ .function_ref = .{ .name = "operation" } }; + 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 = usesGenerics(failing.allocator(), ast.TypeDecl, &declaration); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else try std.testing.expectEqual(generic, try result); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } + } +}