Author: owenca Date: 2026-06-30T21:55:27-07:00 New Revision: bae9ddca423145baf0c35e31898b723aa273f85c
URL: https://github.com/llvm/llvm-project/commit/bae9ddca423145baf0c35e31898b723aa273f85c DIFF: https://github.com/llvm/llvm-project/commit/bae9ddca423145baf0c35e31898b723aa273f85c.diff LOG: [clang-format] Fix a bug in recognizing trailing comments (#206393) Test cases are borrowed/adapted from #196760. Fixes #196663 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 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
