From bda43d2ecbe283ec862fb7053b51b997fd2f9fda Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 22:13:08 +0300 Subject: [PATCH] cli: parse nested expression contexts iteratively --- docs/design/open-questions.md | 2 + docs/design/source-expression-depth-audit.md | 81 +- docs/plan/phase-6-source-language.md | 23 + src/frontend/parse.zig | 1130 ++++++++++++++---- tests/hosted/source_expression_depth.py | 92 +- 5 files changed, 1107 insertions(+), 221 deletions(-) diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index b0e327c..18871ee 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -539,4 +539,6 @@ The [generic transformation increment](source-expression-depth-audit.md#generic- The [parser constructor-path increment](source-expression-depth-audit.md#parser-qualified-constructor-paths) repairs Parser.exprPath independently of generic/lowering paths. Frozen baseline probes confirm enum and struct constructor aborts at 16,384 fields; the repaired CLI returns exact E7002 through 65,536. Named-root classification, spelling, type arguments, spans, syntax errors and host OOM propagation are preserved, with one complete string allocation. Q-061 remains open for the confirmed parenthesized/mixed-call parser failures and the remaining lowering/liveness inventory; no new acceptance limit or external review is claimed. +The [shared expression parser increment](source-expression-depth-audit.md#shared-expression-parser-continuations) removes native re-entry through grouping, call arguments, arrays, index bounds and struct fields, sharing binary/cast/unary/postfix/primary continuations. Token/AST/spans, grammar/error priority and scoped advice remain unchanged; host OOM propagates without diagnostics or partial AST. Reused work storage and stable driver frames retain caller-arena lifetime. Block/control callbacks still recurse outside the large dispatch frame; their bounded regression probes pass, without an arbitrary-depth claim. Grouped programs check through 65,536; mixed calls format through 65,536 but now abort in lowerer `call` at 1,024. Q-061 remains open for that confirmed path and remaining control/liveness traversal; no new limit or external review is claimed. + Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one. diff --git a/docs/design/source-expression-depth-audit.md b/docs/design/source-expression-depth-audit.md index 7ee63fd..9fc573b 100644 --- a/docs/design/source-expression-depth-audit.md +++ b/docs/design/source-expression-depth-audit.md @@ -425,21 +425,90 @@ No normative, source/AIR format, feature, code, bundle, acceptance-limit or runtime/ownership rule changes. This repairs one callback; Q-061 remains open and no external review covers this increment yet. +## Shared expression parser continuations + +Frozen pre-repair CLI production at 371329f (`aji-before-expression-parser`) +aborts while formatting 1,024 grouped or mixed-call levels, with empty stdout. +`expression-parser-probes.json` and `expression-parser-*.before.fmt.stdout/ +.stderr` hold the finite inputs/results. Debug stack excerpts reread current +source files; use `parse-before-expression-driver.zig` for baseline line text. + +Binary precedence/RHS, casts, unary prefixes, postfix and primary entry modes +now share explicit continuations. Groups, ordinary/typed/variant call arguments, +array lists/repetitions, index bounds and struct field expressions suspend on +the same worklist, including alternating forms. Grammar, comparison rejection, +`or trap`, borrowed-place boundaries, constructor classification, trailing +commas, type-closer splitting, spans, argument advice and error priority are +retained. Deferred call/advice restoration is separate from the formerly +success-only group/index restoration. Host OOM propagates without syntax +diagnostics or partial public AST. + +The parser reuses its work buffer across entries. Native block/control callbacks +save a base cursor; each re-entered driver processes/unwinds only entries above +that base. Active driver results and current work live in stable, separately +allocated frames reused by callback depth. No AST or queued pointer targets +relocatable work storage or a driver result. Dispatch of block/if/match callbacks +occurs outside the large per-step frame. An initial local-frame regression at +256 block/if levels was caught and repaired before commit. Final probes preserve +baseline formatted bytes at 64/256 block/if levels and 64 explicit-return levels; +explicit-return block/if forms now also format at 256, where the baseline aborts +(`expression-parser-control-final.json` and its raw outputs). This does not prove +arbitrary callback depth safe. + +Scratch deinit/destroy is logical cleanup for caller arenas. Work capacity, +driver frames, AST nodes and partial outputs retain physical caller-arena +lifetime. Work/driver buffers are reused rather than allocated independently +for every scalar entry. Allocation requests/failure-index outcomes need not +match the old recursive implementation. AST output ownership and host error +handling are unchanged. + +The copied shallow former descent compares 4,160 expression/form/context/entry +combinations, including complete ASTs, failures, positions, token mutations and +advice/scope state. Type, lexical/advice, block/control and path helpers are +shared, outside the oracle's independence. Separate public parser tests cover +32,768 mixed levels, every constructor span, siblings, type arguments and exact +innermost E7001 advice. Re-entry/reuse tests poison scratch bytes before reading +returned ASTs. Every recovering direct allocation failure checks host OOM, +empty work, restored depth/advice/call scopes and no diagnostic; persistent +backing failures through public parse check arena cleanup and no partial AST. + +Final probes accept checks at 65,536 grouped levels and formatting at 65,536 +mixed-call levels. Full mixed-call checking still aborts at 1,024, now in lowerer +`call` rather than parsing (`expression-parser-final-probes.json` and +`expression-parser-*.after.final.*.stdout/.stderr`). Permanent CLI tests separate +full accepted grouped/scalar programs with exact AIR/fuel from syntax-only +mixed/call inputs, and retain complete rejection records across commands. + +Build, unit and Zig format checks pass. All 1,793 ordinary conformance cases pass +with terminal exit 0 and exact unique corpus coverage +(`expression-parser-conformance.jsonl` and its audit). The depth, grammar and +independent-error CLI suites pass 737/312/234 checks. The formatter passes 6,078 +checks over 1,469 files (1,414 parsed, 55 existing syntax errors, 782 identical +AIR outputs). Frozen old/new CLIs retain exact exit/stdout/stderr on all 1,423 +public source checks and 506 accepted lowerings +(`expression-parser-cli-compatibility.json`). These are compiler regressions, +not a full per-step GC pass or a model-capability measurement. + +No normative, source/AIR format, feature, code, bundle, acceptance-limit or +ownership/runtime rule changes. Q-061 remains open for block/control parsing, +non-scalar lowering and the remaining liveness/read/assignment inventory. +This increment has no external review yet. + ## Remaining work Follow-up checks accept 16 parenthesized/mixed-call levels but abort with empty stdout at 1,024. A qualified enum variant returns E7002 at 16 components but aborts in Parser.exprPath at 16,384. Raw evidence is `generic-followup-depth-probes.json` and `generic-followup-*.stdout/.stderr`. -Generic transformation, its path callback and Parser.exprPath above are now -repaired; the remaining inventory includes the other observed parser failures -and inspection-only risks: +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: | Production path | Evidence and next scope | |---|---| -| Parser `postfix`/`primary` through parenthesized `expr` | Confirmed failure at 1,024 levels; preserve grouping, precedence and spans. | -| Parser `callArgs`, array/index/struct initializers, `ifExpr`, block/statement and match/arm expression entry | Mixed `1i64 + id(...)` calls have a confirmed parser abort at 1,024. Other callback depth behavior is unverified; include alternating forms, not only homogeneous spines. | -| Lowerer non-scalar `expr` callbacks: calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Native re-entry remains outside the repaired scalar driver; deep behavior unverified, including alternating scalar/non-scalar expressions. | +| Parser `ifExpr`, block/statement and match/arm expression entry | Native callback re-entry remains. Bounded block/if regression probes above pass; arbitrary and alternating control/statement depth is unverified. | +| Lowerer non-scalar `expr` callbacks: calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Mixed scalar/call source now has a confirmed native abort in `call` at 1,024 after parsing succeeds. 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. | The formatter's expression-marking traversal already uses a worklist, as diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index c9a7045..be88039 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -613,3 +613,26 @@ No normative/bundle/feature/code/acceptance-limit or runtime/ownership rule changes. Parenthesized and mixed-call parsing failures, remaining expression/ statement walks, Q-060 validation and Phase 6 exit gates remain open. This increment has no external review yet. + +## Source shared expression parsing (2026-10-10) + +The [Q-061 parser increment](../design/source-expression-depth-audit.md#shared-expression-parser-continuations) +shares explicit precedence/cast/unary/postfix/primary continuations with groups, +call arguments, arrays, indices and struct fields. Grammar, spans, token/error +order and call/advice scopes are preserved. Reused work storage and stable +driver frames support native callback re-entry without retaining AST pointers +into scratch; host OOM remains separate from source diagnostics. No normative/ +bundle/feature/code/acceptance-limit or ownership/runtime rule changes. + +Independent shallow comparisons (4,160), 32,768 mixed levels with exact spans +and leaf E7001 advice, poisoned scratch/re-entry and recovering/persistent OOM +tests pass. Build/units/format checks, all 1,793 ordinary conformance cases with exact +coverage and 737/312/234 depth/grammar/independent-error CLI checks pass. The +formatter passes 6,078 checks; frozen old/new public checks/lowerings remain +exact (1,423/506). Grouped source checks reach 65,536; mixed-call formatting reaches +65,536. Block/if regression probes preserve accepted baseline output, including +256 levels; explicit-return forms improve from baseline aborts to formatting +at 256. These are bounded probes, not a whole-parser depth guarantee. Full +mixed-call checking now confirms a lowerer `call` abort at 1,024; control/block +parsing, remaining expression/statement/liveness walks, Q-060 validation and +Phase 6 exit gates remain open. No external review covers this increment yet. diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index b02c569..b1ff730 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -27,6 +27,7 @@ pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result { pub fn parseWithFile(arena: Allocator, src: []const u8, file: ?[]const u8) Allocator.Error!Result { const tokens = try lex.tokenize(arena, src); var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens), .file = file }; + defer p.deinitExpressionWork(); const m = p.module() catch |e| switch (e) { error.Syntax => return if (p.failures.items.len > 1) .{ .errors = p.failures.items } else .{ .err = if (p.failures.items.len == 1) p.failures.items[0] else p.failure.? }, error.OutOfMemory => return error.OutOfMemory, @@ -53,6 +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. + expr_work: std.ArrayList(ExprWork) = .empty, + expr_frames: std.ArrayList(*ExprFrame) = .empty, + expr_frame_depth: usize = 0, fn peek(p: *Parser) Token { return p.tokens[p.pos]; @@ -907,182 +913,381 @@ const Parser = struct { }; } - fn binary(p: *Parser, min_prec: u8) Error!ast.Expr { - const start = p.peek().pos; - var lhs = try p.castExpr(); - while (true) { - // `e or trap`: the fallible shorthand (spec 15 §6). - if (p.atWord("or") and isWord(p.peekAt(1), "trap") and min_prec <= 1) { - _ = p.next(); - _ = p.next(); - const inner = try p.box(ast.Expr, lhs); - lhs = .{ .span = p.span(start), .kind = .{ .or_trap = inner } }; - continue; - } - const info = binInfo(p.peek()) orelse break; - if (info.prec <= min_prec) break; - _ = p.next(); - const rhs = try p.binary(info.prec); - // Comparisons do not chain. - const lb = try p.box(ast.Expr, lhs); - const rb = try p.box(ast.Expr, rhs); - lhs = .{ .span = p.span(start), .kind = .{ .binary = .{ .op = info.op, .l = lb, .r = rb } } }; - if (info.prec == 3 and binInfo(p.peek()) != null and binInfo(p.peek()).?.prec == 3) return p.fail(p.peek(), "parentheses around a comparison"); - } - return lhs; + const ExprEntry = enum { binary, cast, unary, postfix, primary }; + const ExprPrefix = struct { + start: lex.Pos, + kind: enum { neg, not, deref, borrow }, + mutable: bool = false, + unchecked: bool = false, + }; + const ExprBinary = struct { start: lex.Pos, min_prec: u8 }; + const ExprCall = struct { + start: lex.Pos, + callee: ast.Expr, + type_arg: ?ast.Type, + borrow_arguments: bool, + args: std.ArrayList(ast.Expr) = .empty, + }; + const ExprArray = struct { start: lex.Pos, items: std.ArrayList(ast.Expr) = .empty }; + const ExprStruct = struct { + start: lex.Pos, + name: []const u8, + type_args: []const ast.Type, + fields: std.ArrayList(ast.FieldInit) = .empty, + }; + const ExprIndex = struct { start: lex.Pos, base: ast.Expr, saved_no_struct: bool }; + const ExprWork = union(enum) { + enter: struct { kind: ExprEntry, min_prec: u8 = 0 }, + binary: ExprBinary, + rhs: struct { context: ExprBinary, lhs: ast.Expr, info: BinInfo }, + cast: lex.Pos, + prefix: ExprPrefix, + postfix: lex.Pos, + group: bool, + call_next: ExprCall, + call_got: ExprCall, + restore_call: bool, + restore_advice: @FieldType(Parser, "borrow_advice"), + array_first: lex.Pos, + array_got: ExprArray, + struct_next: ExprStruct, + struct_got: struct { context: ExprStruct, field_start: lex.Pos, name: []const u8 }, + index_lo: ExprIndex, + index_hi: struct { context: ExprIndex, lo: ast.Expr }, + }; + const ExprFrame = struct { work: ExprWork, result: ast.Expr }; + + fn deinitExpressionWork(p: *Parser) void { + for (p.expr_frames.items) |frame| p.arena.destroy(frame); + p.expr_frames.deinit(p.arena); + p.expr_work.deinit(p.arena); } - fn castExpr(p: *Parser) Error!ast.Expr { - const start = p.peek().pos; - var e = try p.unary(); - while (true) { - const mode: ast.CastMode = if (p.atWord("as")) .widen else if (p.peek().tag == .as_bang) .checked else if (p.peek().tag == .as_pct) .wrap else break; - _ = p.next(); - const ty = try p.typeExpr(); - const inner = try p.box(ast.Expr, e); - e = .{ .span = p.span(start), .kind = .{ .cast = .{ .mode = mode, .e = inner, .ty = ty } } }; + 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); } - return e; + 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().?) { + .restore_call => |saved| p.no_struct = saved, + .restore_advice => |saved| p.borrow_advice = saved, + else => {}, + } + } + } + + fn expressionDriver(p: *Parser, entry: ExprEntry, min_prec: u8) Error!ast.Expr { + 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. + 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); + } + return frame.result; + } + + fn expressionStep(p: *Parser, pending: *std.ArrayList(ExprWork), result: *ast.Expr, work: *const ExprWork) Error!void { + switch (work.*) { + .enter => |request| { + const start = p.peek().pos; + switch (request.kind) { + .binary => { + try pending.append(p.arena, .{ .binary = .{ .start = start, .min_prec = request.min_prec } }); + try pending.append(p.arena, .{ .enter = .{ .kind = .cast } }); + }, + .cast => { + try pending.append(p.arena, .{ .cast = start }); + try pending.append(p.arena, .{ .enter = .{ .kind = .unary } }); + }, + .unary => { + const t = p.peek(); + const kind: ?@FieldType(ExprPrefix, "kind") = if (t.tag == .minus) .neg else if (isWord(t, "not")) .not else if (t.tag == .star) .deref else null; + if (kind) |k| { + _ = p.next(); + try pending.append(p.arena, .{ .prefix = .{ .start = start, .kind = k } }); + try pending.append(p.arena, .{ .enter = .{ .kind = .unary } }); + } else if (isWord(t, "ref") or isWord(t, "mut")) { + _ = p.next(); + var unchecked = false; + if (p.atWord("unchecked")) { + _ = p.next(); + unchecked = true; + } + try pending.append(p.arena, .{ .prefix = .{ .start = start, .kind = .borrow, .mutable = isWord(t, "mut"), .unchecked = unchecked } }); + try pending.append(p.arena, .{ .enter = .{ .kind = if (p.peek().tag == .star) .unary else .postfix } }); + } else if (isWord(t, "move")) { + _ = p.next(); + const name = try p.ident("the name of the value to move"); + result.* = .{ .span = p.span(start), .kind = .{ .move = name } }; + } else try pending.append(p.arena, .{ .enter = .{ .kind = .postfix } }); + }, + .postfix => { + try pending.append(p.arena, .{ .postfix = start }); + try pending.append(p.arena, .{ .enter = .{ .kind = .primary } }); + }, + .primary => { + const t = p.peek(); + if (t.tag == .l_paren) { + _ = p.next(); + try pending.append(p.arena, .{ .group = p.no_struct }); + p.no_struct = false; + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + } else if (t.tag == .l_bracket) { + _ = p.next(); + try pending.append(p.arena, .{ .array_first = start }); + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + } else if (t.tag == .ident and std.ascii.isUpper(t.text[0]) and p.peekAt(1).tag == .l_brace and !p.no_struct) { + _ = p.next(); + _ = try p.expect(.l_brace, "`{`"); + try pending.append(p.arena, .{ .struct_next = .{ .start = start, .name = t.text, .type_args = &.{} } }); + } else result.* = try p.primaryAtom(); + }, + } + }, + .binary => |context| { + if (p.atWord("or") and isWord(p.peekAt(1), "trap") and context.min_prec <= 1) { + _ = p.next(); + _ = p.next(); + const inner = try p.box(ast.Expr, result.*); + result.* = .{ .span = p.span(context.start), .kind = .{ .or_trap = inner } }; + try pending.append(p.arena, .{ .binary = context }); + return; + } + const info = binInfo(p.peek()) orelse return; + if (info.prec <= context.min_prec) return; + _ = p.next(); + try pending.append(p.arena, .{ .rhs = .{ .context = context, .lhs = result.*, .info = info } }); + try pending.append(p.arena, .{ .enter = .{ .kind = .binary, .min_prec = info.prec } }); + }, + .rhs => |rhs| { + const lb = try p.box(ast.Expr, rhs.lhs); + const rb = try p.box(ast.Expr, result.*); + result.* = .{ .span = p.span(rhs.context.start), .kind = .{ .binary = .{ .op = rhs.info.op, .l = lb, .r = rb } } }; + if (rhs.info.prec == 3 and binInfo(p.peek()) != null and binInfo(p.peek()).?.prec == 3) + return p.fail(p.peek(), "parentheses around a comparison"); + try pending.append(p.arena, .{ .binary = rhs.context }); + }, + .cast => |start| { + const mode: ast.CastMode = if (p.atWord("as")) .widen else if (p.peek().tag == .as_bang) .checked else if (p.peek().tag == .as_pct) .wrap else return; + _ = p.next(); + const ty = try p.typeExpr(); + const inner = try p.box(ast.Expr, result.*); + result.* = .{ .span = p.span(start), .kind = .{ .cast = .{ .mode = mode, .e = inner, .ty = ty } } }; + try pending.append(p.arena, .{ .cast = start }); + }, + .prefix => |prefix| { + const operand = try p.box(ast.Expr, result.*); + result.* = .{ .span = p.span(prefix.start), .kind = switch (prefix.kind) { + .neg => .{ .neg = operand }, + .not => .{ .not = operand }, + .deref => .{ .deref = operand }, + .borrow => .{ .borrow = .{ .mutable = prefix.mutable, .unchecked = prefix.unchecked, .place = operand } }, + } }; + }, + .postfix => |start| { + switch (p.peek().tag) { + .colon_colon => { + _ = p.next(); + if (p.peek().tag == .lt) { + const base = try p.box(ast.Expr, result.*); + const args = try p.typeArgs(); + result.* = .{ .span = p.span(start), .kind = .{ .specialize = .{ .base = base, .args = args } } }; + } else { + const base = if (result.*.kind == .specialize) result.*.kind.specialize.base.* else result.*; + const name = try p.exprPath(base) orelse return p.fail(p.peek(), "an enum name before `::`"); + const type_args: []const ast.Type = if (result.*.kind == .specialize) result.*.kind.specialize.args else &.{}; + const variant = try p.ident("a variant name"); + result.* = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant, .type_args = type_args } } }; + } + try pending.append(p.arena, .{ .postfix = start }); + }, + .dot => { + _ = p.next(); + const nt = p.peek(); + if (nt.tag != .ident) return p.fail(nt, "a field, method or operation name"); + const name = p.next().text; + const base = try p.box(ast.Expr, result.*); + result.* = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } }; + try pending.append(p.arena, .{ .postfix = start }); + if (p.peek().tag == .lt and result.*.kind.field.e.kind == .name and ((std.mem.eql(u8, name, "make") and std.mem.eql(u8, result.*.kind.field.e.kind.name, "channel")) or (std.mem.eql(u8, name, "new") and std.mem.eql(u8, result.*.kind.field.e.kind.name, "buffer")))) { + _ = p.next(); + const ty = try p.typeExpr(); + try p.closeAngle(); + try p.queueCall(pending, .{ .start = start, .callee = result.*, .type_arg = ty, .borrow_arguments = true }); + } + }, + .l_brace => { + if (p.no_struct) return; + const base = if (result.*.kind == .specialize) result.*.kind.specialize.base.* else result.*; + const name = try p.exprPath(base) orelse return; + const type_args: []const ast.Type = if (result.*.kind == .specialize) result.*.kind.specialize.args else &.{}; + const last = if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name; + if (!std.ascii.isUpper(last[0])) return; + _ = try p.expect(.l_brace, "`{`"); + try pending.append(p.arena, .{ .postfix = start }); + try pending.append(p.arena, .{ .struct_next = .{ .start = start, .name = name, .type_args = type_args } }); + }, + .l_paren => { + if (result.*.kind == .variant and p.peekAt(1).tag == .r_paren) + return p.fail(p.peek(), "payload values or no parentheses for a payload-free variant"); + try pending.append(p.arena, .{ .postfix = start }); + try p.queueCall(pending, .{ .start = start, .callee = result.*, .type_arg = null, .borrow_arguments = result.*.kind != .variant }); + }, + .l_bracket => { + _ = p.next(); + try pending.append(p.arena, .{ .postfix = start }); + try pending.append(p.arena, .{ .index_lo = .{ .start = start, .base = result.*, .saved_no_struct = p.no_struct } }); + p.no_struct = false; + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + }, + else => {}, + } + }, + .group => |saved| { + p.no_struct = saved; + _ = try p.expect(.r_paren, "`)`"); + }, + .call_next => |call| { + if (p.peek().tag == .r_paren) { + try p.finishCall(pending, call, &result.*); + } else { + try pending.append(p.arena, .{ .call_got = call }); + if (call.borrow_arguments) { + try pending.append(p.arena, .{ .restore_advice = p.borrow_advice }); + p.borrow_advice = .{ .at = p.pos, .kind = .borrow_argument }; + } + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + } + }, + .call_got => |call| { + var updated = call; + try updated.args.append(p.arena, result.*); + if (p.peek().tag == .comma) { + _ = p.next(); + try pending.append(p.arena, .{ .call_next = updated }); + } else try p.finishCall(pending, updated, &result.*); + }, + .restore_call => unreachable, + .restore_advice => |saved| p.borrow_advice = saved, + .array_first => |start| { + if (p.peek().tag == .semicolon) { + _ = try p.expect(.semicolon, "`;` in `[result.*; N]`"); + const n = try p.expect(.int, "array length"); + _ = try p.expect(.r_bracket, "`]`"); + const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); + const element = try p.box(ast.Expr, result.*); + result.* = .{ .span = p.span(start), .kind = .{ .array_rep = .{ .e = element, .len = @intCast(len) } } }; + } else try pending.append(p.arena, .{ .array_got = .{ .start = start } }); + }, + .array_got => |array| { + var updated = array; + try updated.items.append(p.arena, result.*); + if (p.peek().tag == .comma) { + _ = p.next(); + if (p.peek().tag != .r_bracket) { + try pending.append(p.arena, .{ .array_got = updated }); + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + return; + } + } + _ = try p.expect(.r_bracket, "`]`"); + result.* = .{ .span = p.span(updated.start), .kind = .{ .array_list = updated.items.items } }; + }, + .struct_next => |literal| { + if (p.peek().tag == .r_brace) { + _ = try p.expect(.r_brace, "`}`"); + result.* = .{ .span = p.span(literal.start), .kind = .{ .struct_lit = .{ .name = literal.name, .fields = literal.fields.items, .type_args = literal.type_args } } }; + } else { + const fs = p.peek().pos; + const name = try p.ident("a field name"); + _ = try p.expect(.colon, "`:`"); + try pending.append(p.arena, .{ .struct_got = .{ .context = literal, .field_start = fs, .name = name } }); + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + } + }, + .struct_got => |field| { + var updated = field.context; + try updated.fields.append(p.arena, .{ .name = field.name, .span = p.span(field.field_start), .e = result.* }); + if (p.peek().tag == .comma) { + _ = p.next(); + try pending.append(p.arena, .{ .struct_next = updated }); + } else { + _ = try p.expect(.r_brace, "`}`"); + result.* = .{ .span = p.span(updated.start), .kind = .{ .struct_lit = .{ .name = updated.name, .fields = updated.fields.items, .type_args = updated.type_args } } }; + } + }, + .index_lo => |index| { + if (p.peek().tag == .dot_dot) { + _ = p.next(); + if (p.peek().tag == .r_bracket) return p.failAdvice(p.peek(), "an expression", .explicit_range_end); + try pending.append(p.arena, .{ .index_hi = .{ .context = index, .lo = result.* } }); + try pending.append(p.arena, .{ .enter = .{ .kind = .binary } }); + } else result.* = try p.finishIndex(index, result.*, null); + }, + .index_hi => |index| { + const hi = try p.box(ast.Expr, result.*); + result.* = try p.finishIndex(index.context, index.lo, hi); + }, + } + } + + fn queueCall(p: *Parser, pending: *std.ArrayList(ExprWork), call: ExprCall) Error!void { + _ = try p.expect(.l_paren, "`(`"); + try pending.append(p.arena, .{ .restore_call = p.no_struct }); + p.no_struct = false; + try pending.append(p.arena, .{ .call_next = call }); + } + + fn finishCall(p: *Parser, pending: *std.ArrayList(ExprWork), call: ExprCall, e: *ast.Expr) Error!void { + _ = try p.expect(.r_paren, "`)`"); + p.no_struct = pending.pop().?.restore_call; + const callee = try p.box(ast.Expr, call.callee); + e.* = .{ .span = p.span(call.start), .kind = .{ .call = .{ .callee = callee, .type_arg = call.type_arg, .args = call.args.items } } }; + } + + fn finishIndex(p: *Parser, index: ExprIndex, lo: ast.Expr, hi: ?*const ast.Expr) Error!ast.Expr { + p.no_struct = index.saved_no_struct; + _ = try p.expect(.r_bracket, "`]`"); + const base = try p.box(ast.Expr, index.base); + const lob = try p.box(ast.Expr, lo); + return .{ .span = p.span(index.start), .kind = .{ .index = .{ .e = base, .lo = lob, .hi = hi } } }; + } + + fn binary(p: *Parser, min_prec: u8) Error!ast.Expr { + return p.expressionDriver(.binary, min_prec); } fn unary(p: *Parser) Error!ast.Expr { - const Prefix = struct { - start: lex.Pos, - kind: enum { neg, not, deref, borrow }, - mutable: bool = false, - unchecked: bool = false, - }; - var pending: std.ArrayList(Prefix) = .empty; - defer pending.deinit(p.arena); - var e: ast.Expr = while (true) { - const t = p.peek(); - const kind: ?@FieldType(Prefix, "kind") = if (t.tag == .minus) .neg else if (isWord(t, "not")) .not else if (t.tag == .star) .deref else null; - if (kind) |k| { - _ = p.next(); - try pending.append(p.arena, .{ .start = t.pos, .kind = k }); - continue; - } - if (isWord(t, "ref") or isWord(t, "mut")) { - _ = p.next(); - var unchecked = false; - if (p.atWord("unchecked")) { - _ = p.next(); - unchecked = true; - } - try pending.append(p.arena, .{ .start = t.pos, .kind = .borrow, .mutable = isWord(t, "mut"), .unchecked = unchecked }); - // A borrow admits `* unary`; all other operands still use - // postfix directly, preserving the place grammar boundary. - if (p.peek().tag == .star) continue; - break try p.postfix(); - } - if (isWord(t, "move")) { - _ = p.next(); - const name = try p.ident("the name of the value to move"); - break .{ .span = p.span(t.pos), .kind = .{ .move = name } }; - } - break try p.postfix(); - }; - while (pending.pop()) |prefix| { - const operand = try p.box(ast.Expr, e); - e = .{ .span = p.span(prefix.start), .kind = switch (prefix.kind) { - .neg => .{ .neg = operand }, - .not => .{ .not = operand }, - .deref => .{ .deref = operand }, - .borrow => .{ .borrow = .{ .mutable = prefix.mutable, .unchecked = prefix.unchecked, .place = operand } }, - } }; - } - return e; + return p.expressionDriver(.unary, 0); } fn postfix(p: *Parser) Error!ast.Expr { - const start = p.peek().pos; - var e = try p.primary(); - while (true) { - switch (p.peek().tag) { - .colon_colon => { - _ = p.next(); - if (p.peek().tag == .lt) { - const base = try p.box(ast.Expr, e); - const args = try p.typeArgs(); - e = .{ .span = p.span(start), .kind = .{ .specialize = .{ .base = base, .args = args } } }; - continue; - } - const base = if (e.kind == .specialize) e.kind.specialize.base.* else e; - const name = try p.exprPath(base) orelse return p.fail(p.peek(), "an enum name before `::`"); - const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{}; - const variant = try p.ident("a variant name"); - e = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant, .type_args = type_args } } }; - }, - .dot => { - _ = p.next(); - // After `.` a keyword is a member name (`task.cancelled`). - const nt = p.peek(); - if (nt.tag != .ident) return p.fail(nt, "a field, method or operation name"); - const name = p.next().text; - const base = try p.box(ast.Expr, e); - e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } }; - // `channel.make(…)`: the only explicit type argument. - if (p.peek().tag == .lt and e.kind.field.e.kind == .name and ((std.mem.eql(u8, name, "make") and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) or (std.mem.eql(u8, name, "new") and std.mem.eql(u8, e.kind.field.e.kind.name, "buffer")))) { - _ = p.next(); - const ty = try p.typeExpr(); - try p.closeAngle(); - const args = try p.callArgs(true); - const callee = try p.box(ast.Expr, e); - e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } }; - } - }, - .l_brace => { - if (p.no_struct) return e; - const base = if (e.kind == .specialize) e.kind.specialize.base.* else e; - const name = try p.exprPath(base) orelse return e; - const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{}; - const last = if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name; - if (!std.ascii.isUpper(last[0])) return e; - e = try p.structLiteral(start, name); - e.kind.struct_lit.type_args = type_args; - }, - .l_paren => { - if (e.kind == .variant and p.peekAt(1).tag == .r_paren) - return p.fail(p.peek(), "payload values or no parentheses for a payload-free variant"); - const args = try p.callArgs(e.kind != .variant); - const callee = try p.box(ast.Expr, e); - e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = args } } }; - }, - .l_bracket => { - _ = p.next(); - const saved = p.no_struct; - p.no_struct = false; - const lo = try p.expr(); - var hi: ?*const ast.Expr = null; - if (p.peek().tag == .dot_dot) { - _ = p.next(); - if (p.peek().tag == .r_bracket) return p.failAdvice(p.peek(), "an expression", .explicit_range_end); - hi = try p.box(ast.Expr, try p.expr()); - } - p.no_struct = saved; - _ = try p.expect(.r_bracket, "`]`"); - const base = try p.box(ast.Expr, e); - const lob = try p.box(ast.Expr, lo); - e = .{ .span = p.span(start), .kind = .{ .index = .{ .e = base, .lo = lob, .hi = hi } } }; - }, - else => return e, - } - } + return p.expressionDriver(.postfix, 0); } - fn callArgs(p: *Parser, borrow_arguments: bool) Error![]const ast.Expr { - _ = try p.expect(.l_paren, "`(`"); - const saved = p.no_struct; - p.no_struct = false; - defer p.no_struct = saved; - var args: std.ArrayList(ast.Expr) = .empty; - while (p.peek().tag != .r_paren) { - try args.append(p.arena, if (borrow_arguments) try p.exprWithBorrowAdvice(.borrow_argument) else try p.expr()); - if (p.peek().tag != .comma) break; - _ = p.next(); - } - _ = try p.expect(.r_paren, "`)`"); - return args.items; + fn primary(p: *Parser) Error!ast.Expr { + return p.expressionDriver(.primary, 0); } fn pathTail(p: *Parser, first: []const u8) Error![]const u8 { @@ -1126,23 +1331,7 @@ const Parser = struct { return out; } - fn structLiteral(p: *Parser, start: lex.Pos, name: []const u8) Error!ast.Expr { - _ = try p.expect(.l_brace, "`{`"); - var fields: std.ArrayList(ast.FieldInit) = .empty; - while (p.peek().tag != .r_brace) { - const fs = p.peek().pos; - const fname = try p.ident("a field name"); - _ = try p.expect(.colon, "`:`"); - const fe = try p.expr(); - try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe }); - if (p.peek().tag != .comma) break; - _ = p.next(); - } - _ = try p.expect(.r_brace, "`}`"); - return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = name, .fields = fields.items } } }; - } - - fn primary(p: *Parser) Error!ast.Expr { + fn primaryAtom(p: *Parser) Error!ast.Expr { const start = p.peek().pos; const t = p.peek(); switch (t.tag) { @@ -1155,35 +1344,6 @@ 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_paren => { - _ = p.next(); - const saved = p.no_struct; - p.no_struct = false; - const e = try p.expr(); - p.no_struct = saved; - _ = try p.expect(.r_paren, "`)`"); - return e; - }, - .l_bracket => { - _ = p.next(); - const e = try p.expr(); - if (p.peek().tag != .semicolon) { - var items: std.ArrayList(ast.Expr) = .empty; - try items.append(p.arena, e); - while (p.peek().tag == .comma) { - _ = p.next(); - if (p.peek().tag == .r_bracket) break; - try items.append(p.arena, try p.expr()); - } - _ = try p.expect(.r_bracket, "`]`"); - return .{ .span = p.span(start), .kind = .{ .array_list = items.items } }; - } - _ = try p.expect(.semicolon, "`;` in `[e; N]`"); - const n = try p.expect(.int, "array length"); - _ = try p.expect(.r_bracket, "`]`"); - const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); - return .{ .span = p.span(start), .kind = .{ .array_rep = .{ .e = try p.box(ast.Expr, e), .len = @intCast(len) } } }; - }, .l_brace => { const b = try p.block(); return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; @@ -1219,9 +1379,6 @@ const Parser = struct { const v = try p.ident("a variant name"); return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } }; } - if (p.peek().tag == .l_brace and !p.no_struct and std.ascii.isUpper(t.text[0])) { - return p.structLiteral(start, t.text); - } return .{ .span = p.span(start), .kind = .{ .name = t.text } }; }, else => return p.failPrimary(t), @@ -1507,6 +1664,551 @@ test "dereferenced borrow consumes unary place without swallowing outer operatio } } +// Independent former expression descent; type, block/control and path helpers +// are shared and outside this oracle. Used only for shallow comparisons. +const ReferenceExpressions = struct { + fn expr(p: *Parser) Error!ast.Expr { + return binary(p, 0); + } + + fn binary(p: *Parser, min_prec: u8) Error!ast.Expr { + const start = p.peek().pos; + var lhs = try castExpr(p); + while (true) { + // `e or trap`: the fallible shorthand (spec 15 §6). + if (p.atWord("or") and Parser.isWord(p.peekAt(1), "trap") and min_prec <= 1) { + _ = p.next(); + _ = p.next(); + const inner = try p.box(ast.Expr, lhs); + lhs = .{ .span = p.span(start), .kind = .{ .or_trap = inner } }; + continue; + } + const info = Parser.binInfo(p.peek()) orelse break; + if (info.prec <= min_prec) break; + _ = p.next(); + const rhs = try binary(p, info.prec); + // Comparisons do not chain. + const lb = try p.box(ast.Expr, lhs); + const rb = try p.box(ast.Expr, rhs); + lhs = .{ .span = p.span(start), .kind = .{ .binary = .{ .op = info.op, .l = lb, .r = rb } } }; + if (info.prec == 3 and Parser.binInfo(p.peek()) != null and Parser.binInfo(p.peek()).?.prec == 3) return p.fail(p.peek(), "parentheses around a comparison"); + } + return lhs; + } + + fn castExpr(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + var e = try unary(p); + while (true) { + const mode: ast.CastMode = if (p.atWord("as")) .widen else if (p.peek().tag == .as_bang) .checked else if (p.peek().tag == .as_pct) .wrap else break; + _ = p.next(); + const ty = try p.typeExpr(); + const inner = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .cast = .{ .mode = mode, .e = inner, .ty = ty } } }; + } + return e; + } + + fn unary(p: *Parser) Error!ast.Expr { + const Prefix = struct { + start: lex.Pos, + kind: enum { neg, not, deref, borrow }, + mutable: bool = false, + unchecked: bool = false, + }; + var pending: std.ArrayList(Prefix) = .empty; + defer pending.deinit(p.arena); + var e: ast.Expr = while (true) { + const t = p.peek(); + const kind: ?@FieldType(Prefix, "kind") = if (t.tag == .minus) .neg else if (Parser.isWord(t, "not")) .not else if (t.tag == .star) .deref else null; + if (kind) |k| { + _ = p.next(); + try pending.append(p.arena, .{ .start = t.pos, .kind = k }); + continue; + } + if (Parser.isWord(t, "ref") or Parser.isWord(t, "mut")) { + _ = p.next(); + var unchecked = false; + if (p.atWord("unchecked")) { + _ = p.next(); + unchecked = true; + } + try pending.append(p.arena, .{ .start = t.pos, .kind = .borrow, .mutable = Parser.isWord(t, "mut"), .unchecked = unchecked }); + // A borrow admits `* unary`; all other operands still use + // postfix directly, preserving the place grammar boundary. + if (p.peek().tag == .star) continue; + break try postfix(p); + } + if (Parser.isWord(t, "move")) { + _ = p.next(); + const name = try p.ident("the name of the value to move"); + break .{ .span = p.span(t.pos), .kind = .{ .move = name } }; + } + break try postfix(p); + }; + while (pending.pop()) |prefix| { + const operand = try p.box(ast.Expr, e); + e = .{ .span = p.span(prefix.start), .kind = switch (prefix.kind) { + .neg => .{ .neg = operand }, + .not => .{ .not = operand }, + .deref => .{ .deref = operand }, + .borrow => .{ .borrow = .{ .mutable = prefix.mutable, .unchecked = prefix.unchecked, .place = operand } }, + } }; + } + return e; + } + + fn postfix(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + var e = try primary(p); + while (true) { + switch (p.peek().tag) { + .colon_colon => { + _ = p.next(); + if (p.peek().tag == .lt) { + const base = try p.box(ast.Expr, e); + const args = try p.typeArgs(); + e = .{ .span = p.span(start), .kind = .{ .specialize = .{ .base = base, .args = args } } }; + continue; + } + const base = if (e.kind == .specialize) e.kind.specialize.base.* else e; + const name = try p.exprPath(base) orelse return p.fail(p.peek(), "an enum name before `::`"); + const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{}; + const variant = try p.ident("a variant name"); + e = .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = name, .name = variant, .type_args = type_args } } }; + }, + .dot => { + _ = p.next(); + // After `.` a keyword is a member name (`task.cancelled`). + const nt = p.peek(); + if (nt.tag != .ident) return p.fail(nt, "a field, method or operation name"); + const name = p.next().text; + const base = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .field = .{ .e = base, .name = name } } }; + // `channel.make(…)`: the only explicit type argument. + if (p.peek().tag == .lt and e.kind.field.e.kind == .name and ((std.mem.eql(u8, name, "make") and std.mem.eql(u8, e.kind.field.e.kind.name, "channel")) or (std.mem.eql(u8, name, "new") and std.mem.eql(u8, e.kind.field.e.kind.name, "buffer")))) { + _ = p.next(); + const ty = try p.typeExpr(); + try p.closeAngle(); + const args = try callArgs(p, true); + const callee = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } }; + } + }, + .l_brace => { + if (p.no_struct) return e; + const base = if (e.kind == .specialize) e.kind.specialize.base.* else e; + const name = try p.exprPath(base) orelse return e; + const type_args: []const ast.Type = if (e.kind == .specialize) e.kind.specialize.args else &.{}; + const last = if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name; + if (!std.ascii.isUpper(last[0])) return e; + e = try structLiteral(p, start, name); + e.kind.struct_lit.type_args = type_args; + }, + .l_paren => { + if (e.kind == .variant and p.peekAt(1).tag == .r_paren) + return p.fail(p.peek(), "payload values or no parentheses for a payload-free variant"); + const args = try callArgs(p, e.kind != .variant); + const callee = try p.box(ast.Expr, e); + e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = args } } }; + }, + .l_bracket => { + _ = p.next(); + const saved = p.no_struct; + p.no_struct = false; + const lo = try expr(p); + var hi: ?*const ast.Expr = null; + if (p.peek().tag == .dot_dot) { + _ = p.next(); + if (p.peek().tag == .r_bracket) return p.failAdvice(p.peek(), "an expression", .explicit_range_end); + hi = try p.box(ast.Expr, try expr(p)); + } + p.no_struct = saved; + _ = try p.expect(.r_bracket, "`]`"); + const base = try p.box(ast.Expr, e); + const lob = try p.box(ast.Expr, lo); + e = .{ .span = p.span(start), .kind = .{ .index = .{ .e = base, .lo = lob, .hi = hi } } }; + }, + else => return e, + } + } + } + + fn callArgs(p: *Parser, borrow_arguments: bool) Error![]const ast.Expr { + _ = try p.expect(.l_paren, "`(`"); + const saved = p.no_struct; + p.no_struct = false; + defer p.no_struct = saved; + var args: std.ArrayList(ast.Expr) = .empty; + while (p.peek().tag != .r_paren) { + try args.append(p.arena, if (borrow_arguments) try exprWithBorrowAdvice(p, .borrow_argument) else try expr(p)); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + return args.items; + } + + fn structLiteral(p: *Parser, start: lex.Pos, name: []const u8) Error!ast.Expr { + _ = try p.expect(.l_brace, "`{`"); + var fields: std.ArrayList(ast.FieldInit) = .empty; + while (p.peek().tag != .r_brace) { + const fs = p.peek().pos; + const fname = try p.ident("a field name"); + _ = try p.expect(.colon, "`:`"); + const fe = try expr(p); + try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe }); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_brace, "`}`"); + return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = name, .fields = fields.items } } }; + } + + fn primary(p: *Parser) Error!ast.Expr { + const start = p.peek().pos; + const t = p.peek(); + switch (t.tag) { + .int => { + _ = p.next(); + return .{ .span = p.span(start), .kind = .{ .int = .{ .text = t.text } } }; + }, + .bytes => { + _ = p.next(); + 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_paren => { + _ = p.next(); + const saved = p.no_struct; + p.no_struct = false; + const e = try expr(p); + p.no_struct = saved; + _ = try p.expect(.r_paren, "`)`"); + return e; + }, + .l_bracket => { + _ = p.next(); + const e = try expr(p); + if (p.peek().tag != .semicolon) { + var items: std.ArrayList(ast.Expr) = .empty; + try items.append(p.arena, e); + while (p.peek().tag == .comma) { + _ = p.next(); + if (p.peek().tag == .r_bracket) break; + try items.append(p.arena, try expr(p)); + } + _ = try p.expect(.r_bracket, "`]`"); + return .{ .span = p.span(start), .kind = .{ .array_list = items.items } }; + } + _ = try p.expect(.semicolon, "`;` in `[e; N]`"); + const n = try p.expect(.int, "array length"); + _ = try p.expect(.r_bracket, "`]`"); + const len = parseIntText(n.text) orelse return p.fail(n, "an array length"); + return .{ .span = p.span(start), .kind = .{ .array_rep = .{ .e = try p.box(ast.Expr, e), .len = @intCast(len) } } }; + }, + .l_brace => { + const b = try p.block(); + return .{ .span = p.span(start), .kind = .{ .block = try p.box(ast.Block, b) } }; + }, + .ident => { + if (Parser.isWord(t, "true") or Parser.isWord(t, "false")) { + _ = p.next(); + 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()); + return .{ .span = p.span(start), .kind = .{ .if_expr = conditional } }; + } + if (Parser.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 (isKeyword(t.text) and !(Parser.isWord(t, "struct") and p.peekAt(1).tag == .dot and Parser.isWord(p.peekAt(2), "unpack"))) return p.failPrimary(t); + _ = p.next(); + if (p.peek().tag == .colon_colon and p.peekAt(1).tag != .lt) { + _ = p.next(); + const v = try p.ident("a variant name"); + return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } }; + } + if (p.peek().tag == .l_brace and !p.no_struct and std.ascii.isUpper(t.text[0])) { + return structLiteral(p, start, t.text); + } + return .{ .span = p.span(start), .kind = .{ .name = t.text } }; + }, + else => return p.failPrimary(t), + } + } + + 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 expr(p); + } +}; + +const ExpressionForm = struct { before: []const u8, after: []const u8 }; +const expression_forms = [_]ExpressionForm{ + .{ .before = "(", .after = ")" }, + .{ .before = "f(", .after = ", 2u8)" }, + .{ .before = "value[", .after = "]" }, + .{ .before = "value[0u8..", .after = "]" }, + .{ .before = "[", .after = ", 2u8]" }, + .{ .before = "[", .after = "; 1]" }, + .{ .before = "Record { field: ", .after = ", other: 2u8 }" }, + .{ .before = "channel.make>>(", .after = ")" }, + .{ .before = "ns.E::::A(", .after = ")" }, + .{ .before = "not (", .after = ")" }, + .{ .before = "1u8 + (", .after = ")" }, + .{ .before = "(", .after = ") as u8" }, + .{ .before = "ref *(", .after = ")" }, +}; + +test "expression continuations match independent shallow descent and contextual errors" { + const leaves = [_][]const u8{ + "v", "1u8", "true", "\"abc\"", "move owner", "(x + y) as! u8", + "ref *value[1u8]", "mut unchecked *x", "Record { field: 1u8, }", "ns.E::::A(1u8)", "f::(1u8,)", "[1u8; 2]", + "[1u8, 2u8,]", "channel.make>()", "buffer.new(x)", "x or trap", "x < y", "!flag", + "&mut value", "zero", "f(&value)", "E::A(&value)", "ns.E::A()", "ref -x", + "x < y < z", "x[0..]", "[1u8; nope]", "Record { field 1u8 }", "f(1u8 2u8)", "(", + "[]", "", + }; + for (expression_forms) |form| for (leaves) |leaf| for ([_]bool{ false, true }) |no_struct| { + for ([_]Parser.ExprEntry{ .binary, .cast, .unary, .postfix, .primary }) |entry| { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const source = try std.fmt.allocPrint(a, "// UTF-8: λ\n{s}{s}{s}", .{ form.before, leaf, form.after }); + const tokens = try lex.tokenize(a, source); + var old: Parser = .{ .arena = a, .tokens = try a.dupe(Token, tokens), .file = "compare.aji", .module_name = "module", .no_struct = no_struct, .borrow_advice = .{ .at = 0, .kind = .borrow_binding } }; + var current = old; + current.tokens = try a.dupe(Token, tokens); + const before = switch (entry) { + .binary => ReferenceExpressions.binary(&old, 0), + .cast => ReferenceExpressions.castExpr(&old), + .unary => ReferenceExpressions.unary(&old), + .postfix => ReferenceExpressions.postfix(&old), + .primary => ReferenceExpressions.primary(&old), + }; + const after = current.expressionDriver(entry, 0); + if (before) |expected| { + try std.testing.expectEqualDeep(expected, try after); + } else |err| try std.testing.expectError(err, after); + try std.testing.expectEqualDeep(old.failure, current.failure); + try std.testing.expectEqual(old.pos, current.pos); + try std.testing.expectEqualDeep(old.last_end, current.last_end); + 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 "expression callbacks reuse stable work frames 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 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 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.expectEqual(capacity, p.expr_work.capacity); + try std.testing.expectEqual(@as(usize, 0), p.expr_frame_depth); + 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.sliceAsBytes(p.expr_work.items.ptr[0..p.expr_work.capacity]), 0xa5); + try std.testing.expectEqualDeep(reference, first); + p.deinitExpressionWork(); +} + +test "mixed deep expression syntax retains every constructor span and leaf error" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const depth = 32_768; + const header = "module deep\nfn f() -> void effects [] { let x = "; + const starts = try a.alloc(u32, depth); + const ends = try a.alloc(u32, depth); + var source: std.ArrayList(u8) = .empty; + try source.appendSlice(a, header); + for (0..depth) |i| { + starts[i] = @intCast(source.items.len - "module deep\n".len + 1); + try source.appendSlice(a, expression_forms[i % expression_forms.len].before); + } + const leaf_at = source.items.len; + const leaf_col: u32 = @intCast(leaf_at - "module deep\n".len + 1); + try source.appendSlice(a, "leaf"); + const leaf_end = leaf_col + 4; + var i: usize = depth; + while (i != 0) { + i -= 1; + try source.appendSlice(a, expression_forms[i % expression_forms.len].after); + ends[i] = @intCast(source.items.len - "module deep\n".len + 1); + } + try source.appendSlice(a, "; }"); + const result = try parseWithFile(a, source.items, "mixed.aji"); + try std.testing.expect(result == .ok); + var e = result.ok.functions[0].body.stmts[0].kind.let.e; + for (0..depth) |n| { + const kind = n % expression_forms.len; + if (kind == 0) continue; // Grouping has no AST node or added span. + try std.testing.expectEqualStrings("mixed.aji", e.span.file.?); + try std.testing.expectEqual(@as(u32, 2), e.span.start.line); + try std.testing.expectEqual(starts[n], e.span.start.col); + try std.testing.expectEqual(ends[n], e.span.end.col); + e = switch (kind) { + 1 => blk: { + try std.testing.expectEqual(@as(usize, 2), e.kind.call.args.len); + try std.testing.expectEqualStrings("2u8", e.kind.call.args[1].kind.int.text); + break :blk e.kind.call.args[0]; + }, + 2 => e.kind.index.lo.*, + 3 => e.kind.index.hi.?.*, + 4 => blk: { + try std.testing.expectEqual(@as(usize, 2), e.kind.array_list.len); + break :blk e.kind.array_list[0]; + }, + 5 => blk: { + try std.testing.expectEqual(@as(u64, 1), e.kind.array_rep.len); + break :blk e.kind.array_rep.e.*; + }, + 6 => blk: { + try std.testing.expectEqualStrings("Record", e.kind.struct_lit.name); + try std.testing.expectEqual(@as(usize, 2), e.kind.struct_lit.fields.len); + try std.testing.expectEqualStrings("field", e.kind.struct_lit.fields[0].name); + try std.testing.expectEqual(ends[n] - 14, e.kind.struct_lit.fields[0].span.end.col); + break :blk e.kind.struct_lit.fields[0].e; + }, + 7 => blk: { + try std.testing.expectEqualStrings("mut", e.kind.call.type_arg.?.kind.wrapped.wrapper); + break :blk e.kind.call.args[0]; + }, + 8 => blk: { + try std.testing.expectEqualStrings("ns.E", e.kind.call.callee.kind.variant.@"enum"); + try std.testing.expectEqual(@as(usize, 1), e.kind.call.callee.kind.variant.type_args.len); + break :blk e.kind.call.args[0]; + }, + 9 => e.kind.not.*, + 10 => e.kind.binary.r.*, + 11 => e.kind.cast.e.*, + 12 => blk: { + try std.testing.expect(e.kind.borrow.place.kind == .deref); + break :blk e.kind.borrow.place.kind.deref.*; + }, + else => unreachable, + }; + } + try std.testing.expectEqualStrings("leaf", e.kind.name); + try std.testing.expectEqual(leaf_col, e.span.start.col); + try std.testing.expectEqual(leaf_end, e.span.end.col); + source.items[leaf_at] = '!'; + const failure = try parse(a, source.items); + try std.testing.expect(failure == .err); + try std.testing.expectEqual(leaf_col, failure.err.pos.col); + try std.testing.expectEqualStrings("!", failure.err.found); + try std.testing.expectEqualStrings("an expression", failure.err.expected); + 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. +const ExpressionAllocationFailure = struct { + backing: Allocator, + at: usize, + attempts: usize = 0, + failed: 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) { + self.failed = true; + return null; + } + return self.backing.rawAlloc(len, alignment, ra); + } + fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool { + return false; + } + fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 { + return null; + } + fn free(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void { + const self: *@This() = @ptrCast(@alignCast(raw)); + self.backing.rawFree(memory, alignment, ra); + } +}; + +test "expression metadata output and nested scopes propagate recovering host OOM" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const source = "f(g(if true { (x[0u8..y]) as u8 } else { y }, Record:: { field: [1u8; 2], other: ns.E::A(3u8) }), ref *p)"; + const tokens = try lex.tokenize(a, source); + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 512); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var failure: ExpressionAllocationFailure = .{ .backing = arena.allocator(), .at = fail_index }; + var p: Parser = .{ .arena = failure.allocator(), .tokens = try a.dupe(Token, tokens), .no_struct = true, .borrow_advice = .{ .at = 0, .kind = .borrow_binding } }; + const result = p.expr(); + if (failure.failed) { + try std.testing.expectError(error.OutOfMemory, result); + try std.testing.expectEqual(fail_index + 1, failure.attempts); + } else { + try std.testing.expect((try result).kind == .call); + } + 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.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; + } + const module = try std.fmt.allocPrint(a, "module deep fn f() -> void effects [] {{ let x = {s}; }}", .{source}); + fail_index = 0; + while (true) : (fail_index += 1) { + try std.testing.expect(fail_index < 512); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var arena: std.heap.ArenaAllocator = .init(failing.allocator()); + const result = parse(arena.allocator(), module); + if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else try std.testing.expect((try result) == .ok); + arena.deinit(); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + if (!failing.has_induced_failure) break; + } +} + // Independent copy of the pre-repair unary derivation, used only on shallow // prefixes. Postfix parsing is outside this oracle's scope. fn referenceUnary(p: *Parser) Error!ast.Expr { diff --git a/tests/hosted/source_expression_depth.py b/tests/hosted/source_expression_depth.py index 34318c9..1ce5d2c 100644 --- a/tests/hosted/source_expression_depth.py +++ b/tests/hosted/source_expression_depth.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Operand/generic depth, exact lowering/CFG/fuel and rejection positions (Q-061).""" +"""Expression parsing/lowering depth, exact CFG/fuel and rejection positions (Q-061).""" import json from pathlib import Path import subprocess @@ -264,6 +264,96 @@ with tempfile.TemporaryDirectory(prefix='aji-expression-depth-') as directory: for command in ('lower', 'run', 'report', 'explore'): assert json.loads(cli(command, path, code=1)) == error + # Grouping is transparent in the AST; alternating binary/group frames + # also reach ordinary lowering, with independently counted AIR and fuel. + for depth in (0, 1, 16, 1024, 16384, 65536): + for kind in ('group', 'grouped-add'): + expression = ('(' * depth + '1i64' + ')' * depth if kind == 'group' + else '1i64 + (' * depth + '1i64' + ')' * depth) + instructions = 2 if kind == 'group' else 2 * depth + 2 + value = 1 if kind == 'group' else depth + 1 + path = root / f'{kind}-{depth}.aji' + path.write_text('module depth\nfn main() -> i64 effects [] { return ' + expression + '; }\n') + assert cli('check', path) == b'' + lowered = cli('lower', path) + assert sum(b' = ' in line or line.strip().startswith(b'ret ') for line in lowered.splitlines()) == instructions + if depth <= 1024: + assert json.loads(cli('run', path, '--fuel', instructions)) == {'status': 'returned', 'value': value} + assert json.loads(cli('run', path, '--fuel', instructions - 1, code=5)) == { + 'status': 'limit_exceeded', 'kind': 'fuel', 'limit': instructions - 1, 'steps': instructions - 1} + formatted = path.with_suffix('.formatted.aji') + output = cli('fmt', path) + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert json.loads(cli('fmt', formatted, '--check')) == { + 'file': str(formatted), 'status': 'formatted', 'changed': False} + assert cli('lower', formatted) == lowered + print(f'grouping depth: {kind} {depth}', flush=True) + + forms = ( + ('(', ')'), ('f(', ', 2u8)'), ('value[', ']'), ('value[0u8..', ']'), + ('[', ', 2u8]'), ('[', '; 1]'), ('Record { field: ', ', other: 2u8 }'), + ('channel.make>>(', ')'), ('ns.E::::A(', ')'), + ('not (', ')'), ('1u8 + (', ')'), ('(', ') as u8'), ('ref *(', ')'), + ) + header = 'fn f() -> void effects [] { let x = ' + for depth in (16, 1024, 16384, 32768): + prefix = ''.join(forms[i % len(forms)][0] for i in range(depth)) + suffix = ''.join(forms[i % len(forms)][1] for i in reversed(range(depth))) + path = root / f'mixed-syntax-{depth}.aji' + path.write_text('module depth\n' + header + prefix + 'leaf' + suffix + '; }\n') + # Syntax/formatter coverage only: these synthetic expressions need not + # have compatible types. Other non-scalar lowering remains Q-061 work. + output = cli('fmt', path) + formatted = path.with_suffix('.formatted.aji') + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert json.loads(cli('fmt', formatted, '--check')) == { + 'file': str(formatted), 'status': 'formatted', 'changed': False} + path.write_text('module depth\n' + header + prefix + '!' + suffix + '; }\n') + error = json.loads(cli('check', path, code=1)) + assert (error['code'], error['file'], error['line'], error['col']) == ( + 'E7001', str(path), 2, len(header) + len(prefix) + 1), error + assert error['repair_candidates'][0]['kind'] == 'boolean_negation', error + for command in ('lower', 'run', 'report', 'explore', 'fmt'): + assert json.loads(cli(command, path, code=1)) == error + print(f'mixed syntax depth: {depth}', flush=True) + + for depth in (16, 1024, 16384, 65536): + path = root / f'nested-call-syntax-{depth}.aji' + expression = '1i64 + id(' * depth + '1i64' + ')' * depth + path.write_text('module depth\nfn id(x: i64) -> i64 effects [] { return x; }\n' + 'fn main() -> i64 effects [] { return ' + expression + '; }\n') + output = cli('fmt', path) + formatted = path.with_suffix('.formatted.aji') + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert json.loads(cli('fmt', formatted, '--check')) == { + 'file': str(formatted), 'status': 'formatted', 'changed': False} + print(f'nested call syntax depth: {depth}', flush=True) + + # Block/control callbacks remain native. Their existing shallow/deeper + # syntax must retain its capacity while expression dispatch is moved out + # of the native stack, including explicit-return callback re-entry. + for depth in (64, 256): + for kind in ('block', 'if', 'returned-block', 'returned-if'): + if kind == 'block': + expression = '{' * depth + '1i64' + '}' * depth + elif kind == 'if': + expression = 'if true {' * depth + '1i64' + '} else {1i64}' * depth + elif kind == 'returned-block': + expression = '{return ' * depth + '1i64' + ';}' * depth + else: + expression = 'if true {return ' * depth + '1i64' + ';} else {return 1i64;}' * depth + path = root / f'control-syntax-{kind}-{depth}.aji' + path.write_text('module depth\nfn main() -> i64 effects [] { return ' + expression + '; }\n') + output = cli('fmt', path) + formatted = path.with_suffix('.formatted.aji') + formatted.write_bytes(output) + assert cli('fmt', formatted) == output + assert json.loads(cli('fmt', formatted, '--check')) == { + 'file': str(formatted), 'status': 'formatted', 'changed': False} + # Signed boundary literal remains one negative constant; the outer # checked negation traps rather than changing literal acceptance. minimum = root / 'minimum.aji'