[clang-format] Fix a bug in RemoveBracesLLVM
authorowenca <owenpiano@gmail.com>
Fri, 10 Jun 2022 20:01:27 +0000 (13:01 -0700)
committerowenca <owenpiano@gmail.com>
Sat, 11 Jun 2022 08:12:11 +0000 (01:12 -0700)
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

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

index d2d69aa..2721949 100644 (file)
@@ -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);
index 14b169e..27984ec 100644 (file)
@@ -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"