diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index d243016..8ce6dc6 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -521,4 +521,6 @@ The [closing path/lifetime inspection](runtime-value-depth-audit.md#closing-runt Inspection during Q-059's closing inventory finds native recursion through source expression parsing (`binary`/`unary`), expression queries (`peekType`/`useIn`) and generic expression transformation (`expression`/`walk`). The fixed generic type/instantiation guards do not establish a bound on arbitrary expression or statement nesting. **Unverified:** no expression/statement stack-exhaustion probe has been run in this audit; this entry records inspection risk, not an observed failure or a new acceptance rule. +Follow-up [expression-depth probes](source-expression-depth-audit.md) now confirm native-stack aborts without JSON diagnostics: 1,024 `not` prefixes fail in lowering; 16,384/65,536 fail earlier in the unary parser. The parser's direct prefix recursion is replaced by explicit continuations with unchanged grammar, AST spans, syntax errors and OOM propagation. Deep parse/format/missing-operand checks pass, but the confirmed lowering failure and other expression/statement paths remain open. The preceding inspection-only statement describes the initial checkpoint, not the current evidence. + 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 new file mode 100644 index 0000000..b12d352 --- /dev/null +++ b/docs/design/source-expression-depth-audit.md @@ -0,0 +1,73 @@ +# Source expression depth audit + +This non-normative audit tracks Q-061 independently of the resolved compiler +type-traversal inventory (Q-059). It uses finite generated/public source only; +it does not set an expression-depth acceptance limit or report model outcomes. + +## Confirmed baseline failures + +On the Debug CLI preceding the unary-parser repair (code at `fb80413`), +`fn main() -> bool effects [] { return not … false; }` accepts 16 prefixes. +At 1,024 prefixes, checking aborts in `Lowerer.expr`, with repeated `.not` +operand calls. At 16,384 and 65,536 prefixes, it aborts earlier in +`Parser.unary`. Each failing check exits by signal (observed return code -6) +without a stdout diagnostic. These are observed native-stack failures, not +language rejection rules. Stderr reports a segmentation fault at the recursive +entry/operand call, followed by repeated native frames of that function. + +The ignored evidence is under `.zig-cache/contract-gate/type-depth/`: +`expression-depth-before.json`, `prefix-not-*.stdout` and `prefix-not-*.stderr`. +No wall-clock timeout terminates these probes. + +## Unary parser continuations + +The parser records `-`, `not`, `*` and inline borrow prefixes in an explicit +pending list, parses the terminal operand and rebuilds the nodes inside out. +`move` remains a terminal name form. A borrow still parses its operand through +unary only when the next token is `*`; otherwise it uses postfix directly. +This preserves the existing place boundary, rather than admitting new spellings +such as `ref -value`, `mut not value` or `ref move value`. + +Each rebuilt node retains its own start and the final operand end, including +comments, newlines and file provenance. AST node order, operator association, +postfix precedence and syntax failure positions are unchanged. Pending metadata +is host compiler storage and is released on completion/error. Allocation failure +still propagates OutOfMemory; no partial AST escapes, new code or depth rejection +is introduced. AIR, verifier ownership/borrow rules, runtime evaluation, fuel, +effects and source/reference bundle text are unchanged. + +An independent shallow copy of the old unary derivation checks 448 combinations +of prefixes and successful/failed operands. It compares complete ASTs, failure +records, token cursors and last-consumed positions. Its shared postfix parser is +outside that oracle's scope. Separate tests parse 32,768 mixed prefix groups +including borrowed dereferences, inspect every node/span iteratively and check a +missing operand at the deepest position. A failing-allocator test covers all +arena backing requests in a longer chain, including pending-list growth and +output construction, and verifies complete release. + +Syntax-only CLI probes format 1,024/16,384/65,536 `not` prefixes successfully +and idempotently, retaining every prefix. Missing-operand checks at +16,384/65,536 prefixes emit exactly one E7001 with independently computed +line/column and expected/found fields. These do **not** establish successful +deep lowering or execution. The permanent `source_grammar.py` suite includes +those formatting/diagnostic regressions at all three depths, with the same +syntax diagnostic across check/lower/run/report/explore/fmt. + +Validation: build, units and format checks pass; all 1,793 ordinary conformance +cases pass with exact unique corpus coverage. Old/new public source checks and +successful lowerings are byte-identical (1,423/506). The grammar integration +suite passes 312 checks; the formatter suite passes 6,078 checks over 1,469 files +(1,414 parsed, 55 syntax-error fixtures, 782 identical successful AIR outputs). +These are compiler regressions, not a model-capability measurement or full GC +validation. + +## Remaining work + +The confirmed `.not` lowering recursion remains unchanged. Other expression +and statement paths, including parenthesized/nested primary parsing, +`peekType`/`useIn`, generic `expression`/`walk` and lowering's other recursive +expression/block handlers, need separate probes and repairs. Their complete +depth behavior is unverified here. The formatter's expression-marking traversal +already uses a worklist, as inspected and exercised by the deep syntax-only +probes. Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is +independent. No fresh Claude review covers this parser increment. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 4e5f728..637281c 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -520,3 +520,9 @@ This closes type descent, not arbitrary expression/statement recursion (inspecti The [Q-060 closing inspection](../design/runtime-value-depth-audit.md#closing-runtime-paths-and-error-exit-cleanup) repairs an execution-arena leak when host OOM interrupts execution or result copying. Deferred cleanup retains the public API, successful output lifetime, fuel, quotas and collection safe points. Exhaustive caller/heap allocator failures pass under ordinary/per-step collection; units, format checks, test-extended, all 1,793 ordinary conformance cases with exact coverage and 29 exact old/new fuel/value CLI pairs pass. The earlier Debug full GC process is also still live, as is ReleaseSafe; host namespace inspection corrects the previous termination inference. Conformance now flushes each completed result, and an additional focused std GC run has live progress. These are unfinished validation, not full passes. Q-060 and Phase 6 exit gates remain open; no normative/bundle/feature/code/acceptance-limit change or new Claude review is claimed. + +## Source unary parser depth (2026-10-10) + +[Q-061 probes](../design/source-expression-depth-audit.md) confirm native-stack aborts without JSON: 1,024 `not` prefixes fail in lowering, while 16,384/65,536 fail earlier in parsing. Direct unary-prefix parsing now uses explicit continuations, preserving the grammar, borrow/place boundary, AST spans, exact failures and host OOM propagation. Independent shallow-oracle (448 cases), 32,768 mixed-prefix, deep missing-operand and allocation-failure tests pass. Syntax-only formatting works through 65,536 prefixes; this does not close the confirmed lowering failure. + +Build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 312 grammar CLI checks and 6,078 formatter checks pass. Old/new public source check/lower output remains identical (1,423/506). No normative/reference bundle, feature, code or acceptance-limit change; P6-2, Q-061's remaining expression/statement paths, Q-060 GC validation and Phase 6 exit review remain open. No fresh Claude review covers this increment. diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index 2a749ff..f781c27 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -946,41 +946,52 @@ const Parser = struct { } fn unary(p: *Parser) Error!ast.Expr { - const start = p.peek().pos; - const t = p.peek(); - if (t.tag == .minus) { - _ = p.next(); - const operand = try p.box(ast.Expr, try p.unary()); - return .{ .span = p.span(start), .kind = .{ .neg = operand } }; - } - if (isWord(t, "not")) { - _ = p.next(); - const operand = try p.box(ast.Expr, try p.unary()); - return .{ .span = p.span(start), .kind = .{ .not = operand } }; - } - if (t.tag == .star) { - _ = p.next(); - const operand = try p.box(ast.Expr, try p.unary()); - return .{ .span = p.span(start), .kind = .{ .deref = operand } }; - } - if (isWord(t, "ref") or isWord(t, "mut")) { - _ = p.next(); - var unchecked = false; - if (p.atWord("unchecked")) { + const Prefix = struct { + start: lex.Pos, + kind: enum { neg, not, deref, borrow }, + mutable: bool = false, + unchecked: bool = false, + }; + var pending: std.ArrayList(Prefix) = .empty; + defer pending.deinit(p.arena); + var e: ast.Expr = while (true) { + const t = p.peek(); + const kind: ?@FieldType(Prefix, "kind") = if (t.tag == .minus) .neg else if (isWord(t, "not")) .not else if (t.tag == .star) .deref else null; + if (kind) |k| { _ = p.next(); - unchecked = true; + try pending.append(p.arena, .{ .start = t.pos, .kind = k }); + continue; } - // The grammar's place production also permits `* unary`. - // Keep other prefix forms out of an inline borrow operand. - const place = if (p.peek().tag == .star) try p.unary() else try p.postfix(); - return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = isWord(t, "mut"), .unchecked = unchecked, .place = try p.box(ast.Expr, place) } } }; + if (isWord(t, "ref") or isWord(t, "mut")) { + _ = p.next(); + var unchecked = false; + if (p.atWord("unchecked")) { + _ = p.next(); + unchecked = true; + } + try pending.append(p.arena, .{ .start = t.pos, .kind = .borrow, .mutable = isWord(t, "mut"), .unchecked = unchecked }); + // A borrow admits `* unary`; all other operands still use + // postfix directly, preserving the place grammar boundary. + if (p.peek().tag == .star) continue; + break try p.postfix(); + } + if (isWord(t, "move")) { + _ = p.next(); + const name = try p.ident("the name of the value to move"); + break .{ .span = p.span(t.pos), .kind = .{ .move = name } }; + } + break try p.postfix(); + }; + while (pending.pop()) |prefix| { + const operand = try p.box(ast.Expr, e); + e = .{ .span = p.span(prefix.start), .kind = switch (prefix.kind) { + .neg => .{ .neg = operand }, + .not => .{ .not = operand }, + .deref => .{ .deref = operand }, + .borrow => .{ .borrow = .{ .mutable = prefix.mutable, .unchecked = prefix.unchecked, .place = operand } }, + } }; } - if (isWord(t, "move")) { - _ = p.next(); - const name = try p.ident("the name of the value to move"); - return .{ .span = p.span(start), .kind = .{ .move = name } }; - } - return p.postfix(); + return e; } fn postfix(p: *Parser) Error!ast.Expr { @@ -1478,6 +1489,133 @@ test "dereferenced borrow consumes unary place without swallowing outer operatio } } +// Independent copy of the pre-repair unary derivation, used only on shallow +// prefixes. Postfix parsing is outside this oracle's scope. +fn referenceUnary(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + const t = p.peek(); + if (t.tag == .minus or Parser.isWord(t, "not") or t.tag == .star) { + _ = p.next(); + const operand = try p.box(ast.Expr, try referenceUnary(p)); + return .{ .span = p.span(start), .kind = if (t.tag == .minus) .{ .neg = operand } else if (t.tag == .star) .{ .deref = operand } else .{ .not = operand } }; + } + if (Parser.isWord(t, "ref") or Parser.isWord(t, "mut")) { + _ = p.next(); + var unchecked = false; + if (p.atWord("unchecked")) { + _ = p.next(); + unchecked = true; + } + const place = if (p.peek().tag == .star) try referenceUnary(p) else try p.postfix(); + return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = Parser.isWord(t, "mut"), .unchecked = unchecked, .place = try p.box(ast.Expr, place) } } }; + } + if (Parser.isWord(t, "move")) { + _ = p.next(); + const name = try p.ident("the name of the value to move"); + return .{ .span = p.span(start), .kind = .{ .move = name } }; + } + return p.postfix(); +} + +test "unary continuations retain shallow syntax, ranges and exact failures" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const prefixes = [_][]const u8{ "", "- ", "not\n", "* ", "ref * ", "mut unchecked * ", "ref ", "move " }; + const leaves = [_][]const u8{ "value[1u8].field", "(value)", "callee(arg)", "move owner", "!flag", ";", "" }; + for (prefixes) |outer| for (prefixes) |inner| for (leaves) |leaf| { + const source = try std.fmt.allocPrint(a, "// UTF-8: λ\n{s}{s}{s}", .{ outer, inner, leaf }); + const tokens = try lex.tokenize(a, source); + var old: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .file = "prefix.aji" }; + var current: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .file = "prefix.aji" }; + const expected = referenceUnary(&old); + const actual = current.unary(); + if (expected) |expression| { + try std.testing.expectEqualDeep(expression, try actual); + } else |err| { + try std.testing.expectError(err, actual); + try std.testing.expectEqualDeep(old.failure, current.failure); + } + try std.testing.expectEqual(old.pos, current.pos); + try std.testing.expectEqualDeep(old.last_end, current.last_end); + }; +} + +test "deep mixed unary chains parse with exact inner and outer spans" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const depth = 32_768; + const prefixes = [_][]const u8{ "- ", "not ", "* ", "ref * ", "mut unchecked * " }; + const header = "module deep\nfn f() -> void effects [] { apply("; + const column: u32 = @intCast(header.len - "module deep\n".len + 1); + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(a, header); + for (0..depth) |i| try source.appendSlice(a, prefixes[i % prefixes.len]); + const leaf_col: u32 = @intCast(source.items.len - "module deep\n".len + 1); + try source.appendSlice(a, "value.field"); + const end_col: u32 = @intCast(source.items.len - "module deep\n".len + 1); + try source.appendSlice(a, "); }"); + const result = try parseWithFile(a, source.items, "deep.aji"); + try std.testing.expect(result == .ok); + var e = result.ok.functions[0].body.stmts[0].kind.expr.kind.call.args[0]; + var col = column; + for (0..depth) |i| { + try std.testing.expectEqualStrings("deep.aji", e.span.file.?); + try std.testing.expectEqual(@as(u32, 2), e.span.start.line); + try std.testing.expectEqual(col, e.span.start.col); + try std.testing.expectEqual(end_col, e.span.end.col); + switch (i % prefixes.len) { + 0 => e = e.kind.neg.*, + 1 => e = e.kind.not.*, + 2 => e = e.kind.deref.*, + 3, 4 => { + try std.testing.expectEqual(i % prefixes.len == 4, e.kind.borrow.mutable); + try std.testing.expectEqual(i % prefixes.len == 4, e.kind.borrow.unchecked); + const place = e.kind.borrow.place; + try std.testing.expectEqual(col + @as(u32, if (i % prefixes.len == 3) 4 else 14), place.span.start.col); + try std.testing.expectEqual(end_col, place.span.end.col); + e = place.kind.deref.*; + }, + else => unreachable, + } + col += @intCast(prefixes[i % prefixes.len].len); + } + try std.testing.expectEqual(leaf_col, e.span.start.col); + try std.testing.expect(e.kind == .field); + try std.testing.expectEqualStrings("field", e.kind.field.name); + const broken = try std.fmt.allocPrint(a, "{s}); }}", .{source.items[0 .. leaf_col - 1 + "module deep\n".len]}); + const failure = try parse(a, broken); + try std.testing.expect(failure == .err); + try std.testing.expectEqualStrings("an expression", failure.err.expected); + try std.testing.expectEqualStrings(")", failure.err.found); + try std.testing.expectEqual(leaf_col, failure.err.pos.col); +} + +test "unary metadata and output allocation failures publish no partial AST" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(fixture.allocator(), "module m fn f() -> void effects [] { apply("); + for (0..64) |_| try source.appendSlice(fixture.allocator(), "not "); + try source.appendSlice(fixture.allocator(), "- * ref * mut unchecked * value.field); }"); + 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 scratch: std.heap.ArenaAllocator = .init(failing.allocator()); + const result = parse(scratch.allocator(), source.items); + if (failing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + try std.testing.expect((try result) == .ok); + } + scratch.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_grammar.py b/tests/hosted/source_grammar.py index 77184d7..3ef512f 100644 --- a/tests/hosted/source_grammar.py +++ b/tests/hosted/source_grammar.py @@ -68,6 +68,25 @@ with tempfile.TemporaryDirectory(prefix='aji-grammar-') as directory: assert result == json.loads(cli('run', '--fuel', '100000', *grants, formatted)) assert result['value'] == 42, result + # Prefix depth is a parser/formatter regression, not an acceptance bound + # or a claim that deep lowering is already iterative (Q-061). + for depth in (1024, 16384, 65536): + prefix = 'module deep\nfn main() -> bool effects [] { return ' + 'not ' * depth + deep = root / f'deep-{depth}.aji' + deep.write_text(prefix + 'false; }\n') + output = cli('fmt', deep) + assert output.count('not ') == depth and output.count('false') == 1 + formatted = root / f'deep-{depth}.formatted.aji' + formatted.write_text(output) + assert cli('fmt', formatted) == output + deep.write_text(prefix + '; }\n') + error = json.loads(cli('check', deep, code=1)) + assert (error['code'], error['expected'], error['found'], error['file']) == ( + 'E7001', 'an expression', ';', str(deep)), error + assert (error['line'], error['col']) == position(prefix, len(prefix)), error + for command in ('lower', 'run', 'report', 'explore', 'fmt'): + assert json.loads(cli(command, deep, code=1)) == error + # Imported qualifiers take the same syntax path and retain the actual file. helper = root / 'model.aji' helper.write_text('module app.model\nenum Value { Empty, Payload(T), }\n')