[clang] bd4e29e - [clang-format] Use formatted breaks to align trailing comments (#246023)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 26 12:03:28 PST 2026
Author: Raiyyan 3
Date: 2026-11-26T21:03:23+01:00
New Revision: bd4e29e5bff98b3ed4659702de8be8ab56d0cd70
URL: https://github.com/llvm/llvm-project/commit/bd4e29e5bff98b3ed4659702de8be8ab56d0cd70
DIFF: https://github.com/llvm/llvm-project/commit/bd4e29e5bff98b3ed4659702de8be8ab56d0cd70.diff
LOG: [clang-format] Use formatted breaks to align trailing comments (#246023)
With Allman braces, the first formatting pass can pad a block comment
after a closing brace to align it with a comment after `else`. The
second pass removes that padding because the brace now starts a line in
the input.
Use the formatter's recorded line-break decision when checking the
closing brace. Fall back to the original whitespace when the token has
no formatting decision.
The new regression failed before the change and passed afterward. All 54
comment formatting tests passed in a Windows build that reapplied this
change to LLVM 23.1.6.
Fixes #245606.
Assisted-by: OpenAI Codex. Draft for contributor review.
Added:
Modified:
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTestComments.cpp
Removed:
################################################################################
diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp
index 1d5aec62008238..64ac8c129fb168 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1135,7 +1135,9 @@ void WhitespaceManager::alignTrailingComments() {
while (Tok->Previous && Tok->Previous->is(tok::r_brace))
Tok = Tok->Previous;
- return Tok->NewlinesBefore > 0;
+ // Use the formatted line break when one has been decided.
+ return Tok->getDecision() == FD_Break ||
+ (Tok->getDecision() == FD_Unformatted && Tok->NewlinesBefore > 0);
};
if (I > 0 && C.NewlinesBefore == 0 &&
diff --git a/clang/unittests/Format/FormatTestComments.cpp b/clang/unittests/Format/FormatTestComments.cpp
index 3b281dc29fc39f..8743890a634333 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -2879,6 +2879,21 @@ TEST_F(FormatTestComments, AlignTrailingComments) {
"int a; //");
}
+TEST_F(FormatTestComments, DontAlignCommentAfterNewlyWrappedClosingBrace) {
+ auto Style = getLLVMStyle();
+ Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+ verifyFormat("void f()\n"
+ "{\n"
+ " if (true)\n"
+ " {\n"
+ " } /*a*/\n"
+ " else /*b*/\n"
+ " {\n"
+ " }\n"
+ "}",
+ "void f(){if(true){}/*a*/else/*b*/{}}", Style);
+}
+
TEST_F(FormatTestComments, AlignTrailingCommentsAcrossEmptyLines) {
FormatStyle Style = getLLVMStyle();
Style.AlignTrailingComments.Kind = FormatStyle::TCAS_Always;
More information about the cfe-commits
mailing list