diff --git a/lib/Format/WhitespaceManager.cpp b/lib/Format/WhitespaceManager.cpp index a75514ffe7541776cdebd840286bb43dbc74ace1..d4be86e586134daf683bc7553d1b47b7eea8a7e2 100644 --- a/lib/Format/WhitespaceManager.cpp +++ b/lib/Format/WhitespaceManager.cpp @@ -142,12 +142,26 @@ void WhitespaceManager::alignTrailingComments() { 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 4919a142a83e813517d20caccde79da16ec5e698..e51a8fe8cd3f7a4df3adfbb74b027ee077a274a9 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -637,6 +637,19 @@ TEST_F(FormatTest, UnderstandsSingleLineComments) { "// 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) {