[clang-format] Wrap and indent lambda braces in GNU style (#135479)

Fix #133135
This commit is contained in:
Owen Pan 2025-04-12 15:06:21 -07:00 committed by GitHub
parent 09c8cfe219
commit 5f744cc630
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 42 additions and 2 deletions

View File

@ -1334,6 +1334,14 @@ unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
Style.IndentWidth;
}
if (Style.BraceWrapping.BeforeLambdaBody &&
Style.BraceWrapping.IndentBraces && Current.is(TT_LambdaLBrace)) {
const auto From = Style.LambdaBodyIndentation == FormatStyle::LBI_Signature
? CurrentState.Indent
: State.FirstIndent;
return From + Style.IndentWidth;
}
if ((NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) ||
(Style.isVerilog() && Keywords.isVerilogBegin(*NextNonComment))) {
if (Current.NestingLevel == 0 ||
@ -2113,7 +2121,8 @@ void ContinuationIndenter::moveStateToNewBlock(LineState &State, bool NewLine) {
if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
State.NextToken->is(TT_LambdaLBrace) &&
!State.Line->MightBeFunctionDecl) {
State.Stack.back().NestedBlockIndent = State.FirstIndent;
const auto Indent = Style.IndentWidth * Style.BraceWrapping.IndentBraces;
State.Stack.back().NestedBlockIndent = State.FirstIndent + Indent;
}
unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
// ObjC block sometimes follow special indentation rules.

View File

@ -1435,7 +1435,7 @@ static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
/*AfterExternBlock=*/true,
/*BeforeCatch=*/true,
/*BeforeElse=*/true,
/*BeforeLambdaBody=*/false,
/*BeforeLambdaBody=*/true,
/*BeforeWhile=*/true,
/*IndentBraces=*/true,
/*SplitEmptyFunction=*/true,

View File

@ -24267,6 +24267,37 @@ TEST_F(FormatTest, EmptyLinesInLambdas) {
"};");
}
TEST_F(FormatTest, LambdaBracesInGNU) {
auto Style = getGNUStyle();
EXPECT_EQ(Style.LambdaBodyIndentation, FormatStyle::LBI_Signature);
constexpr StringRef Code("auto x = [&] ()\n"
" {\n"
" for (int i = 0; i < y; ++i)\n"
" return 97;\n"
" };");
verifyFormat(Code, Style);
Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
verifyFormat(Code, Style);
verifyFormat("for_each_thread ([] (thread_info *thread)\n"
" {\n"
" /* Lambda body. */\n"
" });",
"for_each_thread([](thread_info *thread) {\n"
" /* Lambda body. */\n"
"});",
Style);
verifyFormat("iterate_over_lwps (scope_ptid, [=] (struct lwp_info *info)\n"
" {\n"
" /* Lambda body. */\n"
" });",
"iterate_over_lwps(scope_ptid, [=](struct lwp_info *info) {\n"
" /* Lambda body. */\n"
"});",
Style);
}
TEST_F(FormatTest, FormatsBlocks) {
FormatStyle ShortBlocks = getLLVMStyle();
ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;