diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -421,7 +421,13 @@ } return MergedLines; } - if (TheLine->First->is(tok::kw_if)) { + bool IsElseLine = + TheLine->First->is(tok::kw_else) || + (TheLine->First->is(tok::r_brace) && TheLine->First->Next && + TheLine->First->Next->is(tok::kw_else)); + if (TheLine->First->is(tok::kw_if) || + (IsElseLine && (Style.AllowShortIfStatementsOnASingleLine == + FormatStyle::SIS_Always))) { return Style.AllowShortIfStatementsOnASingleLine ? tryMergeSimpleControlStatement(I, E, Limit) : 0; @@ -471,7 +477,8 @@ return 0; Limit = limitConsideringMacros(I + 1, E, Limit); AnnotatedLine &Line = **I; - if (!Line.First->is(tok::kw_do) && Line.Last->isNot(tok::r_paren)) + if (!Line.First->is(tok::kw_do) && !Line.First->is(tok::kw_else) && + !Line.Last->is(tok::kw_else) && Line.Last->isNot(tok::r_paren)) return 0; // Only merge do while if do is the only statement on the line. if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do)) diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -510,6 +510,60 @@ AllowsMergedIf.ColumnLimit = 13; verifyFormat("if (a)\n return;", AllowsMergedIf); + + FormatStyle AllowsMergedIfElse = getLLVMStyle(); + AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine = + FormatStyle::SIS_Always; + verifyFormat("if (a)\n" + " // comment\n" + " f();\n" + "else\n" + " // comment\n" + " f();", + AllowsMergedIfElse); + verifyFormat("{\n" + " if (a)\n" + " label:\n" + " f();\n" + " else\n" + " label:\n" + " f();\n" + "}", + AllowsMergedIfElse); + // Hum? + verifyFormat("if (a)\n" + " ;\n" + "else\n" + " ;", + AllowsMergedIfElse); + verifyFormat("if (a) {\n" + "} else {\n" + "}", + AllowsMergedIfElse); + verifyFormat("if (a) return;\n" + "else if (b) return;\n" + "else return;", + AllowsMergedIfElse); + verifyFormat("if (a) {\n" + "} else return;", + AllowsMergedIfElse); + verifyFormat("if (a) {\n" + "} else if (b) return;\n" + "else return;", + AllowsMergedIfElse); + verifyFormat("if (a) return;\n" + "else if (b) {\n" + "} else return;", + AllowsMergedIfElse); + verifyFormat("if (a)\n" + " if (b) return;\n" + " else return;", + AllowsMergedIfElse); + verifyFormat("if constexpr (a)\n" + " if constexpr (b) return;\n" + " else if constexpr (c) return;\n" + " else return;", + AllowsMergedIfElse); } TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {