clang-format: [JS] Support shebang lines on the very first line.

Summary:
Shebang lines (`#!/bin/blah`) can be used in JavaScript scripts to indicate
they should be run using e.g. node. This change treats # lines on the first line
as line comments.

Reviewers: djasper

Subscribers: klimek, cfe-commits

Differential Revision: http://reviews.llvm.org/D20632

llvm-svn: 271185
This commit is contained in:
Martin Probst 2016-05-29 14:41:36 +00:00
parent 409697ecb9
commit 7ea9b6d783
3 changed files with 22 additions and 1 deletions

View File

@ -145,7 +145,7 @@ struct FormatToken {
/// \brief Whether the token text contains newlines (escaped or not).
bool IsMultiline = false;
/// \brief Indicates that this is the first token.
/// \brief Indicates that this is the first token of the file.
bool IsFirst = false;
/// \brief Whether there must be a line break before this token.

View File

@ -690,10 +690,24 @@ private:
}
LineType parsePreprocessorDirective() {
bool IsFirstToken = CurrentToken->IsFirst;
LineType Type = LT_PreprocessorDirective;
next();
if (!CurrentToken)
return Type;
if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
// JavaScript files can contain shebang lines of the form:
// #!/usr/bin/env node
// Treat these like C++ #include directives.
while (CurrentToken) {
// Tokens cannot be comments here.
CurrentToken->Type = TT_ImplicitStringLiteral;
next();
}
return LT_ImportStatement;
}
if (CurrentToken->Tok.is(tok::numeric_constant)) {
CurrentToken->SpacesRequiredBefore = 1;
return Type;

View File

@ -1276,5 +1276,12 @@ TEST_F(FormatTestJS, RequoteStringsLeave) {
verifyFormat("var x = 'foo';", LeaveQuotes);
}
TEST_F(FormatTestJS, SupportShebangLines) {
verifyFormat("#!/usr/bin/env node\n"
"var x = hello();",
"#!/usr/bin/env node\n"
"var x = hello();");
}
} // end namespace tooling
} // end namespace clang