Issue #2135: Fix exception at NeedBraces check in enhanced for loops

This commit is contained in:
Michal Kordas 2015-09-07 22:55:20 +02:00
parent f7698ed23b
commit c0d3652d1b
3 changed files with 33 additions and 1 deletions

View File

@ -282,12 +282,30 @@ public class NeedBracesCheck extends Check {
}
else if (literalFor.getParent().getType() == TokenTypes.SLIST
&& literalFor.getLastChild().getType() != TokenTypes.SLIST) {
final DetailAST block = literalFor.findFirstToken(TokenTypes.EXPR);
final DetailAST block = findExpressionBlockInForLoop(literalFor);
result = literalFor.getLineNo() == block.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 = forEachClause.findFirstToken(TokenTypes.EXPR);
}
else {
firstToken = literalFor.findFirstToken(TokenTypes.EXPR);
}
return firstToken;
}
/**
* Checks if current if statement is single-line statement, e.g.:
* <p>

View File

@ -70,6 +70,7 @@ public class NeedBracesCheckTest extends BaseCheckTestSupport {
"59: " + getCheckMessage(MSG_KEY_NEED_BRACES, "for"),
"88: " + getCheckMessage(MSG_KEY_NEED_BRACES, "if"),
"92: " + getCheckMessage(MSG_KEY_NEED_BRACES, "else"),
"104: " + getCheckMessage(MSG_KEY_NEED_BRACES, "if"),
};
verify(checkConfig, getPath("InputBracesSingleLineStatements.java"), expected);
}

View File

@ -92,4 +92,17 @@ public class InputBracesSingleLineStatements
} else
return 2;
}
void enhancedForLoop(int[] array) {
for (int value: array) return;
}
int[] sourceLocators;
private class StateInfo {
public boolean isInitial() {
for (int locator: sourceLocators) if (locator != 0) return false;
return true;
}
}
}