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 @@ -1869,7 +1869,7 @@ std::string Brace; if (Token->BraceCount < 0) { assert(Token->BraceCount == -1); - Brace = '{'; + Brace = "\n{"; } else { Brace = '\n' + std::string(Token->BraceCount, '}'); } diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2606,7 +2606,10 @@ if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() && PreprocessorDirectives.empty()) { - Tok = getLastNonComment(*Line); + assert(!Line->Tokens.empty()); + Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never + ? getLastNonComment(*Line) + : Line->Tokens.back().Tok; assert(Tok); if (Tok->BraceCount < 0) { assert(Tok->BraceCount == -1); 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 @@ -25201,6 +25201,13 @@ " f();", Style); + verifyFormat("if (a) { //\n" + " b = 1;\n" + "}", + "if (a) //\n" + " b = 1;", + Style); + verifyFormat("if (a) { // comment\n" " // comment\n" " f();\n" @@ -25266,6 +25273,19 @@ "if (a + b > c)\n" " f();", Style); + + Style.BreakBeforeBraces = FormatStyle::BS_Custom; + Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always; + // TODO: Delete the following line after #57421 is fixed. + Style.BraceWrapping.AfterFunction = true; + + verifyFormat("if (a) //\n" + "{\n" + " b = 1;\n" + "}", + "if (a) //\n" + " b = 1;", + Style); } TEST_F(FormatTest, RemoveBraces) {