[PATCH] D120873: [clang-format] Handle wrapped else for RemoveBracesLLVM

Owen Pan via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Mar 2 23:51:15 PST 2022


owenpan created this revision.
owenpan added reviewers: MyDeveloperDay, curdeius, HazardyKnusperkeks.
owenpan added a project: clang-format.
Herald added a project: All.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D120873

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


Index: clang/unittests/Format/FormatTest.cpp
===================================================================
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -24864,6 +24864,20 @@
                "};",
                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;
Index: clang/lib/Format/Format.cpp
===================================================================
--- clang/lib/Format/Format.cpp
+++ clang/lib/Format/Format.cpp
@@ -1812,9 +1812,12 @@
         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, "")));


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D120873.412614.patch
Type: text/x-patch
Size: 1680 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20220303/1edb86c9/attachment.bin>


More information about the cfe-commits mailing list