From 371329f3f0355198b47ec3fe04b0130e5e67d701 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 19:23:50 +0300 Subject: [PATCH] cli: parse qualified constructor paths iteratively --- docs/design/open-questions.md | 2 + docs/design/source-expression-depth-audit.md | 48 +++++- docs/plan/phase-6-source-language.md | 17 +++ src/frontend/parse.zig | 152 ++++++++++++++++++- tests/hosted/source_expression_depth.py | 20 +++ 5 files changed, 227 insertions(+), 12 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 99aa7ec..b0e327c 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -537,4 +537,6 @@ The [external review and host-OOM follow-up](source-expression-depth-audit.md#ex The [generic transformation increment](source-expression-depth-audit.md#generic-ast-transformation-continuations) replaces expression/statement/block cloning and its qualified-path callback with typed work entries. AST/error/instance order, spans, Copy-transfer and static-worker policy are preserved; existing type/instance guards remain. A separate baseline confirms generics.path also aborted on a 16,384-field unknown callee. Full generic scalar checks/lowerings now accept through 65,536; deep unknown callees return exact E7002. Independent shallow/deep/OOM and 497/42/25 CLI checks pass; frozen old/new public checks/lowerings remain exact (1,423/506). All 1,793 ordinary conformance cases pass with exact coverage. Follow-up probes confirm remaining parser failures at 1,024 parenthesized/mixed-call levels and 16,384 qualified-variant fields. Q-061 remains open, without a new limit or external review of this increment. +The [parser constructor-path increment](source-expression-depth-audit.md#parser-qualified-constructor-paths) repairs Parser.exprPath independently of generic/lowering paths. Frozen baseline probes confirm enum and struct constructor aborts at 16,384 fields; the repaired CLI returns exact E7002 through 65,536. Named-root classification, spelling, type arguments, spans, syntax errors and host OOM propagation are preserved, with one complete string allocation. Q-061 remains open for the confirmed parenthesized/mixed-call parser failures and the remaining lowering/liveness inventory; no new acceptance limit or external review is claimed. + Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 3842e42..7ee63fd 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -385,20 +385,60 @@ No normative, source/AIR format, feature, code, bundle, acceptance-limit, ownership, runtime instruction or model result changes. Q-061 remains open; this generic increment has no external review yet. +## Parser qualified constructor paths + +The generic follow-up identified a separate recursive Parser.exprPath, called +for qualified enum variants and struct literals. A frozen pre-repair CLI +(`aji-before-parser-path`, production at d39a422) independently aborts at +16,384 fields for both forms, with empty stdout. Raw inputs and output are +`parser-path-before-probes.json` and `parser-path-*.before.stdout/.stderr` in +the ignored evidence directory. + +Parser.exprPath now validates the root, computes the complete byte length and +fills one owned spelling iteratively. Direct names and invalid roots allocate +nothing. Grammar, generic arguments, constructor classification, token cursor, +spans and syntax/error priority are unchanged. Checked size arithmetic and +allocation failure propagate as host OOM, without a source diagnostic or +public partial AST. The final string has caller-arena lifetime; allocation +requests and failure-index outcomes need not match the former prefix copies. + +The copied shallow recursive path oracle checks both named and invalid roots. +Separate tests exercise 65,536 fields, exact component bytes, a single output +allocation, zero-allocation answers and host OOM. Public parser tests check +qualified enum/struct forms with and without type arguments, exact spans and a +missing variant name at 65,536 fields. Every backing-allocation failure in a +smaller constructor fixture propagates host OOM and releases its arena. +Repaired CLI probes return E7002 with the complete name at line 2, column 38, +for both forms through 65,536 fields (`parser-path-after-probes.json` and +`parser-path-*.after.stdout/.stderr`). + +Build, unit and Zig format checks pass. All 1,793 ordinary conformance cases +pass with terminal exit 0 and exact unique corpus coverage +(`parser-path-conformance.jsonl` and its audit). The expression-depth and grammar +CLI suites pass 577 and 312 checks. Constructor regressions cover generic and +nongeneric forms with exact E7002 records across check/lower/run/report/explore. +Frozen old/new CLIs retain exact exit/stdout/stderr on all 1,423 +public source checks and 506 accepted lowerings +(`parser-path-cli-compatibility.json`). + +No normative, source/AIR format, feature, code, bundle, acceptance-limit or +runtime/ownership rule changes. This repairs one callback; Q-061 remains open +and no external review covers this increment yet. + ## Remaining work -Current follow-up checks accept 16 parenthesized/mixed-call levels but abort +Follow-up checks accept 16 parenthesized/mixed-call levels but abort with empty stdout at 1,024. A qualified enum variant returns E7002 at 16 components but aborts in Parser.exprPath at 16,384. Raw evidence is `generic-followup-depth-probes.json` and `generic-followup-*.stdout/.stderr`. -Generic transformation and its path callback above are repaired; the remaining -inventory includes these observed parser failures and inspection-only risks: +Generic transformation, its path callback and Parser.exprPath above are now +repaired; the remaining inventory includes the other observed parser failures +and inspection-only risks: | Production path | Evidence and next scope | |---|---| | Parser `postfix`/`primary` through parenthesized `expr` | Confirmed failure at 1,024 levels; preserve grouping, precedence and spans. | | Parser `callArgs`, array/index/struct initializers, `ifExpr`, block/statement and match/arm expression entry | Mixed `1i64 + id(...)` calls have a confirmed parser abort at 1,024. Other callback depth behavior is unverified; include alternating forms, not only homogeneous spines. | -| Parser `exprPath` | Confirmed qualified enum-variant abort at 16,384; preserve named-root classification, spelling, syntax/error priority and spans. | | Lowerer non-scalar `expr` callbacks: calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Native re-entry remains outside the repaired scalar driver; deep behavior unverified, including alternating scalar/non-scalar expressions. | | Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. | diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 4e4ffe0..c9a7045 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -596,3 +596,20 @@ return exact E7002. Follow-up probes retain separate parser failures at 1,024 parenthesized/mixed-call levels and confirm Parser.exprPath failure at 16,384 qualified-variant fields. Q-061's remaining inventory, Q-060 validation and Phase 6 exit gates stay open. No external review covers this increment yet. + +## Source parser constructor paths (2026-10-10) + +The [Q-061 parser-path increment](../design/source-expression-depth-audit.md#parser-qualified-constructor-paths) +removes native recursion and intermediate prefix copies from Parser.exprPath. +Root classification, spelling, generic arguments, spans and syntax/error +priority remain unchanged; host OOM propagates separately from source errors. +Frozen baseline enum/struct constructor probes abort at 16,384 fields; repaired +CLI probes return exact E7002 through 65,536. Independent shallow path, deep +parser/spelling and failed-allocation cleanup tests cover this callback. +Build/units/format checks, all 1,793 ordinary conformance cases with exact +coverage and 577/312 expression-depth/grammar CLI checks pass; frozen old/new public checks/ +lowerings remain exact (1,423/506). +No normative/bundle/feature/code/acceptance-limit or runtime/ownership rule +changes. Parenthesized and mixed-call parsing failures, remaining expression/ +statement walks, Q-060 validation and Phase 6 exit gates remain open. This +increment has no external review yet. diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index f781c27..b02c569 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -1098,14 +1098,32 @@ const Parser = struct { } fn exprPath(p: *Parser, e: ast.Expr) Error!?[]const u8 { - return switch (e.kind) { - .name => |name| name, - .field => |field| blk: { - const parent = try p.exprPath(field.e.*) orelse break :blk null; - break :blk try std.fmt.allocPrint(p.arena, "{s}.{s}", .{ parent, field.name }); - }, - else => null, - }; + // Reject non-name roots before allocating, just as recursive descent + // did. Only the final spelling is owned; no intermediate prefixes. + var node = e; + while (node.kind == .field) node = node.kind.field.e.*; + if (node.kind != .name) return null; + if (e.kind == .name) return node.kind.name; + var length = node.kind.name.len; + node = e; + while (node.kind == .field) { + length = std.math.add(usize, length, node.kind.field.name.len) catch return error.OutOfMemory; + length = std.math.add(usize, length, 1) catch return error.OutOfMemory; + node = node.kind.field.e.*; + } + const out = try p.arena.alloc(u8, length); + var cursor = length; + node = e; + while (node.kind == .field) { + const field = node.kind.field; + cursor -= field.name.len; + @memcpy(out[cursor .. cursor + field.name.len], field.name); + cursor -= 1; + out[cursor] = '.'; + node = field.e.*; + } + @memcpy(out[0..cursor], node.kind.name); + return out; } fn structLiteral(p: *Parser, start: lex.Pos, name: []const u8) Error!ast.Expr { @@ -1616,6 +1634,124 @@ test "unary metadata and output allocation failures publish no partial AST" { } } +test "parser qualified paths preserve recursive spelling and root classification" { + const Reference = struct { + fn path(a: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 { + return switch (e.kind) { + .name => |name| name, + .field => |field| blk: { + const parent = try path(a, field.e.*) orelse break :blk null; + break :blk try std.fmt.allocPrint(a, "{s}.{s}", .{ parent, field.name }); + }, + else => null, + }; + } + }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const span: ast.Span = .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 2 } }; + const root: ast.Expr = .{ .span = span, .kind = .{ .name = "Root" } }; + const invalid: ast.Expr = .{ .span = span, .kind = .{ .boolean = true } }; + var p: Parser = .{ .arena = a, .tokens = &.{} }; + for ([_]ast.Expr{ root, invalid }) |leaf| { + var current = leaf; + for (0..16) |i| { + try std.testing.expectEqualDeep(try Reference.path(a, current), try p.exprPath(current)); + const child = try a.create(ast.Expr); + child.* = current; + current = .{ .span = span, .kind = .{ .field = .{ .e = child, .name = if (i % 2 == 0) "left" else "right" } } }; + } + } + var current = root; + for (0..65_536) |i| { + const child = try a.create(ast.Expr); + child.* = current; + current = .{ .span = span, .kind = .{ .field = .{ .e = child, .name = if (i % 2 == 0) "x" else "yz" } } }; + } + var allocation: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); + p.arena = allocation.allocator(); + const owned = (try p.exprPath(current)).?; + defer allocation.allocator().free(owned); + try std.testing.expectEqual(@as(usize, 1), allocation.allocations); + try std.testing.expectEqual(@as(usize, 4 + 32_768 * 5), owned.len); + try std.testing.expectEqualStrings("Root", owned[0..4]); + for (0..32_768) |i| try std.testing.expectEqualStrings(".x.yz", owned[4 + i * 5 .. 4 + (i + 1) * 5]); + var failure: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + p.arena = failure.allocator(); + try std.testing.expectError(error.OutOfMemory, p.exprPath(current)); + try std.testing.expect(p.failure == null); + var no_alloc: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + p.arena = no_alloc.allocator(); + try std.testing.expectEqualStrings("Root", (try p.exprPath(root)).?); + const bad: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &invalid, .name = "field" } } }; + try std.testing.expect(try p.exprPath(bad) == null); + try std.testing.expect(!no_alloc.has_induced_failure); +} + +test "deep qualified constructors preserve names type arguments spans and errors" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var name: std.ArrayList(u8) = .empty; + for (0..65_536) |_| try name.appendSlice(a, "ns."); + try name.appendSlice(a, "Record"); + const header = "module deep\nfn f() -> void effects [] { let x = "; + const col: u32 = @intCast(header.len - "module deep\n".len + 1); + for ([_][]const u8{ "::A", "::::A", " { field: 1u64 }", ":: { field: 1u64 }" }, 0..) |suffix, i| { + const source = try std.fmt.allocPrint(a, "{s}{s}{s}; }}", .{ header, name.items, suffix }); + const result = try parseWithFile(a, source, "qualified.aji"); + try std.testing.expect(result == .ok); + const value = result.ok.functions[0].body.stmts[0].kind.let.e; + try std.testing.expectEqualStrings("qualified.aji", value.span.file.?); + try std.testing.expectEqual(@as(u32, 2), value.span.start.line); + try std.testing.expectEqual(col, value.span.start.col); + try std.testing.expectEqual(col + @as(u32, @intCast(name.items.len + suffix.len)), value.span.end.col); + if (i < 2) { + try std.testing.expectEqualStrings(name.items, value.kind.variant.@"enum"); + try std.testing.expectEqualStrings("A", value.kind.variant.name); + try std.testing.expectEqual(@as(usize, i), value.kind.variant.type_args.len); + } else { + try std.testing.expectEqualStrings(name.items, value.kind.struct_lit.name); + try std.testing.expectEqualStrings("field", value.kind.struct_lit.fields[0].name); + try std.testing.expectEqual(@as(usize, i - 2), value.kind.struct_lit.type_args.len); + } + } + const broken = try std.fmt.allocPrint(a, "{s}{s}::; }}", .{ header, name.items }); + const result = try parse(a, broken); + try std.testing.expect(result == .err); + try std.testing.expectEqualStrings("a variant name", result.err.expected); + try std.testing.expectEqualStrings(";", result.err.found); + try std.testing.expectEqual(col + @as(u32, @intCast(name.items.len + 2)), result.err.pos.col); +} + +test "qualified constructor allocation failures publish no AST or syntax diagnostic" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(a, "module deep fn f() -> void effects [] { let x = "); + for (0..64) |_| try source.appendSlice(a, "ns."); + try source.appendSlice(a, "Record::::A; let y = "); + for (0..64) |_| try source.appendSlice(a, "ns."); + try source.appendSlice(a, "Record:: { field: 1u64 }; }"); + 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()); + const result = parse(arena.allocator(), source.items); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + try std.testing.expect((try result) == .ok); + } + arena.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } +} + test "qualified enum payload lists are nonempty, including grouped and generic variants" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index cff1274..34318c9 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -244,6 +244,26 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: for command in ('lower', 'run', 'report', 'explore'): assert json.loads(cli(command, path, code=1)) == error + # Parser.exprPath is used by qualified enum/struct constructors, including + # explicit type arguments. Unknown names must reach lowering rather than + # exhausting the native stack, with their full spelling and original span. + for depth in (16, 1024, 16384, 65536): + name = 'ns.' * depth + 'Record' + header = 'fn main() -> i64 effects [] { return ' + for kind, suffix, message in ( + ('variant', '::A', 'unknown enum'), + ('struct', ' { field: 1u64 }', 'unknown type'), + ('generic-variant', '::::A', 'unknown or inaccessible generic type'), + ('generic-struct', ':: { field: 1u64 }', 'unknown or inaccessible generic type'), + ): + path = root / f'qualified-{kind}-{depth}.aji' + path.write_text('module depth\n' + header + name + suffix + '; }\n') + error = json.loads(cli('check', path, code=1)) + assert (error['code'], error['name'], error['file'], error['line'], error['col'], error['message']) == ( + 'E7002', name, str(path), 2, len(header) + 1, message), error + for command in ('lower', 'run', 'report', 'explore'): + assert json.loads(cli(command, path, code=1)) == error + # Signed boundary literal remains one negative constant; the outer # checked negation traps rather than changing literal acceptance. minimum = root / 'minimum.aji'