Search in sources :

Example 21 with EnhancedForStatement

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;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement)

Example 22 with EnhancedForStatement

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);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NewVariableCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.NewVariableCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 23 with EnhancedForStatement

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;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Initializer(org.eclipse.jdt.core.dom.Initializer) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 24 with EnhancedForStatement

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;
}
Also used : DoStatement(org.eclipse.jdt.core.dom.DoStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 25 with EnhancedForStatement

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;
}
Also used : DoStatement(org.eclipse.jdt.core.dom.DoStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) Block(org.eclipse.jdt.core.dom.Block) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) HashSet(java.util.HashSet)

Aggregations

EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)25 ForStatement (org.eclipse.jdt.core.dom.ForStatement)18 ASTNode (org.eclipse.jdt.core.dom.ASTNode)16 Statement (org.eclipse.jdt.core.dom.Statement)15 WhileStatement (org.eclipse.jdt.core.dom.WhileStatement)13 Block (org.eclipse.jdt.core.dom.Block)12 DoStatement (org.eclipse.jdt.core.dom.DoStatement)11 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)10 SimpleName (org.eclipse.jdt.core.dom.SimpleName)9 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)8 AST (org.eclipse.jdt.core.dom.AST)7 IfStatement (org.eclipse.jdt.core.dom.IfStatement)7 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)7 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)6 LabeledStatement (org.eclipse.jdt.core.dom.LabeledStatement)6 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)6 Expression (org.eclipse.jdt.core.dom.Expression)5 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)5 Type (org.eclipse.jdt.core.dom.Type)5 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)5