[clang] 1aa608a - [clang-format] Handle wrapped else for RemoveBracesLLVM

via cfe-commits cfe-commits at lists.llvm.org
Thu Mar 3 04:55:13 PST 2022


Author: owenca
Date: 2022-03-03T04:53:15-08:00
New Revision: 1aa608a0208bc6a6945550a2071285ab51d899f1

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

LOG: [clang-format] Handle wrapped else for RemoveBracesLLVM

Removes the newline before the right brace that's followed by an
else on the next line.

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

Added: 
    

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

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c12096dc93ba8..497ebb414384f 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1812,9 +1812,12 @@ class BracesRemover : public TokenAnalyzer {
         if (!Token->Optional)
           continue;
         assert(Token->isOneOf(tok::l_brace, tok::r_brace));
-        const auto Start = Token == Line->Last
-                               ? Token->WhitespaceRange.getBegin()
-                               : Token->Tok.getLocation();
+        assert(Token->Next || Token == Line->Last);
+        const auto Start =
+            Token == Line->Last || (Token->Next->is(tok::kw_else) &&
+                                    Token->Next->NewlinesBefore > 0)
+                ? Token->WhitespaceRange.getBegin()
+                : Token->Tok.getLocation();
         const auto Range =
             CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc());
         cantFail(Result.add(tooling::Replacement(SourceMgr, Range, "")));

diff  --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 94f6dea1a2ed4..6c2b00b97ed3c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24974,6 +24974,20 @@ TEST_F(FormatTest, RemoveBraces) {
                "};",
                Style);
 
+  verifyFormat("if (a)\n"
+               "  foo();\n"
+               "else\n"
+               "  bar();",
+               "if (a)\n"
+               "{\n"
+               "  foo();\n"
+               "}\n"
+               "else\n"
+               "{\n"
+               "  bar();\n"
+               "}",
+               Style);
+
   // FIXME: See https://github.com/llvm/llvm-project/issues/53543.
 #if 0
   Style.ColumnLimit = 65;


        


More information about the cfe-commits mailing list