This is an archive of the discontinued LLVM Phabricator instance.

[clang-format] Remove braces of else blocks that embody an if block
ClosedPublic

Authored by owenpan on Jun 7 2022, 4:17 PM.

Diff Detail

Event Timeline

owenpan created this revision.Jun 7 2022, 4:17 PM
Herald added a project: Restricted Project. · View Herald TranscriptJun 7 2022, 4:17 PM
owenpan requested review of this revision.Jun 7 2022, 4:17 PM
Herald added a project: Restricted Project. · View Herald TranscriptJun 7 2022, 4:17 PM
Herald added a subscriber: cfe-commits. · View Herald Transcript
curdeius added inline comments.Jun 7 2022, 11:17 PM
clang/unittests/Format/FormatTest.cpp
25570–25575

Why isn't this block changed like this?
I might be missing something...

owenpan added inline comments.Jun 7 2022, 11:29 PM
clang/unittests/Format/FormatTest.cpp
25570–25575

It would cause a dangling else error because the last else would be paired with the inner merged else if.

curdeius accepted this revision.Jun 7 2022, 11:44 PM

LGTM. Thanks!

clang/unittests/Format/FormatTest.cpp
25570–25575

True. There are indeed no braces in the outer if.

This revision is now accepted and ready to land.Jun 7 2022, 11:44 PM
owenpan added inline comments.Jun 7 2022, 11:56 PM
clang/lib/Format/UnwrappedLineParser.cpp
2633

To be precise. It doesn't matter now but will when we configure removing braces for other styles.

owenpan updated this revision to Diff 435181.Jun 8 2022, 8:48 AM

Update IfLeftBrace in parseLevel() only if the level is a simple block.

owenpan requested review of this revision.Jun 8 2022, 8:50 AM
curdeius accepted this revision.Jun 8 2022, 10:58 AM

Still looks good. Was there a particular case where the previous version didn't work?

This revision is now accepted and ready to land.Jun 8 2022, 10:58 AM

Still looks good. Was there a particular case where the previous version didn't work?

The assertion I added on line 2626, which would ensure that the RemoveBraces lambda on line 898 didn't miss any potentially removable braces, would fail because parseLevel() was indiscriminately passing the l_brace of the last if in the level to its caller. This new version is also a tiny bit more efficient because IfLBrace on line 2624 will be null if the else block that encloses the if block is not a simple block.

Because neither version would remove non-optional braces, I decided not to add a test case just for the assertion, e.g.,

if (a)
  b;
else {
  c;
  if (d) {
    e;
    f;
  }
}