zig fmt: fix handling of comments at top of file

This commit is contained in:
Andrew Kelley 2018-05-25 01:03:15 -04:00
parent ca49b6f6b4
commit dfc3e11748
3 changed files with 42 additions and 1 deletions

View File

@ -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) {

View File

@ -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" {

View File

@ -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.*);
@ -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);
}
}