Issue #2291: Fix not raising violation NeedBraces with ForEach loop with single stmt

This commit is contained in:
liscju 2015-12-10 14:10:22 +01:00 committed by Roman Ivanov
parent db642355f8
commit ee5d8ec036
3 changed files with 8 additions and 25 deletions

View File

@ -354,35 +354,11 @@ public class NeedBracesCheck extends Check {
}
else if (literalFor.getParent().getType() == TokenTypes.SLIST
&& literalFor.getLastChild().getType() != TokenTypes.SLIST) {
final DetailAST block = findExpressionBlockInForLoop(literalFor);
if (block == null) {
result = literalFor.getLineNo() == literalFor.getLastChild().getLineNo();
}
else {
result = literalFor.getLineNo() == block.getLineNo();
}
result = literalFor.getLineNo() == literalFor.getLastChild().getLineNo();
}
return result;
}
/**
* Detects and returns expression block in classical and enhanced for loops.
*
* @param literalFor parent for loop literal
* @return expression block
*/
private static DetailAST findExpressionBlockInForLoop(DetailAST literalFor) {
final DetailAST forEachClause = literalFor.findFirstToken(TokenTypes.FOR_EACH_CLAUSE);
final DetailAST firstToken;
if (forEachClause == null) {
firstToken = literalFor.findFirstToken(TokenTypes.EXPR);
}
else {
firstToken = forEachClause.findFirstToken(TokenTypes.EXPR);
}
return firstToken;
}
/**
* Checks if current if statement is single-line statement, e.g.:
* <p>

View File

@ -85,6 +85,7 @@ public class NeedBracesCheckTest extends BaseCheckTestSupport {
"91: " + getCheckMessage(MSG_KEY_NEED_BRACES, "if"),
"95: " + getCheckMessage(MSG_KEY_NEED_BRACES, "else"),
"107: " + getCheckMessage(MSG_KEY_NEED_BRACES, "if"),
"114: " + getCheckMessage(MSG_KEY_NEED_BRACES, "for"),
};
verify(checkConfig, getPath("InputBracesSingleLineStatements.java"), expected);
}

View File

@ -108,4 +108,10 @@ public class InputBracesSingleLineStatements
return true;
}
}
private void forEachLoop() {
for (String s: new String[]{""}) break;
for (String s: new String[]{""})
break;
}
}