[clang-format] Handle more cases for RemoveBracesLLVM
authorowenca <owenpiano@gmail.com>
Mon, 13 Jun 2022 07:10:26 +0000 (00:10 -0700)
committerowenca <owenpiano@gmail.com>
Mon, 13 Jun 2022 19:10:35 +0000 (12:10 -0700)
Call mightFitOneOneline() on the line before the closing brace only
if it is at the level of the block.

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

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

index 27219497941955883d3a3f092be260a5934f3fb1..77a59d8585091b20f2a64f07b72a7fab08ca1711 100644 (file)
@@ -844,7 +844,7 @@ FormatToken *UnwrappedLineParser::parseBlock(
 
   size_t PPStartHash = computePPHash();
 
-  unsigned InitialLevel = Line->Level;
+  const unsigned InitialLevel = Line->Level;
   nextToken(/*LevelDifference=*/AddLevels);
 
   // Bail out if there are too many levels. Otherwise, the stack might overflow.
@@ -905,7 +905,8 @@ FormatToken *UnwrappedLineParser::parseBlock(
         return false;
     }
     assert(!CurrentLines->empty());
-    if (!mightFitOnOneLine(CurrentLines->back()))
+    auto &LastLine = CurrentLines->back();
+    if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
       return false;
     if (Tok->is(TT_ElseLBrace))
       return true;
index 27984ecb0fa538c0015fd8b8d50b0a130b176d4f..972f3f195d8562d9a9797b27572cb4e9f94aefe7 100644 (file)
@@ -25784,6 +25784,25 @@ TEST_F(FormatTest, RemoveBraces) {
                "}",
                Style);
 
+  verifyFormat("if (a)\n"
+               "  b;\n"
+               "else if (c) {\n"
+               "  d;\n"
+               "  e;\n"
+               "} else\n"
+               "  f = g(foo, bar,\n"
+               "        baz);",
+               "if (a)\n"
+               "  b;\n"
+               "else {\n"
+               "  if (c) {\n"
+               "    d;\n"
+               "    e;\n"
+               "  } else\n"
+               "    f = g(foo, bar, baz);\n"
+               "}",
+               Style);
+
   Style.ColumnLimit = 0;
   verifyFormat("if (a)\n"
                "  b234567890223456789032345678904234567890 = "