Search in sources :

Example 96 with Assignment

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

the class AssignmentAndAssignmentToSameKill method go.

@Override
protected ASTRewrite go(final ASTRewrite $, final Assignment a, final Statement nextStatement, final TextEditGroup g) {
    final Assignment nextAssignment = // 
    Optional.of(nextStatement).map(// 
    az::expressionStatement).map(λ -> az.assignment(λ.getExpression())).orElse(null);
    if (nextAssignment == null || !Operator.ASSIGN.equals(a.getOperator()) || !Operator.ASSIGN.equals(nextAssignment.getOperator()))
        return null;
    final Name left1 = az.name(a.getLeftHandSide());
    final Expression right1 = a.getRightHandSide();
    if (left1 == null || right1 == null)
        return null;
    final Name left2 = az.name(nextAssignment.getLeftHandSide());
    if (// 
    left2 == null || // 
    !left1.getFullyQualifiedName().equals(left2.getFullyQualifiedName()) || !sideEffects.sink(right1))
        return null;
    $.remove(a.getParent(), g);
    return $;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) il.org.spartan.spartanizer.tipping(il.org.spartan.spartanizer.tipping) java.util(java.util) org.eclipse.jdt.core.dom.rewrite(org.eclipse.jdt.core.dom.rewrite) il.org.spartan.spartanizer.ast.safety(il.org.spartan.spartanizer.ast.safety) org.eclipse.jdt.core.dom(org.eclipse.jdt.core.dom) org.eclipse.text.edits(org.eclipse.text.edits) il.org.spartan.spartanizer.java(il.org.spartan.spartanizer.java) Assignment(org.eclipse.jdt.core.dom.Assignment) il.org.spartan.utils(il.org.spartan.utils)

Example 97 with Assignment

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

the class LocalInitializedUpdateAssignment method go.

@Override
protected ASTRewrite go(final ASTRewrite $, final VariableDeclarationFragment f, final SimpleName n, final Expression initializer, final Statement nextStatement, final TextEditGroup g) {
    if (initializer == null)
        return null;
    final Assignment a = extract.assignment(nextStatement);
    if (a == null || !wizard.eq(n, to(a)) || $FragmentAndStatement.doesUseForbiddenSiblings(f, from(a)))
        return null;
    final Operator o = a.getOperator();
    if (o == ASSIGN)
        return null;
    final InfixExpression newInitializer = subject.pair(to(a), from(a)).to(op.assign2infix(o));
    final InlinerWithValue i = new Inliner(n, $, g).byValue(initializer);
    if (!i.canInlineinto(newInitializer) || i.replacedSize(newInitializer) - metrics.size(nextStatement, initializer) > 0)
        return null;
    $.replace(initializer, newInitializer, g);
    i.inlineInto(newInitializer);
    $.remove(nextStatement, g);
    return $;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) Operator(org.eclipse.jdt.core.dom.Assignment.Operator) Inliner(il.org.spartan.spartanizer.engine.Inliner)

Example 98 with Assignment

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

the class TypeMismatchSubProcessor method addTypeMismatchProposals.

public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    AST ast = astRoot.getAST();
    ASTNode selectedNode = problem.getCoveredNode(astRoot);
    if (!(selectedNode instanceof Expression)) {
        return;
    }
    Expression nodeToCast = (Expression) selectedNode;
    Name receiverNode = null;
    ITypeBinding castTypeBinding = null;
    int parentNodeType = selectedNode.getParent().getNodeType();
    if (parentNodeType == ASTNode.ASSIGNMENT) {
        Assignment assign = (Assignment) selectedNode.getParent();
        Expression leftHandSide = assign.getLeftHandSide();
        if (selectedNode.equals(leftHandSide)) {
            nodeToCast = assign.getRightHandSide();
        }
        castTypeBinding = assign.getLeftHandSide().resolveTypeBinding();
        if (leftHandSide instanceof Name) {
            receiverNode = (Name) leftHandSide;
        } else if (leftHandSide instanceof FieldAccess) {
            receiverNode = ((FieldAccess) leftHandSide).getName();
        }
    } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        VariableDeclarationFragment frag = (VariableDeclarationFragment) selectedNode.getParent();
        if (selectedNode.equals(frag.getName()) || selectedNode.equals(frag.getInitializer())) {
            nodeToCast = frag.getInitializer();
            castTypeBinding = ASTNodes.getType(frag).resolveBinding();
            receiverNode = frag.getName();
        }
    } else if (parentNodeType == ASTNode.MEMBER_VALUE_PAIR) {
        receiverNode = ((MemberValuePair) selectedNode.getParent()).getName();
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    } else if (parentNodeType == ASTNode.SINGLE_MEMBER_ANNOTATION) {
        // use the type name
        receiverNode = ((SingleMemberAnnotation) selectedNode.getParent()).getTypeName();
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    } else {
        // try to find the binding corresponding to 'castTypeName'
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    }
    if (castTypeBinding == null) {
        return;
    }
    ITypeBinding currBinding = nodeToCast.resolveTypeBinding();
    if (currBinding == null && nodeToCast instanceof MethodInvocation) {
        IMethodBinding methodBinding = ((MethodInvocation) nodeToCast).resolveMethodBinding();
        if (methodBinding != null) {
            currBinding = methodBinding.getReturnType();
        }
    }
    if (!(nodeToCast instanceof ArrayInitializer)) {
        ITypeBinding castFixType = null;
        if (currBinding == null || castTypeBinding.isCastCompatible(currBinding) || nodeToCast instanceof CastExpression) {
            castFixType = castTypeBinding;
        } else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
            ITypeBinding boxUnboxedTypeBinding = boxUnboxPrimitives(castTypeBinding, currBinding, ast);
            if (boxUnboxedTypeBinding != castTypeBinding && boxUnboxedTypeBinding.isCastCompatible(currBinding)) {
                castFixType = boxUnboxedTypeBinding;
            }
        }
        if (castFixType != null) {
            proposals.add(createCastProposal(context, castFixType, nodeToCast, IProposalRelevance.CREATE_CAST));
        }
    }
    // $NON-NLS-1$
    boolean nullOrVoid = currBinding == null || "void".equals(currBinding.getName());
    // change method return statement to actual type
    if (!nullOrVoid && parentNodeType == ASTNode.RETURN_STATEMENT) {
        BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
        if (decl instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            currBinding = Bindings.normalizeTypeBinding(currBinding);
            if (currBinding == null) {
                // $NON-NLS-1$
                currBinding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (currBinding.isWildcardType()) {
                currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
            }
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturntype_description, BasicElementLabels.getJavaElementName(currBinding.getName()));
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_METHOD_RETURN_TYPE);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
            Type newReturnType = imports.addImport(currBinding, ast, importRewriteContext, TypeLocation.RETURN_TYPE);
            rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            proposals.add(proposal);
        }
    }
    if (!nullOrVoid && receiverNode != null) {
        currBinding = Bindings.normalizeTypeBinding(currBinding);
        if (currBinding == null) {
            // $NON-NLS-1$
            currBinding = ast.resolveWellKnownType("java.lang.Object");
        }
        if (currBinding.isWildcardType()) {
            currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
        }
        addChangeSenderTypeProposals(context, receiverNode, currBinding, true, IProposalRelevance.CHANGE_TYPE_OF_RECEIVER_NODE, proposals);
    }
    addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, IProposalRelevance.CHANGE_TYPE_OF_NODE_TO_CAST, proposals);
    if (castTypeBinding == ast.resolveWellKnownType("boolean") && currBinding != null && !currBinding.isPrimitive() && !Bindings.isVoidType(currBinding)) {
        // $NON-NLS-1$
        String label = CorrectionMessages.TypeMismatchSubProcessor_insertnullcheck_description;
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        InfixExpression expression = ast.newInfixExpression();
        expression.setLeftOperand((Expression) rewrite.createMoveTarget(nodeToCast));
        expression.setRightOperand(ast.newNullLiteral());
        expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
        rewrite.replace(nodeToCast, expression, null);
        proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_NULL_CHECK));
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) 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) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.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.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) CastExpression(org.eclipse.jdt.core.dom.CastExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 99 with Assignment

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

the class UnresolvedElementsSubProcessor method addNewVariableProposals.

private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection<CUCorrectionProposal> proposals) {
    String name = simpleName.getIdentifier();
    BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(node, true);
    int type = bodyDeclaration.getNodeType();
    if (type == ASTNode.METHOD_DECLARATION) {
        int relevance = StubUtility.hasParameterName(cu.getJavaProject(), name) ? IProposalRelevance.CREATE_PARAMETER_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_PARAMETER;
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, BasicElementLabels.getJavaElementName(name));
        proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.PARAM, simpleName, null, relevance));
    }
    if (type == ASTNode.INITIALIZER || type == ASTNode.METHOD_DECLARATION && !ASTResolving.isInsideConstructorInvocation((MethodDeclaration) bodyDeclaration, node)) {
        int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? IProposalRelevance.CREATE_LOCAL_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_LOCAL;
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createlocal_description, BasicElementLabels.getJavaElementName(name));
        proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance));
    }
    if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
        Assignment assignment = (Assignment) node.getParent();
        if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
            ASTNode statement = assignment.getParent();
            ASTRewrite rewrite = ASTRewrite.create(statement.getAST());
            if (ASTNodes.isControlStatementBody(assignment.getParent().getLocationInParent())) {
                rewrite.replace(statement, rewrite.getAST().newBlock(), null);
            } else {
                rewrite.remove(statement, null);
            }
            String label = CorrectionMessages.UnresolvedElementsSubProcessor_removestatement_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_ASSIGNMENT);
            proposals.add(proposal);
        }
    }
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 100 with Assignment

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

the class GetterSetterUtil method getAssignedValue.

/**
 * Converts an assignment, postfix expression or prefix expression into an
 * assignable equivalent expression using the getter.
 *
 * @param node
 *            the assignment/prefix/postfix node
 * @param astRewrite
 *            the astRewrite to use
 * @param getterExpression
 *            the expression to insert for read accesses or
 *            <code>null</code> if such an expression does not exist
 * @param variableType
 *            the type of the variable that the result will be assigned to
 * @param is50OrHigher
 *            <code>true</code> if a 5.0 or higher environment can be used
 * @return an expression that can be assigned to the type variableType with
 *         node being replaced by a equivalent expression using the getter
 */
public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, Expression getterExpression, ITypeBinding variableType, boolean is50OrHigher) {
    InfixExpression.Operator op = null;
    AST ast = astRewrite.getAST();
    if (isNotInBlock(node)) {
        return null;
    }
    if (node.getNodeType() == ASTNode.ASSIGNMENT) {
        Assignment assignment = ((Assignment) node);
        Expression rightHandSide = assignment.getRightHandSide();
        Expression copiedRightOp = (Expression) astRewrite.createCopyTarget(rightHandSide);
        if (assignment.getOperator() == Operator.ASSIGN) {
            ITypeBinding rightHandSideType = rightHandSide.resolveTypeBinding();
            copiedRightOp = createNarrowCastIfNessecary(copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher);
            return copiedRightOp;
        }
        if (getterExpression != null) {
            InfixExpression infix = ast.newInfixExpression();
            infix.setLeftOperand(getterExpression);
            infix.setOperator(ASTNodes.convertToInfixOperator(assignment.getOperator()));
            ITypeBinding infixType = infix.resolveTypeBinding();
            if (NecessaryParenthesesChecker.needsParenthesesForRightOperand(rightHandSide, infix, variableType)) {
                ParenthesizedExpression p = ast.newParenthesizedExpression();
                p.setExpression(copiedRightOp);
                copiedRightOp = p;
            }
            infix.setRightOperand(copiedRightOp);
            return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher);
        }
    } else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) {
        PostfixExpression po = (PostfixExpression) node;
        if (po.getOperator() == PostfixExpression.Operator.INCREMENT) {
            op = InfixExpression.Operator.PLUS;
        }
        if (po.getOperator() == PostfixExpression.Operator.DECREMENT) {
            op = InfixExpression.Operator.MINUS;
        }
    } else if (node.getNodeType() == ASTNode.PREFIX_EXPRESSION) {
        PrefixExpression pe = (PrefixExpression) node;
        if (pe.getOperator() == PrefixExpression.Operator.INCREMENT) {
            op = InfixExpression.Operator.PLUS;
        }
        if (pe.getOperator() == PrefixExpression.Operator.DECREMENT) {
            op = InfixExpression.Operator.MINUS;
        }
    }
    if (op != null && getterExpression != null) {
        return createInfixInvocationFromPostPrefixExpression(op, getterExpression, ast, variableType, is50OrHigher);
    }
    return null;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression)

Aggregations

Assignment (org.eclipse.jdt.core.dom.Assignment)116 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)53 Expression (org.eclipse.jdt.core.dom.Expression)50 SimpleName (org.eclipse.jdt.core.dom.SimpleName)47 ASTNode (org.eclipse.jdt.core.dom.ASTNode)43 CastExpression (org.eclipse.jdt.core.dom.CastExpression)36 AST (org.eclipse.jdt.core.dom.AST)35 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)33 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)32 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)30 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)29 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)29 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)28 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)27 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)27 Statement (org.eclipse.jdt.core.dom.Statement)24 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)23 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)22 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)22 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)22