use of org.eclipse.jdt.core.dom.EnhancedForStatement in project che by eclipse.
the class ConvertForLoopOperation method convert.
@Override
protected Statement convert(CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException {
ASTRewrite rewrite = cuRewrite.getASTRewrite();
ImportRewrite importRewrite = cuRewrite.getImportRewrite();
ForStatement forStatement = getForStatement();
IJavaProject javaProject = ((CompilationUnit) forStatement.getRoot()).getJavaElement().getJavaProject();
String[] proposals = getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
String parameterName;
if (fElementDeclaration != null) {
parameterName = fElementDeclaration.getName().getIdentifier();
} else {
parameterName = proposals[0];
}
LinkedProposalPositionGroup pg = positionGroups.getPositionGroup(parameterName, true);
if (fElementDeclaration != null)
pg.addProposal(parameterName, null, 10);
for (int i = 0; i < proposals.length; i++) {
pg.addProposal(proposals[i], null, 10);
}
AST ast = forStatement.getAST();
EnhancedForStatement result = ast.newEnhancedForStatement();
SingleVariableDeclaration parameterDeclaration = createParameterDeclaration(parameterName, fElementDeclaration, fArrayAccess, forStatement, importRewrite, rewrite, group, pg, fMakeFinal);
result.setParameter(parameterDeclaration);
result.setExpression((Expression) rewrite.createCopyTarget(fArrayAccess));
convertBody(forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg);
result.setBody(getBody(cuRewrite, group, positionGroups));
positionGroups.setEndPosition(rewrite.track(result));
return result;
}
use of org.eclipse.jdt.core.dom.EnhancedForStatement in project che by eclipse.
the class TypeMismatchSubProcessor method addTypeMismatchInForEachProposals.
public static void addTypeMismatchInForEachProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (selectedNode == null || selectedNode.getLocationInParent() != EnhancedForStatement.EXPRESSION_PROPERTY) {
return;
}
EnhancedForStatement forStatement = (EnhancedForStatement) selectedNode.getParent();
ITypeBinding expressionBinding = forStatement.getExpression().resolveTypeBinding();
if (expressionBinding == null) {
return;
}
ITypeBinding expectedBinding;
if (expressionBinding.isArray()) {
expectedBinding = expressionBinding.getComponentType();
} else {
//$NON-NLS-1$
IMethodBinding iteratorMethod = Bindings.findMethodInHierarchy(expressionBinding, "iterator", new String[0]);
if (iteratorMethod == null) {
return;
}
ITypeBinding[] typeArguments = iteratorMethod.getReturnType().getTypeArguments();
if (typeArguments.length != 1) {
return;
}
expectedBinding = typeArguments[0];
}
AST ast = astRoot.getAST();
expectedBinding = Bindings.normalizeForDeclarationUse(expectedBinding, ast);
SingleVariableDeclaration parameter = forStatement.getParameter();
ICompilationUnit cu = context.getCompilationUnit();
if (parameter.getName().getLength() == 0) {
SimpleName simpleName = null;
if (parameter.getType() instanceof SimpleType) {
SimpleType type = (SimpleType) parameter.getType();
if (type.getName() instanceof SimpleName) {
simpleName = (SimpleName) type.getName();
}
} else if (parameter.getType() instanceof NameQualifiedType) {
simpleName = ((NameQualifiedType) parameter.getType()).getName();
}
if (simpleName != null) {
String name = simpleName.getIdentifier();
int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
return;
}
}
String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_incompatible_for_each_type_description, new String[] { BasicElementLabels.getJavaElementName(parameter.getName().getIdentifier()), BindingLabelProvider.getBindingLabel(expectedBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS) });
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewrite rewrite = ASTRewrite.create(ast);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.INCOMPATIBLE_FOREACH_TYPE, image);
ImportRewrite importRewrite = proposal.createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(selectedNode), importRewrite);
Type newType = importRewrite.addImport(expectedBinding, ast, importRewriteContext);
rewrite.replace(parameter.getType(), newType, null);
proposals.add(proposal);
}
use of org.eclipse.jdt.core.dom.EnhancedForStatement in project eclipse.jdt.ls by eclipse.
the class NewVariableCorrectionProposal method doAddLocal.
private ASTRewrite doAddLocal(CompilationUnit cu) {
AST ast = cu.getAST();
Block body;
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
IBinding targetContext = null;
if (decl instanceof MethodDeclaration) {
body = (((MethodDeclaration) decl).getBody());
targetContext = ((MethodDeclaration) decl).resolveBinding();
} else if (decl instanceof Initializer) {
body = (((Initializer) decl).getBody());
targetContext = Bindings.getBindingOfParentType(decl);
} else {
return null;
}
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
SimpleName[] names = getAllReferences(body);
ASTNode dominant = getDominantNode(names);
Statement dominantStatement = ASTResolving.findParentStatement(dominant);
if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
dominantStatement = (Statement) dominantStatement.getParent();
}
SimpleName node = names[0];
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
if (isAssigned(dominantStatement, node)) {
// x = 1; -> int x = 1;
Assignment assignment = (Assignment) node.getParent();
// trick to avoid comment removal around the statement: keep the expression statement
// and replace the assignment with an VariableDeclarationExpression
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
newDeclFrag.setInitializer(placeholder);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.replace(assignment, newDecl, null);
return rewrite;
} else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
// for (x = 1;;) ->for (int x = 1;;)
Assignment assignment = (Assignment) node.getParent();
VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
frag.setName(ast.newSimpleName(node.getIdentifier()));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
frag.setInitializer(placeholder);
expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
rewrite.replace(assignment, expression, null);
return rewrite;
} else if ((dominant != dominantStatement) && isEnhancedForStatementVariable(dominantStatement, node)) {
// for (x: collectionOfT) -> for (T x: collectionOfT)
EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
Expression expression = enhancedForStatement.getExpression();
SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);
ITypeBinding elementBinding = null;
ITypeBinding typeBinding = expression.resolveTypeBinding();
if (typeBinding != null) {
if (typeBinding.isArray()) {
elementBinding = typeBinding.getElementType();
} else {
// $NON-NLS-1$
ITypeBinding iterable = Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable");
if (iterable != null) {
ITypeBinding[] typeArguments = iterable.getTypeArguments();
if (typeArguments.length == 1) {
elementBinding = typeArguments[0];
elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
}
}
}
}
Type type;
if (elementBinding != null) {
type = imports.addImport(elementBinding, ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE);
} else {
// $NON-NLS-1$
type = ast.newSimpleType(ast.newSimpleName("Object"));
}
rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
return rewrite;
}
// foo(x) -> int x; foo(x)
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
// newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
Statement statement = dominantStatement;
List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
while (list == null && statement.getParent() instanceof Statement) {
// parent must be if, for or while
statement = (Statement) statement.getParent();
list = ASTNodes.getContainingList(statement);
}
if (list != null) {
ASTNode parent = statement.getParent();
StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
if (childProperty.isChildListProperty()) {
rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
return rewrite;
} else {
return null;
}
}
return rewrite;
}
use of org.eclipse.jdt.core.dom.EnhancedForStatement in project flux by eclipse.
the class AdvancedQuickAssistProcessor method isLastStatementInEnclosingMethodOrLambda.
private static boolean isLastStatementInEnclosingMethodOrLambda(Statement statement) {
ASTNode currentStructure = statement;
ASTNode currentParent = statement.getParent();
while (!(currentParent instanceof MethodDeclaration || currentParent instanceof LambdaExpression)) {
// should not be in a loop
if (currentParent instanceof ForStatement || currentParent instanceof EnhancedForStatement || currentParent instanceof WhileStatement || currentParent instanceof DoStatement) {
return false;
}
if (currentParent instanceof Block) {
Block parentBlock = (Block) currentParent;
if (parentBlock.statements().indexOf(currentStructure) != parentBlock.statements().size() - 1) {
// not last statement in the block
return false;
}
}
currentStructure = currentParent;
currentParent = currentParent.getParent();
}
return true;
}
use of org.eclipse.jdt.core.dom.EnhancedForStatement 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