[clang] ca7f471 - [clang-format] Fix a bug that indents else-comment-if incorrectly

via cfe-commits cfe-commits at lists.llvm.org
Wed Jun 23 05:00:14 PDT 2021


Author: owenca
Date: 2021-06-23T04:57:45-07:00
New Revision: ca7f4715858137dc97ac782cead65ba706bffa3c

URL: https://github.com/llvm/llvm-project/commit/ca7f4715858137dc97ac782cead65ba706bffa3c
DIFF: https://github.com/llvm/llvm-project/commit/ca7f4715858137dc97ac782cead65ba706bffa3c.diff

LOG: [clang-format] Fix a bug that indents else-comment-if incorrectly

PR50809

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

Added: 
    

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

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 0fb5428f89673..45ff319b5841d 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -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;

diff  --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 108d918ce3453..59690c722a9ed 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -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"


        


More information about the cfe-commits mailing list