Skip to content

Commit

Permalink
[clang-format] Treat empty for/while loops as short loops (#70768)
Browse files Browse the repository at this point in the history
A for/while loop with only a semicolon as its body should be treated as
an empty loop.

Fixes #61708.
  • Loading branch information
owenca committed Nov 2, 2023
1 parent 3747cde commit 2c2fb8e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
11 changes: 9 additions & 2 deletions clang/lib/Format/UnwrappedLineParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3117,9 +3117,16 @@ void UnwrappedLineParser::parseForOrWhileLoop(bool HasParens) {
FormatTok->setFinalizedType(TT_ConditionLParen);
parseParens();
}
// Event control.
if (Style.isVerilog())

if (Style.isVerilog()) {
// Event control.
parseVerilogSensitivityList();
} else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
Tokens->getPreviousToken()->is(tok::r_paren)) {
nextToken();
addUnwrappedLine();
return;
}

handleAttributes();
parseLoopBody(KeepBraces, /*WrapRightBrace=*/true);
Expand Down
26 changes: 20 additions & 6 deletions clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1355,18 +1355,20 @@ TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
}

TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
verifyFormat("while (true)\n"
" ;");
verifyFormat("for (;;)\n"
" ;");

FormatStyle AllowsMergedLoops = getLLVMStyle();
AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;

verifyFormat("while (true) continue;", AllowsMergedLoops);
verifyFormat("for (;;) continue;", AllowsMergedLoops);
verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
verifyFormat("BOOST_FOREACH (int &v, vec) v *= 2;", AllowsMergedLoops);
verifyFormat("while (true)\n"
" ;",
AllowsMergedLoops);
verifyFormat("for (;;)\n"
" ;",
AllowsMergedLoops);
verifyFormat("while (true);", AllowsMergedLoops);
verifyFormat("for (;;);", AllowsMergedLoops);
verifyFormat("for (;;)\n"
" for (;;) continue;",
AllowsMergedLoops);
Expand Down Expand Up @@ -1404,6 +1406,7 @@ TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
" a++;\n"
"while (true);",
AllowsMergedLoops);

// Without braces labels are interpreted differently.
verifyFormat("{\n"
" do\n"
Expand All @@ -1412,6 +1415,17 @@ TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
" while (true);\n"
"}",
AllowsMergedLoops);

// Don't merge if there are comments before the null statement.
verifyFormat("while (1) //\n"
" ;",
AllowsMergedLoops);
verifyFormat("for (;;) /**/\n"
" ;",
AllowsMergedLoops);
verifyFormat("while (true) /**/\n"
" ;",
"while (true) /**/;", AllowsMergedLoops);
}

TEST_F(FormatTest, FormatShortBracedStatements) {
Expand Down

0 comments on commit 2c2fb8e

Please sign in to comment.