-
Notifications
You must be signed in to change notification settings - Fork 15.2k
[clang-format] Add option to omit wrapping for empty records #151970
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Currently, clang-format does not allow empty records to be formatted on a single line if the corresponding `BraceWrapping.After*` option is set to true. This results in unnecessarily wrapped code: struct foo { int i; }; struct bar { }; This patch adds the `BraceWrapping.WrapEmptyRecord` option, which allows `class`, `struct`, and `union` declarations with empty bodies to be formatted as one-liners, even when `AfterRecord: true`. As such, the following becomes possible: struct foo { int i; }; struct bar {};
Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the LLVM GitHub User Guide. You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums. |
@llvm/pr-subscribers-clang @llvm/pr-subscribers-clang-format Author: Tomáš Slanina (itzexpoexpo) ChangesCurrently, clang-format does not allow empty records to be formatted on a single line if the corresponding This results in unnecessarily wrapped code: struct foo
{
int i;
};
struct bar
{
}; This patch adds the As such, the following becomes possible: struct foo
{
int i;
};
struct bar {}; Full diff: https://github.com/llvm/llvm-project/pull/151970.diff 5 Files Affected:
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 31582a40de866..cc79dcb7b53ec 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1355,6 +1355,32 @@ struct FormatStyle {
BWACS_Always
};
+ enum BraceWrapEmptyRecordStyle : int8_t {
+ /// Use default wrapping rules for records
+ /// (AfterClass,AfterStruct,AfterUnion)
+ /// \code
+ /// class foo
+ /// {
+ /// int foo;
+ /// };
+ ///
+ /// class foo
+ /// {
+ /// };
+ /// \endcode
+ BWER_Default,
+ /// Override wrapping for empty records
+ /// \code
+ /// class foo
+ /// {
+ /// int foo;
+ /// };
+ ///
+ /// class foo {};
+ /// \endcode
+ BWER_Never
+ };
+
/// Precise control over the wrapping of braces.
/// \code
/// # Should be declared this way:
@@ -1585,6 +1611,8 @@ struct FormatStyle {
/// \endcode
///
bool SplitEmptyNamespace;
+ /// Wrap empty record (``class``/``struct``/``union``).
+ BraceWrapEmptyRecordStyle WrapEmptyRecord;
};
/// Control of individual brace wrapping cases.
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 063780721423f..0d72410f00c27 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -200,6 +200,7 @@ template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
+ IO.mapOptional("WrapEmptyRecord", Wrapping.WrapEmptyRecord);
}
};
@@ -232,6 +233,15 @@ struct ScalarEnumerationTraits<
}
};
+template <>
+struct ScalarEnumerationTraits<FormatStyle::BraceWrapEmptyRecordStyle> {
+ static void enumeration(IO &IO,
+ FormatStyle::BraceWrapEmptyRecordStyle &Value) {
+ IO.enumCase(Value, "Default", FormatStyle::BWER_Default);
+ IO.enumCase(Value, "Never", FormatStyle::BWER_Never);
+ }
+};
+
template <>
struct ScalarEnumerationTraits<
FormatStyle::BreakBeforeConceptDeclarationsStyle> {
@@ -1392,7 +1402,8 @@ static void expandPresetsBraceWrapping(FormatStyle &Expanded) {
/*IndentBraces=*/false,
/*SplitEmptyFunction=*/true,
/*SplitEmptyRecord=*/true,
- /*SplitEmptyNamespace=*/true};
+ /*SplitEmptyNamespace=*/true,
+ /*WrapEmptyRecord=*/FormatStyle::BWER_Default};
switch (Expanded.BreakBeforeBraces) {
case FormatStyle::BS_Linux:
Expanded.BraceWrapping.AfterClass = true;
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 4801d27b1395a..22132f6d2fd3b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -5935,10 +5935,11 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
// Don't attempt to interpret struct return types as structs.
if (Right.isNot(TT_FunctionLBrace)) {
- return (Line.startsWith(tok::kw_class) &&
- Style.BraceWrapping.AfterClass) ||
- (Line.startsWith(tok::kw_struct) &&
- Style.BraceWrapping.AfterStruct);
+ return ((Line.startsWith(tok::kw_class) &&
+ Style.BraceWrapping.AfterClass) ||
+ (Line.startsWith(tok::kw_struct) &&
+ Style.BraceWrapping.AfterStruct)) &&
+ Style.BraceWrapping.WrapEmptyRecord == FormatStyle::BWER_Default;
}
}
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index 91b8fdc8a3c38..e3efb0804d988 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -952,20 +952,26 @@ static bool isIIFE(const UnwrappedLine &Line,
}
static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
- const FormatToken &InitialToken) {
+ const FormatToken &InitialToken,
+ const FormatToken &NextToken) {
tok::TokenKind Kind = InitialToken.Tok.getKind();
if (InitialToken.is(TT_NamespaceMacro))
Kind = tok::kw_namespace;
+ bool IsEmptyBlock = NextToken.is(tok::r_brace);
+ bool WrapRecordAllowed =
+ !(IsEmptyBlock &&
+ Style.BraceWrapping.WrapEmptyRecord == FormatStyle::BWER_Never);
+
switch (Kind) {
case tok::kw_namespace:
return Style.BraceWrapping.AfterNamespace;
case tok::kw_class:
- return Style.BraceWrapping.AfterClass;
+ return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
case tok::kw_union:
- return Style.BraceWrapping.AfterUnion;
+ return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
case tok::kw_struct:
- return Style.BraceWrapping.AfterStruct;
+ return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
case tok::kw_enum:
return Style.BraceWrapping.AfterEnum;
default:
@@ -3191,7 +3197,7 @@ void UnwrappedLineParser::parseNamespace() {
if (FormatTok->is(tok::l_brace)) {
FormatTok->setFinalizedType(TT_NamespaceLBrace);
- if (ShouldBreakBeforeBrace(Style, InitialToken))
+ if (ShouldBreakBeforeBrace(Style, InitialToken, *Tokens->peekNextToken()))
addUnwrappedLine();
unsigned AddLevels =
@@ -3856,7 +3862,7 @@ bool UnwrappedLineParser::parseEnum() {
}
if (!Style.AllowShortEnumsOnASingleLine &&
- ShouldBreakBeforeBrace(Style, InitialToken)) {
+ ShouldBreakBeforeBrace(Style, InitialToken, *Tokens->peekNextToken())) {
addUnwrappedLine();
}
// Parse enum body.
@@ -4151,7 +4157,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr, bool IsJavaRecord) {
if (ParseAsExpr) {
parseChildBlock();
} else {
- if (ShouldBreakBeforeBrace(Style, InitialToken))
+ if (ShouldBreakBeforeBrace(Style, InitialToken, *Tokens->peekNextToken()))
addUnwrappedLine();
unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 96cc650f52a5d..3a5233674bd0f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -15615,6 +15615,36 @@ TEST_F(FormatTest, NeverMergeShortRecords) {
Style);
}
+TEST_F(FormatTest, WrapEmptyRecords) {
+ FormatStyle Style = getLLVMStyle();
+
+ Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+ Style.BraceWrapping.AfterStruct = true;
+ Style.BraceWrapping.AfterClass = true;
+ Style.BraceWrapping.AfterUnion = true;
+ Style.BraceWrapping.SplitEmptyRecord = false;
+
+ verifyFormat("class foo\n{\n void bar();\n};", Style);
+ verifyFormat("class foo\n{};", Style);
+
+ verifyFormat("struct foo\n{\n int bar;\n};", Style);
+ verifyFormat("struct foo\n{};", Style);
+
+ verifyFormat("union foo\n{\n int bar;\n};", Style);
+ verifyFormat("union foo\n{};", Style);
+
+ Style.BraceWrapping.WrapEmptyRecord = FormatStyle::BWER_Never;
+
+ verifyFormat("class foo\n{\n void bar();\n};", Style);
+ verifyFormat("class foo {};", Style);
+
+ verifyFormat("struct foo\n{\n int bar;\n};", Style);
+ verifyFormat("struct foo {};", Style);
+
+ verifyFormat("union foo\n{\n int bar;\n};", Style);
+ verifyFormat("union foo {};", Style);
+}
+
TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
// Elaborate type variable declarations.
verifyFormat("struct foo a = {bar};\nint n;");
|
Hi! Would @owenca and @mydeveloperday be willing to review this when time permits? Thank you in advance |
✅ With the latest revision this PR passed the C/C++ code formatter. |
See #151590 (comment). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add an entry to the changelog. And await feedback from @owenca.
We currently have the following:
So why not add an |
My patch targets empty records specifically, an
I feel it's functionally closer to the |
For the config below
You'll get the following format similar to what you want for records:
So it would make sense to try adding an |
I agree that there should be such an option for records too, but my point is that Short != Empty. This does not matter as much for namespaces and functions, but I'd argue that since empty structs are commonly used as tag types, it should be possible to format them on a single line without touching "contentful" structs that just happen to be short elsewhere. I think both options have their own use-case, and in the end it's a matter of style preference. |
Actually, we can use an
|
It might be worth notifying me of such a large change before I take the time to polish a solution you were already going to refuse to merge. Should I close and open a new PR since this means starting from the ground-up or will it be okay to just add commits that reverse the existing changes? |
Closing in favor of #154580 . |
How did you know that I was "already going to refuse to merge" when myself didn't because I had not reviewed your patch? Anyway, we have a long-standing high bar for adding new options although it hasn't always been enforced in recent years. Also, it happened from time to time that patches for new options didn't get merged because reviewers (e.g. #118566) or authors themselves (e.g. #150166) had come up with better alternatives. |
I deeply apologize for being that harsh on a PR, definitely not fitting here. I felt the 3 weeks of review process were a waste of time but in the end I could reuse a lot of the code in the new PR, so it didn't matter. Completely natural that a better alternative can be found and I agree that this enum |
This commit supersedes PR llvm#151970 by adding the option AllowShortRecordsOnASingleLine that allows the following formatting: struct foo {}; struct bar { int i; }; struct baz { int i; int j; int k; };
Currently, clang-format does not allow empty records to be formatted on a single line if the corresponding
BraceWrapping.After*
option is set to true.This results in unnecessarily wrapped code:
This patch adds the
BraceWrapping.WrapEmptyRecord
option, which allowsclass
,struct
, andunion
declarations with empty bodies to be formatted as one-liners, even whenAfter<Record>: true
.As such, the following becomes possible: