[clang] 05d7710 - [clang-format] Fix a bug in RemoveBracesLLVM

via cfe-commits cfe-commits at lists.llvm.org
Sat Jun 11 01:12:21 PDT 2022


Author: owenca
Date: 2022-06-11T01:12:11-07:00
New Revision: 05d771021ad9de12f3e657d464d18731a13578ab

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

LOG: [clang-format] Fix a bug in RemoveBracesLLVM

Remove the braces of an else block only if the r_brace of the block
is followed by an if.

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

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 d2d69aabfd80a..2721949794195 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2610,6 +2610,7 @@ FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
     nextToken();
     handleAttributes();
     if (FormatTok->is(tok::l_brace)) {
+      const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
       FormatTok->setFinalizedType(TT_ElseLBrace);
       ElseLeftBrace = FormatTok;
       CompoundStatementIndenter Indenter(this, Style, Line->Level);
@@ -2621,7 +2622,7 @@ FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
         KeepElseBraces = KeepElseBraces ||
                          ElseBlockKind == IfStmtKind::IfOnly ||
                          ElseBlockKind == IfStmtKind::IfElseIf;
-      } else if (IfLBrace && !IfLBrace->Optional) {
+      } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
         KeepElseBraces = true;
         assert(ElseLeftBrace->MatchingParen);
         markOptionalBraces(ElseLeftBrace);

diff  --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 14b169ebe5869..27984ecb0fa53 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25576,6 +25576,17 @@ TEST_F(FormatTest, RemoveBraces) {
                "  g;",
                Style);
 
+  verifyFormat("if (a) {\n"
+               "  b;\n"
+               "  c;\n"
+               "} else { // comment\n"
+               "  if (d) {\n"
+               "    e;\n"
+               "    f;\n"
+               "  }\n"
+               "}",
+               Style);
+
   verifyFormat("if (a)\n"
                "  b;\n"
                "else if (c)\n"


        


More information about the cfe-commits mailing list