[clang] [clang-format] allow short function body on a single line (PR #151428)
Lidong Yan via cfe-commits
cfe-commits at lists.llvm.org
Tue Aug 26 21:03:35 PDT 2025
https://github.com/brandb97 updated https://github.com/llvm/llvm-project/pull/151428
>From 3a0a246803cdf295c99765bfffd5905c2a94ab38 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 | 23 +++++++++++++++++++++
2 files changed, 30 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..0f11f1dd33737 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14996,6 +14996,29 @@ TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
Style);
}
+TEST_F(FormatTest, SplitShortFunction) {
+ FormatStyle Style = getLLVMStyleWithColumns(40);
+ 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);
+ verifyFormat("int foo()\n"
+ "{\n"
+ " // comment\n"
+ " return 1;\n"
+ "}",
+ Style);
+ verifyFormat("int foo()\n"
+ "{\n"
+ " return 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1;\n"
+ "}",
+ Style);
+}
+
TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
FormatStyle Style = getLLVMStyle();
Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
More information about the cfe-commits
mailing list