]> granicus.if.org Git - clang/commitdiff
clang-format: [JS] Support shebang lines on the very first line.
authorMartin Probst <martin@probst.io>
Sun, 29 May 2016 14:41:36 +0000 (14:41 +0000)
committerMartin Probst <martin@probst.io>
Sun, 29 May 2016 14:41:36 +0000 (14:41 +0000)
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

lib/Format/FormatToken.h
lib/Format/TokenAnnotator.cpp
unittests/Format/FormatTestJS.cpp

index 84a7e4153a0a39b067f7eb08598d22aee20746a8..60b97f598742ba6b6b99e82b558c7c169245698d 100644 (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.
index e06b5de419db3b7b65b7e6de2aa64f00a35c23a5..a8b79b221254fecf1733bb367e33e95e50c5d558 100644 (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;
index 33fd065ce496399e0382ad0a4d2e5d3605cdfc02..e956ae2442494f653989f97b0ea3e7044deeed9b 100644 (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