[llvm-branch-commits] [clang] release/23.x: [clang-format] Fix short functions with nested braced-init (#213550) (PR #216717)
via llvm-branch-commits
llvm-branch-commits at lists.llvm.org
Mon Aug 17 05:21:41 PDT 2026
https://github.com/llvmbot created https://github.com/llvm/llvm-project/pull/216717
Backport e98256cc6abdc97701a3b1fa2588e2628180ead2
Requested by: @HazardyKnusperkeks
>From 839efd31d6e7f4af21954b104fda6819b8abb3e3 Mon Sep 17 00:00:00 2001
From: Gauarv Chaudhary <137998824+ANAMASGARD at users.noreply.github.com>
Date: Mon, 17 Aug 2026 17:36:47 +0530
Subject: [PATCH] [clang-format] Fix short functions with nested braced-init
(#213550)
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)
Signed-off-by: Gaurav Chaudhary <chaudharygaurav2004 at gmail.com>
(cherry picked from commit e98256cc6abdc97701a3b1fa2588e2628180ead2)
---
clang/lib/Format/UnwrappedLineFormatter.cpp | 12 ++++++++----
clang/unittests/Format/FormatTest.cpp | 1 +
2 files changed, 9 insertions(+), 4 deletions(-)
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 ec9ad612832f5..72e0182181763 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"
"};",
More information about the llvm-branch-commits
mailing list