authorgravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2021-04-10 21:08:40+02:00
committergravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2021-04-10 23:10:24+02:00
log5b9ea5dd1ec0467f759d51f080fec68b2788d909
tree89f6d2787cb1c60a4c823fabb505f3cdbbe195dc
parentecd38c70cc0ce9173d7cd1d7e4cc146558e4f66a

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.

2 files changed, 48 insertions(+), 7 deletions(-)

lib/std/zig/parser_test.zig+37
......@@ -4677,6 +4677,43 @@ test "zig fmt: insert trailing comma if there are comments between switch values
46774677 );
46784678}
46794679
4680test "zig fmt: insert trailing comma if comments in array init" {
4681 try testTransform(
4682 \\var a = .{
4683 \\ "foo", //
4684 \\ "bar"
4685 \\};
4686 \\var a = .{
4687 \\ "foo",
4688 \\ "bar" //
4689 \\};
4690 \\var a = .{
4691 \\ "foo",
4692 \\ "//"
4693 \\};
4694 \\var a = .{
4695 \\ "foo",
4696 \\ "//" //
4697 \\};
4698 \\
4699 ,
4700 \\var a = .{
4701 \\ "foo", //
4702 \\ "bar",
4703 \\};
4704 \\var a = .{
4705 \\ "foo",
4706 \\ "bar", //
4707 \\};
4708 \\var a = .{ "foo", "//" };
4709 \\var a = .{
4710 \\ "foo",
4711 \\ "//", //
4712 \\};
4713 \\
4714 );
4715}
4716
46804717test "zig fmt: make single-line if no trailing comma" {
46814718 try testTransform(
46824719 \\test "function call no trailing comma" {
lib/std/zig/render.zig+11-7
......@@ -2240,17 +2240,21 @@ fn renderToken(ais: *Ais, tree: ast.Tree, token_index: ast.TokenIndex, space: Sp
22402240 }
22412241}
22422242
2243/// Returns true if there exists a comment between the start of token
2244/// `start_token` and the start of token `end_token`. This is used to determine
2245/// if e.g. a fn_proto should be wrapped and have a trailing comma inserted
2246/// even if there is none in the source.
2243/// Returns true if there exists a comment between any of the tokens from
2244/// `start_token` to `end_token`. This is used to determine if e.g. a
2245/// fn_proto should be wrapped and have a trailing comma inserted even if
2246/// there is none in the source.
22472247fn hasComment(tree: ast.Tree, start_token: ast.TokenIndex, end_token: ast.TokenIndex) bool {
22482248 const token_starts = tree.tokens.items(.start);
22492249
2250 const start = token_starts[start_token];
2251 const end = token_starts[end_token];
2250 var i = start_token;
2251 while (i < end_token) : (i += 1) {
2252 const start = token_starts[i] + tree.tokenSlice(i).len;
2253 const end = token_starts[i + 1];
2254 if (mem.indexOf(u8, tree.source[start..end], "//") != null) return true;
2255 }
22522256
2253 return mem.indexOf(u8, tree.source[start..end], "//") != null;
2257 return false;
22542258}
22552259
22562260/// Returns true if there exists a multiline string literal between the start