Skip to content

Commit dfc3e11

Browse files
committed
zig fmt: fix handling of comments at top of file
1 parent ca49b6f commit dfc3e11

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

std/zig/parse.zig

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
4141
}
4242
var tok_it = tree.tokens.iterator(0);
4343

44+
// skip over line comments at the top of the file
45+
while (true) {
46+
const next_tok = tok_it.peek() ?? break;
47+
if (next_tok.id != Token.Id.LineComment) break;
48+
_ = tok_it.next();
49+
}
50+
4451
try stack.append(State.TopLevel);
4552

4653
while (true) {

std/zig/parser_test.zig

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,23 @@
1+
test "zig fmt: first thing in file is line comment" {
2+
try testCanonical(
3+
\\// Introspection and determination of system libraries needed by zig.
4+
\\
5+
\\// Introspection and determination of system libraries needed by zig.
6+
\\
7+
\\const std = @import("std");
8+
\\
9+
);
10+
}
11+
12+
test "zig fmt: line comment after doc comment" {
13+
try testCanonical(
14+
\\/// doc comment
15+
\\// line comment
16+
\\fn foo() void {}
17+
\\
18+
);
19+
}
20+
121
test "zig fmt: float literal with exponent" {
222
try testCanonical(
323
\\test "bit field alignment" {

std/zig/render.zig

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,20 @@ pub const Error = error{
1515
pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(stream).Child.Error || Error)!void {
1616
comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer);
1717

18+
// render all the line comments at the beginning of the file
19+
var tok_it = tree.tokens.iterator(0);
20+
while (tok_it.next()) |token| {
21+
if (token.id != Token.Id.LineComment) break;
22+
try stream.print("{}\n", tree.tokenSlicePtr(token));
23+
if (tok_it.peek()) |next_token| {
24+
const loc = tree.tokenLocationPtr(token.end, next_token);
25+
if (loc.line >= 2) {
26+
try stream.writeByte('\n');
27+
}
28+
}
29+
}
30+
31+
1832
var it = tree.root_node.decls.iterator(0);
1933
while (it.next()) |decl| {
2034
try renderTopLevelDecl(allocator, stream, tree, 0, decl.*);
@@ -1455,7 +1469,7 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@t
14551469
const comment = node.doc_comments ?? return;
14561470
var it = comment.lines.iterator(0);
14571471
while (it.next()) |line_token_index| {
1458-
try stream.print("{}\n", tree.tokenSlice(line_token_index.*));
1472+
try renderToken(tree, stream, line_token_index.*, indent, Space.Newline);
14591473
try stream.writeByteNTimes(' ', indent);
14601474
}
14611475
}

0 commit comments

Comments
 (0)