Skip to content

Commit

Permalink
[clang-format] Break after string literals with trailing line breaks (l…
Browse files Browse the repository at this point in the history
…lvm#76795)

This restores a subset of functionality that was forego in
d68826d.

Streaming multiple string literals is rare enough in practice, hence
that change makes sense in general. But it seems people were
incidentally relying on this for having line breaks after string
literals that ended with `\n`.

This patch tries to restore that behavior to prevent regressions in the
upcoming LLVM release, until we can implement some configuration based
approach as proposed in llvm#69859.
  • Loading branch information
kadircet authored Jan 8, 2024
1 parent 0ba868d commit 27f5479
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions clang/lib/Format/TokenAnnotator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5151,6 +5151,14 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
return true;
if (Left.IsUnterminatedLiteral)
return true;
// FIXME: Breaking after newlines seems useful in general. Turn this into an
// option and recognize more cases like endl etc, and break independent of
// what comes after operator lessless.
if (Right.is(tok::lessless) && Right.Next &&
Right.Next->is(tok::string_literal) && Left.is(tok::string_literal) &&
Left.TokenText.ends_with("\\n\"")) {
return true;
}
if (Right.is(TT_RequiresClause)) {
switch (Style.RequiresClausePosition) {
case FormatStyle::RCPS_OwnLine:
Expand Down
2 changes: 2 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26708,6 +26708,8 @@ TEST_F(FormatTest, PPBranchesInBracedInit) {

TEST_F(FormatTest, StreamOutputOperator) {
verifyFormat("std::cout << \"foo\" << \"bar\" << baz;");
verifyFormat("std::cout << \"foo\\n\"\n"
" << \"bar\";");
}

TEST_F(FormatTest, BreakAdjacentStringLiterals) {
Expand Down
9 changes: 9 additions & 0 deletions clang/unittests/Format/TokenAnnotatorTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2499,6 +2499,15 @@ TEST_F(TokenAnnotatorTest, BraceKind) {
EXPECT_BRACE_KIND(Tokens[6], BK_Block);
}

TEST_F(TokenAnnotatorTest, StreamOperator) {
auto Tokens = annotate("\"foo\\n\" << aux << \"foo\\n\" << \"foo\";");
ASSERT_EQ(Tokens.size(), 9u) << Tokens;
EXPECT_FALSE(Tokens[1]->MustBreakBefore);
EXPECT_FALSE(Tokens[3]->MustBreakBefore);
// Only break between string literals if the former ends with \n.
EXPECT_TRUE(Tokens[5]->MustBreakBefore);
}

} // namespace
} // namespace format
} // namespace clang

0 comments on commit 27f5479

Please sign in to comment.