Search in sources :

Example 6 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.

the class GenerateForLoopAssistProposal method generateIteratorBasedForRewrite.

/**
	 * Helper to generate an iterator based <code>for</code> loop to iterate over an
	 * {@link Iterable}.
	 * 
	 * @param ast the {@link AST} instance to rewrite the loop to
	 * @return the complete {@link ASTRewrite} object
	 */
private ASTRewrite generateIteratorBasedForRewrite(AST ast) {
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ForStatement loopStatement = ast.newForStatement();
    ITypeBinding loopOverType = extractElementType(ast);
    //$NON-NLS-1$
    SimpleName loopVariableName = resolveLinkedVariableNameWithProposals(rewrite, "iterator", null, true);
    loopStatement.initializers().add(getIteratorBasedForInitializer(rewrite, loopVariableName));
    MethodInvocation loopExpression = ast.newMethodInvocation();
    //$NON-NLS-1$
    loopExpression.setName(ast.newSimpleName("hasNext"));
    SimpleName expressionName = ast.newSimpleName(loopVariableName.getIdentifier());
    addLinkedPosition(rewrite.track(expressionName), LinkedPositionGroup.NO_STOP, expressionName.getIdentifier());
    loopExpression.setExpression(expressionName);
    loopStatement.setExpression(loopExpression);
    Block forLoopBody = ast.newBlock();
    Assignment assignResolvedVariable = getIteratorBasedForBodyAssignment(rewrite, loopOverType, loopVariableName);
    forLoopBody.statements().add(ast.newExpressionStatement(assignResolvedVariable));
    forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
    loopStatement.setBody(forLoopBody);
    rewrite.replace(fCurrentNode, loopStatement, null);
    return rewrite;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement)

Example 7 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.

the class UnresolvedElementsSubProcessor method addSimilarVariableProposals.

private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, IVariableBinding resolvedField, SimpleName node, boolean isWriteAccess, Collection<ICommandAccess> proposals) {
    int kind = ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
    if (!isWriteAccess) {
        // also try to find similar methods
        kind |= ScopeAnalyzer.METHODS;
    }
    IBinding[] varsAndMethodsInScope = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
    if (varsAndMethodsInScope.length > 0) {
        // avoid corrections like int i= i;
        String otherNameInAssign = null;
        // help with x.getString() -> y.getString()
        String methodSenderName = null;
        String fieldSenderName = null;
        ASTNode parent = node.getParent();
        switch(parent.getNodeType()) {
            case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
                // node must be initializer
                otherNameInAssign = ((VariableDeclarationFragment) parent).getName().getIdentifier();
                break;
            case ASTNode.ASSIGNMENT:
                Assignment assignment = (Assignment) parent;
                if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getRightHandSide()).getIdentifier();
                } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
                }
                break;
            case ASTNode.METHOD_INVOCATION:
                MethodInvocation inv = (MethodInvocation) parent;
                if (inv.getExpression() == node) {
                    methodSenderName = inv.getName().getIdentifier();
                }
                break;
            case ASTNode.QUALIFIED_NAME:
                QualifiedName qualName = (QualifiedName) parent;
                if (qualName.getQualifier() == node) {
                    fieldSenderName = qualName.getName().getIdentifier();
                }
                break;
        }
        ITypeBinding guessedType = ASTResolving.guessBindingForReference(node);
        //$NON-NLS-1$
        ITypeBinding objectBinding = astRoot.getAST().resolveWellKnownType("java.lang.Object");
        String identifier = node.getIdentifier();
        boolean isInStaticContext = ASTResolving.isInStaticContext(node);
        ArrayList<CUCorrectionProposal> newProposals = new ArrayList<CUCorrectionProposal>(51);
        loop: for (int i = 0; i < varsAndMethodsInScope.length && newProposals.size() <= 50; i++) {
            IBinding varOrMeth = varsAndMethodsInScope[i];
            if (varOrMeth instanceof IVariableBinding) {
                IVariableBinding curr = (IVariableBinding) varOrMeth;
                String currName = curr.getName();
                if (currName.equals(otherNameInAssign)) {
                    continue loop;
                }
                if (resolvedField != null && Bindings.equals(resolvedField, curr)) {
                    continue loop;
                }
                boolean isFinal = Modifier.isFinal(curr.getModifiers());
                if (isFinal && curr.isField() && isWriteAccess) {
                    continue loop;
                }
                if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
                    continue loop;
                }
                int relevance = IProposalRelevance.SIMILAR_VARIABLE_PROPOSAL;
                if (NameMatcher.isSimilarName(currName, identifier)) {
                    // variable with a similar name than the unresolved variable
                    relevance += 3;
                }
                if (currName.equalsIgnoreCase(identifier)) {
                    relevance += 5;
                }
                ITypeBinding varType = curr.getType();
                if (varType != null) {
                    if (guessedType != null && guessedType != objectBinding) {
                        // variable type is compatible with the guessed type
                        if (!isWriteAccess && canAssign(varType, guessedType) || isWriteAccess && canAssign(guessedType, varType)) {
                            // unresolved variable can be assign to this variable
                            relevance += 2;
                        }
                    }
                    if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
                        relevance += 2;
                    }
                    if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
                        relevance += 2;
                    }
                }
                if (relevance > 0) {
                    String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, BasicElementLabels.getJavaElementName(currName));
                    newProposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
                }
            } else if (varOrMeth instanceof IMethodBinding) {
                IMethodBinding curr = (IMethodBinding) varOrMeth;
                if (!curr.isConstructor() && guessedType != null && canAssign(curr.getReturnType(), guessedType)) {
                    if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
                        AST ast = astRoot.getAST();
                        ASTRewrite rewrite = ASTRewrite.create(ast);
                        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description, ASTResolving.getMethodSignature(curr));
                        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_METHOD, image);
                        newProposals.add(proposal);
                        MethodInvocation newInv = ast.newMethodInvocation();
                        newInv.setName(ast.newSimpleName(curr.getName()));
                        ITypeBinding[] parameterTypes = curr.getParameterTypes();
                        for (int k = 0; k < parameterTypes.length; k++) {
                            ASTNode arg = ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
                            newInv.arguments().add(arg);
                            proposal.addLinkedPosition(rewrite.track(arg), false, null);
                        }
                        rewrite.replace(node, newInv, null);
                    }
                }
            }
        }
        if (newProposals.size() <= 50)
            proposals.addAll(newProposals);
    }
    if (binding != null && binding.isArray()) {
        //$NON-NLS-1$
        String idLength = "length";
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
        proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, IProposalRelevance.CHANGE_VARIABLE));
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Image(org.eclipse.swt.graphics.Image) Assignment(org.eclipse.jdt.core.dom.Assignment) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 8 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.

the class UnusedCodeFix method hasSideEffect.

private static boolean hasSideEffect(SimpleName reference) {
    ASTNode parent = reference.getParent();
    while (parent instanceof QualifiedName) {
        parent = parent.getParent();
    }
    if (parent instanceof FieldAccess) {
        parent = parent.getParent();
    }
    ASTNode node = null;
    int nameParentType = parent.getNodeType();
    if (nameParentType == ASTNode.ASSIGNMENT) {
        Assignment assignment = (Assignment) parent;
        node = assignment.getRightHandSide();
    } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
        SingleVariableDeclaration decl = (SingleVariableDeclaration) parent;
        node = decl.getInitializer();
        if (node == null)
            return false;
    } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        node = parent;
    } else {
        return false;
    }
    ArrayList<Expression> sideEffects = new ArrayList<Expression>();
    node.accept(new SideEffectFinder(sideEffects));
    return sideEffects.size() > 0;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 9 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.

the class CallInliner method crossCheckArguments.

/**
     * Checks whether arguments are passed to the method which do some assignments
     * inside the expression. If so these arguments can't be inlined into the
     * calling method since the assignments might be reorder. An example is:
     * <code>
     *   add((field=args).length,field.hashCode());
     * </code>
     * Field might not be initialized when the arguments are reorder in the called
     * method.
     * @param arguments the arguments
     * @return all arguments that cannot be inlined
     */
private Set<Expression> crossCheckArguments(List<Expression> arguments) {
    final Set<IBinding> assigned = new HashSet<IBinding>();
    final Set<Expression> result = new HashSet<Expression>();
    for (Iterator<Expression> iter = arguments.iterator(); iter.hasNext(); ) {
        final Expression expression = iter.next();
        expression.accept(new ASTVisitor() {

            @Override
            public boolean visit(Assignment node) {
                Expression lhs = node.getLeftHandSide();
                if (lhs instanceof Name) {
                    IBinding binding = ((Name) lhs).resolveBinding();
                    if (binding instanceof IVariableBinding) {
                        assigned.add(binding);
                        result.add(expression);
                    }
                }
                return true;
            }
        });
    }
    for (Iterator<Expression> iter = arguments.iterator(); iter.hasNext(); ) {
        final Expression expression = iter.next();
        if (!result.contains(expression)) {
            expression.accept(new HierarchicalASTVisitor() {

                @Override
                public boolean visit(Name node) {
                    IBinding binding = node.resolveBinding();
                    if (binding != null && assigned.contains(binding))
                        result.add(expression);
                    return false;
                }
            });
        }
    }
    return result;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) IBinding(org.eclipse.jdt.core.dom.IBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) HierarchicalASTVisitor(org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor) HashSet(java.util.HashSet) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) HierarchicalASTVisitor(org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Example 10 with Assignment

use of org.eclipse.jdt.core.dom.Assignment in project che by eclipse.

the class RemoveDeclarationCorrectionProposal method removeVariableReferences.

/**
	 * Remove the field or variable declaration including the initializer.
	 * @param rewrite the ast rewrite
	 * @param reference the reference
	 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference) {
    ASTNode parent = reference.getParent();
    while (parent instanceof QualifiedName) {
        parent = parent.getParent();
    }
    if (parent instanceof FieldAccess) {
        parent = parent.getParent();
    }
    int nameParentType = parent.getNodeType();
    if (nameParentType == ASTNode.ASSIGNMENT) {
        Assignment assignment = (Assignment) parent;
        Expression rightHand = assignment.getRightHandSide();
        ASTNode assignParent = assignment.getParent();
        if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
            removeVariableWithInitializer(rewrite, rightHand, assignParent);
        } else {
            rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), null);
        }
    } else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
        rewrite.remove(parent, null);
    } else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        VariableDeclarationFragment frag = (VariableDeclarationFragment) parent;
        ASTNode varDecl = frag.getParent();
        List<VariableDeclarationFragment> fragments;
        if (varDecl instanceof VariableDeclarationExpression) {
            fragments = ((VariableDeclarationExpression) varDecl).fragments();
        } else if (varDecl instanceof FieldDeclaration) {
            fragments = ((FieldDeclaration) varDecl).fragments();
        } else {
            fragments = ((VariableDeclarationStatement) varDecl).fragments();
        }
        if (fragments.size() == 1) {
            rewrite.remove(varDecl, null);
        } else {
            // don't try to preserve
            rewrite.remove(frag, null);
        }
    }
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Aggregations

Assignment (org.eclipse.jdt.core.dom.Assignment)96 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)42 Expression (org.eclipse.jdt.core.dom.Expression)41 SimpleName (org.eclipse.jdt.core.dom.SimpleName)37 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 CastExpression (org.eclipse.jdt.core.dom.CastExpression)29 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)29 AST (org.eclipse.jdt.core.dom.AST)28 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)26 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)25 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)24 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)24 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)23 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)21 Statement (org.eclipse.jdt.core.dom.Statement)21 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)19 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)19 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)18 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)18 PostfixExpression (org.eclipse.jdt.core.dom.PostfixExpression)18