diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 6d64b62..fd00adb 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -34,6 +34,7 @@ Status values: `open`, `resolved`. | Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors | | Q-039 | resolved | STD-6d | Explicit static function parameters | | Q-041 | resolved | P6-2 task block forms | Source scope-handle value bindings | +| Q-062 | open | P6-2 | Parenthesized block constructs without a statement terminator | ## Q-001 — Text AIR grammar @@ -574,3 +575,42 @@ The [mutex make/take increment](source-expression-depth-audit.md#mutex-maketake- The [scalar index operand increment](source-expression-depth-audit.md#scalar-index-operand-continuations) preserves base/type/operand priority, usize hints, bounds facts, unchecked state, loans, load/end order, spans and host OOM. Build/units/format and store-mode/array-argument/lifetime/CFG suites pass; exact ordinary conformance (1,793), public frozen parity (1,423/506), the original focused run passes 318 CLI checks (check through 32,768 then existing E5101 at 65,536; lower/fmt through 65,536; runtime/fuel through 1,024), and separate overlapping 30-call fuel/28-call CFG/deref/proven-context subsets pass. Read-only Claude core/final reviews found no production defect and their fixture/wording suggestions are covered. At that scalar-operand checkpoint the recorded nested-array base-index probe still aborted at 1,024 before/after; its subsequent repair is recorded below. Other place/control/liveness callbacks, Q-060 and Phase 6 remain open. No semantic or new depth-limit change. The [raw-place base increment](source-expression-depth-audit.md#raw-place-base-continuations) repairs the recorded 1,024-level nested-array base failure using iterative field/index projections and one ancestor-name list. Borrow modes, parents, child-first ends, range ordering, facts, unchecked selection, spans and host OOM separation are preserved. Exact ordinary conformance coverage, public check/lower parity and 159 focused CLI calls pass; expanded units pass, and scoped read-only Claude core/final reviews found no production defect. Follow-up block/if probes confirm remaining parser aborts at 1,024 before/after. Q-061, Q-060 full GC validation and Phase 6 remain open; no semantic or depth-limit change. + + +The [shared control-parser increment](source-expression-depth-audit.md#shared-control-parser-continuations) +removes native expression/control re-entry through blocks/statements, conditions, +if/else-if, match/arms, select, loops, scopes, shield and lock. Deep mixed, +ungrouped-condition and wide ASTs, token EOF/deletion sweeps, scope/advice, +scratch and recovering/persistent OOM tests pass. All 1,793 ordinary conformance +files have exact successful coverage; public check/lower parity (1,423/506), +grammar/format/error/advice suites and 127 focused CLI calls pass. Scoped +read-only Claude reviews found no production defect. Arena backing/RSS figures +are informational, not an efficiency gate. Full block/if checks still abort at +1,024 in lowering; control/liveness and remaining callbacks, Q-060 full GC and +Phase 6 stay open. Q-062 separately logs a preserved grouped-statement gap. + + +## Q-062 — Parenthesized block constructs without a statement terminator + +**Open; existing source-parser behavior, not a new rule.** Spec 15 §4 makes +unparenthesized block constructs self-delimiting and requires semicolons for +ordinary expression statements; the reference grammar includes `expr ";"` in +`statement`. The parser also accepts a parenthesized block/if/match followed by another +statement without `;`, through the ordinary expression path's block-kind +fallback. Claude identified this during the Q-061 control-parser review. + +A frozen HEAD `9534359` binary and the shared-control-parser candidate both +accept this complete source with exit 0 and no diagnostics: + +```aji +module grouped +fn g() -> void effects [] {} +fn main() -> u64 effects [] { + (if true {} else {}) g(); + return 0u64; +} +``` + +The Q-061 traversal repair deliberately preserves this behavior. A separate +spec/parser decision and positive/negative boundary tests are needed before +changing acceptance. This does not add a semantic rule or close Q-061. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 0fb9f68..1691239 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -1162,6 +1162,86 @@ Control parsing/lowering, multi-result/graph callbacks and liveness/read/ assignment scans keep Q-061 open. Q-060's full GC validation and Phase 6 exit review remain independent open gates. +## Shared control parser continuations + +At HEAD `9534359`, nested block/if expressions parse and check at 16/256 +levels but abort in the parser at 1,024; a separate else-if chain formats at +1,024 but aborts at 16,384. The shared parser driver now queues block, +statement, condition, if/else-if, match/arm, select, loop, scope, shield and +lock children alongside expression continuations. All use one stable result +frame; the expression-returning entry API cannot select control-only outputs. +Unused recursive-entry wrappers and multi-frame machinery are removed. + +This is a traversal repair: tokens, AST/spans, statement/tail/discard boundaries, +`block_statement`, arm-kind selection, error priority and borrow advice retain +their existing rules. Conditions/call advice restore on all exits; for/lock +prefix and group/index restoration remains success-only, as before. Host OOM +propagates without diagnostic conversion or a public partial AST. Work buffers +and AST allocation retain caller-arena lifetime; `deinit` does not promise +physical early release of arena storage. Spec/reference, AIR, verifier, +ownership/concurrency/runtime, diagnostic codes, bundles and acceptance limits +are unchanged. The existing grouped-statement discrepancy is logged separately +as Q-062, with old/new accepted CLI evidence. + +An independent copy of the former mutually recursive control/expression +parser compares shallow ASTs, mutated token buffers, position/end/failure and +scope state. Token/type/pattern helpers remain shared, an explicit oracle +limitation. Added checks cover per-token EOF/deletion sweeps with outer borrow +advice; every control child form's invalid leaf; 32,768 mixed/block and +ungrouped-condition levels; 32,768 statements, match/select arms and else-if +links; control-heavy scratch poisoning; recovering and sticky per-call OOM +above the arena, including grown queues and late failures. A physical backing +tracker measures scalar, block and mixed parsing and verifies complete backing +release after arena teardown. Expanded and final follow-up units pass, +including both OOM modes with resize/remap disabled to inject every growth. +The fixed failure-sweep guards are test bounds, not language limits. + +At 32,768 levels, measured live arena backing allocations peak at: + +| Input | Source bytes | Peak backing bytes | +|---|---:|---:| +| Scalar `not` chain | 131,126 | 89,887,292 | +| Nested blocks | 131,127 | 139,565,186 | +| Mixed 17-form tree | 805,722 | 692,273,454 | + +Work items are 448 bytes, compared with the reconstructed former +expression-only union's 424 bytes; the single frame is 1,992 bytes. The former +payload layouts were checked unchanged, but this is not a before/after peak +measurement. The 24-byte item growth does not justify boxing control payloads +and adding allocation/aliasing paths in this repair. The large stress peaks +are informational, not evidence of efficient memory use or a portable bound. +They include tokenization, owned token duplication, AST, retained work buffers +and arena slack; they exclude source text, allocator overhead and downstream +passes. Backing allocation lengths are distinct from resident process memory. +The separate 12-form, 32,768-depth hosted rejection source is 857,464 bytes; +one Linux/Debug `check` measured 350,804 KiB max child RSS. Its six-command +comparisons run sequentially. This does not bound other environments. + +The focused standalone CLI block passes 127 calls: block/if formatting and +fixed points through 1,024; else-if through 65,536; bounded check/lower through +256 and source/AIR runtime through 16; syntax-only control contexts at 256; +and exact E7001/boolean-negation records for six public commands through +32,768 with CRLF/UTF-8 source. It is an exact extraction of the new block in +`tests/hosted/source_expression_depth.py`, not a run of that whole accumulating +suite. Build/format, frozen public check/lower byte parity (1,423/506), grammar +(312), formatter (6,078), independent-error (234) and repair-advice (299) +checks pass. All 1,793 ordinary conformance files pass with exact unique +coverage; no file is omitted or counted twice. + +Claude's core read-only review found no demonstrated production divergence; +its API/dead-path, mutation, deep/wide, scratch and OOM suggestions are addressed +above. Read-only follow-up/final reviews also found no production defect +within their recorded scope; they ran no tests. Final review clarifications: +peak measurements are informational and the historical work-size reconstruction +is explicit; the hosted memory-heavy scope is documented. Its counter concern +does not reproduce: `cli` increments the global counter and the standalone +extraction records all 127 calls. Current frame/queue poisoning does not cover +abandoned arena buffers, a retained test limitation. +The new parser exposes the next confirmed failure: full checking still aborts +at 1,024 nested block/if levels in `blockBodyWant`/`ifExpr`, with empty stdout. +Lowering/control/liveness, Q-060 full GC validation and Phase 6 exit gates stay +open. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort @@ -1171,11 +1251,11 @@ components but aborts in Parser.exprPath at 16,384. Raw evidence is Generic transformation, its path callback, Parser.exprPath and the shared expression parser above are now repaired. The preceding follow-up records are historical checkpoints, not current parser failures. The remaining inventory -includes a confirmed lowerer failure and inspection-only risks: +includes confirmed block/if lowerer failures and inspection-only risks: | Production path | Evidence and next scope | |---|---| -| Parser `ifExpr`, block/statement and match/arm expression entry | Finite block/if probes above confirm parser aborts at 1,024 before/after the raw-place repair; 16/256 accept. Alternating control/statement combinations still need audit. | +| Parser block/statement/condition and if/match/select expression entry | Shared control/expression continuations are repaired above. Historical parser aborts no longer describe the candidate; parser-only deep coverage does not prove downstream AST traversal. | | Lowerer non-scalar `expr` callbacks: builtin/variant calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Ordinary calls, struct/value-field, array and enum-payload descent are repaired above. Boolean, consuming own/region, atomic, task.join and spawn operands are repaired above. Mutex make/take operands are repaired above. Scalar index operands use continuations above; the recorded nested-array base-index failure is repaired by the raw-place increment above. Dereference/bound expression callbacks and graph/control combinations still need audit. Multi-result task.join_cancel inputs and other graph/place/control callbacks retain native entry. Other callback depth remains unverified; include 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 ce14c78..a1d3e9e 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -832,3 +832,27 @@ production defect. Documentation scope corrections are recorded in the audit. Th claimed. Block/if parsing still aborts at 1,024 before/after; other callbacks and liveness/read/assignment scans, Q-060 full GC validation and Phase 6 exit review remain open. No normative, feature, bundle or accepted-depth change. + + +### Shared control parser depth increment + +The [shared control parser](../design/source-expression-depth-audit.md#shared-control-parser-continuations) +uses one expression/control driver for block/statement, if/else-if, match/arms, +select, loops, scopes, shield and lock. Grammar, AST/spans, error/repair advice, +statement/tail boundaries and scoped state retain their former behavior; OOM +propagates without diagnostics or public partial AST. Unused entry wrappers and +multi-frame machinery are removed. No semantic/feature/bundle/depth-limit change. + +Build/format, frozen public check/lower parity (1,423/506), grammar (312), +formatter (6,078), independent-error (234), repair-advice (299) and 127 new +focused CLI calls pass. Final expanded/follow-up units and all 1,793 ordinary +conformance cases with exact unique coverage pass. Arena backing measurements +are informational, include tokens/AST/work/slack, and do not assert efficiency +or a memory bound; the audit records the large mixed stress peak and separate +hosted RSS measurement. Read-only Claude core/follow-up/final reviews found no +production defect within their scoped inspections; they ran no tests. Parser-only coverage is distinguished from bounded lower/runtime +coverage and from the unrun whole accumulating expression-depth suite. +Full block/if checking at 1,024 now reaches a confirmed lowerer stack failure. +Q-062 logs the independently reproduced existing parenthesized-statement +boundary discrepancy. Q-061 lowering/control/liveness, Q-060 full per-step GC +validation and Phase 6 exit gates remain open. diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index b1ff730..993744c 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -1,5 +1,5 @@ -//! Parser for `.aji` source 0.1 (reference/grammar.ebnf). Recursive -//! descent. At most one E7001 per independently bounded top-level item; +//! Parser for `.aji` source 0.1 (reference/grammar.ebnf). Explicit +//! expression/control/type continuations and direct declaration/token helpers. At most one E7001 per independently bounded top-level item; //! malformed boundaries stop collection. No partial AST escapes on error. const std = @import("std"); @@ -54,11 +54,11 @@ const Parser = struct { type_advice: ?struct { at: usize, kind: diag.SourceRepairKind } = null, borrow_advice: ?struct { at: usize, kind: diag.SourceRepairKind } = null, speculative: bool = false, - /// Reused across expressions and callback re-entry. Each driver owns only - /// entries above its saved base; no queued pointer targets this buffer. + /// Reused across function bodies and direct expression entries. All child + /// parses share one driver; no queued pointer targets this buffer. expr_work: std.ArrayList(ExprWork) = .empty, - expr_frames: std.ArrayList(*ExprFrame) = .empty, - expr_frame_depth: usize = 0, + expr_frame: ?*ExprFrame = null, + driver_active: bool = false, fn peek(p: *Parser) Token { return p.tokens[p.pos]; @@ -150,13 +150,6 @@ const Parser = struct { return try p.arena.dupe(diag.RepairCandidate, &.{candidate}); } - fn exprWithBorrowAdvice(p: *Parser, kind: diag.SourceRepairKind) Error!ast.Expr { - const saved = p.borrow_advice; - p.borrow_advice = .{ .at = p.pos, .kind = kind }; - defer p.borrow_advice = saved; - return p.expr(); - } - fn failPrimary(p: *Parser, t: Token) Error { if (t.tag == .invalid and std.mem.eql(u8, t.text, "!")) return p.failAdvice(t, "an expression", .boolean_negation); if (isWord(t, "zero")) return p.failAdvice(t, "an expression", .zero_storage); @@ -594,243 +587,7 @@ const Parser = struct { // ------------------------------------------------------------ statements fn block(p: *Parser) Error!ast.Block { - const start = (try p.expect(.l_brace, "`{`")).pos; - var stmts: std.ArrayList(ast.Stmt) = .empty; - var tail: ?*const ast.Expr = null; - while (p.peek().tag != .r_brace) { - if (p.peek().tag == .eof) return p.fail(p.peek(), "`}`"); - if (try p.statement(&tail)) |s| { - try stmts.append(p.arena, s); - } else break; // a tail expression ends the block - } - _ = try p.expect(.r_brace, "`}`"); - return .{ .stmts = stmts.items, .tail = tail, .span = p.span(start) }; - } - - /// Parses one statement; returns null after setting `tail` when the - /// block ends with an expression without `;`. - fn statement(p: *Parser, tail: *?*const ast.Expr) Error!?ast.Stmt { - const start = p.peek().pos; - const t = p.peek(); - if (isWord(t, "let")) { - _ = p.next(); - var names: std.ArrayList([]const u8) = .empty; - const tuple = p.peek().tag == .l_paren; - if (tuple) { - _ = p.next(); - while (p.peek().tag != .r_paren) { - try names.append(p.arena, if (p.peek().tag == .underscore) p.next().text else try p.ident("a name")); - if (p.peek().tag != .comma) break; - _ = p.next(); - } - _ = try p.expect(.r_paren, "`)`"); - } else try names.append(p.arena, try p.ident("a name")); - var ty: ?ast.Type = null; - if (p.peek().tag == .colon) { - _ = p.next(); - ty = try p.typeExpr(); - } - _ = try p.expect(.eq, "`=`"); - const e = try p.exprWithBorrowAdvice(.borrow_binding); - _ = try p.expect(.semicolon, "`;`"); - return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e, .tuple = tuple } } }; - } - const unchecked_borrow = isWord(p.peekAt(1), "unchecked") and p.peekAt(2).tag == .ident and p.peekAt(3).tag == .eq; - if ((isWord(t, "ref") or isWord(t, "mut")) and ((p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) or unchecked_borrow)) { - _ = p.next(); - if (unchecked_borrow) _ = p.next(); - const name = try p.ident("a name for the borrow"); - _ = try p.expect(.eq, "`=`"); - const place = try p.expr(); - _ = try p.expect(.semicolon, "`;`"); - return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = isWord(t, "mut"), .unchecked = unchecked_borrow, .name = name, .place = place } } }; - } - if (isWord(t, "var")) { - _ = p.next(); - const name = try p.ident("a name"); - if (p.peek().tag == .eq) return p.failAdvice(p.peek(), "`:` and the variable's type", .annotate_var_type); - _ = try p.expect(.colon, "`:` and the variable's type"); - const ty = try p.typeExpr(); - _ = try p.expect(.eq, "`=`"); - var init: ?ast.Expr = null; - if (p.atWord("zero")) { - _ = p.next(); - } else init = try p.exprWithBorrowAdvice(.borrow_binding); - _ = try p.expect(.semicolon, "`;`"); - return .{ .span = p.span(start), .kind = .{ .@"var" = .{ .name = name, .ty = ty, .init = init } } }; - } - if (isWord(t, "break") or isWord(t, "continue") or isWord(t, "trap")) { - _ = p.next(); - _ = try p.expect(.semicolon, "`;`"); - const k: @FieldType(ast.Stmt, "kind") = if (isWord(t, "break")) .@"break" else if (isWord(t, "continue")) .@"continue" else .trap; - return .{ .span = p.span(start), .kind = k }; - } - if (isWord(t, "return")) { - _ = p.next(); - var e: ?ast.Expr = null; - if (p.peek().tag != .semicolon) e = try p.expr(); - _ = try p.expect(.semicolon, "`;`"); - return .{ .span = p.span(start), .kind = .{ .@"return" = e } }; - } - if (isWord(t, "while")) { - _ = p.next(); - const cond = try p.condition(); - const body = try p.block(); - return .{ .span = p.span(start), .kind = .{ .@"while" = .{ .cond = cond, .body = body } } }; - } - if (isWord(t, "for")) { - _ = p.next(); - const name = try p.ident("loop variable"); - _ = try p.expectWord("in"); - const saved = p.no_struct; - p.no_struct = true; - const lo = try p.binary(0); - _ = try p.expect(.dot_dot, "`..`"); - const hi = try p.binary(0); - p.no_struct = saved; - const body = try p.block(); - return .{ .span = p.span(start), .kind = .{ .@"for" = .{ .name = name, .lo = lo, .hi = hi, .body = body } } }; - } - if (isWord(t, "loop")) { - _ = p.next(); - const body = try p.block(); - return .{ .span = p.span(start), .kind = .{ .loop = body } }; - } - if (isWord(t, "scope")) { - _ = p.next(); - const name = try p.ident("scope name"); - const body = try p.block(); - return .{ .span = p.span(start), .kind = .{ .scope = .{ .name = name, .body = body } } }; - } - if (isWord(t, "shield")) { - _ = p.next(); - const body = try p.block(); - return .{ .span = p.span(start), .kind = .{ .shield = body } }; - } - if (isWord(t, "lock")) { - _ = p.next(); - _ = try p.expectWord("ref"); - const saved = p.no_struct; - p.no_struct = true; - const place = try p.unary(); - p.no_struct = saved; - _ = try p.expectWord("as"); - const name = try p.ident("a name for the locked data"); - const body = try p.block(); - _ = try p.expectWord("cancelled"); - const cancelled = try p.block(); - return .{ .span = p.span(start), .kind = .{ .lock = .{ .place = place, .name = name, .body = body, .cancelled = cancelled } } }; - } - if (isWord(t, "select")) { - const selection = try p.selectStmt(); - return .{ .span = p.span(start), .kind = .{ .select = selection } }; - } - - // A leading bare block construct has priority over an outer expression - // continuation in statement/tail position (spec 15 §4). Recursive - // expression contexts still use expr(), including parentheses. - if (isWord(t, "if") or isWord(t, "match") or t.tag == .l_brace) { - const e = try p.primary(); - if (p.peek().tag == .r_brace) { - tail.* = try p.box(ast.Expr, e); - return null; - } - const discard = p.peek().tag == .semicolon; - if (discard) _ = p.next(); - return .{ .span = p.span(start), .block_statement = !discard, .kind = .{ .expr = e } }; - } - - // Expression statement, assignment or tail expression. - const e = try p.expr(); - if (p.peek().tag == .eq) { - _ = p.next(); - const rhs = try p.expr(); - _ = try p.expect(.semicolon, "`;`"); - return .{ .span = p.span(start), .kind = .{ .assign = .{ .place = e, .e = rhs } } }; - } - if (p.peek().tag == .semicolon) { - _ = p.next(); - return .{ .span = p.span(start), .kind = .{ .expr = e } }; - } - if (p.peek().tag == .r_brace) { - tail.* = try p.box(ast.Expr, e); - return null; - } - // Block-like expressions end without `;`. - switch (e.kind) { - .if_expr, .match_expr, .block => return .{ .span = p.span(start), .kind = .{ .expr = e } }, - else => return p.fail(p.peek(), "`;`"), - } - } - - fn condition(p: *Parser) Error!ast.Expr { - const saved = p.no_struct; - p.no_struct = true; - defer p.no_struct = saved; - return p.expr(); - } - - fn selectStmt(p: *Parser) Error!ast.Select { - const start = p.next().pos; // `select` - _ = try p.expect(.l_brace, "`{`"); - var sel_arms: std.ArrayList(ast.SelectArm) = .empty; - while (p.atWord("recv") or p.atWord("send")) { - const astart = p.peek().pos; - const is_send = p.atWord("send"); - _ = p.next(); - _ = try p.expect(.l_paren, "`(`"); - const ep = try p.ident("an endpoint name"); - var value: ?ast.Expr = null; - if (is_send) { - _ = try p.expect(.comma, "`,` and the value to send"); - value = try p.expr(); - } - _ = try p.expect(.r_paren, "`)`"); - _ = try p.expect(.l_brace, "`{` with the arm's outcomes"); - const outcomes = try p.arms(); - try sel_arms.append(p.arena, .{ .span = p.span(astart), .send = is_send, .endpoint = ep, .value = value, .arms = outcomes }); - } - _ = try p.expectWord("cancelled"); - var binds: std.ArrayList([]const u8) = .empty; - if (p.peek().tag == .l_paren) { - _ = p.next(); - while (p.peek().tag != .r_paren) { - try binds.append(p.arena, try p.ident("a name")); - if (p.peek().tag != .comma) break; - _ = p.next(); - } - _ = try p.expect(.r_paren, "`)`"); - } - _ = try p.expect(.fat_arrow, "`=>`"); - const body = try p.armBody(); - _ = try p.expect(.r_brace, "`}`"); - return .{ .arms = sel_arms.items, .cancelled_binds = binds.items, .cancelled = body, .span = p.span(start) }; - } - - /// Arms up to and including the closing `}`. - fn arms(p: *Parser) Error![]const ast.Arm { - var out: std.ArrayList(ast.Arm) = .empty; - while (p.peek().tag != .r_brace) { - const pat = try p.pattern(); - _ = try p.expect(.fat_arrow, "`=>`"); - try out.append(p.arena, .{ .pattern = pat, .body = try p.armBody() }); - } - _ = p.next(); - return out.items; - } - - fn armBody(p: *Parser) Error!ast.Expr { - if (p.peek().tag == .l_brace) { - const start = p.peek().pos; - const b = try p.block(); - if (p.peek().tag == .comma) _ = p.next(); - return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; - } - const e = try p.expr(); - if (p.peek().tag == .comma) { - _ = p.next(); - } else if (p.peek().tag != .r_brace) return p.fail(p.peek(), "`,` after the arm"); - return e; + return (try p.parseDriver(.block, 0)).block_result; } fn pattern(p: *Parser) Error!ast.Pattern { @@ -914,6 +671,7 @@ const Parser = struct { } const ExprEntry = enum { binary, cast, unary, postfix, primary }; + const ParseEntry = enum { binary, cast, unary, postfix, primary, block, statement, condition, conditional, arms, arm_body, select }; const ExprPrefix = struct { start: lex.Pos, kind: enum { neg, not, deref, borrow }, @@ -936,8 +694,429 @@ const Parser = struct { fields: std.ArrayList(ast.FieldInit) = .empty, }; const ExprIndex = struct { start: lex.Pos, base: ast.Expr, saved_no_struct: bool }; + const ControlBlock = struct { start: lex.Pos, stmts: std.ArrayList(ast.Stmt) = .empty }; + const ControlSelect = struct { start: lex.Pos, arms: std.ArrayList(ast.SelectArm) = .empty }; + const SelectHeader = struct { context: ControlSelect, start: lex.Pos, send: bool, endpoint: []const u8, value: ?ast.Expr = null }; + const StatementContext = struct { + start: lex.Pos, + kind: union(enum) { + let: struct { names: []const []const u8, ty: ?ast.Type, tuple: bool }, + @"var": struct { name: []const u8, ty: ast.Type }, + borrow: struct { name: []const u8, mutable: bool, unchecked: bool }, + @"return", + expr: bool, // leading bare block construct + assign: ast.Expr, + while_cond, + while_body: ast.Expr, + for_lo: struct { name: []const u8, saved: bool }, + for_hi: struct { name: []const u8, lo: ast.Expr, saved: bool }, + for_body: struct { name: []const u8, lo: ast.Expr, hi: ast.Expr }, + loop, + scope: []const u8, + shield, + lock_place: bool, + lock_body: struct { place: ast.Expr, name: []const u8 }, + lock_cancelled: struct { place: ast.Expr, name: []const u8, body: ast.Block }, + select, + }, + }; + const ControlWork = union(enum) { + block_next: ControlBlock, + block_got: ControlBlock, + statement_got: StatementContext, + block_expr: lex.Pos, + if_expr: lex.Pos, + if_cond, + if_then: ast.Expr, + if_else: struct { cond: ast.Expr, then: ast.Block, chained: bool }, + restore_condition: bool, + match_cond: lex.Pos, + match_arms: struct { start: lex.Pos, scrutinee: ast.Expr }, + arms_next: std.ArrayList(ast.Arm), + arm_got: struct { arms: std.ArrayList(ast.Arm), pattern: ast.Pattern }, + arm_body: ?lex.Pos, + select_next: ControlSelect, + select_value: SelectHeader, + select_arms: SelectHeader, + select_cancelled: struct { context: ControlSelect, binds: []const []const u8 }, + }; + + fn queueControl(p: *Parser, pending: *std.ArrayList(ExprWork), work: ControlWork) Error!void { + try pending.append(p.arena, .{ .control = work }); + } + + fn queueEntry(p: *Parser, pending: *std.ArrayList(ExprWork), kind: ParseEntry) Error!void { + try pending.append(p.arena, .{ .enter = .{ .kind = kind } }); + } + + fn queueStatement(p: *Parser, pending: *std.ArrayList(ExprWork), context: StatementContext, entry: ParseEntry, advice: bool) Error!void { + try p.queueControl(pending, .{ .statement_got = context }); + if (advice) { + try pending.append(p.arena, .{ .restore_advice = p.borrow_advice }); + p.borrow_advice = .{ .at = p.pos, .kind = .borrow_binding }; + } + try p.queueEntry(pending, entry); + } + + /// All expression/control children return to the shared driver. Token, + /// type and pattern helpers cannot re-enter statement/expression parsing. + fn controlEntry(p: *Parser, pending: *std.ArrayList(ExprWork), frame: *ExprFrame, entry: ParseEntry) Error!void { + switch (entry) { + .block => { + const start = (try p.expect(.l_brace, "`{`")).pos; + try p.queueControl(pending, .{ .block_next = .{ .start = start } }); + }, + .statement => try p.beginStatement(pending, frame), + .condition => { + try p.queueControl(pending, .{ .restore_condition = p.no_struct }); + p.no_struct = true; + try p.queueEntry(pending, .binary); + }, + .conditional => { + _ = p.next(); // `if` + try p.queueControl(pending, .if_cond); + try p.queueEntry(pending, .condition); + }, + .arms => try p.queueControl(pending, .{ .arms_next = .empty }), + .arm_body => { + const block_start: ?lex.Pos = if (p.peek().tag == .l_brace) p.peek().pos else null; + try p.queueControl(pending, .{ .arm_body = block_start }); + try p.queueEntry(pending, if (block_start != null) .block else .binary); + }, + .select => { + const start = p.next().pos; + _ = try p.expect(.l_brace, "`{`"); + try p.queueControl(pending, .{ .select_next = .{ .start = start } }); + }, + else => unreachable, + } + } + + fn beginStatement(p: *Parser, pending: *std.ArrayList(ExprWork), frame: *ExprFrame) Error!void { + const start = p.peek().pos; + const t = p.peek(); + frame.tail_result = null; + if (isWord(t, "let")) { + _ = p.next(); + var names: std.ArrayList([]const u8) = .empty; + const tuple = p.peek().tag == .l_paren; + if (tuple) { + _ = p.next(); + while (p.peek().tag != .r_paren) { + try names.append(p.arena, if (p.peek().tag == .underscore) p.next().text else try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + } else try names.append(p.arena, try p.ident("a name")); + var ty: ?ast.Type = null; + if (p.peek().tag == .colon) { + _ = p.next(); + ty = try p.typeExpr(); + } + _ = try p.expect(.eq, "`=`"); + return p.queueStatement(pending, .{ .start = start, .kind = .{ .let = .{ .names = names.items, .ty = ty, .tuple = tuple } } }, .binary, true); + } + const unchecked_borrow = isWord(p.peekAt(1), "unchecked") and p.peekAt(2).tag == .ident and p.peekAt(3).tag == .eq; + if ((isWord(t, "ref") or isWord(t, "mut")) and ((p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) or unchecked_borrow)) { + _ = p.next(); + if (unchecked_borrow) _ = p.next(); + const name = try p.ident("a name for the borrow"); + _ = try p.expect(.eq, "`=`"); + return p.queueStatement(pending, .{ .start = start, .kind = .{ .borrow = .{ .name = name, .mutable = isWord(t, "mut"), .unchecked = unchecked_borrow } } }, .binary, false); + } + if (isWord(t, "var")) { + _ = p.next(); + const name = try p.ident("a name"); + if (p.peek().tag == .eq) return p.failAdvice(p.peek(), "`:` and the variable's type", .annotate_var_type); + _ = try p.expect(.colon, "`:` and the variable's type"); + const ty = try p.typeExpr(); + _ = try p.expect(.eq, "`=`"); + if (p.atWord("zero")) { + _ = p.next(); + _ = try p.expect(.semicolon, "`;`"); + frame.stmt_result = .{ .span = p.span(start), .kind = .{ .@"var" = .{ .name = name, .ty = ty, .init = null } } }; + return; + } + return p.queueStatement(pending, .{ .start = start, .kind = .{ .@"var" = .{ .name = name, .ty = ty } } }, .binary, true); + } + if (isWord(t, "break") or isWord(t, "continue") or isWord(t, "trap")) { + _ = p.next(); + _ = try p.expect(.semicolon, "`;`"); + const k: @FieldType(ast.Stmt, "kind") = if (isWord(t, "break")) .@"break" else if (isWord(t, "continue")) .@"continue" else .trap; + frame.stmt_result = .{ .span = p.span(start), .kind = k }; + return; + } + if (isWord(t, "return")) { + _ = p.next(); + if (p.peek().tag == .semicolon) { + _ = try p.expect(.semicolon, "`;`"); + frame.stmt_result = .{ .span = p.span(start), .kind = .{ .@"return" = null } }; + return; + } + return p.queueStatement(pending, .{ .start = start, .kind = .@"return" }, .binary, false); + } + if (isWord(t, "while")) { + _ = p.next(); + return p.queueStatement(pending, .{ .start = start, .kind = .while_cond }, .condition, false); + } + if (isWord(t, "for")) { + _ = p.next(); + const name = try p.ident("loop variable"); + _ = try p.expectWord("in"); + const saved = p.no_struct; + p.no_struct = true; + return p.queueStatement(pending, .{ .start = start, .kind = .{ .for_lo = .{ .name = name, .saved = saved } } }, .binary, false); + } + if (isWord(t, "loop")) { + _ = p.next(); + return p.queueStatement(pending, .{ .start = start, .kind = .loop }, .block, false); + } + if (isWord(t, "scope")) { + _ = p.next(); + const name = try p.ident("scope name"); + return p.queueStatement(pending, .{ .start = start, .kind = .{ .scope = name } }, .block, false); + } + if (isWord(t, "shield")) { + _ = p.next(); + return p.queueStatement(pending, .{ .start = start, .kind = .shield }, .block, false); + } + if (isWord(t, "lock")) { + _ = p.next(); + _ = try p.expectWord("ref"); + const saved = p.no_struct; + p.no_struct = true; + return p.queueStatement(pending, .{ .start = start, .kind = .{ .lock_place = saved } }, .unary, false); + } + if (isWord(t, "select")) return p.queueStatement(pending, .{ .start = start, .kind = .select }, .select, false); + const bare = isWord(t, "if") or isWord(t, "match") or t.tag == .l_brace; + return p.queueStatement(pending, .{ .start = start, .kind = .{ .expr = bare } }, if (bare) .primary else .binary, false); + } + + fn resumeStatement(p: *Parser, pending: *std.ArrayList(ExprWork), frame: *ExprFrame, ctx: StatementContext) Error!void { + const e = &frame.result; + const kind: @FieldType(ast.Stmt, "kind") = switch (ctx.kind) { + .let => |x| blk: { + _ = try p.expect(.semicolon, "`;`"); + break :blk .{ .let = .{ .names = x.names, .ty = x.ty, .tuple = x.tuple, .e = e.* } }; + }, + .@"var" => |x| blk: { + _ = try p.expect(.semicolon, "`;`"); + break :blk .{ .@"var" = .{ .name = x.name, .ty = x.ty, .init = e.* } }; + }, + .borrow => |x| blk: { + _ = try p.expect(.semicolon, "`;`"); + break :blk .{ .borrow = .{ .name = x.name, .mutable = x.mutable, .unchecked = x.unchecked, .place = e.* } }; + }, + .@"return" => blk: { + _ = try p.expect(.semicolon, "`;`"); + break :blk .{ .@"return" = e.* }; + }, + .assign => |place| blk: { + _ = try p.expect(.semicolon, "`;`"); + break :blk .{ .assign = .{ .place = place, .e = e.* } }; + }, + .expr => |bare| blk: { + if (bare) { + if (p.peek().tag == .r_brace) { + frame.tail_result = try p.box(ast.Expr, e.*); + frame.stmt_result = null; + return; + } + const discard = p.peek().tag == .semicolon; + if (discard) _ = p.next(); + frame.stmt_result = .{ .span = p.span(ctx.start), .block_statement = !discard, .kind = .{ .expr = e.* } }; + return; + } + if (p.peek().tag == .eq) { + _ = p.next(); + return p.queueStatement(pending, .{ .start = ctx.start, .kind = .{ .assign = e.* } }, .binary, false); + } + if (p.peek().tag == .semicolon) { + _ = p.next(); + break :blk .{ .expr = e.* }; + } + if (p.peek().tag == .r_brace) { + frame.tail_result = try p.box(ast.Expr, e.*); + frame.stmt_result = null; + return; + } + switch (e.kind) { + .if_expr, .match_expr, .block => break :blk .{ .expr = e.* }, + else => return p.fail(p.peek(), "`;`"), + } + }, + .while_cond => return p.queueStatement(pending, .{ .start = ctx.start, .kind = .{ .while_body = e.* } }, .block, false), + .while_body => |cond| .{ .@"while" = .{ .cond = cond, .body = frame.block_result } }, + .for_lo => |x| { + _ = try p.expect(.dot_dot, "`..`"); + return p.queueStatement(pending, .{ .start = ctx.start, .kind = .{ .for_hi = .{ .name = x.name, .lo = e.*, .saved = x.saved } } }, .binary, false); + }, + .for_hi => |x| { + p.no_struct = x.saved; + return p.queueStatement(pending, .{ .start = ctx.start, .kind = .{ .for_body = .{ .name = x.name, .lo = x.lo, .hi = e.* } } }, .block, false); + }, + .for_body => |x| .{ .@"for" = .{ .name = x.name, .lo = x.lo, .hi = x.hi, .body = frame.block_result } }, + .loop => .{ .loop = frame.block_result }, + .scope => |name| .{ .scope = .{ .name = name, .body = frame.block_result } }, + .shield => .{ .shield = frame.block_result }, + .lock_place => |saved| { + p.no_struct = saved; + _ = try p.expectWord("as"); + const name = try p.ident("a name for the locked data"); + return p.queueStatement(pending, .{ .start = ctx.start, .kind = .{ .lock_body = .{ .place = e.*, .name = name } } }, .block, false); + }, + .lock_body => |x| { + _ = try p.expectWord("cancelled"); + return p.queueStatement(pending, .{ .start = ctx.start, .kind = .{ .lock_cancelled = .{ .place = x.place, .name = x.name, .body = frame.block_result } } }, .block, false); + }, + .lock_cancelled => |x| .{ .lock = .{ .place = x.place, .name = x.name, .body = x.body, .cancelled = frame.block_result } }, + .select => .{ .select = frame.select_result }, + }; + frame.stmt_result = .{ .span = p.span(ctx.start), .kind = kind }; + } + + fn controlStep(p: *Parser, pending: *std.ArrayList(ExprWork), frame: *ExprFrame, work: ControlWork) Error!void { + switch (work) { + .block_next => |ctx| { + if (p.peek().tag == .r_brace) { + _ = try p.expect(.r_brace, "`}`"); + frame.block_result = .{ .stmts = ctx.stmts.items, .tail = null, .span = p.span(ctx.start) }; + } else { + if (p.peek().tag == .eof) return p.fail(p.peek(), "`}`"); + try p.queueControl(pending, .{ .block_got = ctx }); + try p.queueEntry(pending, .statement); + } + }, + .block_got => |ctx| { + var updated = ctx; + if (frame.stmt_result) |stmt| { + try updated.stmts.append(p.arena, stmt); + try p.queueControl(pending, .{ .block_next = updated }); + } else { + _ = try p.expect(.r_brace, "`}`"); + frame.block_result = .{ .stmts = updated.stmts.items, .tail = frame.tail_result, .span = p.span(updated.start) }; + } + }, + .statement_got => |ctx| try p.resumeStatement(pending, frame, ctx), + .block_expr => |start| frame.result = .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, frame.block_result) } }, + .if_expr => |start| frame.result = .{ .span = p.span(start), .kind = .{ .if_expr = try p.box(ast.If, frame.if_result) } }, + .restore_condition => |saved| p.no_struct = saved, + .if_cond => { + try p.queueControl(pending, .{ .if_then = frame.result }); + try p.queueEntry(pending, .block); + }, + .if_then => |cond| { + if (p.atWord("else")) { + _ = p.next(); + const chained = p.atWord("if"); + try p.queueControl(pending, .{ .if_else = .{ .cond = cond, .then = frame.block_result, .chained = chained } }); + try p.queueEntry(pending, if (chained) .conditional else .block); + } else frame.if_result = .{ .cond = cond, .then = frame.block_result, .@"else" = null }; + }, + .if_else => |ctx| { + // Boxing must read the complete child before overwriting the + // reused result slot with the enclosing conditional. + const els: ast.Else = if (ctx.chained) .{ .@"if" = try p.box(ast.If, frame.if_result) } else .{ .block = frame.block_result }; + frame.if_result = .{ .cond = ctx.cond, .then = ctx.then, .@"else" = els }; + }, + .match_cond => |start| { + _ = try p.expect(.l_brace, "`{`"); + try p.queueControl(pending, .{ .match_arms = .{ .start = start, .scrutinee = frame.result } }); + try p.queueEntry(pending, .arms); + }, + .match_arms => |ctx| { + var kind: ast.Match.Kind = .integer; + for (frame.arms_result) |a| switch (a.pattern.kind) { + .ctor => |c| { + kind = if (c.qualifier != null) .@"enum" else .outcome; + break; + }, + else => {}, + }; + frame.result = .{ .span = p.span(ctx.start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = ctx.scrutinee, .arms = frame.arms_result, .span = p.span(ctx.start), .kind = kind }) } }; + }, + .arms_next => |list| { + if (p.peek().tag == .r_brace) { + _ = p.next(); + frame.arms_result = list.items; + } else { + const pat = try p.pattern(); + _ = try p.expect(.fat_arrow, "`=>`"); + try p.queueControl(pending, .{ .arm_got = .{ .arms = list, .pattern = pat } }); + try p.queueEntry(pending, .arm_body); + } + }, + .arm_got => |ctx| { + var list = ctx.arms; + try list.append(p.arena, .{ .pattern = ctx.pattern, .body = frame.result }); + try p.queueControl(pending, .{ .arms_next = list }); + }, + .arm_body => |start| { + if (start) |pos| { + if (p.peek().tag == .comma) _ = p.next(); + frame.result = .{ .span = p.span(pos), .kind = .{ .block = try p.box(ast.Block, frame.block_result) } }; + } else if (p.peek().tag == .comma) { + _ = p.next(); + } else if (p.peek().tag != .r_brace) return p.fail(p.peek(), "`,` after the arm"); + }, + .select_next => |ctx| { + if (p.atWord("recv") or p.atWord("send")) { + const start = p.peek().pos; + const send = p.atWord("send"); + _ = p.next(); + _ = try p.expect(.l_paren, "`(`"); + const endpoint = try p.ident("an endpoint name"); + const header: SelectHeader = .{ .context = ctx, .start = start, .send = send, .endpoint = endpoint }; + if (send) { + _ = try p.expect(.comma, "`,` and the value to send"); + try p.queueControl(pending, .{ .select_value = header }); + try p.queueEntry(pending, .binary); + } else try p.finishSelectHeader(pending, header); + } else { + _ = try p.expectWord("cancelled"); + var binds: std.ArrayList([]const u8) = .empty; + if (p.peek().tag == .l_paren) { + _ = p.next(); + while (p.peek().tag != .r_paren) { + try binds.append(p.arena, try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + } + _ = try p.expect(.fat_arrow, "`=>`"); + try p.queueControl(pending, .{ .select_cancelled = .{ .context = ctx, .binds = binds.items } }); + try p.queueEntry(pending, .arm_body); + } + }, + .select_value => |ctx| { + var header = ctx; + header.value = frame.result; + try p.finishSelectHeader(pending, header); + }, + .select_arms => |ctx| { + var updated = ctx.context; + try updated.arms.append(p.arena, .{ .span = p.span(ctx.start), .send = ctx.send, .endpoint = ctx.endpoint, .value = ctx.value, .arms = frame.arms_result }); + try p.queueControl(pending, .{ .select_next = updated }); + }, + .select_cancelled => |ctx| { + _ = try p.expect(.r_brace, "`}`"); + frame.select_result = .{ .arms = ctx.context.arms.items, .cancelled_binds = ctx.binds, .cancelled = frame.result, .span = p.span(ctx.context.start) }; + }, + } + } + + fn finishSelectHeader(p: *Parser, pending: *std.ArrayList(ExprWork), ctx: SelectHeader) Error!void { + _ = try p.expect(.r_paren, "`)`"); + _ = try p.expect(.l_brace, "`{` with the arm's outcomes"); + try p.queueControl(pending, .{ .select_arms = ctx }); + try p.queueEntry(pending, .arms); + } + const ExprWork = union(enum) { - enter: struct { kind: ExprEntry, min_prec: u8 = 0 }, + control: ControlWork, + enter: struct { kind: ParseEntry, min_prec: u8 = 0 }, binary: ExprBinary, rhs: struct { context: ExprBinary, lhs: ast.Expr, info: BinInfo }, cast: lex.Pos, @@ -955,28 +1134,29 @@ const Parser = struct { index_lo: ExprIndex, index_hi: struct { context: ExprIndex, lo: ast.Expr }, }; - const ExprFrame = struct { work: ExprWork, result: ast.Expr }; + const ExprFrame = struct { + work: ExprWork, + result: ast.Expr, + block_result: ast.Block, + if_result: ast.If, + stmt_result: ?ast.Stmt, + tail_result: ?*const ast.Expr, + arms_result: []const ast.Arm, + select_result: ast.Select, + }; fn deinitExpressionWork(p: *Parser) void { - for (p.expr_frames.items) |frame| p.arena.destroy(frame); - p.expr_frames.deinit(p.arena); + if (p.expr_frame) |frame| p.arena.destroy(frame); + p.expr_frame = null; p.expr_work.deinit(p.arena); } - fn expressionFrame(p: *Parser) Error!*ExprFrame { - if (p.expr_frame_depth == p.expr_frames.items.len) { - const frame = try p.arena.create(ExprFrame); - errdefer p.arena.destroy(frame); - try p.expr_frames.append(p.arena, frame); - } - const frame = p.expr_frames.items[p.expr_frame_depth]; - p.expr_frame_depth += 1; - return frame; - } - fn restoreExpressionScopes(p: *Parser, base: usize) void { while (p.expr_work.items.len > base) { switch (p.expr_work.pop().?) { + .control => |work| if (work == .restore_condition) { + p.no_struct = work.restore_condition; + }, .restore_call => |saved| p.no_struct = saved, .restore_advice => |saved| p.borrow_advice = saved, else => {}, @@ -985,33 +1165,65 @@ const Parser = struct { } fn expressionDriver(p: *Parser, entry: ExprEntry, min_prec: u8) Error!ast.Expr { + const request: ParseEntry = switch (entry) { + .binary => .binary, + .cast => .cast, + .unary => .unary, + .postfix => .postfix, + .primary => .primary, + }; + return (try p.parseDriver(request, min_prec)).result; + } + + fn parseDriver(p: *Parser, entry: ParseEntry, min_prec: u8) Error!*ExprFrame { const pending = &p.expr_work; const base = pending.items.len; - const frame = try p.expressionFrame(); - defer p.expr_frame_depth -= 1; - // Only callArgs and argument advice had deferred restoration in the - // former parser. Group/index restoration remains success-only. + // Children queue continuations instead of re-entering this driver. + std.debug.assert(!p.driver_active and base == 0); + if (p.expr_frame == null) p.expr_frame = try p.arena.create(ExprFrame); + const frame = p.expr_frame.?; + p.driver_active = true; + defer p.driver_active = false; + // Calls, advice and conditions restore on every exit as before. + // Group/index and for/lock prefix restoration remain success-only. errdefer p.restoreExpressionScopes(base); try pending.append(p.arena, .{ .enter = .{ .kind = entry, .min_prec = min_prec } }); while (pending.items.len > base) { frame.work = pending.items[pending.items.len - 1]; pending.items.len -= 1; - // Control/block helpers still re-enter expression parsing. Keep - // their native call outside the large per-step dispatch frame. - if (frame.work == .enter and frame.work.enter.kind == .primary and - (p.peek().tag == .l_brace or p.atWord("if") or p.atWord("match"))) - { - frame.result = try p.primaryAtom(); - } else try p.expressionStep(pending, &frame.result, &frame.work); + switch (frame.work) { + .control => |work| try p.controlStep(pending, frame, work), + .enter => |request| switch (request.kind) { + .block, .statement, .condition, .conditional, .arms, .arm_body, .select => try p.controlEntry(pending, frame, request.kind), + .primary => { + const start = p.peek().pos; + if (p.peek().tag == .l_brace) { + try p.queueControl(pending, .{ .block_expr = start }); + try p.queueEntry(pending, .block); + } else if (p.atWord("if")) { + try p.queueControl(pending, .{ .if_expr = start }); + try p.queueEntry(pending, .conditional); + } else if (p.atWord("match")) { + _ = p.next(); + try p.queueControl(pending, .{ .match_cond = start }); + try p.queueEntry(pending, .condition); + } else try p.expressionStep(pending, &frame.result, &frame.work); + }, + else => try p.expressionStep(pending, &frame.result, &frame.work), + }, + else => try p.expressionStep(pending, &frame.result, &frame.work), + } } - return frame.result; + return frame; } fn expressionStep(p: *Parser, pending: *std.ArrayList(ExprWork), result: *ast.Expr, work: *const ExprWork) Error!void { switch (work.*) { + .control => unreachable, .enter => |request| { const start = p.peek().pos; switch (request.kind) { + .block, .statement, .condition, .conditional, .arms, .arm_body, .select => unreachable, .binary => { try pending.append(p.arena, .{ .binary = .{ .start = start, .min_prec = request.min_prec } }); try pending.append(p.arena, .{ .enter = .{ .kind = .cast } }); @@ -1278,18 +1490,6 @@ const Parser = struct { return p.expressionDriver(.binary, min_prec); } - fn unary(p: *Parser) Error!ast.Expr { - return p.expressionDriver(.unary, 0); - } - - fn postfix(p: *Parser) Error!ast.Expr { - return p.expressionDriver(.postfix, 0); - } - - fn primary(p: *Parser) Error!ast.Expr { - return p.expressionDriver(.primary, 0); - } - fn pathTail(p: *Parser, first: []const u8) Error![]const u8 { if (p.peek().tag != .dot) return first; var name: std.ArrayList(u8) = .empty; @@ -1344,34 +1544,13 @@ const Parser = struct { const b = (try lex.decodeBytes(p.arena, t.text)) orelse return p.fail(t, "a byte string with valid escapes"); return .{ .span = p.span(start), .kind = .{ .bytes = b } }; }, - .l_brace => { - const b = try p.block(); - return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; - }, + .l_brace => unreachable, .ident => { if (isWord(t, "true") or isWord(t, "false")) { _ = p.next(); return .{ .span = p.span(start), .kind = .{ .boolean = isWord(t, "true") } }; } - if (isWord(t, "if")) { - const conditional = try p.box(ast.If, try p.ifExpr()); - return .{ .span = p.span(start), .kind = .{ .if_expr = conditional } }; - } - if (isWord(t, "match")) { - _ = p.next(); - const scrut = try p.condition(); - _ = try p.expect(.l_brace, "`{`"); - const as = try p.arms(); - var kind: ast.Match.Kind = .integer; - for (as) |a| switch (a.pattern.kind) { - .ctor => |c| { - kind = if (c.qualifier != null) .@"enum" else .outcome; - break; - }, - else => {}, - }; - return .{ .span = p.span(start), .kind = .{ .match_expr = try p.box(ast.Match, .{ .scrutinee = scrut, .arms = as, .span = p.span(start), .kind = kind }) } }; - } + if (isWord(t, "if") or isWord(t, "match")) unreachable; if (isKeyword(t.text) and !(isWord(t, "struct") and p.peekAt(1).tag == .dot and isWord(p.peekAt(2), "unpack"))) return p.failPrimary(t); _ = p.next(); if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) { @@ -1384,20 +1563,6 @@ const Parser = struct { else => return p.failPrimary(t), } } - - fn ifExpr(p: *Parser) Error!ast.If { - _ = p.next(); // `if` - const cond = try p.condition(); - const then = try p.block(); - var els: ?ast.Else = null; - if (p.atWord("else")) { - _ = p.next(); - if (p.atWord("if")) { - els = .{ .@"if" = try p.box(ast.If, try p.ifExpr()) }; - } else els = .{ .block = try p.block() }; - } - return .{ .cond = cond, .then = then, .@"else" = els }; - } }; const keywords = [_][]const u8{ @@ -1908,7 +2073,7 @@ const ReferenceExpressions = struct { return .{ .span = p.span(start), .kind = .{ .array_rep = .{ .e = try p.box(ast.Expr, e), .len = @intCast(len) } } }; }, .l_brace => { - const b = try p.block(); + const b = try ReferenceControl.block(p); return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; }, .ident => { @@ -1917,14 +2082,14 @@ const ReferenceExpressions = struct { return .{ .span = p.span(start), .kind = .{ .boolean = Parser.isWord(t, "true") } }; } if (Parser.isWord(t, "if")) { - const conditional = try p.box(ast.If, try p.ifExpr()); + const conditional = try p.box(ast.If, try ReferenceControl.ifExpr(p)); return .{ .span = p.span(start), .kind = .{ .if_expr = conditional } }; } if (Parser.isWord(t, "match")) { _ = p.next(); - const scrut = try p.condition(); + const scrut = try ReferenceControl.condition(p); _ = try p.expect(.l_brace, "`{`"); - const as = try p.arms(); + const as = try ReferenceControl.arms(p); var kind: ast.Match.Kind = .integer; for (as) |a| switch (a.pattern.kind) { .ctor => |c| { @@ -2016,34 +2181,34 @@ test "expression continuations match independent shallow descent and contextual }; } -test "expression callbacks reuse stable work frames without retaining output pointers" { +test "control and expression continuations reuse one frame without retaining output pointers" { var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const source = "f(if true { g(x[0u8..y]) } else { g(y) }, Record { field: [1u8; 2] })"; + const source = "f(if true { g(x[0u8..y]) } else { g(y) }, { let x = match e { ok(v) => { v }, closed => { y } }; select { recv(rx) { ok(v) => { f(v); }, closed => {} } cancelled(a,) => { f(a); } } lock ref m as v { g(v); } cancelled { trap; } x }, Record { field: [1u8; 2] })"; const tokens = try lex.tokenize(a, source); var old: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .no_struct = true }; const reference = try ReferenceExpressions.expr(&old); var p: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .no_struct = true }; const first = try p.expr(); - const frames = p.expr_frames.items.len; + const frame = p.expr_frame.?; const capacity = p.expr_work.capacity; - try std.testing.expect(frames >= 2); + for (0..64) |_| { p.pos = 0; p.last_end = null; try std.testing.expectEqualDeep(reference, try p.expr()); try std.testing.expectEqualDeep(reference, first); - try std.testing.expectEqual(frames, p.expr_frames.items.len); + try std.testing.expect(frame == p.expr_frame.?); try std.testing.expectEqual(capacity, p.expr_work.capacity); - try std.testing.expectEqual(@as(usize, 0), p.expr_frame_depth); + try std.testing.expect(!p.driver_active); try std.testing.expectEqual(@as(usize, 0), p.expr_work.items.len); try std.testing.expect(p.no_struct); try std.testing.expect(p.borrow_advice == null); } // Returned ASTs must not point into driver or queue storage. Poison all // scratch bytes before reading the first result and destroying scratch. - for (p.expr_frames.items) |frame| @memset(std.mem.asBytes(frame), 0xa5); + @memset(std.mem.asBytes(frame), 0xa5); @memset(std.mem.sliceAsBytes(p.expr_work.items.ptr[0..p.expr_work.capacity]), 0xa5); try std.testing.expectEqualDeep(reference, first); p.deinitExpressionWork(); @@ -2138,19 +2303,21 @@ test "mixed deep expression syntax retains every constructor span and leaf error try std.testing.expectEqualDeep(diag.SourceRepairKind.boolean_negation.one(), failure.err.repair_candidates); } -// Fail one direct allocation and then recover; retries cannot mask lost work. +// Fail a direct allocation, once or persistently. Resize/remap are disabled +// so every worklist growth is an injection point; retries cannot mask lost work. const ExpressionAllocationFailure = struct { backing: Allocator, at: usize, attempts: usize = 0, failed: bool = false, + sticky: bool = false, fn allocator(self: *@This()) Allocator { return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; } fn alloc(raw: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { const self: *@This() = @ptrCast(@alignCast(raw)); self.attempts += 1; - if (self.attempts == self.at + 1) { + if (self.attempts >= self.at + 1 and (self.sticky or self.attempts == self.at + 1)) { self.failed = true; return null; } @@ -2190,7 +2357,7 @@ test "expression metadata output and nested scopes propagate recovering host OOM } try std.testing.expect(p.failure == null); try std.testing.expect(p.no_struct); - try std.testing.expectEqual(@as(usize, 0), p.expr_frame_depth); + try std.testing.expect(!p.driver_active); try std.testing.expectEqual(@as(usize, 0), p.expr_work.items.len); try std.testing.expectEqualDeep(@as(@FieldType(Parser, "borrow_advice"), .{ .at = 0, .kind = .borrow_binding }), p.borrow_advice); if (!failure.failed) break; @@ -2226,7 +2393,7 @@ fn referenceUnary(p: *Parser) Error!ast.Expr { _ = p.next(); unchecked = true; } - const place = if (p.peek().tag == .star) try referenceUnary(p) else try p.postfix(); + const place = if (p.peek().tag == .star) try referenceUnary(p) else try p.expressionDriver(.postfix, 0); 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")) { @@ -2234,7 +2401,7 @@ fn referenceUnary(p: *Parser) Error!ast.Expr { const name = try p.ident("the name of the value to move"); return .{ .span = p.span(start), .kind = .{ .move = name } }; } - return p.postfix(); + return p.expressionDriver(.postfix, 0); } test "unary continuations retain shallow syntax, ranges and exact failures" { @@ -2249,7 +2416,7 @@ test "unary continuations retain shallow syntax, ranges and exact failures" { 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(); + const actual = current.expressionDriver(.unary, 0); if (expected) |expression| { try std.testing.expectEqualDeep(expression, try actual); } else |err| { @@ -2653,3 +2820,714 @@ test "type parser metadata failures propagate without exposing a partial AST" { if (!failing.has_induced_failure) break; } } + +const ReferenceControl = struct { + fn block(p: *Parser) Error!ast.Block { + const start = (try p.expect(.l_brace, "`{`")).pos; + var stmts: std.ArrayList(ast.Stmt) = .empty; + var tail: ?*const ast.Expr = null; + while (p.peek().tag != .r_brace) { + if (p.peek().tag == .eof) return p.fail(p.peek(), "`}`"); + if (try statement(p, &tail)) |s| { + try stmts.append(p.arena, s); + } else break; // a tail expression ends the block + } + _ = try p.expect(.r_brace, "`}`"); + return .{ .stmts = stmts.items, .tail = tail, .span = p.span(start) }; + } + + /// Parses one statement; returns null after setting `tail` when the + /// block ends with an expression without `;`. + fn statement(p: *Parser, tail: *?*const ast.Expr) Error!?ast.Stmt { + const start = p.peek().pos; + const t = p.peek(); + if (Parser.isWord(t, "let")) { + _ = p.next(); + var names: std.ArrayList([]const u8) = .empty; + const tuple = p.peek().tag == .l_paren; + if (tuple) { + _ = p.next(); + while (p.peek().tag != .r_paren) { + try names.append(p.arena, if (p.peek().tag == .underscore) p.next().text else try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + } else try names.append(p.arena, try p.ident("a name")); + var ty: ?ast.Type = null; + if (p.peek().tag == .colon) { + _ = p.next(); + ty = try p.typeExpr(); + } + _ = try p.expect(.eq, "`=`"); + const e = try ReferenceExpressions.exprWithBorrowAdvice(p, .borrow_binding); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .let = .{ .names = names.items, .ty = ty, .e = e, .tuple = tuple } } }; + } + const unchecked_borrow = Parser.isWord(p.peekAt(1), "unchecked") and p.peekAt(2).tag == .ident and p.peekAt(3).tag == .eq; + if ((Parser.isWord(t, "ref") or Parser.isWord(t, "mut")) and ((p.peekAt(1).tag == .ident and p.peekAt(2).tag == .eq) or unchecked_borrow)) { + _ = p.next(); + if (unchecked_borrow) _ = p.next(); + const name = try p.ident("a name for the borrow"); + _ = try p.expect(.eq, "`=`"); + const place = try ReferenceExpressions.expr(p); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .borrow = .{ .mutable = Parser.isWord(t, "mut"), .unchecked = unchecked_borrow, .name = name, .place = place } } }; + } + if (Parser.isWord(t, "var")) { + _ = p.next(); + const name = try p.ident("a name"); + if (p.peek().tag == .eq) return p.failAdvice(p.peek(), "`:` and the variable's type", .annotate_var_type); + _ = try p.expect(.colon, "`:` and the variable's type"); + const ty = try p.typeExpr(); + _ = try p.expect(.eq, "`=`"); + var init: ?ast.Expr = null; + if (p.atWord("zero")) { + _ = p.next(); + } else init = try ReferenceExpressions.exprWithBorrowAdvice(p, .borrow_binding); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .@"var" = .{ .name = name, .ty = ty, .init = init } } }; + } + if (Parser.isWord(t, "break") or Parser.isWord(t, "continue") or Parser.isWord(t, "trap")) { + _ = p.next(); + _ = try p.expect(.semicolon, "`;`"); + const k: @FieldType(ast.Stmt, "kind") = if (Parser.isWord(t, "break")) .@"break" else if (Parser.isWord(t, "continue")) .@"continue" else .trap; + return .{ .span = p.span(start), .kind = k }; + } + if (Parser.isWord(t, "return")) { + _ = p.next(); + var e: ?ast.Expr = null; + if (p.peek().tag != .semicolon) e = try ReferenceExpressions.expr(p); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .@"return" = e } }; + } + if (Parser.isWord(t, "while")) { + _ = p.next(); + const cond = try condition(p); + const body = try block(p); + return .{ .span = p.span(start), .kind = .{ .@"while" = .{ .cond = cond, .body = body } } }; + } + if (Parser.isWord(t, "for")) { + _ = p.next(); + const name = try p.ident("loop variable"); + _ = try p.expectWord("in"); + const saved = p.no_struct; + p.no_struct = true; + const lo = try ReferenceExpressions.binary(p, 0); + _ = try p.expect(.dot_dot, "`..`"); + const hi = try ReferenceExpressions.binary(p, 0); + p.no_struct = saved; + const body = try block(p); + return .{ .span = p.span(start), .kind = .{ .@"for" = .{ .name = name, .lo = lo, .hi = hi, .body = body } } }; + } + if (Parser.isWord(t, "loop")) { + _ = p.next(); + const body = try block(p); + return .{ .span = p.span(start), .kind = .{ .loop = body } }; + } + if (Parser.isWord(t, "scope")) { + _ = p.next(); + const name = try p.ident("scope name"); + const body = try block(p); + return .{ .span = p.span(start), .kind = .{ .scope = .{ .name = name, .body = body } } }; + } + if (Parser.isWord(t, "shield")) { + _ = p.next(); + const body = try block(p); + return .{ .span = p.span(start), .kind = .{ .shield = body } }; + } + if (Parser.isWord(t, "lock")) { + _ = p.next(); + _ = try p.expectWord("ref"); + const saved = p.no_struct; + p.no_struct = true; + const place = try ReferenceExpressions.unary(p); + p.no_struct = saved; + _ = try p.expectWord("as"); + const name = try p.ident("a name for the locked data"); + const body = try block(p); + _ = try p.expectWord("cancelled"); + const cancelled = try block(p); + return .{ .span = p.span(start), .kind = .{ .lock = .{ .place = place, .name = name, .body = body, .cancelled = cancelled } } }; + } + if (Parser.isWord(t, "select")) { + const selection = try selectStmt(p); + return .{ .span = p.span(start), .kind = .{ .select = selection } }; + } + + // A leading bare block construct has priority over an outer expression + // continuation in statement/tail position (spec 15 §4). Recursive + // expression contexts still use expr(), including parentheses. + if (Parser.isWord(t, "if") or Parser.isWord(t, "match") or t.tag == .l_brace) { + const e = try ReferenceExpressions.primary(p); + if (p.peek().tag == .r_brace) { + tail.* = try p.box(ast.Expr, e); + return null; + } + const discard = p.peek().tag == .semicolon; + if (discard) _ = p.next(); + return .{ .span = p.span(start), .block_statement = !discard, .kind = .{ .expr = e } }; + } + + // Expression statement, assignment or tail expression. + const e = try ReferenceExpressions.expr(p); + if (p.peek().tag == .eq) { + _ = p.next(); + const rhs = try ReferenceExpressions.expr(p); + _ = try p.expect(.semicolon, "`;`"); + return .{ .span = p.span(start), .kind = .{ .assign = .{ .place = e, .e = rhs } } }; + } + if (p.peek().tag == .semicolon) { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .expr = e } }; + } + if (p.peek().tag == .r_brace) { + tail.* = try p.box(ast.Expr, e); + return null; + } + // Block-like expressions end without `;`. + switch (e.kind) { + .if_expr, .match_expr, .block => return .{ .span = p.span(start), .kind = .{ .expr = e } }, + else => return p.fail(p.peek(), "`;`"), + } + } + + fn condition(p: *Parser) Error!ast.Expr { + const saved = p.no_struct; + p.no_struct = true; + defer p.no_struct = saved; + return ReferenceExpressions.expr(p); + } + + fn selectStmt(p: *Parser) Error!ast.Select { + const start = p.next().pos; // `select` + _ = try p.expect(.l_brace, "`{`"); + var sel_arms: std.ArrayList(ast.SelectArm) = .empty; + while (p.atWord("recv") or p.atWord("send")) { + const astart = p.peek().pos; + const is_send = p.atWord("send"); + _ = p.next(); + _ = try p.expect(.l_paren, "`(`"); + const ep = try p.ident("an endpoint name"); + var value: ?ast.Expr = null; + if (is_send) { + _ = try p.expect(.comma, "`,` and the value to send"); + value = try ReferenceExpressions.expr(p); + } + _ = try p.expect(.r_paren, "`)`"); + _ = try p.expect(.l_brace, "`{` with the arm's outcomes"); + const outcomes = try arms(p); + try sel_arms.append(p.arena, .{ .span = p.span(astart), .send = is_send, .endpoint = ep, .value = value, .arms = outcomes }); + } + _ = try p.expectWord("cancelled"); + var binds: std.ArrayList([]const u8) = .empty; + if (p.peek().tag == .l_paren) { + _ = p.next(); + while (p.peek().tag != .r_paren) { + try binds.append(p.arena, try p.ident("a name")); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + } + _ = try p.expect(.fat_arrow, "`=>`"); + const body = try armBody(p); + _ = try p.expect(.r_brace, "`}`"); + return .{ .arms = sel_arms.items, .cancelled_binds = binds.items, .cancelled = body, .span = p.span(start) }; + } + + /// Arms up to and including the closing `}`. + fn arms(p: *Parser) Error![]const ast.Arm { + var out: std.ArrayList(ast.Arm) = .empty; + while (p.peek().tag != .r_brace) { + const pat = try p.pattern(); + _ = try p.expect(.fat_arrow, "`=>`"); + try out.append(p.arena, .{ .pattern = pat, .body = try armBody(p) }); + } + _ = p.next(); + return out.items; + } + + fn armBody(p: *Parser) Error!ast.Expr { + if (p.peek().tag == .l_brace) { + const start = p.peek().pos; + const b = try block(p); + if (p.peek().tag == .comma) _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; + } + const e = try ReferenceExpressions.expr(p); + if (p.peek().tag == .comma) { + _ = p.next(); + } else if (p.peek().tag != .r_brace) return p.fail(p.peek(), "`,` after the arm"); + return e; + } + + fn ifExpr(p: *Parser) Error!ast.If { + _ = p.next(); // `if` + const cond = try condition(p); + const then = try block(p); + var els: ?ast.Else = null; + if (p.atWord("else")) { + _ = p.next(); + if (p.atWord("if")) { + els = .{ .@"if" = try p.box(ast.If, try ifExpr(p)) }; + } else els = .{ .block = try block(p) }; + } + return .{ .cond = cond, .then = then, .@"else" = els }; + } +}; + +fn expectControlParseMatches(a: Allocator, source: []const u8, no_struct: bool) !void { + return expectControlTokensMatch(a, try lex.tokenize(a, source), no_struct); +} + +fn expectControlTokensMatch(a: Allocator, tokens: []const Token, no_struct: bool) !void { + const advice: @FieldType(Parser, "borrow_advice") = .{ .at = 0, .kind = .borrow_argument }; + var old: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .file = "control.aji", .module_name = "module", .no_struct = no_struct, .borrow_advice = advice }; + defer old.deinitExpressionWork(); + var current: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .file = "control.aji", .module_name = "module", .no_struct = no_struct, .borrow_advice = advice }; + defer current.deinitExpressionWork(); + const expected = ReferenceControl.block(&old); + const actual = current.block(); + if (expected) |b| try std.testing.expectEqualDeep(b, try actual) else |err| try std.testing.expectError(err, actual); + try std.testing.expectEqual(old.pos, current.pos); + try std.testing.expectEqualDeep(old.last_end, current.last_end); + try std.testing.expectEqualDeep(old.failure, current.failure); + try std.testing.expectEqual(old.no_struct, current.no_struct); + try std.testing.expectEqualDeep(old.borrow_advice, current.borrow_advice); + try std.testing.expectEqualDeep(old.tokens, current.tokens); +} + +test "control continuations preserve former statement expression arm and scope grammar" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const statements = [_][]const u8{ + "let x: u8 = 1u8;", "let x = &v;", "let (a, b,) = f();", "let x = ref x;", "var x: u8 = zero;", "var x: u8 = { 1u8 };", "var x = 1;", + "ref r = xs[0usize..1usize];", "mut unchecked r = xs[0usize];", "return;", "return if true { 1u8 } else { 2u8 };", "break;", "continue;", "trap;", + "loop { break; }", "while (Record { field: true }).field { continue; }", "for i in 0usize..4usize { f(i); }", "scope s { shield { f(); } }", "lock ref m as v { f(); } cancelled { trap; }", "x = if true { 1u8 } else { 2u8 };", "f(if true { 1u8 } else { 2u8 });", + "if true { f(); } else if false { trap; } else { f(); }", "match value { E::A(x) => { f(x); }, E::B => 0u8, _ => { 1u8 } }", "select { send(tx, if true { value } else { other }) { ok => {}, closed(v) => { f(v); } } recv(rx) { ok(v) => f(v), closed => {} } cancelled(a,) => { f(a); } }", "{ 1u8 };", "{ f(); }", "if true { 1u8 } + 2u8;", "(if true { 1u8 } else { 2u8 }) + 3u8;", + "while !x {}", "for x in 0.. {}", "lock ref x as {}", "lock ref x as v {}", "if true {} else", "match x { E::A() => {} }", "match x { _ => 1u8 2u8 }", + "select { send(tx,) { ok => {} } cancelled => {} }", "select { recv(rx) { ok => {}, } cancelled => }", "{ return 1u8 }", "return !x;", + }; + const forms = [_]ExpressionForm{ + .{ .before = "{ ", .after = " }" }, + .{ .before = "{ if true { ", .after = " } else { trap; } }" }, + .{ .before = "{ loop { ", .after = " } }" }, + .{ .before = "{ return { ", .after = " }; }" }, + }; + for (forms) |form| for (statements) |statement_text| for ([_]bool{ false, true }) |no_struct| try expectControlParseMatches(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ form.before, statement_text, form.after }), no_struct); +} + +const control_forms = [_]ExpressionForm{ + .{ .before = "{ ", .after = " }" }, + .{ .before = "if true { ", .after = " } else { 2u8 }" }, + .{ .before = "if false { 1u8 } else if true { ", .after = " } else { 2u8 }" }, + .{ .before = "{ let x = ", .after = "; x }" }, + .{ .before = "{ return ", .after = "; }" }, + .{ .before = "{ while true { ", .after = "; } }" }, + .{ .before = "{ for i in 0u8..1u8 { ", .after = "; } }" }, + .{ .before = "{ loop { ", .after = "; } }" }, + .{ .before = "{ scope s { ", .after = "; } }" }, + .{ .before = "{ shield { ", .after = "; } }" }, + .{ .before = "{ lock ref m as x { ", .after = "; } cancelled {} }" }, + .{ .before = "match e { _ => ", .after = " }" }, + .{ .before = "{ select { cancelled => ", .after = " } }" }, + .{ .before = "{ select { send(tx, ", .after = ") { ok => {} } cancelled => {} } }" }, + .{ .before = "{ select { recv(rx) { ok => ", .after = " } cancelled => {} } }" }, + .{ .before = "f(", .after = ", 2u8)" }, + .{ .before = "if (", .after = ") { 1u8 } else { 2u8 }" }, +}; + +fn controlChild(e: ast.Expr, form: usize) ast.Expr { + return switch (form) { + 0 => e.kind.block.tail.?.*, + 1 => e.kind.if_expr.then.tail.?.*, + 2 => e.kind.if_expr.@"else".?.@"if".then.tail.?.*, + 3 => e.kind.block.stmts[0].kind.let.e, + 4 => e.kind.block.stmts[0].kind.@"return".?, + 5 => e.kind.block.stmts[0].kind.@"while".body.stmts[0].kind.expr, + 6 => e.kind.block.stmts[0].kind.@"for".body.stmts[0].kind.expr, + 7 => e.kind.block.stmts[0].kind.loop.stmts[0].kind.expr, + 8 => e.kind.block.stmts[0].kind.scope.body.stmts[0].kind.expr, + 9 => e.kind.block.stmts[0].kind.shield.stmts[0].kind.expr, + 10 => e.kind.block.stmts[0].kind.lock.body.stmts[0].kind.expr, + 11 => e.kind.match_expr.arms[0].body, + 12 => e.kind.block.stmts[0].kind.select.cancelled, + 13 => e.kind.block.stmts[0].kind.select.arms[0].value.?, + 14 => e.kind.block.stmts[0].kind.select.arms[0].arms[0].body, + 15 => e.kind.call.args[0], + 16 => e.kind.if_expr.cond, + else => unreachable, + }; +} + +fn controlSource(a: Allocator, count: usize, mixed: bool, leaf: []const u8) ![]const u8 { + var text: std.ArrayList(u8) = .empty; + try text.appendSlice(a, "module deep\nfn f() -> void effects [] { return "); + for (0..count) |i| try text.appendSlice(a, control_forms[if (mixed) i % control_forms.len else 0].before); + try text.appendSlice(a, leaf); + var i = count; + while (i != 0) { + i -= 1; + try text.appendSlice(a, control_forms[if (mixed) i % control_forms.len else 0].after); + } + try text.appendSlice(a, "; }\n"); + return text.items; +} + +test "deep mixed control and expression parsing retains every span child and error" { + for ([_]bool{ false, true }) |mixed| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const count = 32_768; + const source_text = try controlSource(a, count, mixed, "leaf"); + const parsed = try parseWithFile(a, source_text, "control-deep.aji"); + try std.testing.expect(parsed == .ok); + var e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?; + var start: u32 = @intCast("fn f() -> void effects [] { return ".len + 1); + var end: u32 = @intCast(source_text.len - "module deep\n".len - "; }\n".len + 1); + for (0..count) |i| { + const form = if (mixed) i % control_forms.len else 0; + try std.testing.expectEqualStrings("control-deep.aji", e.span.file.?); + try std.testing.expectEqualStrings("deep", e.span.namespace.?); + try std.testing.expectEqual(@as(u32, 2), e.span.start.line); + try std.testing.expectEqual(start, e.span.start.col); + try std.testing.expectEqual(end, e.span.end.col); + e = controlChild(e, form); + start += @intCast(control_forms[form].before.len); + end -= @intCast(control_forms[form].after.len); + } + try std.testing.expectEqualStrings("leaf", e.kind.name); + try std.testing.expectEqual(start, e.span.start.col); + try std.testing.expectEqual(end, e.span.end.col); + // One first error at the exact leaf, no partial AST or cascade. + const invalid = try controlSource(a, count, mixed, "!leaf"); + const rejected = try parseWithFile(a, invalid, "control-deep.aji"); + try std.testing.expect(rejected == .err); + try std.testing.expectEqual(start, rejected.err.pos.col); + try std.testing.expectEqualStrings("!", rejected.err.found); + try std.testing.expectEqualStrings("an expression", rejected.err.expected); + try std.testing.expectEqual(@as(usize, 1), rejected.err.repair_candidates.len); + } +} + +test "public control parser allocation failures publish no partial AST and release backing" { + const programs = [_]struct { source: []const u8, tag: std.meta.Tag(Result) }{ + .{ .source = "module oom fn f() -> void effects [] { let x = if true { let y = 1u8; y } else if false { 2u8 } else { 3u8 }; return x; }", .tag = .ok }, + .{ .source = "module oom fn f() -> void effects [] { loop { while true { for i in 0u8..1u8 { shield { scope s { lock ref m as x { f(); } cancelled { trap; } } } } } } }", .tag = .ok }, + .{ .source = "module oom fn f() -> void effects [] { select { send(tx, { value }) { ok => {}, closed(v) => match v { _ => { f(v); } } } recv(rx) { ok(v) => f(v), closed => {} } cancelled(a,) => { f(a); } } }", .tag = .ok }, + .{ .source = "module oom fn f() -> void effects [] { return if true { !value } else { value }; }", .tag = .err }, + .{ .source = "module oom fn f() -> void effects [] { for i in 0.. {} } fn g() -> void effects [] { lock ref m as x {} }", .tag = .errors }, + }; + for (programs) |program| for ([_]bool{ false, true }) |persistent| { + var fail_at: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 2048); + var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); + var output: std.heap.ArenaAllocator = .init(backing.allocator()); + var recovering: ExpressionAllocationFailure = .{ .backing = output.allocator(), .at = fail_at, .sticky = persistent }; + const result = parse(recovering.allocator(), program.source); + const failed = recovering.failed; + if (failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts); + } else { + try std.testing.expectEqual(program.tag, std.meta.activeTag(try result)); + } + output.deinit(); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!failed) break; + } + }; +} + +test "grown mixed control worklist propagates each allocation failure after token setup" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const source_text = try controlSource(a, 64, true, "leaf"); + const tokens = try lex.tokenize(a, source_text); + for ([_]bool{ false, true }) |persistent| { + var fail_at: usize = 0; + var late_failures: usize = 0; + while (true) : (fail_at += 1) { + try std.testing.expect(fail_at < 4096); + var backing: std.testing.FailingAllocator = .init(std.testing.allocator, .{}); + var output: std.heap.ArenaAllocator = .init(backing.allocator()); + const owned_tokens = try output.allocator().dupe(Token, tokens); + var recovering: ExpressionAllocationFailure = .{ .backing = output.allocator(), .at = fail_at, .sticky = persistent }; + var p: Parser = .{ .arena = recovering.allocator(), .tokens = owned_tokens }; + const result = p.module(); + const failed = recovering.failed; + if (failed) { + try std.testing.expectError(error.OutOfMemory, result); + if (!persistent) try std.testing.expectEqual(fail_at + 1, recovering.attempts); + try std.testing.expect(p.failure == null); + if (p.pos > tokens.len / 2) late_failures += 1; + } else try std.testing.expectEqual(@as(usize, 1), (try result).functions.len); + try std.testing.expectEqual(@as(usize, 0), p.expr_work.items.len); + try std.testing.expect(!p.driver_active); + p.deinitExpressionWork(); + output.deinit(); + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!failed) break; + } + try std.testing.expect(late_failures > 0); + } +} + +// Token helpers are deliberately shared; each parser owns its mutable token +// copy, so split >> tokens and exact failure state are still compared. +test "control token prefix and deletion sweeps preserve first error and outer advice" { + const samples = [_][]const u8{ + "{ let x: slice> = value; x }", + "{ var x: u8 = if c { 1u8 } else if d { 2u8 } else { 3u8 }; x = f(x); }", + "{ f(&v); }", + "{ var x: u8 = &v; }", + "{ x = &v; }", + "{ while c or trap {} for i in 0u8..1u8 {} }", + "{ match x { -1 => 0u8, 2 => 1u8, _ => 2u8 } }", + "{ match x { _ => {}, E::A(v) => { f(v); }, E::B => {} } }", + "{ match x { ok(v) => f(v), err(e) => {}, cancelled => {} } }", + "{ match Record { field: value } { _ => {} } }", + "{ for i in Record { field: value }..end {} }", + "{ lock ref m as x { if c {} } cancelled { trap; } }", + "{ select { send(tx, f(value)) { ok => {}, closed(v) => {} } recv(rx) { ok(v) => v, closed => {} } cancelled(a,) => {} } }", + "{ if c {} else if d {} }", + "{ if c {}; f(); }", + "{ (if c {} else {}) f(); }", + "{ ({}) // comment after grouped construct\n f(); }", + "{ if c {} // boundary\n f(); }", + "{ return { ref r = xs[0usize..1usize]; r }; }", + }; + for (samples) |source| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const tokens = try lex.tokenize(fixture.allocator(), source); + for ([_]bool{ false, true }) |no_struct| { + try expectControlTokensMatch(fixture.allocator(), tokens, no_struct); + for (0..tokens.len - 1) |i| { + var output: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer output.deinit(); + const a = output.allocator(); + const prefix = try a.alloc(Token, i + 1); + @memcpy(prefix[0..i], tokens[0..i]); + prefix[i] = .{ .tag = .eof, .text = "", .pos = tokens[i].pos, .end = tokens[i].pos }; + try expectControlTokensMatch(a, prefix, no_struct); + const deleted = try a.alloc(Token, tokens.len - 1); + @memcpy(deleted[0..i], tokens[0..i]); + @memcpy(deleted[i..], tokens[i + 1 ..]); + try expectControlTokensMatch(a, deleted, no_struct); + } + } + } + // Invalid leaf in every control child shape, not only the final deep form. + for (control_forms) |form| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const source = try std.fmt.allocPrint(a, "{{ return {s}!leaf{s}; }}", .{ form.before, form.after }); + try expectControlParseMatches(a, source, false); + } + const child_errors = [_][]const u8{ + "{ if !c {} }", "{ while !c {} }", "{ match !v { _ => {} } }", + "{ for i in !lo..hi {} }", "{ for i in lo..!hi {} }", "{ lock ref !m as x {} cancelled {} }", + "{ select { send(tx, !v) { ok => {} } cancelled => {} } }", + }; + for (child_errors) |source| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + try expectControlParseMatches(fixture.allocator(), source, true); + } +} + +test "deep ungrouped conditions restore scopes and retain ordered condition children" { + for ([_]bool{ false, true }) |invalid| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const depth = 32_768; + var text: std.ArrayList(u8) = .empty; + for (0..depth) |_| try text.appendSlice(a, "if "); + try text.appendSlice(a, if (invalid) "!leaf" else "leaf"); + for (0..depth) |_| try text.appendSlice(a, " { 1u8 } else { 2u8 }"); + var p: Parser = .{ .arena = a, .tokens = try a.dupe(Token, try lex.tokenize(a, text.items)), .borrow_advice = .{ .at = 0, .kind = .borrow_argument } }; + defer p.deinitExpressionWork(); + const result = p.expr(); + if (invalid) { + try std.testing.expectError(error.Syntax, result); + try std.testing.expectEqual(@as(u32, depth * 3 + 1), p.failure.?.pos.col); + try std.testing.expectEqualStrings("!", p.failure.?.found); + } else { + var e = try result; + for (0..depth) |i| { + try std.testing.expectEqual(@as(u32, @intCast(i * 3 + 1)), e.span.start.col); + try std.testing.expectEqualStrings("1u8", e.kind.if_expr.then.tail.?.kind.int.text); + try std.testing.expectEqualStrings("2u8", e.kind.if_expr.@"else".?.block.tail.?.kind.int.text); + e = e.kind.if_expr.cond; + } + try std.testing.expectEqualStrings("leaf", e.kind.name); + } + try std.testing.expect(!p.no_struct and !p.driver_active); + try std.testing.expectEqual(@as(usize, 0), p.expr_work.items.len); + try std.testing.expectEqualDeep(@as(@FieldType(Parser, "borrow_advice"), .{ .at = 0, .kind = .borrow_argument }), p.borrow_advice); + } +} + +test "wide statements match select arms and else if chains preserve every item" { + const count = 32_768; + for (0..4) |form| { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + var text: std.ArrayList(u8) = .empty; + try text.appendSlice(a, switch (form) { + 0 => "{ ", + 1 => "{ match e { ", + 2 => "{ select { ", + 3 => "{ if c {}", + else => unreachable, + }); + for (0..count) |i| switch (form) { + 0 => try text.appendSlice(a, "f(); "), + 1 => try text.appendSlice(a, try std.fmt.allocPrint(a, "{d} => {d}u64, ", .{ i, i })), + 2 => try text.appendSlice(a, try std.fmt.allocPrint(a, "recv(rx{d}) {{ ok(v) => v, closed => {{}} }} ", .{i})), + 3 => try text.appendSlice(a, " else if c {}"), + else => unreachable, + }; + try text.appendSlice(a, switch (form) { + 0 => "leaf }", + 1 => "} }", + 2 => "cancelled => {} } }", + 3 => " else {} }", + else => unreachable, + }); + var p: Parser = .{ .arena = a, .tokens = try a.dupe(Token, try lex.tokenize(a, text.items)) }; + defer p.deinitExpressionWork(); + const b = try p.block(); + switch (form) { + 0 => { + try std.testing.expectEqual(count, b.stmts.len); + for (b.stmts) |stmt| { + try std.testing.expect(!stmt.block_statement); + try std.testing.expectEqualStrings("f", stmt.kind.expr.kind.call.callee.kind.name); + } + try std.testing.expectEqualStrings("leaf", b.tail.?.kind.name); + }, + 1 => { + const arms = b.tail.?.kind.match_expr.arms; + try std.testing.expectEqual(count, arms.len); + for (arms, 0..) |arm, i| { + try std.testing.expectEqual(i, try std.fmt.parseInt(usize, arm.pattern.kind.int, 10)); + try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "{d}u64", .{i}), arm.body.kind.int.text); + } + }, + 2 => { + const select = b.stmts[0].kind.select; + try std.testing.expectEqual(count, select.arms.len); + for (select.arms, 0..) |arm, i| { + try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "rx{d}", .{i}), arm.endpoint); + try std.testing.expectEqual(@as(usize, 2), arm.arms.len); + } + try std.testing.expect(select.cancelled.kind == .block); + }, + 3 => { + var conditional = b.tail.?.kind.if_expr.*; + for (0..count) |_| { + try std.testing.expectEqualStrings("c", conditional.cond.kind.name); + try std.testing.expectEqual(@as(usize, 0), conditional.then.stmts.len); + conditional = conditional.@"else".?.@"if".*; + } + try std.testing.expect(conditional.@"else".? == .block); + }, + else => unreachable, + } + try std.testing.expectEqual(Tag.eof, p.peek().tag); + } +} + +// Tracks physical arena backing, including buffers retained when a worklist +// outgrows its capacity. Peaks are informational: no depth acceptance or +// memory limit is asserted. These bytes are not resident process memory. +const ControlMemory = struct { + backing: Allocator, + current: usize = 0, + peak: usize = 0, + fn allocator(self: *@This()) Allocator { + return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } }; + } + fn grew(self: *@This(), old: usize, new: usize) void { + self.current = self.current - old + new; + self.peak = @max(self.peak, self.current); + } + fn alloc(raw: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(raw)); + const memory = self.backing.rawAlloc(len, alignment, ra) orelse return null; + self.grew(0, len); + return memory; + } + fn resize(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool { + const self: *@This() = @ptrCast(@alignCast(raw)); + if (!self.backing.rawResize(memory, alignment, len, ra)) return false; + self.grew(memory.len, len); + return true; + } + fn remap(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 { + const self: *@This() = @ptrCast(@alignCast(raw)); + const resized = self.backing.rawRemap(memory, alignment, len, ra) orelse return null; + self.grew(memory.len, len); + return resized; + } + fn free(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void { + const self: *@This() = @ptrCast(@alignCast(raw)); + self.grew(memory.len, 0); + self.backing.rawFree(memory, alignment, ra); + } +}; + +test "control parser physical backing is released after deep scalar and mixed parses" { + // Reconstructed HEAD 9534359 expression-only work layout. Payload structs + // match that revision today; update this reconstruction if they change. + // This is a historical item-size comparison, not a before/after peak. + const OldWork = union(enum) { + enter: struct { kind: Parser.ExprEntry, min_prec: u8 = 0 }, + binary: Parser.ExprBinary, + rhs: struct { context: Parser.ExprBinary, lhs: ast.Expr, info: Parser.BinInfo }, + cast: lex.Pos, + prefix: Parser.ExprPrefix, + postfix: lex.Pos, + group: bool, + call_next: Parser.ExprCall, + call_got: Parser.ExprCall, + restore_call: bool, + restore_advice: @FieldType(Parser, "borrow_advice"), + array_first: lex.Pos, + array_got: Parser.ExprArray, + struct_next: Parser.ExprStruct, + struct_got: struct { context: Parser.ExprStruct, field_start: lex.Pos, name: []const u8 }, + index_lo: Parser.ExprIndex, + index_hi: struct { context: Parser.ExprIndex, lo: ast.Expr }, + }; + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const depth = 32_768; + var scalar: std.ArrayList(u8) = .empty; + try scalar.appendSlice(a, "module deep fn f() -> void effects [] { return "); + for (0..depth) |_| try scalar.appendSlice(a, "not "); + try scalar.appendSlice(a, "leaf; }"); + const sources = [_][]const u8{ scalar.items, try controlSource(a, depth, false, "leaf"), try controlSource(a, depth, true, "leaf") }; + for (sources, 0..) |source, kind| { + var memory: ControlMemory = .{ .backing = std.testing.allocator }; + var output: std.heap.ArenaAllocator = .init(memory.allocator()); + const result = parse(output.allocator(), source); + const peak = memory.peak; + const accepted = if (result) |r| r == .ok else |_| false; + output.deinit(); + try std.testing.expectEqual(@as(usize, 0), memory.current); + try std.testing.expect(accepted); + std.debug.print("control parser memory: kind={d} depth={d} source={d} old_work={d} work={d} frame={d} peak={d}\n", .{ kind, depth, source.len, @sizeOf(OldWork), @sizeOf(Parser.ExprWork), @sizeOf(Parser.ExprFrame), peak }); + } +} diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 700782e..18d3e94 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -1370,4 +1370,79 @@ with tempfile.TemporaryDirectory(prefix='aji-place-base-depth-') as directory: print('place base contexts and rejection positions passed', flush=True) +with tempfile.TemporaryDirectory(prefix='aji-control-parser-depth-') as directory: + root = Path(directory) + for kind in ('block', 'if', 'else-if'): + depths = (1, 16, 256, 1024) if kind != 'else-if' else (1, 16, 256, 1024, 16384, 65536) + for depth in depths: + if kind == 'block': + expression = '{ ' * depth + '0usize' + ' }' * depth + elif kind == 'if': + expression = 'if true { ' * depth + '0usize' + ' } else { 1usize }' * depth + else: + expression = 'if false { 1usize } else ' * depth + '{ 0usize }' + path = root / f'control-parser-{kind}-{depth}.aji' + path.write_text('module depth\nfn main() -> usize effects [] { return ' + expression + '; }\n') + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + if depth <= 256: + assert cli('check', path) == b'' + lowered = cli('lower', path) + assert cli('lower', formatted) == lowered + if depth <= 16: + air = path.with_suffix('.air') + air.write_bytes(lowered) + options = ('--quantum', 1, '--schedule-seed', 7, '--fuel', 4096) + result = cli('run', path, *options) + assert json.loads(result) == {'status': 'returned', 'value': 0}, (kind, depth, result) + assert cli('run', air, *options) == result + print(f'control parser {kind} {depth} passed', flush=True) + + # Syntax-only control contexts avoid conflating parser depth with the + # still-open lowering/liveness audit or requiring semantic task fixtures. + syntax_forms = ( + ('let', '{ let x = ', '; x }'), + ('return', '{ return ', '; }'), + ('while', '{ while true { ', '; } }'), + ('for', '{ for i in 0usize..1usize { ', '; } }'), + ('loop', '{ loop { ', '; } }'), + ('scope', '{ scope s { ', '; } }'), + ('shield', '{ shield { ', '; } }'), + ('lock', '{ lock ref m as x { ', '; } cancelled {} }'), + ('match', 'match e { _ => ', ' }'), + ('select-send', '{ select { send(tx, ', ') { ok => {} } cancelled => {} } }'), + ('select-outcome', '{ select { recv(rx) { ok => ', ' } cancelled => {} } }'), + ('select-cancelled', '{ select { cancelled => ', ' } }'), + ) + for label, before, after in syntax_forms: + path = root / f'control-syntax-{label}.aji' + path.write_text('module depth\nfn main() -> usize effects [] { return ' + before * 256 + '0usize' + after * 256 + '; }\n') + output = cli('fmt', path) + formatted = path.with_suffix('.formatted.aji') + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + + # Six sequential CLI processes at each depth. The 32,768 mixed check + # measured 350,804 KiB max RSS on Linux/Debug; this is informational, + # environment-dependent evidence, not a CI memory bound. + for mixed in (False, True): + for depth in (16, 1024, 32768): + forms = syntax_forms if mixed else syntax_forms[:1] + expression = ''.join(forms[i % len(forms)][1] for i in range(depth)) + '!0usize' + ''.join(forms[i % len(forms)][2] for i in reversed(range(depth))) + path = root / f'control-error-{mixed}-{depth}.aji' + source = '// UTF-8: λ\r\nmodule depth\r\nfn main() -> usize effects [] { return ' + expression + '; }\r\n' + path.write_bytes(source.encode()) + rejected = cli('check', path, code=1) + record = json.loads(rejected) + pos = source.index('!0usize') + assert (record['code'], record['line'], record['col']) == ('E7001', 3, pos - source.rfind('\n', 0, pos)), record + assert record['expected'] == 'an expression' and record['found'] == '!', record + assert record['repair_candidates'][0]['kind'] == 'boolean_negation', record + for command in ('lower', 'run', 'report', 'explore', 'fmt'): + assert cli(command, path, code=1) == rejected + print('control parser syntax and first-error positions passed', flush=True) + + print(f'source expression depth: {checks} checks passed')