[clang] [clang-format] allow short function body on a single line (PR #151428)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Aug 28 19:57:26 PDT 2025
https://github.com/brandb97 updated https://github.com/llvm/llvm-project/pull/151428
>From 53c90d4f81bf9d10949d2f398a8ccfa0c83af52d Mon Sep 17 00:00:00 2001
From: Lidong Yan <yldhome2d2 at gmail.com>
Date: Tue, 26 Aug 2025 19:40:05 +0800
Subject: [PATCH] [clang-format] allow short function body on a single line
When set AllowShortBlocksOnASingleLine to Always and short function
cannot be put on a single line, clang-format doesn't tries to put
the function body on a seperate new single line. Add
tryMergeSimpleBlocks() to put short function body on a single line if
possible.
Signed-off-by: Lidong Yan <yldhome2d2 at gmail.com>
---
clang/lib/Format/UnwrappedLineFormatter.cpp | 11 +++++++----
clang/unittests/Format/FormatTest.cpp | 12 ++++++++++++
2 files changed, 19 insertions(+), 4 deletions(-)
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp
index c938ff3965f9e..2a7bfd1a7dc5b 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -251,10 +251,13 @@ class LineJoiner {
: Limit - TheLine->Last->TotalLength;
if (TheLine->Last->is(TT_FunctionLBrace) &&
- TheLine->First == TheLine->Last &&
- !Style.BraceWrapping.SplitEmptyFunction &&
- NextLine.First->is(tok::r_brace)) {
- return tryMergeSimpleBlock(I, E, Limit);
+ TheLine->First == TheLine->Last) {
+ const bool EmptyFunctionBody = NextLine.First->is(tok::r_brace);
+ if ((EmptyFunctionBody && !Style.BraceWrapping.SplitEmptyFunction) ||
+ (!EmptyFunctionBody &&
+ Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Always)) {
+ return tryMergeSimpleBlock(I, E, Limit);
+ }
}
const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr;
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 8bc4ba53c3e1a..2144c2cce240f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14996,6 +14996,18 @@ TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
Style);
}
+TEST_F(FormatTest, MergeShortFunctionBody) {
+ auto Style = getLLVMStyle();
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
+ Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterFunction = true;
+
+ verifyFormat("int foo()\n"
+ "{ return 1; }",
+ Style);
+}
+
TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
FormatStyle Style = getLLVMStyle();
Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
More information about the cfe-commits
mailing list