commit 14fb82109b8c5d46721f93a5e2c87569e8bdd3dc (tree)
parent 2b48992a2f86a5c88fccaab6879774eb9266c24b
Author: Motiejus Jakštys <motiejus@jakstys.lt>
Date: Tue, 10 Feb 2026 18:26:33 +0000
parser: port zig fmt on/off in middle of code tests
Port tests:
- "'zig fmt: (off|on)' works in the middle of code"
- "'zig fmt: on' indentation is unchanged"
Handle block-terminated expressions (if, while) that don't need
semicolons by checking if previous token was '}'.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Diffstat:
2 files changed, 51 insertions(+), 0 deletions(-)
diff --git a/parser.c b/parser.c
@@ -2017,6 +2017,10 @@ static AstNodeIndex expectVarDeclExprStatement(Parser* p) {
// Expression that doesn't need semicolon (block-terminated)
return lhs;
default: {
+ // Check if expression ended with a block (previous token is })
+ // and thus doesn't need a semicolon
+ if (p->token_tags[p->tok_i - 1] == TOKEN_R_BRACE)
+ return lhs;
const AstNodeTag assign_tag = assignOpTag(p->token_tags[p->tok_i]);
if (assign_tag == AST_NODE_ROOT) {
fprintf(stderr,
diff --git a/parser_test.zig b/parser_test.zig
@@ -1869,6 +1869,53 @@ test "zig fmt: doc and line comment following 'zig fmt: on'" {
);
}
+test "zig fmt: 'zig fmt: (off|on)' works in the middle of code" {
+ try testTransform(
+ \\test "" {
+ \\ const x = 42;
+ \\
+ \\ if (foobar) |y| {
+ \\ // zig fmt: off
+ \\ }// zig fmt: on
+ \\
+ \\ const z = 420;
+ \\}
+ \\
+ ,
+ \\test "" {
+ \\ const x = 42;
+ \\
+ \\ if (foobar) |y| {
+ \\ // zig fmt: off
+ \\ }// zig fmt: on
+ \\
+ \\ const z = 420;
+ \\}
+ \\
+ );
+}
+
+test "zig fmt: 'zig fmt: on' indentation is unchanged" {
+ try testCanonical(
+ \\fn initOptionsAndLayouts(output: *Output, context: *Context) !void {
+ \\ // zig fmt: off
+ \\ try output.main_amount.init(output, "main_amount"); errdefer optput.main_amount.deinit();
+ \\ try output.main_factor.init(output, "main_factor"); errdefer optput.main_factor.deinit();
+ \\ try output.view_padding.init(output, "view_padding"); errdefer optput.view_padding.deinit();
+ \\ try output.outer_padding.init(output, "outer_padding"); errdefer optput.outer_padding.deinit();
+ \\ // zig fmt: on
+ \\
+ \\ // zig fmt: off
+ \\ try output.top.init(output, .top); errdefer optput.top.deinit();
+ \\ try output.right.init(output, .right); errdefer optput.right.deinit();
+ \\ try output.bottom.init(output, .bottom); errdefer optput.bottom.deinit();
+ \\ try output.left.init(output, .left); errdefer optput.left.deinit();
+ \\ // zig fmt: on
+ \\}
+ \\
+ );
+}
+
test "zig fmt: pointer of unknown length" {
try testCanonical(
\\fn foo(ptr: [*]u8) void {}