From: Daniel Jasper Date: Wed, 7 Jan 2015 14:00:11 +0000 (+0000) Subject: clang-format: Understand single-line comments at the end of blocks. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=143cd925d8c7da707013cb8a82afc1fa61186ee6;p=clang clang-format: Understand single-line comments at the end of blocks. 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 --- diff --git a/lib/Format/WhitespaceManager.cpp b/lib/Format/WhitespaceManager.cpp index a2f599142d..bf1207e59c 100644 --- a/lib/Format/WhitespaceManager.cpp +++ b/lib/Format/WhitespaceManager.cpp @@ -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; } } diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index a0f450338b..fc49bde714 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -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"