Search in sources :

Example 21 with MethodInvocation

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

the class ExtractMethodRefactoring method createCallNodes.

//---- Code generation -----------------------------------------------------------------------
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
    List<ASTNode> result = new ArrayList<ASTNode>(2);
    IVariableBinding[] locals = fAnalyzer.getCallerLocals();
    for (int i = 0; i < locals.length; i++) {
        result.add(createDeclaration(locals[i], null));
    }
    MethodInvocation invocation = fAST.newMethodInvocation();
    invocation.setName(fAST.newSimpleName(fMethodName));
    ASTNode typeNode = ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
    RefactoringStatus status = new RefactoringStatus();
    while (fDestination != typeNode) {
        fAnalyzer.checkInput(status, fMethodName, typeNode);
        if (!status.isOK()) {
            SimpleName destinationTypeName = fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
            if ((modifiers & Modifier.STATIC) == 0) {
                ThisExpression thisExpression = fAST.newThisExpression();
                thisExpression.setQualifier(destinationTypeName);
                invocation.setExpression(thisExpression);
            } else {
                invocation.setExpression(destinationTypeName);
            }
            break;
        }
        typeNode = typeNode.getParent();
    }
    List<Expression> arguments = invocation.arguments();
    for (int i = 0; i < fParameterInfos.size(); i++) {
        ParameterInfo parameter = fParameterInfos.get(i);
        arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
    }
    if (fLinkedProposalModel != null) {
        LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
        nameGroup.addPosition(fRewriter.track(invocation.getName()), false);
    }
    ASTNode call;
    int returnKind = fAnalyzer.getReturnKind();
    switch(returnKind) {
        case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
            IVariableBinding binding = fAnalyzer.getReturnLocal();
            if (binding != null) {
                VariableDeclarationStatement decl = createDeclaration(getMappedBinding(duplicate, binding), invocation);
                call = decl;
            } else {
                Assignment assignment = fAST.newAssignment();
                assignment.setLeftHandSide(ASTNodeFactory.newName(fAST, getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
                assignment.setRightHandSide(invocation);
                call = assignment;
            }
            break;
        case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
            ReturnStatement rs = fAST.newReturnStatement();
            rs.setExpression(invocation);
            call = rs;
            break;
        default:
            call = invocation;
    }
    if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
        call = fAST.newExpressionStatement((Expression) call);
    }
    result.add(call);
    // return;
    if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
        result.add(fAST.newReturnStatement());
    }
    return result.toArray(new ASTNode[result.size()]);
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) ParameterInfo(org.eclipse.jdt.internal.corext.refactoring.ParameterInfo) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Assignment(org.eclipse.jdt.core.dom.Assignment) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 22 with MethodInvocation

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

the class IntroduceIndirectionRefactoring method updateMethodInvocation.

// ******************* UPDATE CALLS **********************
private RefactoringStatus updateMethodInvocation(MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) throws JavaModelException {
    RefactoringStatus status = new RefactoringStatus();
    // call as the new target method may have additional parameters
    if (originalInvocation.typeArguments().size() > 0)
        return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_type_arguments);
    MethodInvocation newInvocation = unitRewriter.getAST().newMethodInvocation();
    List<Expression> newInvocationArgs = newInvocation.arguments();
    List<Expression> originalInvocationArgs = originalInvocation.arguments();
    // static call => always use a qualifier
    String qualifier = unitRewriter.getImportRewrite().addImport(fIntermediaryTypeBinding);
    newInvocation.setExpression(ASTNodeFactory.newName(unitRewriter.getAST(), qualifier));
    newInvocation.setName(unitRewriter.getAST().newSimpleName(getIntermediaryMethodName()));
    final Expression expression = originalInvocation.getExpression();
    if (!isStaticTarget()) {
        // Add the expression as the first parameter
        if (expression == null) {
            // There is no expression for this call. Use a (possibly qualified) "this" expression.
            ThisExpression expr = unitRewriter.getAST().newThisExpression();
            RefactoringStatus qualifierStatus = qualifyThisExpression(expr, originalInvocation, enclosing, unitRewriter);
            status.merge(qualifierStatus);
            if (qualifierStatus.hasEntries())
                // warning means don't include this invocation
                return status;
            newInvocationArgs.add(expr);
        } else {
            Expression expressionAsParam = (Expression) unitRewriter.getASTRewrite().createMoveTarget(expression);
            newInvocationArgs.add(expressionAsParam);
        }
    } else {
        if (expression != null) {
            // be side effects (e.g. inside methods) -> don't update
            if (!(expression instanceof Name) || ASTNodes.getTypeBinding((Name) expression) == null)
                return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_static_expression_access);
        }
    }
    for (int i = 0; i < originalInvocationArgs.size(); i++) {
        Expression originalInvocationArg = originalInvocationArgs.get(i);
        Expression movedArg = (Expression) unitRewriter.getASTRewrite().createMoveTarget(originalInvocationArg);
        newInvocationArgs.add(movedArg);
    }
    unitRewriter.getASTRewrite().replace(originalInvocation, newInvocation, unitRewriter.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_replace_call));
    return status;
}
Also used : ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Name(org.eclipse.jdt.core.dom.Name)

Example 23 with MethodInvocation

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

the class IntroduceIndirectionRefactoring method createIntermediaryMethod.

private void createIntermediaryMethod() throws CoreException {
    CompilationUnitRewrite imRewrite = getCachedCURewrite(fIntermediaryType.getCompilationUnit());
    AST ast = imRewrite.getAST();
    MethodDeclaration intermediary = ast.newMethodDeclaration();
    // Intermediary class is non-anonymous
    AbstractTypeDeclaration type = (AbstractTypeDeclaration) typeToDeclaration(fIntermediaryType, imRewrite.getRoot());
    // Name
    intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));
    // Flags
    List<IExtendedModifier> modifiers = intermediary.modifiers();
    if (!fIntermediaryType.isInterface()) {
        modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    }
    modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));
    // Parameters
    String targetParameterName = StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(type, imRewrite.getImportRewrite());
    if (!isStaticTarget()) {
        // Add first param
        SingleVariableDeclaration parameter = imRewrite.getAST().newSingleVariableDeclaration();
        Type t = imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST(), context);
        if (fIntermediaryFirstParameterType.isGenericType()) {
            ParameterizedType parameterized = imRewrite.getAST().newParameterizedType(t);
            ITypeBinding[] typeParameters = fIntermediaryFirstParameterType.getTypeParameters();
            for (int i = 0; i < typeParameters.length; i++) parameterized.typeArguments().add(imRewrite.getImportRewrite().addImport(typeParameters[i], imRewrite.getAST()));
            t = parameterized;
        }
        parameter.setType(t);
        parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
        intermediary.parameters().add(parameter);
    }
    // Add other params
    copyArguments(intermediary, imRewrite);
    // Add type parameters of declaring type (and enclosing types)
    if (!isStaticTarget() && fIntermediaryFirstParameterType.isGenericType())
        addTypeParameters(imRewrite, intermediary.typeParameters(), fIntermediaryFirstParameterType);
    // Add type params of method
    copyTypeParameters(intermediary, imRewrite);
    // Return type
    intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast, context));
    // Exceptions
    copyExceptions(intermediary, imRewrite);
    // Body
    MethodInvocation invocation = imRewrite.getAST().newMethodInvocation();
    invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
    if (isStaticTarget()) {
        Type importedType = imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast, context);
        invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(importedType)));
    } else {
        invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
    }
    copyInvocationParameters(invocation, ast);
    Statement call = encapsulateInvocation(intermediary, invocation);
    final Block body = imRewrite.getAST().newBlock();
    body.statements().add(call);
    intermediary.setBody(body);
    // method comment
    ICompilationUnit targetCU = imRewrite.getCu();
    if (StubUtility.doAddComments(targetCU.getJavaProject())) {
        String comment = CodeGeneration.getMethodComment(targetCU, getIntermediaryTypeName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
        if (comment != null) {
            Javadoc javadoc = (Javadoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
            intermediary.setJavadoc(javadoc);
        }
    }
    // Add the completed method to the intermediary type:
    ChildListPropertyDescriptor typeBodyDeclarationsProperty = typeToBodyDeclarationProperty(fIntermediaryType, imRewrite.getRoot());
    ListRewrite bodyDeclarationsListRewrite = imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
    bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Javadoc(org.eclipse.jdt.core.dom.Javadoc) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) Block(org.eclipse.jdt.core.dom.Block) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 24 with MethodInvocation

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

the class IntroduceFactoryRefactoring method rewriteFactoryMethodCall.

/**
	 * Updates the constructor call.
	 *
	 * @param ctorCall the ClassInstanceCreation to be marked as replaced
	 * @param unitRewriter the AST rewriter
	 * @param gd the edit group to use
	 */
private void rewriteFactoryMethodCall(ClassInstanceCreation ctorCall, ASTRewrite unitRewriter, TextEditGroup gd) {
    AST ast = unitRewriter.getAST();
    MethodInvocation factoryMethodCall = ast.newMethodInvocation();
    ASTNode ctorCallParent = ctorCall.getParent();
    StructuralPropertyDescriptor ctorCallLocation = ctorCall.getLocationInParent();
    if (ctorCallLocation instanceof ChildListPropertyDescriptor) {
        ListRewrite ctorCallParentListRewrite = unitRewriter.getListRewrite(ctorCallParent, (ChildListPropertyDescriptor) ctorCallLocation);
        int index = ctorCallParentListRewrite.getOriginalList().indexOf(ctorCall);
        ctorCall = (ClassInstanceCreation) ctorCallParentListRewrite.getRewrittenList().get(index);
    } else {
        ctorCall = (ClassInstanceCreation) unitRewriter.get(ctorCallParent, ctorCallLocation);
    }
    ListRewrite actualFactoryArgs = unitRewriter.getListRewrite(factoryMethodCall, MethodInvocation.ARGUMENTS_PROPERTY);
    ListRewrite actualCtorArgs = unitRewriter.getListRewrite(ctorCall, ClassInstanceCreation.ARGUMENTS_PROPERTY);
    // Need to use a qualified name for the factory method if we're not
    // in the context of the class holding the factory.
    AbstractTypeDeclaration callOwner = (AbstractTypeDeclaration) ASTNodes.getParent(ctorCall, AbstractTypeDeclaration.class);
    ITypeBinding callOwnerBinding = callOwner.resolveBinding();
    if (callOwnerBinding == null || !Bindings.equals(callOwner.resolveBinding(), fFactoryOwningClass.resolveBinding())) {
        String qualifier = fImportRewriter.addImport(fFactoryOwningClass.resolveBinding());
        factoryMethodCall.setExpression(ASTNodeFactory.newName(ast, qualifier));
    }
    factoryMethodCall.setName(ast.newSimpleName(fNewMethodName));
    List<Expression> actualCtorArgsList = actualCtorArgs.getRewrittenList();
    for (int i = 0; i < actualCtorArgsList.size(); i++) {
        Expression actualCtorArg = actualCtorArgsList.get(i);
        ASTNode movedArg;
        if (ASTNodes.isExistingNode(actualCtorArg)) {
            movedArg = unitRewriter.createMoveTarget(actualCtorArg);
        } else {
            unitRewriter.remove(actualCtorArg, null);
            movedArg = actualCtorArg;
        }
        actualFactoryArgs.insertLast(movedArg, gd);
    }
    unitRewriter.replace(ctorCall, factoryMethodCall, gd);
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Expression(org.eclipse.jdt.core.dom.Expression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 25 with MethodInvocation

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

the class InlineMethodRefactoring method setCurrentMode.

public RefactoringStatus setCurrentMode(Mode mode) throws JavaModelException {
    if (fCurrentMode == mode)
        return new RefactoringStatus();
    Assert.isTrue(getInitialMode() == Mode.INLINE_SINGLE);
    fCurrentMode = mode;
    if (mode == Mode.INLINE_SINGLE) {
        if (fInitialNode instanceof MethodInvocation)
            fTargetProvider = TargetProvider.create((ICompilationUnit) fInitialTypeRoot, (MethodInvocation) fInitialNode);
        else if (fInitialNode instanceof SuperMethodInvocation)
            fTargetProvider = TargetProvider.create((ICompilationUnit) fInitialTypeRoot, (SuperMethodInvocation) fInitialNode);
        else if (fInitialNode instanceof ConstructorInvocation)
            fTargetProvider = TargetProvider.create((ICompilationUnit) fInitialTypeRoot, (ConstructorInvocation) fInitialNode);
        else
            throw new IllegalStateException(String.valueOf(fInitialNode));
    } else {
        fTargetProvider = TargetProvider.create(fSourceProvider.getDeclaration());
    }
    return fTargetProvider.checkActivation();
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ConstructorInvocation(org.eclipse.jdt.core.dom.ConstructorInvocation) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation)

Aggregations

MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)265 Expression (org.eclipse.jdt.core.dom.Expression)112 SuperMethodInvocation (org.eclipse.jdt.core.dom.SuperMethodInvocation)59 ASTNode (org.eclipse.jdt.core.dom.ASTNode)53 SimpleName (org.eclipse.jdt.core.dom.SimpleName)53 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)51 ASTRewrite (org.autorefactor.jdt.core.dom.ASTRewrite)48 ASTNodeFactory (org.autorefactor.jdt.internal.corext.dom.ASTNodeFactory)47 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)43 ArrayList (java.util.ArrayList)40 CastExpression (org.eclipse.jdt.core.dom.CastExpression)40 TextEditGroup (org.eclipse.text.edits.TextEditGroup)37 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)34 Block (org.eclipse.jdt.core.dom.Block)33 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)33 ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)31 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)31 AST (org.eclipse.jdt.core.dom.AST)30 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)29 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)28