clang-format: [JS] Fix template string ASI.
authorMartin Probst <martin@probst.io>
Fri, 21 Oct 2016 05:11:38 +0000 (05:11 +0000)
committerMartin Probst <martin@probst.io>
Fri, 21 Oct 2016 05:11:38 +0000 (05:11 +0000)
Summary:
Previously, automatic semicolon insertion would add an unwrapped line
when a template string contained a line break.

    var x = `foo${
        bar}`;

Would be formatted with `bar...` on a separate line and no indent.

Reviewers: djasper

Subscribers: cfe-commits, klimek

Differential Revision: https://reviews.llvm.org/D25675

llvm-svn: 284807

clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestJS.cpp

index 76dc413..42bee8c 100644 (file)
@@ -727,6 +727,8 @@ void UnwrappedLineParser::readTokenWithJavaScriptASI() {
     return;
 
   bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
+  bool PreviousStartsTemplateExpr =
+      Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
   if (PreviousMustBeValue && Line && Line->Tokens.size() > 1) {
     // If the token before the previous one is an '@', the previous token is an
     // annotation and can precede another identifier/value.
@@ -737,9 +739,12 @@ void UnwrappedLineParser::readTokenWithJavaScriptASI() {
   if (Next->is(tok::exclaim) && PreviousMustBeValue)
     addUnwrappedLine();
   bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
-  if (NextMustBeValue && (PreviousMustBeValue ||
-                          Previous->isOneOf(tok::r_square, tok::r_paren,
-                                            tok::plusplus, tok::minusminus)))
+  bool NextEndsTemplateExpr =
+      Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
+  if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
+      (PreviousMustBeValue ||
+       Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
+                         tok::minusminus)))
     addUnwrappedLine();
   if (PreviousMustBeValue && isJSDeclOrStmt(Keywords, Next))
     addUnwrappedLine();
index 3296138..66d7253 100644 (file)
@@ -1276,6 +1276,12 @@ TEST_F(FormatTestJS, TemplateStrings) {
   verifyFormat("var x = ` \\${foo}`;\n");
 }
 
+TEST_F(FormatTestJS, TemplateStringASI) {
+  verifyFormat("var x = `hello${world}`;", "var x = `hello${\n"
+                                           "    world\n"
+                                           "}`;");
+}
+
 TEST_F(FormatTestJS, NestedTemplateStrings) {
   verifyFormat(
       "var x = `<ul>${xs.map(x => `<li>${x}</li>`).join('\\n')}</ul>`;");