From 64df51624f08f3b8d7370f820ab3545b1de98a0e Mon Sep 17 00:00:00 2001 From: Marek Kurdej Date: Fri, 28 Jan 2022 10:37:22 +0100 Subject: [PATCH] [clang-format] Fix misaligned trailing comments in the presence of an empty block comment. Fixes https://github.com/llvm/llvm-project/issues/53441. Expected code: ``` /**/ // int a; // ``` was before misformatted to: ``` /**/ // int a; // ``` Because the "remaining length" (after the starting `/*`) of an empty block comment `/**/` was computed to be 0 instead of 2. Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan Differential Revision: https://reviews.llvm.org/D118475 --- clang/lib/Format/BreakableToken.cpp | 4 +++- clang/unittests/Format/FormatTestComments.cpp | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/clang/lib/Format/BreakableToken.cpp b/clang/lib/Format/BreakableToken.cpp index 085713b5c81c..f68d802c1f95 100644 --- a/clang/lib/Format/BreakableToken.cpp +++ b/clang/lib/Format/BreakableToken.cpp @@ -555,7 +555,9 @@ unsigned BreakableBlockComment::getRemainingLength(unsigned LineIndex, // We never need a decoration when breaking just the trailing "*/" postfix. bool HasRemainingText = Offset < Content[LineIndex].size(); if (!HasRemainingText) { - LineLength -= Decoration.size(); + bool HasDecoration = Lines[LineIndex].ltrim().startswith(Decoration); + if (HasDecoration) + LineLength -= Decoration.size(); } } return LineLength; diff --git a/clang/unittests/Format/FormatTestComments.cpp b/clang/unittests/Format/FormatTestComments.cpp index b5db353d4ae0..b487440a06a3 100644 --- a/clang/unittests/Format/FormatTestComments.cpp +++ b/clang/unittests/Format/FormatTestComments.cpp @@ -2842,6 +2842,12 @@ TEST_F(FormatTestComments, AlignTrailingComments) { "#define FOO_NODELOCAL 4 // Loopback\n\n" "} // namespace m\n", getLLVMStyleWithColumns(80))); + + // https://llvm.org/PR53441 + verifyFormat("/* */ //\n" + "int a; //\n"); + verifyFormat("/**/ //\n" + "int a; //\n"); } TEST_F(FormatTestComments, AlignsBlockCommentDecorations) {