From: Daniel Jasper Date: Fri, 21 Mar 2014 11:58:45 +0000 (+0000) Subject: clang-format: Preserve meaning of trailing comments on parameters. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=bafa9ec6582f0122ebee55a9b145242c0147ad83;p=clang clang-format: Preserve meaning of trailing comments on parameters. Formatting: SomeFunction(a, b, // comment c); Before: SomeFunction(a, b, // comment c); After: SomeFunction(a, b, // comment c); git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@204456 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp index a91c847452..08f2b27ed5 100644 --- a/lib/Format/TokenAnnotator.cpp +++ b/lib/Format/TokenAnnotator.cpp @@ -1114,6 +1114,27 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) { Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1; else Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; + + // If we find a trailing comment, iterate backwards to determine whether + // it seems to relate to a specific parameter. If so, break before that + // parameter to avoid changing the comment's meaning. E.g. don't move 'b' + // to the previous line in: + // SomeFunction(a, + // b, // comment + // c); + if (Current->isTrailingComment()) { + for (FormatToken *Parameter = Current->Previous; Parameter; + Parameter = Parameter->Previous) { + if (Parameter->isOneOf(tok::comment, tok::r_brace)) + break; + if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { + if (Parameter->Previous->Type != TT_CtorInitializerComma && + Parameter->HasUnescapedNewline) + Parameter->MustBreakBefore = true; + break; + } + } + } } else if (Current->SpacesRequiredBefore == 0 && spaceRequiredBefore(Line, *Current)) { Current->SpacesRequiredBefore = 1; diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index 282a443247..537a01f954 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -777,6 +777,25 @@ TEST_F(FormatTest, UnderstandsSingleLineComments) { "otherLine();")); } +TEST_F(FormatTest, KeepsParameterWithTrailingCommentsOnTheirOwnLine) { + EXPECT_EQ("SomeFunction(a,\n" + " b, // comment\n" + " c);", + format("SomeFunction(a,\n" + " b, // comment\n" + " c);")); + EXPECT_EQ("SomeFunction(a, b, // comment (unclear relation)\n" + " c);", + format("SomeFunction(a, b, // comment (unclear relation)\n" + " c);")); + EXPECT_EQ("SomeFunction(a, // comment\n" + " b,\n" + " c); // comment", + format("SomeFunction(a, // comment\n" + " b,\n" + " c); // comment")); +} + TEST_F(FormatTest, CanFormatCommentsLocally) { EXPECT_EQ("int a; // comment\n" "int b; // comment",