Skip to content

Commit 878ce21

Browse files
authored
[clang-format] Propagate LeadingEmptyLinesAffected when joining lines (#146761)
Before this commit, when `LineJoiner` joins a line with affected leading whitespace, it would drop the knowledge of this entirely. However, when the `AffectedRangeManager` is computing the affected lines, the leading empty whitespace lines are potentially considered for non-first tokens in the `AnnotatedLine`. This causes a discrepancy in behavior when an `AnnotatedLine` is put together from joining multiple lines versus when it is not. We change `LineJoiner::join` to follow `AffectedRangeManager`'s logic, considering the leading whitespace when determining `Affected` for a token. https://github.com/llvm/llvm-project/blob/a63f57262898588b576d66e5fd79c0aa64b35f2d/clang/lib/Format/AffectedRangeManager.cpp#L111-L130 Fixes #138942.
1 parent c43efcb commit 878ce21

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

clang/lib/Format/UnwrappedLineFormatter.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -986,8 +986,10 @@ class LineJoiner {
986986
void join(AnnotatedLine &A, const AnnotatedLine &B) {
987987
assert(!A.Last->Next);
988988
assert(!B.First->Previous);
989-
if (B.Affected)
989+
if (B.Affected || B.LeadingEmptyLinesAffected) {
990+
assert(B.Affected || A.Last->Children.empty());
990991
A.Affected = true;
992+
}
991993
A.Last->Next = B.First;
992994
B.First->Previous = A.Last;
993995
B.First->CanBreakBefore = true;

clang/unittests/Format/FormatTestSelective.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ TEST_F(FormatTestSelective, RemovesTrailingWhitespaceOfFormattedLine) {
4141
EXPECT_EQ("int a;", format("int a; ", 0, 0));
4242
EXPECT_EQ("int a;\n", format("int a; \n \n \n ", 0, 0));
4343
EXPECT_EQ("int a;\nint b; ", format("int a; \nint b; ", 0, 0));
44+
45+
EXPECT_EQ("void f() {}", format("void f() {\n"
46+
" \n"
47+
"}",
48+
11, 0));
4449
}
4550

4651
TEST_F(FormatTestSelective, FormatsCorrectRegionForLeadingWhitespace) {

0 commit comments

Comments
 (0)