Skip to content

Commit

Permalink
zig fmt: fix handling of comments at top of file
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewrk committed May 25, 2018
1 parent ca49b6f commit dfc3e11
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
7 changes: 7 additions & 0 deletions std/zig/parse.zig
Expand Up @@ -41,6 +41,13 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree {
}
var tok_it = tree.tokens.iterator(0);

// skip over line comments at the top of the file
while (true) {
const next_tok = tok_it.peek() ?? break;
if (next_tok.id != Token.Id.LineComment) break;
_ = tok_it.next();
}

try stack.append(State.TopLevel);

while (true) {
Expand Down
20 changes: 20 additions & 0 deletions std/zig/parser_test.zig
@@ -1,3 +1,23 @@
test "zig fmt: first thing in file is line comment" {
try testCanonical(
\\// Introspection and determination of system libraries needed by zig.
\\
\\// Introspection and determination of system libraries needed by zig.
\\
\\const std = @import("std");
\\
);
}

test "zig fmt: line comment after doc comment" {
try testCanonical(
\\/// doc comment
\\// line comment
\\fn foo() void {}
\\
);
}

test "zig fmt: float literal with exponent" {
try testCanonical(
\\test "bit field alignment" {
Expand Down
16 changes: 15 additions & 1 deletion std/zig/render.zig
Expand Up @@ -15,6 +15,20 @@ pub const Error = error{
pub fn render(allocator: &mem.Allocator, stream: var, tree: &ast.Tree) (@typeOf(stream).Child.Error || Error)!void {
comptime assert(@typeId(@typeOf(stream)) == builtin.TypeId.Pointer);

// render all the line comments at the beginning of the file
var tok_it = tree.tokens.iterator(0);
while (tok_it.next()) |token| {
if (token.id != Token.Id.LineComment) break;
try stream.print("{}\n", tree.tokenSlicePtr(token));
if (tok_it.peek()) |next_token| {
const loc = tree.tokenLocationPtr(token.end, next_token);
if (loc.line >= 2) {
try stream.writeByte('\n');
}
}
}


var it = tree.root_node.decls.iterator(0);
while (it.next()) |decl| {
try renderTopLevelDecl(allocator, stream, tree, 0, decl.*);
Expand Down Expand Up @@ -1455,7 +1469,7 @@ fn renderDocComments(tree: &ast.Tree, stream: var, node: var, indent: usize) (@t
const comment = node.doc_comments ?? return;
var it = comment.lines.iterator(0);
while (it.next()) |line_token_index| {
try stream.print("{}\n", tree.tokenSlice(line_token_index.*));
try renderToken(tree, stream, line_token_index.*, indent, Space.Newline);
try stream.writeByteNTimes(' ', indent);
}
}

0 comments on commit dfc3e11

Please sign in to comment.