Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang Format chained else ifs on single lines

I'm trying to write a .clang-format file that will allow the following:

if (value.Is<bool>()) { index = 1; }
else if (value.Is<int>()) { index = 2; }
else if (value.Is<unsigned int>()) { index = 3; }
else if (value.Is<long long>()) { index = 4; }
else if (value.Is<unsigned long long>()) { index = 5; }
else if (value.Is<float>()) { index = 6; }
else if (value.Is<double>()) { index = 7; }
else if (value.Is<long double>()) { index = 8; }
else if (value.Is<std::string>()) { index = 9; }
else if (value.IsArray()) { index = 10; }
else { index = 0; }

I've tried every option I can find related to breaks and allowShort*, and no matter what I do it seems to split them into multi-lines after the first like so:

if (value.Is<bool>()) { index = 1; }
else if (value.Is<int>()) {
  index = 2;
}
...

Is there some option I'm missing that could support this?

like image 669
Walrus Avatar asked Oct 17 '22 19:10

Walrus


1 Answers

Unfortunately, this is currently not supported for if-else statements, only for simple if's (as of revision 329373, dating 6/4/18). The AllowShortBlocksOnASingleLine and AllowShortIfStatementsOnASingleLine options are not applicable for if-else statements.

Hopefully this will change in the future.


The doc is not explicit about this, saying that AllowShortIfStatementsOnASingleLine will allow simple if statements on a single line:

AllowShortIfStatementsOnASingleLine (bool)
If true, if (a) return; can be put on a single line.

However, clang-format code suggests that if-else blocks are not allowed on single lines:

1) UnwrappedLineFormatter.cpp, tryMergeSimpleControlStatement:

// Only inline simple if's (no nested if or else).
if (I + 2 != E && Line.startsWith(tok::kw_if) &&
    I[2]->First->is(tok::kw_else))
  return 0;

2) FormatTest.cpp, FormatShortBracedStatements test.
Notice the test parameters, and that in the expected formatting in the unittests, else always resides in its own line, while plain if statements with no else are on a single line with their blocks, for example:

verifyFormat("if (true) {\n"
             "  f();\n"
             "} else {\n"
             "  f();\n"
             "}",
  AllowSimpleBracedStatements);
like image 134
valiano Avatar answered Oct 21 '22 06:10

valiano