Fix ForLoopCanBeForeach flagging loops with two iterators
Resolves #784
This commit is contained in:
1 parent
b7950cca1b
commit
69937a40e5
2 files changed
+28
-1
No files matched your search
+7
-1
@@ -16,6 +16,7 @@ import net.sourceforge.pmd.lang.java.ast.ASTExpression;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTForInit;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTForStatement;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTForUpdate;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTLocalVariableDeclaration;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTName;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
|
||||
import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
|
||||
@@ -102,12 +103,17 @@ public class ForLoopCanBeForeachRule extends AbstractJavaRule {
|
||||
}
|
||||
|
||||
|
||||
/* Finds the declaration of the index variable and its occurrences */
|
||||
/* Finds the declaration of the index variable and its occurrences, null to abort */
|
||||
private Entry<VariableNameDeclaration, List<NameOccurrence>> getIndexVarDeclaration(ASTForInit init, ASTForUpdate update) {
|
||||
if (init == null) {
|
||||
return guessIndexVarFromUpdate(update);
|
||||
}
|
||||
|
||||
int numDeclaredVars = init.getFirstChildOfType(ASTLocalVariableDeclaration.class).findChildrenOfType(ASTVariableDeclarator.class).size();
|
||||
if (numDeclaredVars > 1) {
|
||||
return null; // will abort in the calling function
|
||||
}
|
||||
|
||||
Map<VariableNameDeclaration, List<NameOccurrence>> decls = init.getScope().getDeclarations(VariableNameDeclaration.class);
|
||||
Entry<VariableNameDeclaration, List<NameOccurrence>> indexVarAndOccurrences = null;
|
||||
|
||||
|
||||
+21
@@ -287,4 +287,25 @@
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
|
||||
<test-code>
|
||||
<description>Iterating on multiple iterators should whitelist the loop, refs #784
|
||||
</description>
|
||||
<expected-problems>0</expected-problems>
|
||||
<code><![CDATA[
|
||||
class Foo {
|
||||
void loop() {
|
||||
Iterable<E> it;
|
||||
Iterable<E> other;
|
||||
for (Iterator<E> iterator = it.iterator(), otherIterator = other.iterator(); iterator.hasNext();) {
|
||||
E item = iterator.next();
|
||||
E otherItem = otherIterator.next();
|
||||
doStuff();
|
||||
}
|
||||
}
|
||||
}
|
||||
]]></code>
|
||||
</test-code>
|
||||
|
||||
|
||||
</test-data>
|
||||
Reference in new issue
Block a user