]> granicus.if.org Git - clang/commitdiff
clang-format: Understand single-line comments at the end of blocks.
authorDaniel Jasper <djasper@google.com>
Wed, 7 Jan 2015 14:00:11 +0000 (14:00 +0000)
committerDaniel Jasper <djasper@google.com>
Wed, 7 Jan 2015 14:00:11 +0000 (14:00 +0000)
This prevents clang-format from moving/aligning the comment in the
snippet:
  void f() {
    int i; // some comment
    // some unrelated comment
  }

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

lib/Format/WhitespaceManager.cpp
unittests/Format/FormatTest.cpp

index a2f599142df87109caee4d9c83c81ad970f2658b..bf1207e59c9020b6ea5961ebfde9602d9f72a854 100644 (file)
@@ -163,15 +163,17 @@ void WhitespaceManager::alignTrailingComments() {
                                   Changes[i - 1].StartOfTokenColumn == 0;
     bool WasAlignedWithStartOfNextLine = false;
     if (Changes[i].NewlinesBefore == 1) { // A comment on its own line.
+      unsigned CommentColumn = SourceMgr.getSpellingColumnNumber(
+          Changes[i].OriginalWhitespaceRange.getEnd());
       for (unsigned j = i + 1; j != e; ++j) {
         if (Changes[j].Kind != tok::comment) { // Skip over comments.
+          unsigned NextColumn = SourceMgr.getSpellingColumnNumber(
+              Changes[j].OriginalWhitespaceRange.getEnd());
           // The start of the next token was previously aligned with the
           // start of this comment.
           WasAlignedWithStartOfNextLine =
-              (SourceMgr.getSpellingColumnNumber(
-                   Changes[i].OriginalWhitespaceRange.getEnd()) ==
-               SourceMgr.getSpellingColumnNumber(
-                   Changes[j].OriginalWhitespaceRange.getEnd()));
+              CommentColumn == NextColumn ||
+              CommentColumn == NextColumn + Style.IndentWidth;
           break;
         }
       }
index a0f450338b13baf1333f1f1178c94b366483dc31..fc49bde7140c6e3f909957533659bd83940f228c 100644 (file)
@@ -998,6 +998,14 @@ TEST_F(FormatTest, UnderstandsSingleLineComments) {
                    " // first\n"
                    "// at start\n"
                    "otherLine();"));
+  EXPECT_EQ("void f() {\n"
+            "  lineWith(); // comment\n"
+            "  // at start\n"
+            "}",
+            format("void              f() {\n"
+                   "  lineWith(); // comment\n"
+                   "  // at start\n"
+                   "}"));
 
   verifyFormat(
       "#define A                                                  \\\n"