[clang] [clang-format] Fix short functions with nested braced-init (PR #213550)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Aug 2 08:21:52 PDT 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-format
Author: Gauarv Chaudhary (ANAMASGARD)
<details>
<summary>Changes</summary>
Fixes #<!-- -->213286.
Keep short functions on one line when their return statement contains nested braced initializers.
The closing brace now checks the kind of its matching opening brace, so braced-init lists are allowed while structural
braces still prevent merging.
Tests:
- `FormatTest.CustomShortFunctionOptions`
- `FormatTest.AllowShortRecordOnASingleLine`
- full `FormatTests` suite (1275 passed)
---
Full diff: https://github.com/llvm/llvm-project/pull/213550.diff
2 Files Affected:
- (modified) clang/lib/Format/UnwrappedLineFormatter.cpp (+8-4)
- (modified) clang/unittests/Format/FormatTest.cpp (+1)
``````````diff
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 7ea424349d923..7afc7a46dd1c0 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -983,13 +983,17 @@ class LineJoiner {
if (!nextTwoLinesFitInto(I, Limit))
return 0;
- // Second, check that the next line does not contain any braces - if it
- // does, readability declines when putting it into a single line.
+ // Second, check that the next line does not contain non-braced-init
+ // braces - if it does, readability declines when putting it into a
+ // single line.
if (I[1]->Last->is(TT_LineComment))
return 0;
do {
- if (Tok->isOneOf(tok::l_brace, tok::r_brace) &&
- Tok->isNot(BK_BracedInit)) {
+ if (Tok->is(tok::l_brace) && Tok->isNot(BK_BracedInit))
+ return 0;
+ if (Tok->is(tok::r_brace) &&
+ (!Tok->MatchingParen ||
+ Tok->MatchingParen->isNot(BK_BracedInit))) {
return 0;
}
Tok = Tok->Next;
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index b72a683ac1fff..6f604167f785c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -15368,6 +15368,7 @@ TEST_F(FormatTest, CustomShortFunctionOptions) {
// All functions should be on a single line if they fit
verifyFormat("int f() { return 42; }", CustomAll);
verifyFormat("int g() { return f() + h(); }", CustomAll);
+ verifyFormat("pair<int, int> g() { return {1, {}}; }", CustomAll);
verifyFormat("class C {\n"
" int f() { return 42; }\n"
"};",
``````````
</details>
https://github.com/llvm/llvm-project/pull/213550
More information about the cfe-commits
mailing list