[clang-format] Respect definition separators when MaxEmptyLinesToKeep: 0 (#206406)
Fixes #206340.
The formatter should remove empty lines before Allman opening braces,
but should preserve the required empty line between function
definitions.
I have added a test case "AlwaysMaxEmptyLinesZeroAllman", and have
ensured other test cases run fine along with this one.
diff --git a/clang/lib/Format/DefinitionBlockSeparator.cpp b/clang/lib/Format/DefinitionBlockSeparator.cpp
index 6b52b1f..5fc5ba0 100644
--- a/clang/lib/Format/DefinitionBlockSeparator.cpp
+++ b/clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -66,6 +66,10 @@
};
unsigned NewlineCount =
(Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always ? 1 : 0) + 1;
+
+ Style.MaxEmptyLinesToKeep =
+ std::max(Style.MaxEmptyLinesToKeep, NewlineCount - 1);
+
WhitespaceManager Whitespaces(
Env.getSourceManager(), Style,
Style.LineEnding > FormatStyle::LE_CRLF
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index e5533c3..574014f 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -4387,12 +4387,6 @@
}
}
- if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
- Passes.emplace_back([&](const Environment &Env) {
- return DefinitionBlockSeparator(Env, Expanded).process();
- });
- }
-
if (Style.Language == FormatStyle::LK_ObjC &&
!Style.ObjCPropertyAttributeOrder.empty()) {
Passes.emplace_back([&](const Environment &Env) {
@@ -4411,6 +4405,12 @@
return Formatter(Env, Expanded, Status).process();
});
+ if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) {
+ Passes.emplace_back([&](const Environment &Env) {
+ return DefinitionBlockSeparator(Env, Expanded).process();
+ });
+ }
+
if (Style.isJavaScript() &&
Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) {
Passes.emplace_back([&](const Environment &Env) {
diff --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index 5e4c574..d18ab4e 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -391,6 +391,35 @@
Style, Prefix + Infix + Postfix);
}
+TEST_F(DefinitionBlockSeparatorTest, AlwaysMaxEmptyLinesZeroAllman) {
+ FormatStyle Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ Style.MaxEmptyLinesToKeep = 0;
+ Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+ Style.AllowShortFunctionsOnASingleLine = FormatStyle::ShortFunctionStyle();
+
+ verifyFormat("int my_function(int a)\n"
+ "\n"
+ "{\n"
+ " return a;\n"
+ "}\n"
+ "int other_function(int a)\n"
+ "\n"
+ "{\n"
+ " return a;\n"
+ "}",
+ Style,
+ "int my_function(int a)\n"
+ "{\n"
+ " return a;\n"
+ "}\n"
+ "\n"
+ "int other_function(int a)\n"
+ "{\n"
+ " return a;\n"
+ "}");
+}
+
TEST_F(DefinitionBlockSeparatorTest, Never) {
FormatStyle Style = getLLVMStyle();
Style.SeparateDefinitionBlocks = FormatStyle::SDS_Never;