Author: owenca Date: 2022-08-30T22:50:36-07:00 New Revision: bc10ab8da1b511e794fbed2396c60c87e2e05ef2
URL: https://github.com/llvm/llvm-project/commit/bc10ab8da1b511e794fbed2396c60c87e2e05ef2 DIFF: https://github.com/llvm/llvm-project/commit/bc10ab8da1b511e794fbed2396c60c87e2e05ef2.diff LOG: [clang-format] Fix a bug in inserting braces at trailing comments If the style wraps control statement braces, the opening braces should be inserted after the trailing comments if present. Fixes #57419. Differential Revision: https://reviews.llvm.org/D132905 Added: Modified: clang/lib/Format/Format.cpp clang/lib/Format/UnwrappedLineParser.cpp clang/unittests/Format/FormatTest.cpp Removed: ################################################################################ diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index c2c020ea7ca85..1108a02407e4f 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1869,7 +1869,7 @@ class BracesInserter : public TokenAnalyzer { 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 index 03c6565598a7a..1e775f70a24a1 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -2606,7 +2606,10 @@ void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) { 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 index 257be01c3dae2..5d1129b851dff 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -25201,6 +25201,13 @@ TEST_F(FormatTest, InsertBraces) { " 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 @@ TEST_F(FormatTest, InsertBraces) { "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) { _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits