[clang] [clang-format] Add SignatureColumn lambda body indentation (PR #245575)
via cfe-commits
cfe-commits at lists.llvm.org
Tue Nov 24 18:49:19 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-format
Author: ihzgniqgnem
<details>
<summary>Changes</summary>
## Summary
Add a new `SignatureColumn` value to `LambdaBodyIndentation`. Lambda bodies are indented one level from the column of the lambda introducer (`[`), with the closing brace aligned to that same column. This is useful for lambdas whose signature starts well after the beginning of the enclosing line.
Also fix `BraceWrapping.IndentBraces` for lambda bodies: only apply the extra brace indentation when the opening brace is actually wrapped.
## Details
- Register `SignatureColumn` in the configuration enum, YAML mapping, documentation, and configuration tests.
- Preserve the lambda signature column and conditional-expression alignment column across nested scopes and fake parentheses.
- Avoid setting `NoLineBreak` for a lambda body immediately followed by a conditional colon, since that would conflict with the required break before `:` and leave the lambda body unformatted.
- Add regression coverage for:
- lambdas in conditional expressions, including trailing return types;
- nested lambdas and lambdas in function arguments;
- `IndentBraces` with and without `BeforeLambdaBody`;
- lambdas starting in column 0;
- reformatting deliberately mis-indented input.
## Tests
- `ninja -C build clang-format FormatTests`
- `FormatTests`: 1315 tests passed.
- `python clang/docs/tools/dump_format_style.py` matches `ClangFormatStyleOptions.md`.
## Notes
- Use AI tools to understand codebases and write test cases.
---
Full diff: https://github.com/llvm/llvm-project/pull/245575.diff
8 Files Affected:
- (modified) clang/docs/ClangFormatStyleOptions.md (+17-3)
- (modified) clang/docs/ReleaseNotes.md (+3)
- (modified) clang/include/clang/Format/Format.h (+15-3)
- (modified) clang/lib/Format/ContinuationIndenter.cpp (+54-8)
- (modified) clang/lib/Format/ContinuationIndenter.h (+10)
- (modified) clang/lib/Format/Format.cpp (+1)
- (modified) clang/unittests/Format/ConfigParseTest.cpp (+8)
- (modified) clang/unittests/Format/FormatTest.cpp (+151)
``````````diff
diff --git a/clang/docs/ClangFormatStyleOptions.md b/clang/docs/ClangFormatStyleOptions.md
index c7de6fc25e1f3a..0212e9e5317c3a 100644
--- a/clang/docs/ClangFormatStyleOptions.md
+++ b/clang/docs/ClangFormatStyleOptions.md
@@ -5498,9 +5498,11 @@ the configuration (without a prefix: `Auto`).
: The indentation style of lambda bodies. `Signature` (the default)
causes the lambda body to be indented one additional level relative to
- the indentation level of the signature. `OuterScope` forces the lambda
- body to be indented one additional level relative to the parent scope
- containing the lambda signature.
+ the indentation level of the signature. `SignatureColumn` causes the
+ lambda body to be indented one additional level relative to the column
+ of the signature, with the closing brace aligned to the signature column.
+ `OuterScope` forces the lambda body to be indented one additional level
+ relative to the parent scope containing the lambda signature.
Possible values:
@@ -5530,6 +5532,18 @@ the configuration (without a prefix: `Auto`).
}));
```
+ - `LBI_SignatureColumn` (in configuration: `SignatureColumn`)
+ Align lambda body relative to the column of the lambda signature,
+ i.e. one additional indentation level from the column where the
+ lambda signature starts, regardless of where the enclosing line
+ starts. The closing brace is aligned with the lambda signature column.
+
+ ```c++
+ someMethod(arg, [](SomeReallyLongLambdaSignatureArgument foo) {
+ return;
+ });
+ ```
+
(language)=
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 785455d8d58c6a..462d240e04a205 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1633,6 +1633,9 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
category priority and top-level directory.
- Add `SpacesInBlockComments` option to control spacing after `/*` and
before `*/` in ordinary block comments.
+- Add `SignatureColumn` value to `LambdaBodyIndentation` to indent lambda
+ bodies one additional level relative to the column where the lambda
+ signature starts, with the closing brace aligned to the signature column.
- Add `AfterRequiresExpression` sub-option of `BraceWrapping` to wrap the
body of requires expressions. It is enabled by the `Allman`, `Whitesmiths`,
and `GNU` styles of `BreakBeforeBraces`.
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 1f29dd630b8020..ead8c43cfcfa63 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -3856,13 +3856,25 @@ struct FormatStyle {
/// }));
/// \endcode
LBI_OuterScope,
+ /// Align lambda body relative to the column of the lambda signature,
+ /// i.e. one additional indentation level from the column where the
+ /// lambda signature starts, regardless of where the enclosing line
+ /// starts. The closing brace is aligned with the lambda signature column.
+ /// \code
+ /// someMethod(arg, [](SomeReallyLongLambdaSignatureArgument foo) {
+ /// return;
+ /// });
+ /// \endcode
+ LBI_SignatureColumn,
};
/// The indentation style of lambda bodies. `Signature` (the default)
/// causes the lambda body to be indented one additional level relative to
- /// the indentation level of the signature. `OuterScope` forces the lambda
- /// body to be indented one additional level relative to the parent scope
- /// containing the lambda signature.
+ /// the indentation level of the signature. `SignatureColumn` causes the
+ /// lambda body to be indented one additional level relative to the column
+ /// of the signature, with the closing brace aligned to the signature column.
+ /// `OuterScope` forces the lambda body to be indented one additional level
+ /// relative to the parent scope containing the lambda signature.
/// \version 13
LambdaBodyIndentationKind LambdaBodyIndentation;
diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp
index 2f96ad06385cfa..044df635777289 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1522,9 +1522,11 @@ ContinuationIndenter::getNewLineColumn(const LineState &State) {
if (Style.BraceWrapping.BeforeLambdaBody &&
Style.BraceWrapping.IndentBraces && Current.is(TT_LambdaLBrace)) {
- const auto From = Style.LambdaBodyIndentation == FormatStyle::LBI_Signature
- ? CurrentState.Indent
- : State.FirstIndent;
+ IndentationAndAlignment From = State.FirstIndent;
+ if (Style.LambdaBodyIndentation == FormatStyle::LBI_Signature)
+ From = CurrentState.Indent;
+ else if (Style.LambdaBodyIndentation == FormatStyle::LBI_SignatureColumn)
+ From = CurrentState.LambdaSignatureColumn.value_or(State.FirstIndent);
return From + Style.IndentWidth;
}
@@ -1537,6 +1539,14 @@ ContinuationIndenter::getNewLineColumn(const LineState &State) {
if ((NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) ||
(Style.isVerilog() && Keywords.isVerilogBegin(*NextNonComment))) {
+ if (Style.LambdaBodyIndentation == FormatStyle::LBI_SignatureColumn &&
+ State.NextToken->is(TT_LambdaLBrace)) {
+ unsigned SignatureColumn =
+ CurrentState.LambdaSignatureColumn.value_or(State.FirstIndent);
+ if (Style.BraceWrapping.IndentBraces)
+ SignatureColumn += Style.IndentWidth;
+ return SignatureColumn;
+ }
if (Current.NestingLevel == 0 ||
(Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
State.NextToken->is(TT_LambdaLBrace))) {
@@ -1944,6 +1954,9 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1;
if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow))
CurrentState.LastSpace = State.Column;
+ if (Current.is(TT_LambdaLSquare) &&
+ Style.LambdaBodyIndentation == FormatStyle::LBI_SignatureColumn)
+ CurrentState.LambdaSignatureColumn = State.Column;
if (Current.is(TT_RequiresExpression) &&
Style.RequiresExpressionIndentation == FormatStyle::REI_Keyword) {
CurrentState.NestedBlockIndent = State.Column;
@@ -1962,7 +1975,16 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,
Previous && Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
Previous->isNot(TT_DictLiteral) && State.Stack.size() > 1 &&
!CurrentState.HasMultipleNestedBlocks) {
- if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
+ const bool LambdaBeforeConditionalColon = [&] {
+ if (Style.LambdaBodyIndentation != FormatStyle::LBI_SignatureColumn ||
+ Previous->isNot(TT_LambdaLBrace) || !Previous->MatchingParen)
+ return false;
+ const FormatToken *Next =
+ Previous->MatchingParen->getNextNonComment();
+ return Next && Next->is(tok::colon) && Next->is(TT_ConditionalExpr);
+ }();
+ if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline &&
+ !LambdaBeforeConditionalColon)
for (ParenState &PState : llvm::drop_end(State.Stack))
PState.NoLineBreak = true;
State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
@@ -2145,12 +2167,20 @@ void ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
void ContinuationIndenter::moveStatePastFakeRParens(LineState &State) {
for (unsigned i = 0, e = State.NextToken->FakeRParens; i != e; ++i) {
unsigned VariablePos = State.Stack.back().VariablePos;
+ unsigned QuestionColumn = State.Stack.back().QuestionColumn;
+ auto LambdaSignatureColumn = State.Stack.back().LambdaSignatureColumn;
if (State.Stack.size() == 1) {
// Do not pop the last element.
break;
}
State.Stack.pop_back();
State.Stack.back().VariablePos = VariablePos;
+ // Keep the conditional alignment column across lambda signature scopes so
+ // that a following conditional colon can still be aligned.
+ if (Style.LambdaBodyIndentation == FormatStyle::LBI_SignatureColumn &&
+ QuestionColumn != 0)
+ State.Stack.back().QuestionColumn = QuestionColumn;
+ State.Stack.back().LambdaSignatureColumn = LambdaSignatureColumn;
}
if (State.NextToken->ClosesRequiresClause && Style.IndentRequiresClause) {
@@ -2304,9 +2334,16 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State,
(CurrentState.NoLineBreak || CurrentState.NoLineBreakInOperand ||
(Current.is(TT_TemplateOpener) &&
CurrentState.ContainsUnwrappedBuilder));
+ auto LambdaSignatureColumn = CurrentState.LambdaSignatureColumn;
+ unsigned QuestionColumn = CurrentState.QuestionColumn;
State.Stack.push_back(
ParenState(&Current, NewIndent, LastSpace, AvoidBinPacking, NoLineBreak));
auto &NewState = State.Stack.back();
+ // Keep the conditional alignment column across lambda signature scopes so
+ // that a following conditional colon can still be aligned.
+ if (Style.LambdaBodyIndentation == FormatStyle::LBI_SignatureColumn)
+ NewState.QuestionColumn = QuestionColumn;
+ NewState.LambdaSignatureColumn = LambdaSignatureColumn;
NewState.NestedBlockIndent = NestedBlockIndent;
NewState.BreakBeforeParameter = BreakBeforeParameter;
NewState.HasMultipleNestedBlocks = (Current.BlockParameterCount > 1);
@@ -2381,11 +2418,20 @@ void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) {
}
void ContinuationIndenter::moveStateToNewBlock(LineState &State, bool NewLine) {
- if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
- State.NextToken->is(TT_LambdaLBrace) &&
- !State.Line->MightBeFunctionDecl) {
+ if (State.NextToken->is(TT_LambdaLBrace)) {
const auto Indent = Style.IndentWidth * Style.BraceWrapping.IndentBraces;
- State.Stack.back().NestedBlockIndent = State.FirstIndent + Indent;
+ if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope &&
+ !State.Line->MightBeFunctionDecl) {
+ State.Stack.back().NestedBlockIndent =
+ State.FirstIndent + (NewLine ? Indent : 0);
+ } else if (Style.LambdaBodyIndentation ==
+ FormatStyle::LBI_SignatureColumn) {
+ unsigned SignatureColumn =
+ State.Stack.back().LambdaSignatureColumn.value_or(State.FirstIndent);
+ if (NewLine)
+ SignatureColumn += Indent;
+ State.Stack.back().NestedBlockIndent = SignatureColumn;
+ }
}
unsigned NestedBlockIndent = State.Stack.back().NestedBlockIndent;
// ObjC block sometimes follow special indentation rules.
diff --git a/clang/lib/Format/ContinuationIndenter.h b/clang/lib/Format/ContinuationIndenter.h
index ed347591525ea4..45b053161c9f07 100644
--- a/clang/lib/Format/ContinuationIndenter.h
+++ b/clang/lib/Format/ContinuationIndenter.h
@@ -18,6 +18,8 @@
#include "Encoding.h"
#include "FormatToken.h"
+#include <optional>
+
namespace clang {
class SourceManager;
@@ -301,6 +303,12 @@ struct ParenState {
/// Used to align further variables if necessary.
unsigned VariablePos = 0;
+ /// The column of the most recent lambda signature that applies to this
+ /// scope, i.e. the column of the lambda introducer '['. Used by
+ /// LambdaBodyIndentation: SignatureColumn. std::nullopt if no lambda
+ /// signature has been encountered in this scope.
+ std::optional<unsigned> LambdaSignatureColumn;
+
/// The precedence. The outermost level and the levels corresponding to tokens
/// have prec::Unknown.
prec::Level Precedence = prec::Unknown;
@@ -430,6 +438,8 @@ struct ParenState {
return CallContinuation < Other.CallContinuation;
if (VariablePos != Other.VariablePos)
return VariablePos < Other.VariablePos;
+ if (LambdaSignatureColumn != Other.LambdaSignatureColumn)
+ return LambdaSignatureColumn < Other.LambdaSignatureColumn;
if (ContainsLineBreak != Other.ContainsLineBreak)
return ContainsLineBreak;
if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index d284948253d628..3fa5959d4bb489 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -582,6 +582,7 @@ struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {
FormatStyle::LambdaBodyIndentationKind &Value) {
IO.enumCase(Value, "Signature", FormatStyle::LBI_Signature);
IO.enumCase(Value, "OuterScope", FormatStyle::LBI_OuterScope);
+ IO.enumCase(Value, "SignatureColumn", FormatStyle::LBI_SignatureColumn);
}
};
diff --git a/clang/unittests/Format/ConfigParseTest.cpp b/clang/unittests/Format/ConfigParseTest.cpp
index c7903d3cc51879..28e437e3bf42d7 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -1069,6 +1069,14 @@ TEST(ConfigParseTest, ParsesConfiguration) {
CHECK_PARSE("IndentGotoLabels: true", IndentGotoLabels,
FormatStyle::IGLS_OuterIndent);
+ Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
+ CHECK_PARSE("LambdaBodyIndentation: Signature", LambdaBodyIndentation,
+ FormatStyle::LBI_Signature);
+ CHECK_PARSE("LambdaBodyIndentation: OuterScope", LambdaBodyIndentation,
+ FormatStyle::LBI_OuterScope);
+ CHECK_PARSE("LambdaBodyIndentation: SignatureColumn", LambdaBodyIndentation,
+ FormatStyle::LBI_SignatureColumn);
+
Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
FormatStyle::BFCS_Both);
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index be4936e9a8d95e..cf0c83234921d7 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22051,6 +22051,157 @@ TEST_F(FormatTest, FormatsLambdas) {
" });\n"
"}",
BeforeLambdaBodyStyle);
+
+ // Lambdas with bodies aligned to the signature column.
+ Style = getLLVMStyleWithColumns(60);
+ Style.LambdaBodyIndentation = FormatStyle::LBI_SignatureColumn;
+ verifyFormat("Result doSomething(Promise promise) {\n"
+ " return promise.then(\n"
+ " [this, obj = std::move(s)](int bar) mutable {\n"
+ " return someObject.startAsyncAction().then(\n"
+ " [this, &obj](Result result) mutable {\n"
+ " result.processMore();\n"
+ " });\n"
+ " });\n"
+ "}",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.LambdaBodyIndentation = FormatStyle::LBI_SignatureColumn;
+ verifyFormat("void test() {\n"
+ " std::sort(v.begin(), v.end(), [](const auto &foo, "
+ "const auto &bar) {\n"
+ " return foo.baz < bar.baz &&\n"
+ " foo.qux < bar.qux && "
+ "foo.zot < bar.zot;\n"
+ " });\n"
+ "}",
+ Style);
+ verifyFormat("auto f = []() -> int {\n"
+ " return 4242424242424242424242424242424242424242424"
+ "242424242424242;\n"
+ " };",
+ "auto f = []() -> int {\n"
+ "return 4242424242424242424242424242424242424242424"
+ "242424242424242;\n"
+ "};",
+ Style);
+ verifyFormat("aFunction(1, b(c(foo, bar, baz, [](d) {\n"
+ " auto f = e(d);\n"
+ " return f;\n"
+ " })));",
+ Style);
+ verifyFormat("Namespace::Foo::Foo(LongClassName bar, "
+ "AnotherLongClassName baz)\n"
+ " : baz{baz}, func{[&] {\n"
+ " auto qux = bar;\n"
+ " return aFunkyFunctionCall(qux);\n"
+ " }} {}",
+ Style);
+
+ Style.ColumnLimit = 0;
+ Style.IndentWidth = 4;
+ verifyFormat("auto it = std::find_if_not(src_.begin() + pos + 1, src_.end(), "
+ "[](char c) {\n"
+ " "
+ " return std::isalnum(c) || c == '_';\n"
+ " "
+ "});",
+ "auto it = std::find_if_not(src_.begin() + pos + 1, src_.end(), "
+ "[](char c) {\n"
+ " return std::isalnum(c) || c == '_';\n"
+ "});",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.LambdaBodyIndentation = FormatStyle::LBI_SignatureColumn;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.BeforeLambdaBody = true;
+ Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+ verifyFormat("auto f = []() -> int\n"
+ " {\n"
+ " return 42;\n"
+ " };",
+ Style);
+ Style.BraceWrapping.IndentBraces = true;
+ verifyFormat("auto f = []() -> int\n"
+ " {\n"
+ " return 42;\n"
+ " };",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.LambdaBodyIndentation = FormatStyle::LBI_SignatureColumn;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.BeforeLambdaBody = false;
+ Style.BraceWrapping.IndentBraces = true;
+ Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+ verifyFormat("void test() {\n"
+ " auto f = [](int x) {\n"
+ " return x;\n"
+ " };\n"
+ "}",
+ "void test() {\n"
+ " auto f = [](int x) {\n"
+ "return x;\n"
+ "};\n"
+ "}",
+ Style);
+
+ Style = getLLVMStyle();
+ Style.LambdaBodyIndentation = FormatStyle::LBI_SignatureColumn;
+ Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+ verifyFormat("[] {\n"
+ " return 1;\n"
+ "};",
+ "[] {\n"
+ "return 1;\n"
+ "};",
+ Style);
+
+ verifyFormat("void test() {\n"
+ " auto f = c ? [] {\n"
+ " return 1;\n"
+ " }\n"
+ " : 0;\n"
+ "}",
+ "void test() {\n"
+ " auto f = c ? [] {\n"
+ "return 1;\n"
+ "} : 0;\n"
+ "}",
+ Style);
+ verifyFormat("void test() {\n"
+ " auto f = c ? []() -> int {\n"
+ " return 1;\n"
+ " }\n"
+ " : 0;\n"
+ "}",
+ "void test() {\n"
+ " auto f = c ? []() -> int {\n"
+ "return 1;\n"
+ "} : 0;\n"
+ "}",
+ Style);
+}
+
+TEST_F(FormatTest, LambdaOuterScopeIndentBraces) {
+ auto Style = getLLVMStyle();
+ Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.IndentBraces = true;
+ Style.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
+ verifyFormat("void test() {\n"
+ " auto f = [](int x) {\n"
+ " return x;\n"
+ " };\n"
+ "}",
+ "void test() {\n"
+ " auto f = [](int x) {\n"
+ "return x;\n"
+ "};\n"
+ "}",
+ Style);
}
TEST_F(FormatTest, LambdaWithLineComments) {
``````````
</details>
https://github.com/llvm/llvm-project/pull/245575
More information about the cfe-commits
mailing list