From cef944d30e145a778317420e864c861c4c0a7118 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 12:41:41 +0300 Subject: [PATCH] cli: parse nested source types with explicit continuations --- docs/design/air-type-depth-audit.md | 10 + docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 6 + src/frontend/parse.zig | 264 +++++++++++++++++++++++---- 4 files changed, 244 insertions(+), 38 deletions(-) diff --git a/docs/design/air-type-depth-audit.md b/docs/design/air-type-depth-audit.md index a3b37ce..539ed73 100644 --- a/docs/design/air-type-depth-audit.md +++ b/docs/design/air-type-depth-audit.md @@ -110,3 +110,13 @@ The preserved invariant is that ownership/transfer/aliasing decisions use the sa Tests compare both raw and prepared queries against 9,216 independent shallow pre-repair derivations (18,432 comparisons). Twenty-seven deep queries cover plain, task-local and endpoint leaves with pending sibling fields. Every temporary allocation is failed in turn for all nine properties, checking OutOfMemory and complete cleanup; prepared/terminal reads succeed with an allocator that rejects its first request. Generic-argument metadata failure produces no semantic diagnostic. Units, format checks and test-extended pass. The full property-engine conformance snapshot passes all 1,791 cases; old/new CLI checks are byte-identical for all 370 AIR and 1,421 source files, as are all 506 accepted source lowerings. Final full conformance after the generic-argument call-site correction also passes all 1,791 cases, with exact corpus coverage. Q-059 remains open for the closing public-call-path audit and source AST traversal inspection. The earlier full per-instruction collection suite is still running; no incomplete suite or unavailable Claude review is counted as a pass. Phase 6 and contract decisions remain open. + +## Source type-syntax parser + +At 3563560, an 82,013-byte monomorphic source file containing 16,384 nested length-one arrays aborts in `typeExpr` with 8,704 symbolized frames and exit -6. Depths 63, 64 and 4,096 accept. Spec 15 §15's depth-64 generic traversal guard is not a universal parser limit: specialization returns an unchanged module when there are no generic declarations or uses. Applying that guard to every parsed annotation would change existing acceptance. Only child core capture is disabled during probes; no timeout terminates them. + +The source type parser now suspends array suffixes and argument lists in explicit frames, including nested static function arguments. Array lengths, argument order, wrapper classification, qualified names, `cap`/`file` paths, wrapper-arity errors and split `>>` positions retain their original behavior. Static function references remain argument syntax; no ordinary type synonym is added. Frame storage is released, AST argument/element storage retains the caller's arena lifetime, and host allocation errors propagate without exposing a partial AST. Spec/reference, verifier and runtime rules, diagnostics and bundles are unchanged; there is no new nesting limit, feature or semantic flag. + +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. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index c88653c..50ad79d 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -475,6 +475,8 @@ The [cache-free nominal size increment](air-type-depth-audit.md#cache-free-nomin The [cache-free nominal property increment](air-type-depth-audit.md#cache-free-nominal-property-queries) repairs independently reproduced failures in all nine uncached structural queries at 32,768 declarations. Public allocator/error APIs reuse the existing iterative fixed-point preparation in temporary storage; cached reads and anonymous terminal paths allocate nothing. Independent shallow comparisons, deep leaf/sibling cases, failed-allocation cleanup and raw/prepared generic-argument accept/reject tests preserve structural rules and diagnostic facts. No acceptance limit or semantic feature is introduced. Closing public-call-path and frontend AST traversal audits keep Q-059 open. +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. + ## 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 b5501c1..17ce94b 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -446,3 +446,9 @@ Both new copy cases also pass with collection before every instruction; their sh The [Q-059 property increment](../design/air-type-depth-audit.md#cache-free-nominal-property-queries) repairs all nine reproduced recursive uncached nominal queries. Public queries explicitly receive a compiler allocator and propagate OutOfMemory; temporary preparation uses the existing fixed points, while cached/terminal reads allocate nothing. Ownership, concurrency, verifier acceptance, runtime accounting and diagnostic facts remain unchanged. Deep queries, 18,432 independent-oracle comparisons, allocation cleanup and public generic-argument acceptance/rejection tests pass. Units/format checks, test-extended and the 1,791-case property-engine conformance snapshot pass. All 370 AIR and 1,421 source CLI checks, plus 506 accepted lowerings, retain exact old/new outputs. Final full conformance after the public helper correction passes all 1,791 cases with exact corpus coverage. The earlier full ReleaseSafe per-step suite also remains in progress. No normative/bundle/feature/code change or depth limit is introduced; Q-059's closing audit, Q-060's closing validation and Phase 6/contract gates remain open. No fresh Claude review was available. + +## Source type-syntax parser (2026-10-10) + +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. diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index cc62efb..2a749ff 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -415,36 +415,105 @@ const Parser = struct { // ------------------------------------------------------------ types fn typeExpr(p: *Parser) Error!ast.Type { - const start = p.peek().pos; - if (p.peek().tag == .l_bracket) { - _ = p.next(); - const elem = try p.typeExpr(); - _ = try p.expect(.semicolon, "`;` in `[T; N]`"); - const n = try p.expect(.int, "array length"); - _ = try p.expect(.r_bracket, "`]`"); - const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); - return .{ .span = p.span(start), .kind = .{ .array = .{ .elem = try p.box(ast.Type, elem), .len = @intCast(len) } } }; + return p.typeTree(false); + } + + // Suspend array suffixes and argument lists explicitly. A static function + // reference is an argument only, never an ordinary type annotation. + // Argument buffers belong to the returned AST; only frames are temporary. + const TypeFrame = union(enum) { + array: lex.Pos, + arguments: struct { + start: lex.Pos, + token: Token, + name: []const u8, + function: bool, + values: std.ArrayList(ast.Type) = .empty, + }, + }; + + fn typeTree(p: *Parser, initial_argument: bool) Error!ast.Type { + var frames: std.ArrayList(TypeFrame) = .empty; + defer frames.deinit(p.arena); + var argument = initial_argument; + while (true) { + const first = p.peek(); + const start = first.pos; + var ty: ast.Type = undefined; + if (argument and p.atWord("fn")) { + _ = p.next(); + const name = try p.path(); + if (p.peek().tag == .colon_colon) { + _ = p.next(); + _ = try p.expect(.lt, "`<`"); + try frames.append(p.arena, .{ .arguments = .{ .start = start, .token = first, .name = name, .function = true } }); + argument = true; + continue; + } + ty = .{ .span = p.span(start), .kind = .{ .function_ref = .{ .name = name } } }; + } else if (p.peek().tag == .l_bracket) { + _ = p.next(); + try frames.append(p.arena, .{ .array = start }); + argument = false; + continue; + } else { + const t = p.peek(); + if (t.tag != .ident) return p.fail(t, "a type"); + _ = p.next(); + const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text; + if (!p.speculative and std.mem.eql(u8, name, t.text) and (isWord(t, "mut") or isWord(t, "ref")) and p.atWord("slice")) + p.type_advice = .{ .at = p.pos, .kind = if (isWord(t, "mut")) .slice_mut_type else .slice_ref_type }; + if (p.peek().tag != .lt) { + ty = .{ .span = p.span(start), .kind = .{ .name = name } }; + } else if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) { + _ = p.next(); + const value = try p.path(); + try p.closeAngle(); + ty = .{ .span = p.span(start), .kind = if (std.mem.eql(u8, name, "cap")) .{ .cap = value } else .{ .file = value } }; + } else { + _ = p.next(); + try frames.append(p.arena, .{ .arguments = .{ .start = start, .token = t, .name = name, .function = false } }); + argument = true; + continue; + } + } + while (frames.items.len != 0) { + const top = &frames.items[frames.items.len - 1]; + switch (top.*) { + .array => |outer| { + _ = try p.expect(.semicolon, "`;` in `[T; N]`"); + const n = try p.expect(.int, "array length"); + _ = try p.expect(.r_bracket, "`]`"); + const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); + const elem = try p.box(ast.Type, ty); + ty = .{ .span = p.span(outer), .kind = .{ .array = .{ .elem = elem, .len = @intCast(len) } } }; + }, + .arguments => |*args| { + try args.values.append(p.arena, ty); + if (p.peek().tag == .comma) { + _ = p.next(); + argument = true; + break; + } + try p.closeAngle(); + ty = .{ .span = p.span(args.start), .kind = .{ .applied = .{ .name = args.name, .args = args.values.items } } }; + if (args.function) { + ty.kind = .{ .function_ref = .{ .name = args.name, .args = args.values.items } }; + } else { + const wrappers = [_][]const u8{ "ref", "mut", "slice", "slice_mut", "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "iref", "atomic" }; + for (wrappers) |wrapper| if (std.mem.eql(u8, args.name, wrapper)) { + // Preserve the name-token location even after a + // split >> closer; source spelling is unchanged. + if (args.values.items.len != 1) return p.fail(args.token, "one wrapper type argument"); + ty.kind = .{ .wrapped = .{ .wrapper = args.name, .inner = try p.box(ast.Type, args.values.items[0]) } }; + break; + }; + } + }, + } + _ = frames.pop(); + } else return ty; } - const t = p.peek(); - if (t.tag != .ident) return p.fail(t, "a type"); - _ = p.next(); - const name = if (p.peek().tag == .dot) try p.pathTail(t.text) else t.text; - if (!p.speculative and std.mem.eql(u8, name, t.text) and (isWord(t, "mut") or isWord(t, "ref")) and p.atWord("slice")) - p.type_advice = .{ .at = p.pos, .kind = if (isWord(t, "mut")) .slice_mut_type else .slice_ref_type }; - if (p.peek().tag != .lt) return .{ .span = p.span(start), .kind = .{ .name = name } }; - if (std.mem.eql(u8, name, "cap") or std.mem.eql(u8, name, "file")) { - _ = p.next(); - const value = try p.path(); - try p.closeAngle(); - return .{ .span = p.span(start), .kind = if (std.mem.eql(u8, name, "cap")) .{ .cap = value } else .{ .file = value } }; - } - const args = try p.typeArgs(); - const wrappers = [_][]const u8{ "ref", "mut", "slice", "slice_mut", "own", "own_array", "buffer", "task", "sender", "receiver", "mutex", "island", "frozen", "arc", "iref", "atomic" }; - for (wrappers) |wrapper| if (std.mem.eql(u8, name, wrapper)) { - if (args.len != 1) return p.fail(t, "one wrapper type argument"); - return .{ .span = p.span(start), .kind = .{ .wrapped = .{ .wrapper = name, .inner = try p.box(ast.Type, args[0]) } } }; - }; - return .{ .span = p.span(start), .kind = .{ .applied = .{ .name = name, .args = args } } }; } fn typeArgs(p: *Parser) Error![]const ast.Type { @@ -460,15 +529,7 @@ const Parser = struct { } fn genericArg(p: *Parser) Error!ast.Type { - if (!p.atWord("fn")) return p.typeExpr(); - const start = p.next().pos; - const name = try p.path(); - var args: []const ast.Type = &.{}; - if (p.peek().tag == .colon_colon) { - _ = p.next(); - args = try p.typeArgs(); - } - return .{ .span = p.span(start), .kind = .{ .function_ref = .{ .name = name, .args = args } } }; + return p.typeTree(true); } fn functionContract(p: *Parser) Error!ast.FunctionContract { @@ -1489,3 +1550,130 @@ test "grammar surface preserves typed-call, comparison and body-brace choices" { try std.testing.expect((try parse(a, source)) == .err); } } + +test "type parsing suspends deep array wrapper and sibling argument frames" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const depth = 32_768; + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(a, "module deep\nfn f(x: "); + for (0..depth) |i| try source.appendSlice(a, switch (i % 3) { + 0 => "[", + 1 => "own<", + else => "Pair<", + }); + try source.appendSlice(a, "u8"); + var i: usize = depth; + while (i != 0) { + i -= 1; + try source.appendSlice(a, switch (i % 3) { + 0 => "; 1]", + 1 => ">", + else => ", bool>", + }); + } + const end: u32 = @intCast(source.items.len - "module deep\n".len + 1); + try source.appendSlice(a, ") -> void effects [] {}\n"); + const result = try parse(a, source.items); + try std.testing.expect(result == .ok); + var t = result.ok.functions[0].params[0].ty; + try std.testing.expectEqual(@as(u32, 9), t.span.start.col); + try std.testing.expectEqual(end, t.span.end.col); + for (0..depth) |level| { + try std.testing.expectEqual(@as(u32, 2), t.span.start.line); + switch (level % 3) { + 0 => { + try std.testing.expect(t.kind == .array); + try std.testing.expectEqual(@as(u64, 1), t.kind.array.len); + t = t.kind.array.elem.*; + }, + 1 => { + try std.testing.expect(t.kind == .wrapped); + try std.testing.expectEqualStrings("own", t.kind.wrapped.wrapper); + t = t.kind.wrapped.inner.*; + }, + else => { + try std.testing.expect(t.kind == .applied); + try std.testing.expectEqualStrings("Pair", t.kind.applied.name); + try std.testing.expectEqual(@as(usize, 2), t.kind.applied.args.len); + try std.testing.expect(t.kind.applied.args[1].kind == .name); + try std.testing.expectEqualStrings("bool", t.kind.applied.args[1].kind.name); + t = t.kind.applied.args[0]; + }, + } + } + try std.testing.expect(t.kind == .name); + try std.testing.expectEqualStrings("u8", t.kind.name); +} + +test "nested static function arguments and split angle spans need no native recursion" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const depth = 16_384; + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(a, "module deep\nfn f(x: "); + for (0..depth) |_| try source.appendSlice(a, "Box>"); + try source.appendSlice(a, ") -> void effects [] {}\n"); + const result = try parse(a, source.items); + try std.testing.expect(result == .ok); + var t = result.ok.functions[0].params[0].ty; + for (0..depth) |_| { + try std.testing.expect(t.kind == .applied); + try std.testing.expectEqualStrings("Box", t.kind.applied.name); + try std.testing.expectEqual(@as(usize, 1), t.kind.applied.args.len); + const f = t.kind.applied.args[0]; + try std.testing.expect(f.kind == .function_ref); + try std.testing.expectEqualStrings("pick", f.kind.function_ref.name); + try std.testing.expectEqual(@as(usize, 1), f.kind.function_ref.args.len); + try std.testing.expectEqual(t.span.end.col - 1, f.span.end.col); + t = f.kind.function_ref.args[0]; + } + try std.testing.expect(t.kind == .name); + try std.testing.expectEqualStrings("u8", t.kind.name); +} + +test "deep type failures retain leaf and wrapper name locations" { + var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(a, "module deep\nfn f(x: "); + for (0..8_192) |_| try source.appendSlice(a, "Box<"); + const col: u32 = @intCast(source.items.len - "module deep\n".len + 1); + try source.appendSlice(a, "own"); + for (0..8_192) |_| try source.append(a, '>'); + try source.appendSlice(a, ") -> void effects [] {}\n"); + const result = try parse(a, source.items); + try std.testing.expect(result == .err); + try std.testing.expectEqualStrings("one wrapper type argument", result.err.expected); + try std.testing.expectEqualStrings("own", result.err.found); + try std.testing.expectEqual(@as(u32, 2), result.err.pos.line); + try std.testing.expectEqual(col, result.err.pos.col); + const missing = try parse(a, source.items[0 .. col - 1 + "module deep\n".len]); + try std.testing.expect(missing == .err); + try std.testing.expectEqualStrings("a type", missing.err.expected); + try std.testing.expectEqualStrings("end of file", missing.err.found); +} + +test "type parser metadata failures propagate without exposing a partial AST" { + const source = "module m fn f(x: Pair<[own; 2], fn pick::>>) -> void effects [] {}"; + 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); + 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; + } +}