Skip to content

Commit bbae59a

Browse files
authored
[clang-format] Finalize children after formatting them (#73753)
This would also fix the overlapping replacements below: ``` $ clang-format a( #else #endif ) = []() { )} The new replacement overlaps with an existing replacement. New replacement: <stdin>: 38:+7:" " Existing replacement: <stdin>: 38:+7:" " ``` Fixed #73487.
1 parent 4c17452 commit bbae59a

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

clang/lib/Format/UnwrappedLineFormatter.cpp

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -939,6 +939,12 @@ class LineJoiner {
939939
};
940940

941941
static void markFinalized(FormatToken *Tok) {
942+
if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
943+
Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
944+
tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
945+
tok::pp_else, tok::pp_endif)) {
946+
Tok = Tok->Next;
947+
}
942948
for (; Tok; Tok = Tok->Next) {
943949
if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
944950
// In the first pass we format all macro arguments in the expanded token
@@ -1060,6 +1066,8 @@ class LineFormatter {
10601066
}
10611067
Penalty +=
10621068
formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
1069+
if (!DryRun)
1070+
markFinalized(Child->First);
10631071

10641072
State.Column += 1 + Child->Last->TotalLength;
10651073
return true;
@@ -1429,16 +1437,8 @@ unsigned UnwrappedLineFormatter::format(
14291437
NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
14301438
RangeMinLevel = UINT_MAX;
14311439
}
1432-
if (!DryRun) {
1433-
auto *Tok = TheLine.First;
1434-
if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
1435-
Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
1436-
tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
1437-
tok::pp_else, tok::pp_endif)) {
1438-
Tok = Tok->Next;
1439-
}
1440-
markFinalized(Tok);
1441-
}
1440+
if (!DryRun)
1441+
markFinalized(TheLine.First);
14421442
}
14431443
PenaltyCache[CacheKey] = Penalty;
14441444
return Penalty;

clang/unittests/Format/FormatTest.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6361,6 +6361,13 @@ TEST_F(FormatTest, FormatAlignInsidePreprocessorElseBlock) {
63616361
" int quux = 4;\n"
63626362
"}",
63636363
Style);
6364+
verifyFormat("auto foo = [] { return; };\n"
6365+
"#if FOO\n"
6366+
"#else\n"
6367+
"count = bar;\n"
6368+
"mbid = bid;\n"
6369+
"#endif",
6370+
Style);
63646371

63656372
// Test with a mix of #if and #else blocks.
63666373
verifyFormat("void f1() {\n"

0 commit comments

Comments
 (0)