[clang] [clang-format] Use formatted breaks to align trailing comments (PR #246023)

Raiyyan via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 26 03:12:26 PST 2026


https://github.com/7se7en72025 updated https://github.com/llvm/llvm-project/pull/246023

>From a6b12fdc3a9e7d32e16fb91c5e592c6283ec9303 Mon Sep 17 00:00:00 2001
From: 7se7en72025 <f20241312 at pilani.bits-pilani.ac.in>
Date: Wed, 25 Nov 2026 19:51:52 +0530
Subject: [PATCH] [clang-format] Use formatted breaks to align trailing
 comments

Assisted-by: OpenAI Codex
---
 clang/lib/Format/WhitespaceManager.cpp        |  4 +++-
 clang/unittests/Format/FormatTestComments.cpp | 15 +++++++++++++++
 2 files changed, 18 insertions(+), 1 deletion(-)

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