Search in sources :

Example 1 with InfixExpression

use of org.eclipse.jdt.core.dom.InfixExpression in project che 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)

Example 2 with InfixExpression

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

the class NecessaryParenthesesChecker method needsParentheses.

/**
	 * Does the <code>expression</code> need parentheses when inserted into <code>parent</code> at
	 * <code>locationInParent</code> ?
	 *
	 * @param expression the expression
	 * @param parent the parent node
	 * @param locationInParent location of expression in the parent
	 * @param leftOperandType the type of the left operand in <code>parent</code> if
	 *            <code>parent</code> is an infix expression with no bindings and
	 *            <code>expression</code> is the right operand in it, <code>null</code> otherwise
	 * @return <code>true</code> if <code>expression</code> needs parentheses, <code>false</code>
	 *         otherwise.
	 *
	 * @since 3.9
	 */
private static boolean needsParentheses(Expression expression, ASTNode parent, StructuralPropertyDescriptor locationInParent, ITypeBinding leftOperandType) {
    if (!expressionTypeNeedsParentheses(expression))
        return false;
    if (!locationNeedsParentheses(locationInParent)) {
        return false;
    }
    if (parent instanceof Expression) {
        Expression parentExpression = (Expression) parent;
        if (expression instanceof PrefixExpression) {
            // see bug 405096
            return needsParenthesesForPrefixExpression(parentExpression, ((PrefixExpression) expression).getOperator());
        }
        int expressionPrecedence = OperatorPrecedence.getExpressionPrecedence(expression);
        int parentPrecedence = OperatorPrecedence.getExpressionPrecedence(parentExpression);
        if (expressionPrecedence > parentPrecedence)
            //(opEx) opParent and opEx binds more -> parentheses not needed
            return false;
        if (expressionPrecedence < parentPrecedence)
            //(opEx) opParent and opEx binds less -> parentheses needed
            return true;
        if (parentExpression instanceof InfixExpression) {
            return needsParenthesesInInfixExpression(expression, (InfixExpression) parentExpression, locationInParent, leftOperandType);
        }
        if (parentExpression instanceof ConditionalExpression && locationInParent == ConditionalExpression.EXPRESSION_PROPERTY) {
            return true;
        }
        return false;
    }
    return true;
}
Also used : ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression)

Example 3 with InfixExpression

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

the class NecessaryParenthesesChecker method isAllOperandsHaveSameType.

/*
	 * Do all operands in expression have same type
	 */
private static boolean isAllOperandsHaveSameType(InfixExpression expression, ITypeBinding leftOperandType, ITypeBinding rightOperandType) {
    ITypeBinding binding = leftOperandType;
    if (binding == null)
        return false;
    ITypeBinding current = rightOperandType;
    if (binding != current)
        return false;
    for (Iterator<Expression> iterator = expression.extendedOperands().iterator(); iterator.hasNext(); ) {
        Expression operand = iterator.next();
        current = operand.resolveTypeBinding();
        if (binding != current)
            return false;
    }
    return true;
}
Also used : ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Example 4 with InfixExpression

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

the class ExtractToNullCheckedLocalProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    // infrastructure:
    AST ast = this.compilationUnit.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = ImportRewrite.create(this.compilationUnit, true);
    TextEditGroup group = new TextEditGroup(FixMessages.ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName);
    LinkedProposalPositionGroup localNameGroup = new LinkedProposalPositionGroup(LOCAL_NAME_POSITION_GROUP);
    getLinkedProposalModel().addPositionGroup(localNameGroup);
    // AST context:
    Statement origStmt = (Statement) ASTNodes.getParent(this.fieldReference, Statement.class);
    // determine suitable strategy for rearranging elements towards a new code structure:
    RearrangeStrategy rearrangeStrategy = RearrangeStrategy.create(origStmt, rewrite, group);
    Expression toReplace;
    ASTNode directParent = this.fieldReference.getParent();
    if (directParent instanceof FieldAccess) {
        toReplace = (Expression) directParent;
    } else if (directParent instanceof QualifiedName && this.fieldReference.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
        toReplace = (Expression) directParent;
    } else {
        toReplace = this.fieldReference;
    }
    // new local declaration initialized from the field reference
    VariableDeclarationFragment localFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement localDecl = ast.newVariableDeclarationStatement(localFrag);
    // ... type
    localDecl.setType(newType(toReplace.resolveTypeBinding(), ast, imports));
    localDecl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
    // ... name
    String localName = proposeLocalName(this.fieldReference, this.compilationUnit, getCompilationUnit().getJavaProject());
    localFrag.setName(ast.newSimpleName(localName));
    // ... initialization
    localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, toReplace));
    rearrangeStrategy.insertLocalDecl(localDecl);
    // if statement:
    IfStatement ifStmt = ast.newIfStatement();
    // condition:
    InfixExpression nullCheck = ast.newInfixExpression();
    nullCheck.setLeftOperand(ast.newSimpleName(localName));
    nullCheck.setRightOperand(ast.newNullLiteral());
    nullCheck.setOperator(InfixExpression.Operator.NOT_EQUALS);
    ifStmt.setExpression(nullCheck);
    // then block: the original statement
    Block thenBlock = ast.newBlock();
    thenBlock.statements().add(rearrangeStrategy.createMoveTargetForOrigStmt());
    ifStmt.setThenStatement(thenBlock);
    // ... but with the field reference replaced by the new local:
    SimpleName dereferencedName = ast.newSimpleName(localName);
    rewrite.replace(toReplace, dereferencedName, group);
    // else block: a Todo comment
    Block elseBlock = ast.newBlock();
    //$NON-NLS-1$
    String elseStatement = "// TODO " + FixMessages.ExtractToNullCheckedLocalProposal_todoHandleNullDescription;
    if (origStmt instanceof ReturnStatement) {
        Type returnType = newType(((ReturnStatement) origStmt).getExpression().resolveTypeBinding(), ast, imports);
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
        elseStatement += '\n' + ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
    }
    EmptyStatement todoNode = (EmptyStatement) rewrite.createStringPlaceholder(elseStatement, ASTNode.EMPTY_STATEMENT);
    elseBlock.statements().add(todoNode);
    ifStmt.setElseStatement(elseBlock);
    // link all three occurrences of the new local variable:
    addLinkedPosition(rewrite.track(localFrag.getName()), true, /*first*/
    LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(nullCheck.getLeftOperand()), false, LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(dereferencedName), false, LOCAL_NAME_POSITION_GROUP);
    rearrangeStrategy.insertIfStatement(ifStmt, thenBlock);
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Block(org.eclipse.jdt.core.dom.Block) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 5 with InfixExpression

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

the class AssociativeInfixExpressionFragment method createCopyTarget.

public Expression createCopyTarget(ASTRewrite rewrite, boolean removeSurroundingParenthesis) throws JavaModelException {
    List<Expression> allOperands = findGroupMembersInOrderFor(fGroupRoot);
    if (allOperands.size() == fOperands.size()) {
        return (Expression) rewrite.createCopyTarget(fGroupRoot);
    }
    CompilationUnit root = (CompilationUnit) fGroupRoot.getRoot();
    ICompilationUnit cu = (ICompilationUnit) root.getJavaElement();
    String source = cu.getBuffer().getText(getStartPosition(), getLength());
    return (Expression) rewrite.createStringPlaceholder(source, ASTNode.INFIX_EXPRESSION);
//		//Todo: see whether we could copy bigger chunks of the original selection
//		// (probably only possible from extendedOperands list or from nested InfixExpressions)
//		InfixExpression result= rewrite.getAST().newInfixExpression();
//		result.setOperator(getOperator());
//		Expression first= (Expression) fOperands.get(0);
//		Expression second= (Expression) fOperands.get(1);
//		result.setLeftOperand((Expression) rewrite.createCopyTarget(first));
//		result.setRightOperand((Expression) rewrite.createCopyTarget(second));
//		for (int i= 2; i < fOperands.size(); i++) {
//			Expression next= (Expression) fOperands.get(i);
//			result.extendedOperands().add(rewrite.createCopyTarget(next));
//		}
//		return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression)

Aggregations

InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)196 Expression (org.eclipse.jdt.core.dom.Expression)137 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)85 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)67 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)55 CastExpression (org.eclipse.jdt.core.dom.CastExpression)47 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)37 PostfixExpression (org.eclipse.jdt.core.dom.PostfixExpression)34 InstanceofExpression (org.eclipse.jdt.core.dom.InstanceofExpression)31 AST (org.eclipse.jdt.core.dom.AST)29 ASTNode (org.eclipse.jdt.core.dom.ASTNode)29 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)25 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)24 ASTNodeFactory (org.autorefactor.jdt.internal.corext.dom.ASTNodeFactory)24 TextEditGroup (org.eclipse.text.edits.TextEditGroup)22 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)20 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)20 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)18 Assignment (org.eclipse.jdt.core.dom.Assignment)17 IfStatement (org.eclipse.jdt.core.dom.IfStatement)17