zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 5b9ea5dd1ec0467f759d51f080fec68b2788d909 (tree)
parent ecd38c70cc0ce9173d7cd1d7e4cc146558e4f66a
Author: Isaac Freund <ifreund@ifreund.xyz>
Date:   Sat, 10 Apr 2021 21:08:40 +0200

zig fmt: fix line comment detection

Previously hasComment() would consider a string literal "//" to be a
line comment. Fix this by only searching the bytes between tokens.

Diffstat:
Mlib/std/zig/parser_test.zig | 37+++++++++++++++++++++++++++++++++++++
Mlib/std/zig/render.zig | 18+++++++++++-------
2 files changed, 48 insertions(+), 7 deletions(-)

diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig @@ -4677,6 +4677,43 @@ test "zig fmt: insert trailing comma if there are comments between switch values ); } +test "zig fmt: insert trailing comma if comments in array init" { + try testTransform( + \\var a = .{ + \\ "foo", // + \\ "bar" + \\}; + \\var a = .{ + \\ "foo", + \\ "bar" // + \\}; + \\var a = .{ + \\ "foo", + \\ "//" + \\}; + \\var a = .{ + \\ "foo", + \\ "//" // + \\}; + \\ + , + \\var a = .{ + \\ "foo", // + \\ "bar", + \\}; + \\var a = .{ + \\ "foo", + \\ "bar", // + \\}; + \\var a = .{ "foo", "//" }; + \\var a = .{ + \\ "foo", + \\ "//", // + \\}; + \\ + ); +} + test "zig fmt: make single-line if no trailing comma" { try testTransform( \\test "function call no trailing comma" { diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig @@ -2240,17 +2240,21 @@ fn renderToken(ais: *Ais, tree: ast.Tree, token_index: ast.TokenIndex, space: Sp } } -/// Returns true if there exists a comment between the start of token -/// `start_token` and the start of token `end_token`. This is used to determine -/// if e.g. a fn_proto should be wrapped and have a trailing comma inserted -/// even if there is none in the source. +/// Returns true if there exists a comment between any of the tokens from +/// `start_token` to `end_token`. This is used to determine if e.g. a +/// fn_proto should be wrapped and have a trailing comma inserted even if +/// there is none in the source. fn hasComment(tree: ast.Tree, start_token: ast.TokenIndex, end_token: ast.TokenIndex) bool { const token_starts = tree.tokens.items(.start); - const start = token_starts[start_token]; - const end = token_starts[end_token]; + var i = start_token; + while (i < end_token) : (i += 1) { + const start = token_starts[i] + tree.tokenSlice(i).len; + const end = token_starts[i + 1]; + if (mem.indexOf(u8, tree.source[start..end], "//") != null) return true; + } - return mem.indexOf(u8, tree.source[start..end], "//") != null; + return false; } /// Returns true if there exists a multiline string literal between the start