diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp --- a/clang/lib/Format/Format.cpp +++ b/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, ""))); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -24974,6 +24974,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;