Search in sources :

Example 6 with CastExpression

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

the class SourceProvider method replaceParameterWithExpression.

private void replaceParameterWithExpression(ASTRewrite rewriter, CallContext context, ImportRewrite importRewrite) throws CoreException {
    Expression[] arguments = context.arguments;
    try {
        ITextFileBuffer buffer = RefactoringFileBuffers.acquire(context.compilationUnit);
        for (int i = 0; i < arguments.length; i++) {
            Expression expression = arguments[i];
            String expressionString = null;
            if (expression instanceof SimpleName) {
                expressionString = ((SimpleName) expression).getIdentifier();
            } else {
                try {
                    expressionString = buffer.getDocument().get(expression.getStartPosition(), expression.getLength());
                } catch (BadLocationException exception) {
                    JavaPlugin.log(exception);
                    continue;
                }
            }
            ParameterData parameter = getParameterData(i);
            List<SimpleName> references = parameter.references();
            for (Iterator<SimpleName> iter = references.iterator(); iter.hasNext(); ) {
                ASTNode element = iter.next();
                Expression newExpression = (Expression) rewriter.createStringPlaceholder(expressionString, expression.getNodeType());
                AST ast = rewriter.getAST();
                ITypeBinding explicitCast = ASTNodes.getExplicitCast(expression, (Expression) element);
                if (explicitCast != null) {
                    CastExpression cast = ast.newCastExpression();
                    if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
                        newExpression = createParenthesizedExpression(newExpression, ast);
                    }
                    cast.setExpression(newExpression);
                    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(expression, importRewrite);
                    cast.setType(importRewrite.addImport(explicitCast, ast, importRewriteContext));
                    expression = newExpression = cast;
                }
                if (NecessaryParenthesesChecker.needsParentheses(expression, element.getParent(), element.getLocationInParent())) {
                    newExpression = createParenthesizedExpression(newExpression, ast);
                }
                rewriter.replace(element, newExpression, null);
            }
        }
    } finally {
        RefactoringFileBuffers.release(context.compilationUnit);
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) 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) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CastExpression(org.eclipse.jdt.core.dom.CastExpression) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 7 with CastExpression

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

the class InferTypeArgumentsConstraintCreator method endVisit.

@Override
public void endVisit(CastExpression node) {
    //		if (! (expressionCv instanceof CollectionElementVariable2))
    //			return; //TODO: returns too early when dealing with nested collections.
    Type type = node.getType();
    ITypeBinding typeBinding = type.resolveBinding();
    if (typeBinding.isPrimitive()) {
        ImmutableTypeVariable2 boxed = fTCModel.makeImmutableTypeVariable(typeBinding, node);
        setConstraintVariable(node, boxed);
        // avoid removing numeric conversions
        return;
    }
    ConstraintVariable2 typeCv = getConstraintVariable(type);
    if (typeCv == null)
        return;
    //TODO: can this be loosened when we remove casts?
    setConstraintVariable(node, typeCv);
    Expression expression = node.getExpression();
    ConstraintVariable2 expressionCv = getConstraintVariable(expression);
    //Avoid removing casts that have not been made obsolete by this refactoring:
    if (expressionCv == null)
        return;
    if (expressionCv instanceof ImmutableTypeVariable2)
        return;
    if (!(expressionCv instanceof TypeVariable2 || expressionCv instanceof IndependentTypeVariable2 || expressionCv instanceof CollectionElementVariable2) && fTCModel.getElementVariables(expressionCv).size() == 0 && fTCModel.getArrayElementVariable(expressionCv) == null)
        return;
    fTCModel.createAssignmentElementConstraints(typeCv, expressionCv);
    if (expression instanceof MethodInvocation) {
        MethodInvocation invoc = (MethodInvocation) expression;
        if (!isSpecialCloneInvocation(invoc.resolveMethodBinding(), invoc.getExpression())) {
            fTCModel.makeCastVariable(node, expressionCv);
        }
    } else {
        fTCModel.makeCastVariable(node, expressionCv);
    }
    boolean eitherIsIntf = typeBinding.isInterface() || expression.resolveTypeBinding().isInterface();
    if (eitherIsIntf)
        return;
//TODO: preserve up- and down-castedness!
}
Also used : GenericType(org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.GenericType) ParameterizedType(org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.ParameterizedType) WildcardType(org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.WildcardType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Type(org.eclipse.jdt.core.dom.Type) TType(org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType) ImmutableTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.ImmutableTypeVariable2) CollectionElementVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.CollectionElementVariable2) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ParameterTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.ParameterTypeVariable2) TypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.TypeVariable2) IndependentTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.IndependentTypeVariable2) ParameterizedTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.ParameterizedTypeVariable2) ImmutableTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.ImmutableTypeVariable2) ReturnTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.ReturnTypeVariable2) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) ConstraintVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.ConstraintVariable2) IndependentTypeVariable2(org.eclipse.jdt.internal.corext.refactoring.typeconstraints2.IndependentTypeVariable2)

Example 8 with CastExpression

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

the class UnusedCodeFix method createCleanUp.

public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, IProblemLocation[] problems, boolean removeUnusedPrivateMethods, boolean removeUnusedPrivateConstructors, boolean removeUnusedPrivateFields, boolean removeUnusedPrivateTypes, boolean removeUnusedLocalVariables, boolean removeUnusedImports, boolean removeUnusedCast) {
    List<CompilationUnitRewriteOperation> result = new ArrayList<CompilationUnitRewriteOperation>();
    Hashtable<ASTNode, List<SimpleName>> variableDeclarations = new Hashtable<ASTNode, List<SimpleName>>();
    LinkedHashSet<CastExpression> unnecessaryCasts = new LinkedHashSet<CastExpression>();
    for (int i = 0; i < problems.length; i++) {
        IProblemLocation problem = problems[i];
        int id = problem.getProblemId();
        if (removeUnusedImports && (id == IProblem.UnusedImport || id == IProblem.DuplicateImport || id == IProblem.ConflictingImport || id == IProblem.CannotImportPackage || id == IProblem.ImportNotFound)) {
            ImportDeclaration node = UnusedCodeFix.getImportDeclaration(problem, compilationUnit);
            if (node != null) {
                result.add(new RemoveImportOperation(node));
            }
        }
        if ((removeUnusedPrivateMethods && id == IProblem.UnusedPrivateMethod) || (removeUnusedPrivateConstructors && id == IProblem.UnusedPrivateConstructor) || (removeUnusedPrivateTypes && id == IProblem.UnusedPrivateType)) {
            SimpleName name = getUnusedName(compilationUnit, problem);
            if (name != null) {
                IBinding binding = name.resolveBinding();
                if (binding != null) {
                    result.add(new RemoveUnusedMemberOperation(new SimpleName[] { name }, false));
                }
            }
        }
        if ((removeUnusedLocalVariables && id == IProblem.LocalVariableIsNeverUsed) || (removeUnusedPrivateFields && id == IProblem.UnusedPrivateField)) {
            SimpleName name = getUnusedName(compilationUnit, problem);
            if (name != null) {
                IBinding binding = name.resolveBinding();
                if (binding instanceof IVariableBinding && !isFormalParameterInEnhancedForStatement(name) && (!((IVariableBinding) binding).isField() || isSideEffectFree(name, compilationUnit))) {
                    VariableDeclarationFragment parent = (VariableDeclarationFragment) ASTNodes.getParent(name, VariableDeclarationFragment.class);
                    if (parent != null) {
                        ASTNode varDecl = parent.getParent();
                        if (!variableDeclarations.containsKey(varDecl)) {
                            variableDeclarations.put(varDecl, new ArrayList<SimpleName>());
                        }
                        variableDeclarations.get(varDecl).add(name);
                    } else {
                        result.add(new RemoveUnusedMemberOperation(new SimpleName[] { name }, false));
                    }
                }
            }
        }
        if (removeUnusedCast && id == IProblem.UnnecessaryCast) {
            ASTNode selectedNode = problem.getCoveringNode(compilationUnit);
            ASTNode curr = selectedNode;
            while (curr instanceof ParenthesizedExpression) {
                curr = ((ParenthesizedExpression) curr).getExpression();
            }
            if (curr instanceof CastExpression) {
                unnecessaryCasts.add((CastExpression) curr);
            }
        }
    }
    for (Iterator<ASTNode> iter = variableDeclarations.keySet().iterator(); iter.hasNext(); ) {
        ASTNode node = iter.next();
        List<SimpleName> names = variableDeclarations.get(node);
        result.add(new RemoveUnusedMemberOperation(names.toArray(new SimpleName[names.size()]), false));
    }
    if (unnecessaryCasts.size() > 0)
        result.add(new RemoveAllCastOperation(unnecessaryCasts));
    if (result.size() == 0)
        return null;
    return new UnusedCodeFix(FixMessages.UnusedCodeFix_change_name, compilationUnit, result.toArray(new CompilationUnitRewriteOperation[result.size()]));
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) List(java.util.List) ArrayList(java.util.ArrayList) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) Hashtable(java.util.Hashtable) IProblemLocation(org.eclipse.jdt.ui.text.java.IProblemLocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Example 9 with CastExpression

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

the class UnusedCodeFix method createRemoveUnusedCastFix.

public static UnusedCodeFix createRemoveUnusedCastFix(CompilationUnit compilationUnit, IProblemLocation problem) {
    if (problem.getProblemId() != IProblem.UnnecessaryCast)
        return null;
    ASTNode selectedNode = problem.getCoveringNode(compilationUnit);
    ASTNode curr = selectedNode;
    while (curr instanceof ParenthesizedExpression) {
        curr = ((ParenthesizedExpression) curr).getExpression();
    }
    if (!(curr instanceof CastExpression))
        return null;
    return new UnusedCodeFix(FixMessages.UnusedCodeFix_RemoveCast_description, compilationUnit, new CompilationUnitRewriteOperation[] { new RemoveCastOperation((CastExpression) curr) });
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Example 10 with CastExpression

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

the class CallInliner method replaceCall.

private void replaceCall(RefactoringStatus status, String[] blocks, TextEditGroup textEditGroup) {
    // Inline empty body
    if (blocks.length == 0 && fTargetNode != null) {
        if (fNeedsStatement) {
            fRewrite.replace(fTargetNode, fTargetNode.getAST().newEmptyStatement(), textEditGroup);
        } else {
            fRewrite.remove(fTargetNode, textEditGroup);
        }
    } else {
        ASTNode node = null;
        for (int i = 0; i < blocks.length - 1; i++) {
            node = fRewrite.createStringPlaceholder(blocks[i], ASTNode.RETURN_STATEMENT);
            fListRewrite.insertAt(node, fInsertionIndex++, textEditGroup);
        }
        String block = blocks[blocks.length - 1];
        // returned expression must be evaluated.
        if (fContext.callMode == ASTNode.EXPRESSION_STATEMENT && fSourceProvider.hasReturnValue()) {
            if (fSourceProvider.mustEvaluateReturnedExpression()) {
                if (fSourceProvider.returnValueNeedsLocalVariable()) {
                    IMethodBinding invocation = Invocations.resolveBinding(fInvocation);
                    node = createLocalDeclaration(invocation.getReturnType(), fInvocationScope.createName(fSourceProvider.getMethodName(), true), (Expression) fRewrite.createStringPlaceholder(block, ASTNode.METHOD_INVOCATION));
                } else {
                    node = fRewrite.getAST().newExpressionStatement((Expression) fRewrite.createStringPlaceholder(block, ASTNode.METHOD_INVOCATION));
                }
            } else {
                node = null;
            }
        } else if (fTargetNode instanceof Expression) {
            node = fRewrite.createStringPlaceholder(block, ASTNode.METHOD_INVOCATION);
            // fixes bug #24941
            if (needsExplicitCast(status)) {
                AST ast = node.getAST();
                CastExpression castExpression = ast.newCastExpression();
                Type returnType = fImportRewrite.addImport(fSourceProvider.getReturnType(), ast);
                castExpression.setType(returnType);
                if (NecessaryParenthesesChecker.needsParentheses(fSourceProvider.getReturnExpressions().get(0), castExpression, CastExpression.EXPRESSION_PROPERTY)) {
                    ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
                    parenthesized.setExpression((Expression) node);
                    node = parenthesized;
                }
                castExpression.setExpression((Expression) node);
                node = castExpression;
                if (NecessaryParenthesesChecker.needsParentheses(castExpression, fTargetNode.getParent(), fTargetNode.getLocationInParent())) {
                    ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
                    parenthesized.setExpression((Expression) node);
                    node = parenthesized;
                }
            } else if (fSourceProvider.needsReturnedExpressionParenthesis(fTargetNode.getParent(), fTargetNode.getLocationInParent())) {
                ParenthesizedExpression pExp = fTargetNode.getAST().newParenthesizedExpression();
                pExp.setExpression((Expression) node);
                node = pExp;
            }
        } else {
            node = fRewrite.createStringPlaceholder(block, ASTNode.RETURN_STATEMENT);
        }
        // Now replace the target node with the source node
        if (node != null) {
            if (fTargetNode == null) {
                fListRewrite.insertAt(node, fInsertionIndex++, textEditGroup);
            } else {
                fRewrite.replace(fTargetNode, node, textEditGroup);
            }
        } else {
            if (fTargetNode != null) {
                fRewrite.remove(fTargetNode, textEditGroup);
            }
        }
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) Type(org.eclipse.jdt.core.dom.Type) TType(org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType) 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) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Aggregations

CastExpression (org.eclipse.jdt.core.dom.CastExpression)24 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)18 ASTNode (org.eclipse.jdt.core.dom.ASTNode)16 Expression (org.eclipse.jdt.core.dom.Expression)16 AST (org.eclipse.jdt.core.dom.AST)11 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)11 Type (org.eclipse.jdt.core.dom.Type)10 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)7 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)7 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)7 Assignment (org.eclipse.jdt.core.dom.Assignment)6 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)6 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)6 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)6 SimpleName (org.eclipse.jdt.core.dom.SimpleName)6 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)6 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)6 IBinding (org.eclipse.jdt.core.dom.IBinding)4