[clang] 64df516 - [clang-format] Fix misaligned trailing comments in the presence of an empty block comment.

Marek Kurdej via cfe-commits cfe-commits at lists.llvm.org
Fri Jan 28 13:28:55 PST 2022


Author: Marek Kurdej
Date: 2022-01-28T22:28:48+01:00
New Revision: 64df51624f08f3b8d7370f820ab3545b1de98a0e

URL: https://github.com/llvm/llvm-project/commit/64df51624f08f3b8d7370f820ab3545b1de98a0e
DIFF: https://github.com/llvm/llvm-project/commit/64df51624f08f3b8d7370f820ab3545b1de98a0e.diff

LOG: [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

Added: 
    

Modified: 
    clang/lib/Format/BreakableToken.cpp
    clang/unittests/Format/FormatTestComments.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/BreakableToken.cpp b/clang/lib/Format/BreakableToken.cpp
index 085713b5c81ca..f68d802c1f95f 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 b5db353d4ae0a..b487440a06a3b 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) {


        


More information about the cfe-commits mailing list