Stop aligning trailing comments which are aligned with the next line.
Previously we would align:
f(); // comment
// other comment
g();
Even if // other comment was at the start of the line. Now we do not
align trailing comments if they have been already aligned correctly
with the next line.
Thus,
f(); // comment
// other comment
g();
will not be changed, while:
f(); // comment
// other commment
g();
will lead to the two trailing comments being aligned.
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@182577 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Format/WhitespaceManager.cpp b/lib/Format/WhitespaceManager.cpp
index a75514f..d4be86e 100644
--- a/lib/Format/WhitespaceManager.cpp
+++ b/lib/Format/WhitespaceManager.cpp
@@ -142,12 +142,26 @@
unsigned ChangeMaxColumn = Style.ColumnLimit - Changes[i].TokenLength;
Newlines += Changes[i].NewlinesBefore;
if (Changes[i].IsTrailingComment) {
+ bool WasAlignedWithStartOfNextLine =
+ // A comment on its own line.
+ Changes[i].NewlinesBefore == 1 &&
+ // Not the last line.
+ i + 1 != e &&
+ // The start of the next token was previously aligned with
+ // the start of this comment.
+ (SourceMgr.getSpellingColumnNumber(
+ Changes[i].OriginalWhitespaceRange.getEnd()) ==
+ SourceMgr.getSpellingColumnNumber(
+ Changes[i + 1].OriginalWhitespaceRange.getEnd())) &&
+ // Which is not a comment itself.
+ Changes[i + 1].Kind != tok::comment;
if (BreakBeforeNext || Newlines > 1 ||
(ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
// Break the comment sequence if the previous line did not end
// in a trailing comment.
(Changes[i].NewlinesBefore == 1 && i > 0 &&
- !Changes[i - 1].IsTrailingComment)) {
+ !Changes[i - 1].IsTrailingComment) ||
+ WasAlignedWithStartOfNextLine) {
alignTrailingComments(StartOfSequence, i, MinColumn);
MinColumn = ChangeMinColumn;
MaxColumn = ChangeMaxColumn;
diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp
index 4919a14..e51a8fe 100644
--- a/unittests/Format/FormatTest.cpp
+++ b/unittests/Format/FormatTest.cpp
@@ -637,6 +637,19 @@
"// test\n"
"int a;\n"
"});"));
+
+ EXPECT_EQ("lineWith(); // comment\n"
+ "// at start\n"
+ "otherLine();",
+ format("lineWith(); // comment\n"
+ "// at start\n"
+ "otherLine();"));
+ EXPECT_EQ("lineWith(); // comment\n"
+ " // at start\n"
+ "otherLine();",
+ format("lineWith(); // comment\n"
+ " // at start\n"
+ "otherLine();"));
}
TEST_F(FormatTest, CanFormatCommentsLocally) {