Skip to content

Commit 91b9e67

Browse files
committed
[clang-format] Fix BraceWrapping: AfterFunction affecting synchronized blocks in Java.
Fixes #32031. Before this change, BraceWrapping: AfterFunction would affect synchronized blocks in Java, but they should be formatted w.r.t. BraceWrapping: AfterControlStatement. Using the config: ``` BreakBeforeBraces: Custom BraceWrapping: AfterControlStatement: false AfterFunction: true ``` would result in misformatted code like: ``` class Foo { void bar() { synchronized (this) { a(); a(); } } } ``` instead of: ``` class Foo { void bar() { synchronized (this) { a(); a(); } } } ``` Reviewed By: MyDeveloperDay, owenpan Differential Revision: https://reviews.llvm.org/D116767
1 parent 01f355f commit 91b9e67

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

clang/lib/Format/UnwrappedLineParser.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1523,8 +1523,16 @@ void UnwrappedLineParser::parseStructuralElement(bool IsTopLevel) {
15231523
// structural element.
15241524
// FIXME: Figure out cases where this is not true, and add projections
15251525
// for them (the one we know is missing are lambdas).
1526-
if (Style.BraceWrapping.AfterFunction)
1526+
if (Style.Language == FormatStyle::LK_Java &&
1527+
Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1528+
// If necessary, we could set the type to something different than
1529+
// TT_FunctionLBrace.
1530+
if (Style.BraceWrapping.AfterControlStatement ==
1531+
FormatStyle::BWACS_Always)
1532+
addUnwrappedLine();
1533+
} else if (Style.BraceWrapping.AfterFunction) {
15271534
addUnwrappedLine();
1535+
}
15281536
FormatTok->setType(TT_FunctionLBrace);
15291537
parseBlock();
15301538
addUnwrappedLine();

clang/unittests/Format/FormatTestJava.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,24 @@ TEST_F(FormatTestJava, SynchronizedKeyword) {
431431
verifyFormat("synchronized (mData) {\n"
432432
" // ...\n"
433433
"}");
434+
435+
FormatStyle Style = getLLVMStyle(FormatStyle::LK_Java);
436+
Style.BreakBeforeBraces = FormatStyle::BS_Custom;
437+
438+
Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
439+
Style.BraceWrapping.AfterFunction = false;
440+
verifyFormat("synchronized (mData)\n"
441+
"{\n"
442+
" // ...\n"
443+
"}",
444+
Style);
445+
446+
Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
447+
Style.BraceWrapping.AfterFunction = true;
448+
verifyFormat("synchronized (mData) {\n"
449+
" // ...\n"
450+
"}",
451+
Style);
434452
}
435453

436454
TEST_F(FormatTestJava, AssertKeyword) {

0 commit comments

Comments
 (0)