Search in sources :

Example 1 with ClassInstanceCreation

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

the class IntroduceFactoryRefactoring method getCtorCallAt.

/**
	 * Look "in the vicinity" of the given range to find the <code>ClassInstanceCreation</code>
	 * node that this search hit identified. Necessary because the <code>SearchEngine</code>
	 * doesn't always cough up text extents that <code>NodeFinder.perform()</code> agrees with.
	 * @param start
	 * @param length
	 * @param unitAST
	 * @return return a {@link ClassInstanceCreation} or a {@link MethodRef} or <code>null</code> if this is really a constructor->constructor call (e.g. "this(...)")
	 * @throws CoreException
	 */
private ASTNode getCtorCallAt(int start, int length, CompilationUnit unitAST) throws CoreException {
    ICompilationUnit unitHandle = ASTCreator.getCu(unitAST);
    ASTNode node = NodeFinder.perform(unitAST, start, length);
    if (node == null)
        throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_noASTNodeForConstructorSearchHit, new Object[] { Integer.toString(start), Integer.toString(start + length), BasicElementLabels.getJavaCodeString(unitHandle.getSource().substring(start, start + length)), BasicElementLabels.getFileName(unitHandle) }), null));
    if (node instanceof ClassInstanceCreation) {
        if (((ClassInstanceCreation) node).getAnonymousClassDeclaration() != null) {
            // Cannot replace anonymous inner class, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=250660
            fConstructorVisibility = Modifier.PROTECTED;
            return null;
        }
        return node;
    } else if (node instanceof VariableDeclaration) {
        Expression init = ((VariableDeclaration) node).getInitializer();
        if (init instanceof ClassInstanceCreation) {
            return init;
        } else if (init != null)
            throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedInitializerNodeType, new Object[] { BasicElementLabels.getJavaCodeString(init.toString()), BasicElementLabels.getFileName(unitHandle) }), null));
        else
            throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl, BasicElementLabels.getJavaCodeString(node.toString())), null));
    } else if (node instanceof ConstructorInvocation) {
        // to another flavor on the same class.
        return null;
    } else if (node instanceof SuperConstructorInvocation) {
        // This is a call we can bypass; it's from one constructor flavor
        // to another flavor on the same class.
        fConstructorVisibility = Modifier.PROTECTED;
        return null;
    } else if (node instanceof ExpressionStatement) {
        Expression expr = ((ExpressionStatement) node).getExpression();
        if (expr instanceof ClassInstanceCreation)
            return expr;
        else
            throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit, new Object[] { BasicElementLabels.getJavaCodeString(expr.toString()), BasicElementLabels.getFileName(unitHandle) }), null));
    } else if (node instanceof SimpleName && (node.getParent() instanceof MethodDeclaration || node.getParent() instanceof AbstractTypeDeclaration)) {
        // We seem to have been given a hit for an implicit call to the base-class constructor.
        // Do nothing with this (implicit) call, but have to make sure we make the derived class
        // doesn't lose access to the base-class constructor (so make it 'protected', not 'private').
        fConstructorVisibility = Modifier.PROTECTED;
        return null;
    } else if (node instanceof MethodRef) {
        return node;
    } else
        throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit, new Object[] { BasicElementLabels.getJavaElementName(node.getClass().getName() + "('" + node.toString() + "')"), BasicElementLabels.getFileName(unitHandle) }), //$NON-NLS-1$ //$NON-NLS-2$
        null));
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) MethodRef(org.eclipse.jdt.core.dom.MethodRef) CoreException(org.eclipse.core.runtime.CoreException) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) ConstructorInvocation(org.eclipse.jdt.core.dom.ConstructorInvocation) Expression(org.eclipse.jdt.core.dom.Expression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 2 with ClassInstanceCreation

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

the class IntroduceFactoryRefactoring method checkSelection.

/**
	 * Determines what kind of AST node was selected, and returns an error status
	 * if the kind of node is inappropriate for this refactoring.
	 * @param pm
	 * @return a RefactoringStatus indicating whether the selection is valid
	 * @throws JavaModelException
	 */
private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaModelException {
    try {
        pm.beginTask(RefactoringCoreMessages.IntroduceFactory_examiningSelection, 2);
        fSelectedNode = getTargetNode(fCUHandle, fSelectionStart, fSelectionLength);
        if (fSelectedNode == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_notAConstructorInvocation);
        // constructor MethodDeclaration; nothing else.
        if (fSelectedNode instanceof ClassInstanceCreation) {
            ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) fSelectedNode;
            fCtorBinding = classInstanceCreation.resolveConstructorBinding();
        } else if (fSelectedNode instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) fSelectedNode;
            fCtorBinding = methodDeclaration.resolveBinding();
        }
        if (fCtorBinding == null)
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_unableToResolveConstructorBinding);
        // If this constructor is of a generic type, get the generic version,
        // not some instantiation thereof.
        fCtorBinding = fCtorBinding.getMethodDeclaration();
        pm.worked(1);
        // We don't handle constructors of nested types at the moment
        if (fCtorBinding.getDeclaringClass().isNested())
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_unsupportedNestedTypes);
        ITypeBinding ctorType = fCtorBinding.getDeclaringClass();
        IType ctorOwningType = (IType) ctorType.getJavaElement();
        if (ctorOwningType.isBinary())
            // Can't modify binary CU; don't know what CU to put factory method
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_constructorInBinaryClass);
        if (ctorOwningType.isEnum())
            // Doesn't make sense to encapsulate enum constructors
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_constructorInEnum);
        // Put the generated factory method inside the type that owns the constructor
        fFactoryUnitHandle = ctorOwningType.getCompilationUnit();
        fFactoryCU = getASTFor(fFactoryUnitHandle);
        Name ctorOwnerName = (Name) NodeFinder.perform(fFactoryCU, ctorOwningType.getNameRange());
        fCtorOwningClass = (AbstractTypeDeclaration) ASTNodes.getParent(ctorOwnerName, AbstractTypeDeclaration.class);
        fFactoryOwningClass = fCtorOwningClass;
        pm.worked(1);
        if (fNewMethodName == null)
            //$NON-NLS-1$
            return setNewMethodName("create" + fCtorBinding.getName());
        else
            return new RefactoringStatus();
    } finally {
        pm.done();
    }
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IType(org.eclipse.jdt.core.IType) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Example 3 with ClassInstanceCreation

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

the class ExtractTempRefactoring method createTempType.

private Type createTempType() throws CoreException {
    Expression expression = getSelectedExpression().getAssociatedExpression();
    Type resultingType = null;
    ITypeBinding typeBinding = expression.resolveTypeBinding();
    ASTRewrite rewrite = fCURewrite.getASTRewrite();
    AST ast = rewrite.getAST();
    if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) {
        resultingType = (Type) rewrite.createCopyTarget(((ClassInstanceCreation) expression).getType());
    } else if (expression instanceof CastExpression) {
        resultingType = (Type) rewrite.createCopyTarget(((CastExpression) expression).getType());
    } else {
        if (typeBinding == null) {
            typeBinding = ASTResolving.guessBindingForReference(expression);
        }
        if (typeBinding != null) {
            typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
            ImportRewrite importRewrite = fCURewrite.getImportRewrite();
            ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite);
            resultingType = importRewrite.addImport(typeBinding, ast, context);
        } else {
            //$NON-NLS-1$
            resultingType = ast.newSimpleType(ast.newSimpleName("Object"));
        }
    }
    if (fLinkedProposalModel != null) {
        LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
        typeGroup.addPosition(rewrite.track(resultingType), false);
        if (typeBinding != null) {
            ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding);
            for (int i = 0; i < relaxingTypes.length; i++) {
                typeGroup.addProposal(relaxingTypes[i], fCURewrite.getCu(), relaxingTypes.length - i);
            }
        }
    }
    return resultingType;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Type(org.eclipse.jdt.core.dom.Type) 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) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CastExpression(org.eclipse.jdt.core.dom.CastExpression) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 4 with ClassInstanceCreation

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

the class ExtractMethodAnalyzer method initReturnType.

private void initReturnType(ImportRewrite rewriter) {
    AST ast = fEnclosingBodyDeclaration.getAST();
    fReturnType = null;
    fReturnTypeBinding = null;
    switch(fReturnKind) {
        case ACCESS_TO_LOCAL:
            VariableDeclaration declaration = ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
            fReturnType = ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
            if (declaration.resolveBinding() != null) {
                fReturnTypeBinding = declaration.resolveBinding().getType();
            }
            break;
        case EXPRESSION:
            Expression expression = (Expression) getFirstSelectedNode();
            if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
                fExpressionBinding = ((ClassInstanceCreation) expression).getType().resolveBinding();
            } else {
                fExpressionBinding = expression.resolveTypeBinding();
            }
            if (fExpressionBinding != null) {
                if (fExpressionBinding.isNullType()) {
                    getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
                } else {
                    ITypeBinding normalizedBinding = Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
                    if (normalizedBinding != null) {
                        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
                        fReturnType = rewriter.addImport(normalizedBinding, ast, context);
                        fReturnTypeBinding = normalizedBinding;
                    }
                }
            } else {
                fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
                //$NON-NLS-1$
                fReturnTypeBinding = ast.resolveWellKnownType("void");
                getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
            }
            break;
        case RETURN_STATEMENT_VALUE:
            LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
            if (enclosingLambdaExpr != null) {
                fReturnType = ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
                IMethodBinding methodBinding = enclosingLambdaExpr.resolveMethodBinding();
                fReturnTypeBinding = methodBinding != null ? methodBinding.getReturnType() : null;
            } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
                fReturnType = ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
                fReturnTypeBinding = fReturnType != null ? fReturnType.resolveBinding() : null;
            }
            break;
        default:
            fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
            //$NON-NLS-1$
            fReturnTypeBinding = ast.resolveWellKnownType("void");
    }
    if (fReturnType == null) {
        fReturnType = ast.newPrimitiveType(PrimitiveType.VOID);
        //$NON-NLS-1$
        fReturnTypeBinding = ast.resolveWellKnownType("void");
    }
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) 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) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 5 with ClassInstanceCreation

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

the class Invocations method getInferredTypeArguments.

public static ITypeBinding[] getInferredTypeArguments(Expression invocation) {
    IMethodBinding methodBinding;
    switch(invocation.getNodeType()) {
        case ASTNode.METHOD_INVOCATION:
            methodBinding = ((MethodInvocation) invocation).resolveMethodBinding();
            return methodBinding == null ? null : methodBinding.getTypeArguments();
        case ASTNode.SUPER_METHOD_INVOCATION:
            methodBinding = ((SuperMethodInvocation) invocation).resolveMethodBinding();
            return methodBinding == null ? null : methodBinding.getTypeArguments();
        case ASTNode.CLASS_INSTANCE_CREATION:
            Type type = ((ClassInstanceCreation) invocation).getType();
            ITypeBinding typeBinding = type.resolveBinding();
            return typeBinding == null ? null : typeBinding.getTypeArguments();
        default:
            throw new IllegalArgumentException(invocation.toString());
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) Type(org.eclipse.jdt.core.dom.Type) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Aggregations

ClassInstanceCreation (org.eclipse.jdt.core.dom.ClassInstanceCreation)32 ASTNode (org.eclipse.jdt.core.dom.ASTNode)18 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)16 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)12 SimpleName (org.eclipse.jdt.core.dom.SimpleName)12 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)9 Type (org.eclipse.jdt.core.dom.Type)9 Expression (org.eclipse.jdt.core.dom.Expression)8 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)8 ParameterizedType (org.eclipse.jdt.core.dom.ParameterizedType)8 ArrayList (java.util.ArrayList)6 IType (org.eclipse.jdt.core.IType)6 SuperConstructorInvocation (org.eclipse.jdt.core.dom.SuperConstructorInvocation)6 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)5 AST (org.eclipse.jdt.core.dom.AST)5 ArrayType (org.eclipse.jdt.core.dom.ArrayType)5 CastExpression (org.eclipse.jdt.core.dom.CastExpression)5 SimpleType (org.eclipse.jdt.core.dom.SimpleType)5 VariableDeclaration (org.eclipse.jdt.core.dom.VariableDeclaration)5 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)4