Search in sources :

Example 16 with SuperMethodInvocation

use of org.eclipse.jdt.core.dom.SuperMethodInvocation in project AutoRefactor by JnRouvignac.

the class ASTNodeFactory method newSuperMethodInvocation.

/**
 * Builds a new super method invocation.
 *
 * @param methodName name of the method to be invoked
 * @return expression with a method invocation
 */
public Expression newSuperMethodInvocation(final String methodName) {
    SuperMethodInvocation smi = ast.newSuperMethodInvocation();
    smi.setName(newSimpleName(methodName));
    return smi;
}
Also used : SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation)

Example 17 with SuperMethodInvocation

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

the class IntroduceIndirectionRefactoring method checkInitialConditions.

// ********** CONDITION CHECKING **********
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    try {
        pm.beginTask(RefactoringCoreMessages.IntroduceIndirectionRefactoring_checking_activation, 1);
        fRewrites = new HashMap<ICompilationUnit, CompilationUnitRewrite>();
        if (fTargetMethod == null) {
            if (fSelectionStart == 0)
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
            // if a text selection exists, source is available.
            CompilationUnit selectionCURoot;
            ASTNode selectionNode;
            if (fSelectionCompilationUnit != null) {
                // compilation unit - could use CuRewrite later on
                selectionCURoot = getCachedCURewrite(fSelectionCompilationUnit).getRoot();
                selectionNode = getSelectedNode(fSelectionCompilationUnit, selectionCURoot, fSelectionStart, fSelectionLength);
            } else {
                // binary class file - no cu rewrite
                ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
                parser.setResolveBindings(true);
                parser.setSource(fSelectionClassFile);
                selectionCURoot = (CompilationUnit) parser.createAST(null);
                selectionNode = getSelectedNode(null, selectionCURoot, fSelectionStart, fSelectionLength);
            }
            if (selectionNode == null)
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
            IMethodBinding targetMethodBinding = null;
            if (selectionNode.getNodeType() == ASTNode.METHOD_INVOCATION) {
                targetMethodBinding = ((MethodInvocation) selectionNode).resolveMethodBinding();
            } else if (selectionNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
                targetMethodBinding = ((MethodDeclaration) selectionNode).resolveBinding();
            } else if (selectionNode.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
                // Allow invocation on super methods calls. makes sense as other
                // calls or even only the declaration can be updated.
                targetMethodBinding = ((SuperMethodInvocation) selectionNode).resolveMethodBinding();
            } else {
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
            }
            // resolve generics
            fTargetMethodBinding = targetMethodBinding.getMethodDeclaration();
            fTargetMethod = (IMethod) fTargetMethodBinding.getJavaElement();
            //allow single updating mode if an invocation was selected and the invocation can be updated
            if (selectionNode instanceof MethodInvocation && fSelectionCompilationUnit != null)
                fSelectionMethodInvocation = (MethodInvocation) selectionNode;
        } else {
            if (fTargetMethod.getDeclaringType().isAnnotation())
                return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_annotation);
            if (fTargetMethod.getCompilationUnit() != null) {
                // source method
                CompilationUnit selectionCURoot = getCachedCURewrite(fTargetMethod.getCompilationUnit()).getRoot();
                MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(fTargetMethod, selectionCURoot);
                fTargetMethodBinding = declaration.resolveBinding().getMethodDeclaration();
            } else {
                // binary method - no CURewrite available (and none needed as we cannot update the method anyway)
                ASTParser parser = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
                parser.setProject(fTargetMethod.getJavaProject());
                IBinding[] bindings = parser.createBindings(new IJavaElement[] { fTargetMethod }, null);
                fTargetMethodBinding = ((IMethodBinding) bindings[0]).getMethodDeclaration();
            }
        }
        if (fTargetMethod == null || fTargetMethodBinding == null || (!RefactoringAvailabilityTester.isIntroduceIndirectionAvailable(fTargetMethod)))
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_on_this_selection);
        if (fTargetMethod.getDeclaringType().isLocal() || fTargetMethod.getDeclaringType().isAnonymous())
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_for_local_or_anonymous_types);
        if (fTargetMethod.isConstructor())
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceIndirectionRefactoring_not_available_for_constructors);
        if (fIntermediaryMethodName == null)
            fIntermediaryMethodName = fTargetMethod.getElementName();
        if (fIntermediaryType == null) {
            if (fSelectionCompilationUnit != null && !fSelectionCompilationUnit.isReadOnly())
                fIntermediaryType = getEnclosingInitialSelectionMember().getDeclaringType();
            else if (!fTargetMethod.isBinary() && !fTargetMethod.isReadOnly())
                fIntermediaryType = fTargetMethod.getDeclaringType();
        }
        return new RefactoringStatus();
    } finally {
        pm.done();
    }
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IBinding(org.eclipse.jdt.core.dom.IBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 18 with SuperMethodInvocation

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

the class StubUtility2 method createImplementationStub.

public static MethodDeclaration createImplementationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String[] parameterNames, String type, CodeGenerationSettings settings, boolean inInterface) throws CoreException {
    Assert.isNotNull(imports);
    Assert.isNotNull(rewrite);
    AST ast = rewrite.getAST();
    MethodDeclaration decl = ast.newMethodDeclaration();
    decl.modifiers().addAll(getImplementationModifiers(ast, binding, inInterface, imports, context));
    decl.setName(ast.newSimpleName(binding.getName()));
    decl.setConstructor(false);
    ITypeBinding bindingReturnType = binding.getReturnType();
    if (bindingReturnType.isWildcardType()) {
        ITypeBinding bound = bindingReturnType.getBound();
        bindingReturnType = (bound != null) ? bound : bindingReturnType.getErasure();
    }
    IJavaProject javaProject = unit.getJavaProject();
    if (JavaModelUtil.is50OrHigher(javaProject)) {
        createTypeParameters(imports, context, ast, binding, decl);
    } else {
        bindingReturnType = bindingReturnType.getErasure();
    }
    decl.setReturnType2(imports.addImport(bindingReturnType, ast, context));
    List<SingleVariableDeclaration> parameters = createParameters(javaProject, imports, context, ast, binding, parameterNames, decl);
    createThrownExceptions(decl, binding, imports, context, ast);
    String delimiter = unit.findRecommendedLineSeparator();
    int modifiers = binding.getModifiers();
    if (!(inInterface && Modifier.isAbstract(modifiers))) {
        // generate a method body
        Map<String, String> options = javaProject.getOptions(true);
        Block body = ast.newBlock();
        decl.setBody(body);
        //$NON-NLS-1$
        String bodyStatement = "";
        if (Modifier.isAbstract(modifiers)) {
            Expression expression = ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions());
            if (expression != null) {
                ReturnStatement returnStatement = ast.newReturnStatement();
                returnStatement.setExpression(expression);
                bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
            }
        } else {
            SuperMethodInvocation invocation = ast.newSuperMethodInvocation();
            ITypeBinding declaringType = binding.getDeclaringClass();
            if (declaringType.isInterface()) {
                String qualifier = imports.addImport(declaringType.getErasure(), context);
                Name name = ASTNodeFactory.newName(ast, qualifier);
                invocation.setQualifier(name);
            }
            invocation.setName(ast.newSimpleName(binding.getName()));
            SingleVariableDeclaration varDecl = null;
            for (Iterator<SingleVariableDeclaration> iterator = parameters.iterator(); iterator.hasNext(); ) {
                varDecl = iterator.next();
                invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
            }
            Expression expression = invocation;
            Type returnType = decl.getReturnType2();
            if (returnType instanceof PrimitiveType && ((PrimitiveType) returnType).getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
                bodyStatement = ASTNodes.asFormattedString(ast.newExpressionStatement(expression), 0, delimiter, options);
            } else {
                ReturnStatement returnStatement = ast.newReturnStatement();
                returnStatement.setExpression(expression);
                bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, options);
            }
        }
        String placeHolder = CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), false, bodyStatement, delimiter);
        if (placeHolder != null) {
            ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
            body.statements().add(todoNode);
        }
    }
    if (settings != null && settings.createComments) {
        String string = CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
        if (string != null) {
            Javadoc javadoc = (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
            decl.setJavadoc(javadoc);
        }
    }
    if (settings != null && settings.overrideAnnotation && JavaModelUtil.is50OrHigher(javaProject)) {
        addOverrideAnnotation(javaProject, rewrite, decl, binding);
    }
    return decl;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Name(org.eclipse.jdt.core.dom.Name) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType)

Example 19 with SuperMethodInvocation

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

the class StubUtility method getBaseNameFromExpression.

private static String getBaseNameFromExpression(IJavaProject project, Expression assignedExpression, int variableKind) {
    String name = null;
    if (assignedExpression instanceof CastExpression) {
        assignedExpression = ((CastExpression) assignedExpression).getExpression();
    }
    if (assignedExpression instanceof Name) {
        Name simpleNode = (Name) assignedExpression;
        IBinding binding = simpleNode.resolveBinding();
        if (binding instanceof IVariableBinding)
            return getBaseName((IVariableBinding) binding, project);
        return ASTNodes.getSimpleNameIdentifier(simpleNode);
    } else if (assignedExpression instanceof MethodInvocation) {
        name = ((MethodInvocation) assignedExpression).getName().getIdentifier();
    } else if (assignedExpression instanceof SuperMethodInvocation) {
        name = ((SuperMethodInvocation) assignedExpression).getName().getIdentifier();
    } else if (assignedExpression instanceof FieldAccess) {
        return ((FieldAccess) assignedExpression).getName().getIdentifier();
    } else if (variableKind == NamingConventions.VK_STATIC_FINAL_FIELD && (assignedExpression instanceof StringLiteral || assignedExpression instanceof NumberLiteral)) {
        String string = assignedExpression instanceof StringLiteral ? ((StringLiteral) assignedExpression).getLiteralValue() : ((NumberLiteral) assignedExpression).getToken();
        StringBuffer res = new StringBuffer();
        boolean needsUnderscore = false;
        for (int i = 0; i < string.length(); i++) {
            char ch = string.charAt(i);
            if (Character.isJavaIdentifierPart(ch)) {
                if (res.length() == 0 && !Character.isJavaIdentifierStart(ch) || needsUnderscore) {
                    res.append('_');
                }
                res.append(ch);
                needsUnderscore = false;
            } else {
                needsUnderscore = res.length() > 0;
            }
        }
        if (res.length() > 0) {
            return res.toString();
        }
    }
    if (name != null) {
        for (int i = 0; i < KNOWN_METHOD_NAME_PREFIXES.length; i++) {
            String curr = KNOWN_METHOD_NAME_PREFIXES[i];
            if (name.startsWith(curr)) {
                if (name.equals(curr)) {
                    // don't suggest 'get' as variable name
                    return null;
                } else if (Character.isUpperCase(name.charAt(curr.length()))) {
                    return name.substring(curr.length());
                }
            }
        }
    }
    return name;
}
Also used : IBinding(org.eclipse.jdt.core.dom.IBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Name(org.eclipse.jdt.core.dom.Name) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) CastExpression(org.eclipse.jdt.core.dom.CastExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) NumberLiteral(org.eclipse.jdt.core.dom.NumberLiteral)

Example 20 with SuperMethodInvocation

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

the class UnresolvedElementsSubProcessor method getMethodProposals.

public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean isOnlyParameterMismatch, Collection<ICommandAccess> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (!(selectedNode instanceof SimpleName)) {
        return;
    }
    SimpleName nameNode = (SimpleName) selectedNode;
    List<Expression> arguments;
    Expression sender;
    boolean isSuperInvocation;
    ASTNode invocationNode = nameNode.getParent();
    if (invocationNode instanceof MethodInvocation) {
        MethodInvocation methodImpl = (MethodInvocation) invocationNode;
        arguments = methodImpl.arguments();
        sender = methodImpl.getExpression();
        isSuperInvocation = false;
    } else if (invocationNode instanceof SuperMethodInvocation) {
        SuperMethodInvocation methodImpl = (SuperMethodInvocation) invocationNode;
        arguments = methodImpl.arguments();
        sender = methodImpl.getQualifier();
        isSuperInvocation = true;
    } else {
        return;
    }
    String methodName = nameNode.getIdentifier();
    int nArguments = arguments.size();
    // corrections
    IBinding[] bindings = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
    HashSet<String> suggestedRenames = new HashSet<String>();
    for (int i = 0; i < bindings.length; i++) {
        IMethodBinding binding = (IMethodBinding) bindings[i];
        String curr = binding.getName();
        if (!curr.equals(methodName) && binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr) && suggestedRenames.add(curr)) {
            String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changemethod_description, BasicElementLabels.getJavaElementName(curr));
            proposals.add(new RenameNodeCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, IProposalRelevance.CHANGE_METHOD));
        }
    }
    suggestedRenames = null;
    if (isOnlyParameterMismatch) {
        ArrayList<IMethodBinding> parameterMismatchs = new ArrayList<IMethodBinding>();
        for (int i = 0; i < bindings.length; i++) {
            IMethodBinding binding = (IMethodBinding) bindings[i];
            if (binding.getName().equals(methodName)) {
                parameterMismatchs.add(binding);
            }
        }
        addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals);
    }
    if (sender == null) {
        addStaticImportFavoriteProposals(context, nameNode, true, proposals);
    }
    // new method
    addNewMethodProposals(cu, astRoot, sender, arguments, isSuperInvocation, invocationNode, methodName, proposals);
    if (!isOnlyParameterMismatch && !isSuperInvocation && sender != null) {
        addMissingCastParentsProposal(cu, (MethodInvocation) invocationNode, proposals);
    }
    if (!isSuperInvocation && sender == null && invocationNode.getParent() instanceof ThrowStatement) {
        //$NON-NLS-1$ // do it the manual way, copting all the arguments is nasty
        String str = "new ";
        String label = CorrectionMessages.UnresolvedElementsSubProcessor_addnewkeyword_description;
        int relevance = Character.isUpperCase(methodName.charAt(0)) ? IProposalRelevance.ADD_NEW_KEYWORD_UPPERCASE : IProposalRelevance.ADD_NEW_KEYWORD;
        ReplaceCorrectionProposal proposal = new ReplaceCorrectionProposal(label, cu, invocationNode.getStartPosition(), 0, str, relevance);
        proposals.add(proposal);
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) 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) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer) ThrowStatement(org.eclipse.jdt.core.dom.ThrowStatement) HashSet(java.util.HashSet) ReplaceCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposal)

Aggregations

SuperMethodInvocation (org.eclipse.jdt.core.dom.SuperMethodInvocation)29 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)19 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)12 ASTNode (org.eclipse.jdt.core.dom.ASTNode)11 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)10 Expression (org.eclipse.jdt.core.dom.Expression)9 SimpleName (org.eclipse.jdt.core.dom.SimpleName)9 CastExpression (org.eclipse.jdt.core.dom.CastExpression)8 IBinding (org.eclipse.jdt.core.dom.IBinding)8 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)7 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)7 Name (org.eclipse.jdt.core.dom.Name)7 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 AST (org.eclipse.jdt.core.dom.AST)6 ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)5 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)5 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)5 Block (org.eclipse.jdt.core.dom.Block)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4 SuperFieldAccess (org.eclipse.jdt.core.dom.SuperFieldAccess)4