Skip to content

clang-format: AllowShortCaseLabelsOnASingleLine only for simple cases #57609

Open
@AdamBucior

Description

@AdamBucior

Hi,

I would like clang-format to put short case labels on single line only for simple single-case cases like:

switch (i) {
case 0: return 3;
case 1: return 7;
case 2: return 1;
case 3: return 5;
}

But not for more complicated multiple-case cases like:

switch (i) {
case 0:
case 1:
  return i;
case 2:
case 3:
  i *= 2;
  break;
}

Which clang-format -style="{AllowShortCaseLabelsOnASingleLine: true}" formats as:

switch (i) {
case 0:
case 1: return i;
case 2:
case 3: i *= 2; break;
}

which doesn't make it obvious that return i; is also done in case i is 0 (and similarly for case 2:).

The problem also exists for fallthrough cases like:

switch (i) {
case 0:
  g();
  [[fallthrough]];
case 1:
  f();
  break;
}

Which clang-format -style="{AllowShortCaseLabelsOnASingleLine: true}" formats as:

switch (i) {
case 0: g(); [[fallthrough]];
case 1: f(); break;
}

I propose to add a new option: AllowShortCaseLabelsOnASingleLine: SingleCases

The last example might be more challenging because clang-format would need a way to detect whether the previous case can fallthrough. I see 2 ways:

  • Just check if there is a [[fallthrough]] attribute (this option would cause wrong formatting if someone forgets [[fallthrough]])
  • Check for return or break (this option might be harder to implement correctly)

I'm fine with both ways.

Metadata

Metadata

Assignees

No one assigned

    Labels

    awaiting-reviewHas pending Phabricator reviewclang-formatenhancementImproving things as opposed to bug fixing, e.g. new or missing feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions