Skip to content

Commit

Permalink
[clang-format] Finalize children after formatting them (#73753)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
owenca committed Nov 29, 2023
1 parent 4c17452 commit bbae59a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
20 changes: 10 additions & 10 deletions clang/lib/Format/UnwrappedLineFormatter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,12 @@ class LineJoiner {
};

static void markFinalized(FormatToken *Tok) {
if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
tok::pp_else, tok::pp_endif)) {
Tok = Tok->Next;
}
for (; Tok; Tok = Tok->Next) {
if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) {
// In the first pass we format all macro arguments in the expanded token
Expand Down Expand Up @@ -1060,6 +1066,8 @@ class LineFormatter {
}
Penalty +=
formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
if (!DryRun)
markFinalized(Child->First);

State.Column += 1 + Child->Last->TotalLength;
return true;
Expand Down Expand Up @@ -1429,16 +1437,8 @@ unsigned UnwrappedLineFormatter::format(
NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
RangeMinLevel = UINT_MAX;
}
if (!DryRun) {
auto *Tok = TheLine.First;
if (Tok->is(tok::hash) && !Tok->Previous && Tok->Next &&
Tok->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_ifndef,
tok::pp_elif, tok::pp_elifdef, tok::pp_elifndef,
tok::pp_else, tok::pp_endif)) {
Tok = Tok->Next;
}
markFinalized(Tok);
}
if (!DryRun)
markFinalized(TheLine.First);
}
PenaltyCache[CacheKey] = Penalty;
return Penalty;
Expand Down
7 changes: 7 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6361,6 +6361,13 @@ TEST_F(FormatTest, FormatAlignInsidePreprocessorElseBlock) {
" int quux = 4;\n"
"}",
Style);
verifyFormat("auto foo = [] { return; };\n"
"#if FOO\n"
"#else\n"
"count = bar;\n"
"mbid = bid;\n"
"#endif",
Style);

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

0 comments on commit bbae59a

Please sign in to comment.