Search in sources :

Example 11 with PrefixExpression

use of org.eclipse.jdt.core.dom.PrefixExpression in project eclipse-cs by checkstyle.

the class SimplifyBooleanReturnQuickfix method handleGetCorrectingASTVisitor.

/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo, final int markerStartOffset) {
    return new ASTVisitor() {

        @Override
        public boolean visit(final IfStatement node) {
            if (containsPosition(node, markerStartOffset)) {
                final Boolean isThenStatementTrue = isReturnStatementTrue(node.getThenStatement());
                if (isThenStatementTrue == null) {
                    // the AST structure of the if statement is not as expected
                    return true;
                }
                final Expression condition = removeNotFromCondition(node.getExpression());
                final boolean isNotCondition = condition != node.getExpression();
                final ReturnStatement replacement;
                if (isThenStatementTrue ^ isNotCondition) {
                    // create replacement: return condition;
                    replacement = node.getAST().newReturnStatement();
                    replacement.setExpression(copy(condition));
                } else {
                    // create replacement: return !(condition);
                    final AST ast = node.getAST();
                    replacement = ast.newReturnStatement();
                    final PrefixExpression not = ast.newPrefixExpression();
                    not.setOperator(Operator.NOT);
                    if (omitParantheses(condition)) {
                        not.setOperand(copy(condition));
                    } else {
                        final ParenthesizedExpression parentheses = ast.newParenthesizedExpression();
                        parentheses.setExpression(copy(condition));
                        not.setOperand(parentheses);
                    }
                    replacement.setExpression(not);
                }
                replace(node, replacement);
            }
            return true;
        }

        private Boolean isReturnStatementTrue(final Statement node) {
            if (node instanceof ReturnStatement) {
                final Expression expression = ((ReturnStatement) node).getExpression();
                if (expression instanceof BooleanLiteral) {
                    return ((BooleanLiteral) expression).booleanValue();
                }
            } else if (node instanceof Block) {
                // the return statement might be wrapped in a block statement
                @SuppressWarnings("unchecked") final List<Statement> statements = ((Block) node).statements();
                if (statements.size() > 0) {
                    return isReturnStatementTrue(statements.get(0));
                }
            }
            return null;
        }

        private Expression removeNotFromCondition(final Expression condition) {
            if (condition instanceof PrefixExpression) {
                final PrefixExpression prefix = (PrefixExpression) condition;
                if (PrefixExpression.Operator.NOT.equals(prefix.getOperator())) {
                    return prefix.getOperand();
                }
            }
            return condition;
        }

        private boolean omitParantheses(final Expression condition) {
            return OMIT_PARANETHESES_CLASSES.contains(condition.getClass());
        }
    };
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) BooleanLiteral(org.eclipse.jdt.core.dom.BooleanLiteral) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) List(java.util.List)

Example 12 with PrefixExpression

use of org.eclipse.jdt.core.dom.PrefixExpression in project eclipse-cs by checkstyle.

the class StringLiteralEqualityQuickfix method handleGetCorrectingASTVisitor.

/**
 * {@inheritDoc}
 */
@Override
protected ASTVisitor handleGetCorrectingASTVisitor(final IRegion lineInfo, final int markerStartPosition) {
    return new ASTVisitor() {

        @SuppressWarnings("unchecked")
        @Override
        public boolean visit(InfixExpression node) {
            if (containsPosition(lineInfo, node.getStartPosition())) {
                StringLiteral literal = null;
                Expression otherOperand = null;
                if (node.getLeftOperand() instanceof StringLiteral) {
                    literal = (StringLiteral) node.getLeftOperand();
                    otherOperand = node.getRightOperand();
                } else if (node.getRightOperand() instanceof StringLiteral) {
                    literal = (StringLiteral) node.getRightOperand();
                    otherOperand = node.getLeftOperand();
                } else {
                    return true;
                }
                Expression replacementNode = null;
                MethodInvocation equalsInvocation = node.getAST().newMethodInvocation();
                // $NON-NLS-1$
                equalsInvocation.setName(node.getAST().newSimpleName("equals"));
                equalsInvocation.setExpression((Expression) ASTNode.copySubtree(node.getAST(), literal));
                equalsInvocation.arguments().add(ASTNode.copySubtree(node.getAST(), otherOperand));
                // expression
                if (node.getOperator().equals(InfixExpression.Operator.NOT_EQUALS)) {
                    PrefixExpression prefixExpression = node.getAST().newPrefixExpression();
                    prefixExpression.setOperator(PrefixExpression.Operator.NOT);
                    prefixExpression.setOperand(equalsInvocation);
                    replacementNode = prefixExpression;
                } else {
                    replacementNode = equalsInvocation;
                }
                replaceNode(node, replacementNode);
            }
            return true;
        }

        /**
         * Replaces the given node with the replacement node (using reflection
         * since I am not aware of a proper API to do this).
         *
         * @param node
         *          the node to replace
         * @param replacementNode
         *          the replacement
         */
        private void replaceNode(ASTNode node, ASTNode replacementNode) {
            try {
                if (node.getLocationInParent().isChildProperty()) {
                    String property = node.getLocationInParent().getId();
                    String capitalizedProperty = property.substring(0, 1).toUpperCase() + property.substring(1);
                    String setterMethodName = "set" + capitalizedProperty;
                    Class<?> testClass = node.getClass();
                    while (testClass != null) {
                        try {
                            Method setterMethod = node.getParent().getClass().getMethod(setterMethodName, testClass);
                            setterMethod.invoke(node.getParent(), replacementNode);
                            break;
                        } catch (NoSuchMethodException e) {
                            testClass = testClass.getSuperclass();
                        }
                    }
                } else if (node.getLocationInParent().isChildListProperty()) {
                    Method listMethod = node.getParent().getClass().getMethod(node.getLocationInParent().getId(), (Class<?>[]) null);
                    @SuppressWarnings("unchecked") List<ASTNode> list = (List<ASTNode>) listMethod.invoke(node.getParent(), (Object[]) null);
                    list.set(list.indexOf(node), replacementNode);
                }
            } catch (InvocationTargetException e) {
                CheckstyleLog.log(e);
            } catch (IllegalAccessException e) {
                CheckstyleLog.log(e);
            } catch (NoSuchMethodException e) {
                CheckstyleLog.log(e);
            }
        }
    };
}
Also used : MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) List(java.util.List)

Example 13 with PrefixExpression

use of org.eclipse.jdt.core.dom.PrefixExpression in project evosuite by EvoSuite.

the class TestExtractingVisitor method retrieveVariableReference.

/**
 * <p>
 * retrieveVariableReference
 * </p>
 *
 * @param argument
 *            a {@link java.lang.Object} object.
 * @param varType
 *            a {@link java.lang.Class} object.
 * @return a {@link org.evosuite.testcase.VariableReference} object.
 */
protected VariableReference retrieveVariableReference(Object argument, Class<?> varType) {
    if (argument instanceof ClassInstanceCreation) {
        return retrieveVariableReference((ClassInstanceCreation) argument, varType);
    }
    if (argument instanceof VariableDeclarationFragment) {
        return retrieveVariableReference((VariableDeclarationFragment) argument);
    }
    if (argument instanceof SimpleName) {
        SimpleName simpleName = (SimpleName) argument;
        lineNumber = testReader.getLineNumber(simpleName.getStartPosition());
        return retrieveVariableReference(simpleName.resolveBinding(), varType);
    }
    if (argument instanceof IVariableBinding) {
        return retrieveVariableReference((IVariableBinding) argument, varType);
    }
    if (argument instanceof PrefixExpression) {
        return retrieveVariableReference((PrefixExpression) argument);
    }
    if (argument instanceof InfixExpression) {
        return retrieveVariableReference((InfixExpression) argument, varType);
    }
    if (argument instanceof ExpressionStatement) {
        ExpressionStatement exprStmt = (ExpressionStatement) argument;
        Expression expression = exprStmt.getExpression();
        return retrieveVariableReference(expression, varType);
    }
    if (argument instanceof NullLiteral) {
        return retrieveVariableReference((NullLiteral) argument, varType);
    }
    if (argument instanceof StringLiteral) {
        return retrieveVariableReference((StringLiteral) argument);
    }
    if (argument instanceof NumberLiteral) {
        return retrieveVariableReference((NumberLiteral) argument);
    }
    if (argument instanceof CharacterLiteral) {
        return retrieveVariableReference((CharacterLiteral) argument);
    }
    if (argument instanceof BooleanLiteral) {
        return retrieveVariableReference((BooleanLiteral) argument);
    }
    if (argument instanceof ITypeBinding) {
        if (varType != null) {
            return new ValidVariableReference(testCase.getReference(), varType);
        }
        return new ValidVariableReference(testCase.getReference(), retrieveTypeClass(argument));
    }
    if (argument instanceof QualifiedName) {
        return retrieveVariableReference((QualifiedName) argument);
    }
    if (argument instanceof MethodInvocation) {
        MethodInvocation methodInvocation = (MethodInvocation) argument;
        VariableReference result = retrieveResultReference(methodInvocation);
        nestedCallResults.push(result);
        return result;
    }
    if (argument instanceof ArrayCreation) {
        return retrieveVariableReference((ArrayCreation) argument);
    }
    if (argument instanceof VariableDeclaration) {
        return retrieveVariableReference((VariableDeclaration) argument);
    }
    if (argument instanceof ArrayAccess) {
        // argument).getArray(), null);
        return retrieveVariableReference((ArrayAccess) argument);
    }
    if (argument instanceof Assignment) {
        return retrieveVariableReference(((Assignment) argument).getLeftHandSide(), null);
    }
    if (argument instanceof CastExpression) {
        CastExpression castExpression = (CastExpression) argument;
        VariableReference result = retrieveVariableReference(castExpression.getExpression(), null);
        Class<?> castClass = retrieveTypeClass(castExpression.resolveTypeBinding());
        assert castClass.isAssignableFrom(toClass(result.getType()));
        result.setType(castClass);
        return result;
    }
    throw new UnsupportedOperationException("Argument type " + argument.getClass() + " not implemented!");
}
Also used : BooleanLiteral(org.eclipse.jdt.core.dom.BooleanLiteral) SimpleName(org.eclipse.jdt.core.dom.SimpleName) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Assignment(org.eclipse.jdt.core.dom.Assignment) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) VariableReference(org.evosuite.testcase.VariableReference) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) PrimitiveExpression(org.evosuite.testcase.PrimitiveExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) CastExpression(org.eclipse.jdt.core.dom.CastExpression) NullLiteral(org.eclipse.jdt.core.dom.NullLiteral) NumberLiteral(org.eclipse.jdt.core.dom.NumberLiteral) CharacterLiteral(org.eclipse.jdt.core.dom.CharacterLiteral)

Example 14 with PrefixExpression

use of org.eclipse.jdt.core.dom.PrefixExpression in project flux by eclipse.

the class AdvancedQuickAssistProcessor method getPushNegationDownProposals.

private static boolean getPushNegationDownProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
    PrefixExpression negationExpression = null;
    ParenthesizedExpression parenthesizedExpression = null;
    // check for case when cursor is on '!' before parentheses
    if (covering instanceof PrefixExpression) {
        PrefixExpression prefixExpression = (PrefixExpression) covering;
        if (prefixExpression.getOperator() == PrefixExpression.Operator.NOT && prefixExpression.getOperand() instanceof ParenthesizedExpression) {
            negationExpression = prefixExpression;
            parenthesizedExpression = (ParenthesizedExpression) prefixExpression.getOperand();
        }
    }
    // check for case when cursor is on parenthesized expression that is negated
    if (covering instanceof ParenthesizedExpression && covering.getParent() instanceof PrefixExpression && ((PrefixExpression) covering.getParent()).getOperator() == PrefixExpression.Operator.NOT) {
        negationExpression = (PrefixExpression) covering.getParent();
        parenthesizedExpression = (ParenthesizedExpression) covering;
    }
    if (negationExpression == null || (!(parenthesizedExpression.getExpression() instanceof InfixExpression) && !(parenthesizedExpression.getExpression() instanceof ConditionalExpression))) {
        return false;
    }
    // we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    // 
    final AST ast = covering.getAST();
    final ASTRewrite rewrite = ASTRewrite.create(ast);
    // prepared inverted expression
    Expression inversedExpression = getInversedExpression(rewrite, parenthesizedExpression.getExpression());
    // check, may be we should keep parentheses
    boolean keepParentheses = false;
    if (negationExpression.getParent() instanceof Expression) {
        int parentPrecedence = OperatorPrecedence.getExpressionPrecedence(((Expression) negationExpression.getParent()));
        int inversedExpressionPrecedence = OperatorPrecedence.getExpressionPrecedence(inversedExpression);
        keepParentheses = parentPrecedence > inversedExpressionPrecedence;
    }
    // replace negated expression with inverted one
    if (keepParentheses) {
        ParenthesizedExpression pe = ast.newParenthesizedExpression();
        pe.setExpression(inversedExpression);
        rewrite.replace(negationExpression, pe, null);
    } else {
        rewrite.replace(negationExpression, inversedExpression, null);
    }
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_pushNegationDown;
    // Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.PULL_NEGATION_DOWN);
    resultingCollections.add(proposal);
    return true;
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AST(org.eclipse.jdt.core.dom.AST) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) 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) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 15 with PrefixExpression

use of org.eclipse.jdt.core.dom.PrefixExpression in project flux by eclipse.

the class AdvancedQuickAssistProcessor method isNegated.

private static boolean isNegated(Expression expression) {
    if (!(expression.getParent() instanceof ParenthesizedExpression))
        return false;
    ParenthesizedExpression parenthesis = (ParenthesizedExpression) expression.getParent();
    if (!(parenthesis.getParent() instanceof PrefixExpression))
        return false;
    PrefixExpression prefix = (PrefixExpression) parenthesis.getParent();
    if (!(prefix.getOperator() == PrefixExpression.Operator.NOT))
        return false;
    return true;
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression)

Aggregations

PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)60 Expression (org.eclipse.jdt.core.dom.Expression)48 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)47 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)27 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)22 CastExpression (org.eclipse.jdt.core.dom.CastExpression)19 PostfixExpression (org.eclipse.jdt.core.dom.PostfixExpression)15 InstanceofExpression (org.eclipse.jdt.core.dom.InstanceofExpression)12 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)12 ASTNode (org.eclipse.jdt.core.dom.ASTNode)10 AST (org.eclipse.jdt.core.dom.AST)9 Assignment (org.eclipse.jdt.core.dom.Assignment)9 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)9 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)9 NumberLiteral (org.eclipse.jdt.core.dom.NumberLiteral)7 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)7 SimpleName (org.eclipse.jdt.core.dom.SimpleName)6 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)6 List (java.util.List)5 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)5