diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index ec6574b33a8cf..c12096dc93ba8 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1855,7 +1855,7 @@ class BracesInserter : public TokenAnalyzer { assert(Token->BraceCount == -1); Brace = '{'; } else { - Brace = std::string(Token->BraceCount, '}'); + Brace = '\n' + std::string(Token->BraceCount, '}'); } Token->BraceCount = 0; const auto Start = Token->Tok.getEndLoc(); diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index e2cbcea14d7a9..502a84cbcc8b4 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2336,10 +2336,9 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) { assert(!Line->InPPDirective); Tok = nullptr; for (const auto &L : llvm::reverse(*CurrentLines)) { - if (!L.InPPDirective) { - Tok = getLastNonComment(L); - if (Tok) - break; + if (!L.InPPDirective && getLastNonComment(L)) { + Tok = L.Tokens.back().Tok; + break; } } assert(Tok); diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 624f3a78755f0..8008cce232d36 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -24481,6 +24481,13 @@ TEST_F(FormatTest, InsertBraces) { " f();", Style); + verifyFormat("if (a) {\n" + " f(); // comment\n" + "}", + "if (a)\n" + " f(); // comment", + Style); + verifyFormat("if (a) {\n" " f();\n" "}\n"