[clang-format] Fix a bug that indents else-comment-if incorrectly
authorowenca <owenca@users.noreply.github.com>
Wed, 23 Jun 2021 09:40:29 +0000 (02:40 -0700)
committerowenca <owenca@users.noreply.github.com>
Wed, 23 Jun 2021 11:57:45 +0000 (04:57 -0700)
PR50809

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

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

index 0fb5428..45ff319 100644 (file)
@@ -2021,7 +2021,15 @@ void UnwrappedLineParser::parseIfThenElse() {
       parseBlock(/*MustBeDeclaration=*/false);
       addUnwrappedLine();
     } else if (FormatTok->Tok.is(tok::kw_if)) {
+      FormatToken *Previous = AllTokens[Tokens->getPosition() - 1];
+      bool PrecededByComment = Previous->is(tok::comment);
+      if (PrecededByComment) {
+        addUnwrappedLine();
+        ++Line->Level;
+      }
       parseIfThenElse();
+      if (PrecededByComment)
+        --Line->Level;
     } else {
       addUnwrappedLine();
       ++Line->Level;
index 108d918..59690c7 100644 (file)
@@ -1181,6 +1181,13 @@ TEST_F(FormatTest, ElseIf) {
                "  g();\n"
                "else\n"
                "  h();");
+  verifyFormat("if (a)\n"
+               "  f();\n"
+               "else // comment\n"
+               "  if (b) {\n"
+               "    g();\n"
+               "    h();\n"
+               "  }");
   verifyFormat("if constexpr (a)\n"
                "  f();\n"
                "else if constexpr (b)\n"