https://github.com/owenca created https://github.com/llvm/llvm-project/pull/206393
Test cases are borrowed/adapted from #196760. Fixes #196663 >From 3f01a59c87268272f8533ab9ba0f78c6fc16de5b Mon Sep 17 00:00:00 2001 From: Owen Pan <[email protected]> Date: Sun, 28 Jun 2026 20:02:27 -0700 Subject: [PATCH] [clang-format] Fix a bug in recognizing trailing comments Test cases are borrowed/adapted from #196760. Fixes #196663 --- clang/lib/Format/WhitespaceManager.cpp | 2 ++ clang/unittests/Format/FormatTestComments.cpp | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp index 4a72abbfa9ec3..5596532556538 100644 --- a/clang/lib/Format/WhitespaceManager.cpp +++ b/clang/lib/Format/WhitespaceManager.cpp @@ -154,6 +154,7 @@ void WhitespaceManager::calculateLineBreakInformation() { auto &C = Changes[I]; auto &P = Changes[I - 1]; auto &PrevTokLength = P.TokenLength; + const auto *PP = I > 1 ? &Changes[I - 2] : nullptr; SourceLocation OriginalWhitespaceStart = C.OriginalWhitespaceRange.getBegin(); SourceLocation PreviousOriginalWhitespaceEnd = @@ -214,6 +215,7 @@ void WhitespaceManager::calculateLineBreakInformation() { (C.NewlinesBefore > 0 || C.Tok->is(tok::eof) || (C.IsInsideToken && C.Tok->is(tok::comment))) && P.Tok->is(tok::comment) && + (P.NewlinesBefore == 0 || !PP || PP->IsTrailingComment) && // FIXME: This is a dirty hack. The problem is that // BreakableLineCommentSection does comment reflow changes and here is // the aligning of trailing comments. Consider the case where we reflow diff --git a/clang/unittests/Format/FormatTestComments.cpp b/clang/unittests/Format/FormatTestComments.cpp index 707016096f7d2..d9a9f4c18efec 100644 --- a/clang/unittests/Format/FormatTestComments.cpp +++ b/clang/unittests/Format/FormatTestComments.cpp @@ -3060,6 +3060,42 @@ TEST_F(FormatTestComments, AlignTrailingCommentsLeave) { "}", Style); + // Move comments along, when it appears, that the indentation changed when a + // scope has been added or removed. + verifyFormat("void func() {\n" + " int i;\n" + " // comment\n" + " // comment 2\n" + "}", + "void func() {\n" + " int i;\n" + " // comment\n" + " // comment 2\n" + "}", + Style); + + verifyFormat("void func() {\n" + " // comment\n" + " // comment 2\n" + " int i;\n" + "}", + "void func() {\n" + " // comment\n" + " // comment 2\n" + " int i;\n" + "}", + Style); + + verifyFormat("void func() {\n" + " // non-trailing comment\n" + " int i;\n" + "}", + "void func() {\n" + " // non-trailing comment\n" + " int i;\n" + "}", + Style); + Style.AlignEscapedNewlines = FormatStyle::ENAS_Left; verifyNoChange("#define FOO \\\n" " /* foo(); */ \\\n" _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
