From: Daniel Jasper Date: Thu, 30 Apr 2015 09:24:17 +0000 (+0000) Subject: clang-format: Don't merge short else blocks. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=2f67613c4fb0ab4bb24fc49e45a605a392e0a28c;p=clang clang-format: Don't merge short else blocks. Before (with the appropriate flags settings): if (a) { f(); } else { g(); } Before (with other appropriate flags settings): if (a) { f(); } else { g(); } After: if (a) { f(); } else { g(); } git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@236217 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/UnwrappedLineFormatter.cpp b/lib/Format/UnwrappedLineFormatter.cpp index dd65230cc4..888c69176e 100644 --- a/lib/Format/UnwrappedLineFormatter.cpp +++ b/lib/Format/UnwrappedLineFormatter.cpp @@ -203,7 +203,8 @@ private: // Check that the current line allows merging. This depends on whether we // are in a control flow statements as well as several style flags. - if (Line.First->isOneOf(tok::kw_else, tok::kw_case)) + if (Line.First->isOneOf(tok::kw_else, tok::kw_case) || + (Line.First->Next && Line.First->Next->is(tok::kw_else))) return 0; if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try, tok::kw___try, tok::kw_catch, tok::kw___finally, @@ -264,6 +265,10 @@ private: if (Tok->isNot(tok::r_brace)) return 0; + // Don't merge "if (a) { .. } else {". + if (Tok->Next && Tok->Next->is(tok::kw_else)) + return 0; + return 2; } return 0; diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index 9f340042c4..e2db4d10b9 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -416,6 +416,12 @@ TEST_F(FormatTest, FormatShortBracedStatements) { " f();\n" "}", AllowSimpleBracedStatements); + verifyFormat("if (true) {\n" + " f();\n" + "} else {\n" + " f();\n" + "}", + AllowSimpleBracedStatements); verifyFormat("template struct A2 {\n" " struct B {};\n" @@ -427,6 +433,12 @@ TEST_F(FormatTest, FormatShortBracedStatements) { " f();\n" "}", AllowSimpleBracedStatements); + verifyFormat("if (true) {\n" + " f();\n" + "} else {\n" + " f();\n" + "}", + AllowSimpleBracedStatements); AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; verifyFormat("while (true) {\n"