diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index fd6a1799578d87..c2c020ea7ca851 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1902,31 +1902,30 @@ class BracesRemover : public TokenAnalyzer { void removeBraces(SmallVectorImpl &Lines, tooling::Replacements &Result) { const auto &SourceMgr = Env.getSourceManager(); - bool EndsWithComment = false; - for (AnnotatedLine *Line : Lines) { + const auto End = Lines.end(); + for (auto I = Lines.begin(); I != End; ++I) { + const auto Line = *I; removeBraces(Line->Children, Result); - if (Line->Affected) { - for (FormatToken *Token = Line->First; Token && !Token->Finalized; - Token = Token->Next) { - if (!Token->Optional) - continue; - assert(Token->isOneOf(tok::l_brace, tok::r_brace)); - assert(Token->Previous || Token == Line->First); - const FormatToken *Next = Token->Next; - assert(Next || Token == Line->Last); - const auto Start = - (!Token->Previous && EndsWithComment) || - (Next && !(Next->isOneOf(tok::kw_else, tok::comment) && - Next->NewlinesBefore > 0)) - ? Token->Tok.getLocation() - : Token->WhitespaceRange.getBegin(); - const auto Range = - CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc()); - cantFail(Result.add(tooling::Replacement(SourceMgr, Range, ""))); - } + if (!Line->Affected) + continue; + const auto NextLine = I + 1 == End ? nullptr : I[1]; + for (auto Token = Line->First; Token && !Token->Finalized; + Token = Token->Next) { + if (!Token->Optional) + continue; + assert(Token->isOneOf(tok::l_brace, tok::r_brace)); + auto Next = Token->Next; + assert(Next || Token == Line->Last); + if (!Next && NextLine) + Next = NextLine->First; + const auto Start = + Next && Next->NewlinesBefore == 0 && Next->isNot(tok::eof) + ? Token->Tok.getLocation() + : Token->WhitespaceRange.getBegin(); + const auto Range = + CharSourceRange::getCharRange(Start, Token->Tok.getEndLoc()); + cantFail(Result.add(tooling::Replacement(SourceMgr, Range, ""))); } - assert(Line->Last); - EndsWithComment = Line->Last->is(tok::comment); } } }; diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 4879b0e06bd381..6abe155c388da8 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -26005,6 +26005,14 @@ TEST_F(FormatTest, RemoveBraces) { "}", Style); + verifyFormat("if (a) // comment\n" + " b = 1;", + "if (a) // comment\n" + "{\n" + " b = 1;\n" + "}", + Style); + Style.ColumnLimit = 20; verifyFormat("int ab = [](int i) {\n"