From: Martin Probst Date: Sun, 29 May 2016 14:41:36 +0000 (+0000) Subject: clang-format: [JS] Support shebang lines on the very first line. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=513a0b11fd23965b29b8a0e3d1edc84c5a040ca3;p=clang 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 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@271185 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/FormatToken.h b/lib/Format/FormatToken.h index 84a7e4153a..60b97f5987 100644 --- a/lib/Format/FormatToken.h +++ b/lib/Format/FormatToken.h @@ -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. diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp index e06b5de419..a8b79b2212 100644 --- a/lib/Format/TokenAnnotator.cpp +++ b/lib/Format/TokenAnnotator.cpp @@ -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; diff --git a/unittests/Format/FormatTestJS.cpp b/unittests/Format/FormatTestJS.cpp index 33fd065ce4..e956ae2442 100644 --- a/unittests/Format/FormatTestJS.cpp +++ b/unittests/Format/FormatTestJS.cpp @@ -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