cli: disambiguate block statement boundaries

This commit is contained in:
dev committed 2026-10-07 18:21:07 +03:00
1 parent 462ddd2c5c
commit 911982dd1c
33 files changed
+465 -7

No files matched your search

+50
View File
@@ -473,6 +473,20 @@ const Parser = struct {
}
if (isWord(t, "select")) return .{ .span = p.span(start), .kind = .{ .select = try p.selectStmt() } };
// 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) {
@@ -1003,3 +1017,39 @@ test "parse a function" {
try std.testing.expectEqualStrings("`;`", bad.err.expected);
try std.testing.expectEqual(@as(u32, 2), bad.err.pos.line);
}
test "bare block constructs end before unary-leading statements regardless of gaps" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for ([_][]const u8{ "{}", "if true {} else if false {} else {}", "match 0u64 { 0 => {} _ => {} }" }) |construct| {
for ([_][]const u8{ " ", "\n", " // boundary\n" }) |gap| {
const source = try std.fmt.allocPrint(a, "module m fn f()->u64 effects [] {{{s}{s}*p=3u64; 42u64}}", .{ construct, gap });
const r = try parse(a, source);
try std.testing.expect(r == .ok);
const b = r.ok.functions[0].body;
try std.testing.expectEqual(@as(usize, 2), b.stmts.len);
try std.testing.expect(b.stmts[0].block_statement);
try std.testing.expect(b.stmts[1].kind == .assign);
try std.testing.expect(b.stmts[1].kind.assign.place.kind == .deref);
try std.testing.expect(b.tail.?.kind == .int);
}
}
}
test "tail, explicit discard and parentheses choose expression context syntactically" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const r = try parse(a, "module m fn f()->u64 effects [] {{2u64}; ({2u64})*3u64; {4u64}}");
try std.testing.expect(r == .ok);
const b = r.ok.functions[0].body;
try std.testing.expectEqual(@as(usize, 2), b.stmts.len);
try std.testing.expect(!b.stmts[0].block_statement);
try std.testing.expect(b.stmts[1].kind.expr.kind == .binary);
try std.testing.expect(b.tail.?.kind == .block);
for ([_][]const u8{ "+3u64", "as u64", ".x" }) |suffix| {
const source = try std.fmt.allocPrint(a, "module m fn f()->u64 effects [] {{{{2u64}} {s}}}", .{suffix});
try std.testing.expect((try parse(a, source)) == .err);
}
}