This is an archive of the discontinued LLVM Phabricator instance.

[clang-format] Correctly format loops and `if` statements even if preceded with comments.
ClosedPublic

Authored by curdeius on Feb 12 2022, 12:48 PM.

Details

Summary

Fixes https://github.com/llvm/llvm-project/issues/53758.

Braces in loops and in if statements with leading (block) comments were formatted according to BraceWrapping.AfterFunction and not AllowShortBlocksOnASingleLine/AllowShortLoopsOnASingleLine/AllowShortIfStatementsOnASingleLine.

Previously, the code:

while (true) {
  f();
}
/*comment*/ while (true) {
  f();
}

was incorrectly formatted to:

while (true) {
  f();
}
/*comment*/ while (true) { f(); }

when using config:

BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: false
AllowShortBlocksOnASingleLine: false
AllowShortLoopsOnASingleLine: false

and it was (correctly but by chance) formatted to:

while (true) {
  f();
}
/*comment*/ while (true) {
  f();
}

when using enabling brace wrapping after functions:

BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: true
AllowShortBlocksOnASingleLine: false
AllowShortLoopsOnASingleLine: false

Diff Detail

Event Timeline

curdeius requested review of this revision.Feb 12 2022, 12:48 PM
curdeius created this revision.
Herald added a project: Restricted Project. · View Herald TranscriptFeb 12 2022, 12:48 PM
Herald added a subscriber: cfe-commits. · View Herald Transcript
This revision is now accepted and ready to land.Feb 12 2022, 12:58 PM
curdeius updated this revision to Diff 408215.Feb 12 2022, 1:28 PM

Test ifs and FOREACH loops.

curdeius retitled this revision from [clang-format] Correctly format loops even if preceded with comments. to [clang-format] Correctly format loops and `if` statements even if preceded with comments..Feb 12 2022, 1:29 PM
curdeius edited the summary of this revision. (Show Details)
sstwcw added a subscriber: sstwcw.Feb 12 2022, 1:47 PM
sstwcw added inline comments.
clang/lib/Format/UnwrappedLineFormatter.cpp
379

Why not use FirstNonComment instead of TheLine->First down here?

curdeius added inline comments.Feb 12 2022, 1:58 PM
clang/lib/Format/UnwrappedLineFormatter.cpp
379

Because I haven't added a test case for it and prefer doing it in a different revision (and because as you see, I already got confused enough :) ).

MyDeveloperDay accepted this revision.Feb 12 2022, 3:54 PM
owenpan accepted this revision.Feb 12 2022, 10:14 PM