]> granicus.if.org Git - clang/commitdiff
[clang-format] Don't align too long broken trailing comments
authorKrasimir Georgiev <krasimir@google.com>
Sun, 4 Jun 2017 19:27:02 +0000 (19:27 +0000)
committerKrasimir Georgiev <krasimir@google.com>
Sun, 4 Jun 2017 19:27:02 +0000 (19:27 +0000)
Summary:
This patch fixes a bug where clang-format will align newly broken trailing
comments even if this will make them exceed the line limit. The bug was caused
by a combination of unsigned arithmetic overflow and an imprecise computation
of the length of broken comment lines.

Reviewers: djasper, alexfh

Reviewed By: alexfh

Subscribers: klimek

Differential Revision: https://reviews.llvm.org/D33830

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@304687 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Format/WhitespaceManager.cpp
unittests/Format/FormatTestComments.cpp

index 3b6311d15487f8d9fd7b41a9f20bde9b2c7f7d06..c48883351c7093abcf2c53e73dc08480c4b71b55 100644 (file)
@@ -111,7 +111,7 @@ void WhitespaceManager::calculateLineBreakInformation() {
 
     // If there are multiple changes in this token, sum up all the changes until
     // the end of the line.
-    if (Changes[i - 1].IsInsideToken)
+    if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0)
       LastOutsideTokenChange->TokenLength +=
           Changes[i - 1].TokenLength + Changes[i - 1].Spaces;
     else
@@ -434,7 +434,9 @@ void WhitespaceManager::alignTrailingComments() {
       continue;
 
     unsigned ChangeMinColumn = Changes[i].StartOfTokenColumn;
-    unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
+    unsigned ChangeMaxColumn = Style.ColumnLimit >= Changes[i].TokenLength
+                                   ? Style.ColumnLimit - Changes[i].TokenLength
+                                   : ChangeMinColumn;
 
     // If we don't create a replacement for this change, we have to consider
     // it to be immovable.
index a44a6845587da6cde0bda60b8972d94c57b8ef07..09ee4645f591414da46470b63e7dd73309fbea05 100644 (file)
@@ -2170,6 +2170,15 @@ TEST_F(FormatTestComments, AlignTrailingComments) {
                    "// long",
                    getLLVMStyleWithColumns(15)));
 
+  // Don't align newly broken trailing comments if that would put them over the
+  // column limit.
+  EXPECT_EQ("int i, j; // line 1\n"
+            "int k; // line longg\n"
+            "       // long",
+            format("int i, j; // line 1\n"
+                   "int k; // line longg long",
+                   getLLVMStyleWithColumns(20)));
+
   // Align comment line sections aligned with the next token with the next
   // token.
   EXPECT_EQ("class A {\n"