use of org.eclipse.jdt.core.dom.DoStatement in project AutoRefactor by JnRouvignac.
the class DeclarationOutsideLoopRatherThanInsideCleanUp method visit.
@Override
public boolean visit(final Block visited) {
List<Statement> blockStatement = ASTNodes.asList(visited);
boolean result = true;
for (int i = 0; i < blockStatement.size(); i++) {
Statement statement = blockStatement.get(i);
ForStatement forStatement = ASTNodes.as(statement, ForStatement.class);
EnhancedForStatement enhancedForStatement = ASTNodes.as(statement, EnhancedForStatement.class);
WhileStatement whileStatement = ASTNodes.as(statement, WhileStatement.class);
DoStatement doStatement = ASTNodes.as(statement, DoStatement.class);
List<Statement> forStatements = null;
if (forStatement != null) {
forStatements = ASTNodes.asList(forStatement.getBody());
} else if (enhancedForStatement != null) {
forStatements = ASTNodes.asList(enhancedForStatement.getBody());
} else if (whileStatement != null) {
forStatements = ASTNodes.asList(whileStatement.getBody());
} else if (doStatement != null) {
forStatements = ASTNodes.asList(doStatement.getBody());
}
if (forStatements != null) {
Set<SimpleName> conflictingNamesOutOfTheLoop = new HashSet<>();
for (int j = 0; j < i; j++) {
if (!(blockStatement.get(j) instanceof Block)) {
conflictingNamesOutOfTheLoop.addAll(ASTNodes.getLocalVariableIdentifiers(blockStatement.get(j), false));
}
}
for (int j = i + 1; j < blockStatement.size(); j++) {
conflictingNamesOutOfTheLoop.addAll(ASTNodes.getLocalVariableIdentifiers(blockStatement.get(j), true));
}
Set<SimpleName> conflictingNamesInLoop = new HashSet<>();
for (Statement oneStatement : forStatements) {
conflictingNamesInLoop.addAll(ASTNodes.getLocalVariableIdentifiers(oneStatement, true));
}
List<VariableDeclarationStatement> candidates = new ArrayList<>();
for (Statement declarationStatement : forStatements) {
VariableDeclarationStatement declaration = ASTNodes.as(declarationStatement, VariableDeclarationStatement.class);
VariableDeclarationFragment fragment = ASTNodes.getUniqueFragment(declaration);
if (fragment != null && !isEffectivelyFinalRequired(declaration, fragment) && !hasAnnotation(declaration.modifiers())) {
SimpleName name = fragment.getName();
if (isUniqueNameInLoop(name.getIdentifier(), conflictingNamesInLoop) && isUniqueNameOutOfTheLoop(conflictingNamesOutOfTheLoop, name.getIdentifier())) {
candidates.add(declaration);
conflictingNamesOutOfTheLoop.add(name);
}
}
}
for (VariableDeclarationStatement candidate : candidates) {
moveDeclaration(statement, candidate);
result = false;
}
}
}
return result;
}
Aggregations