Search in sources :

Example 71 with Expression

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

the class InlineTempRefactoring method getModifiedInitializerSource.

private Expression getModifiedInitializerSource(CompilationUnitRewrite rewrite, SimpleName reference) throws JavaModelException {
    VariableDeclaration varDecl = getVariableDeclaration();
    Expression initializer = varDecl.getInitializer();
    ASTNode referenceContext = reference.getParent();
    if (Invocations.isResolvedTypeInferredFromExpectedType(initializer)) {
        if (!(referenceContext instanceof VariableDeclarationFragment || referenceContext instanceof SingleVariableDeclaration || referenceContext instanceof Assignment)) {
            ITypeBinding[] typeArguments = Invocations.getInferredTypeArguments(initializer);
            if (typeArguments != null) {
                String newSource = createParameterizedInvocation(initializer, typeArguments, rewrite);
                return (Expression) rewrite.getASTRewrite().createStringPlaceholder(newSource, initializer.getNodeType());
            }
        }
    }
    Expression copy = (Expression) rewrite.getASTRewrite().createCopyTarget(initializer);
    AST ast = rewrite.getAST();
    if (NecessaryParenthesesChecker.needsParentheses(initializer, reference.getParent(), reference.getLocationInParent())) {
        ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
        parenthesized.setExpression(copy);
        copy = parenthesized;
    }
    ITypeBinding explicitCast = ASTNodes.getExplicitCast(initializer, reference);
    if (explicitCast != null) {
        CastExpression cast = ast.newCastExpression();
        if (NecessaryParenthesesChecker.needsParentheses(copy, cast, CastExpression.EXPRESSION_PROPERTY)) {
            ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
            parenthesized.setExpression(copy);
            copy = parenthesized;
        }
        cast.setExpression(copy);
        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(reference, rewrite.getImportRewrite());
        cast.setType(rewrite.getImportRewrite().addImport(explicitCast, ast, context));
        copy = cast;
    } else if (initializer instanceof ArrayInitializer && ASTNodes.getDimensions(varDecl) > 0) {
        ArrayType newType = (ArrayType) ASTNodeFactory.newType(ast, varDecl);
        ArrayCreation newArrayCreation = ast.newArrayCreation();
        newArrayCreation.setType(newType);
        newArrayCreation.setInitializer((ArrayInitializer) copy);
        return newArrayCreation;
    }
    return copy;
}
Also used : ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) AST(org.eclipse.jdt.core.dom.AST) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) Assignment(org.eclipse.jdt.core.dom.Assignment) ArrayType(org.eclipse.jdt.core.dom.ArrayType) 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) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 72 with Expression

use of org.eclipse.jdt.core.dom.Expression 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 73 with Expression

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

the class ExtractMethodAnalyzer method visit.

@Override
public boolean visit(LambdaExpression node) {
    Selection selection = getSelection();
    int selectionStart = selection.getOffset();
    int selectionExclusiveEnd = selection.getExclusiveEnd();
    int lambdaStart = node.getStartPosition();
    int lambdaExclusiveEnd = lambdaStart + node.getLength();
    ASTNode body = node.getBody();
    int bodyStart = body.getStartPosition();
    int bodyExclusiveEnd = bodyStart + body.getLength();
    boolean isValidSelection = false;
    if ((body instanceof Block) && (bodyStart < selectionStart && selectionExclusiveEnd <= bodyExclusiveEnd)) {
        // if selection is inside lambda body's block
        isValidSelection = true;
    } else if (body instanceof Expression) {
        try {
            TokenScanner scanner = new TokenScanner(fCUnit);
            int arrowExclusiveEnd = scanner.getTokenEndOffset(ITerminalSymbols.TokenNameARROW, lambdaStart);
            if (selectionStart >= arrowExclusiveEnd) {
                isValidSelection = true;
            }
        } catch (CoreException e) {
        // ignore
        }
    }
    if (selectionStart <= lambdaStart && selectionExclusiveEnd >= lambdaExclusiveEnd) {
        // if selection covers the lambda node
        isValidSelection = true;
    }
    if (!isValidSelection) {
        return false;
    }
    return super.visit(node);
}
Also used : TokenScanner(org.eclipse.jdt.internal.corext.dom.TokenScanner) CoreException(org.eclipse.core.runtime.CoreException) 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) Selection(org.eclipse.jdt.internal.corext.dom.Selection) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block)

Example 74 with Expression

use of org.eclipse.jdt.core.dom.Expression 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 75 with Expression

use of org.eclipse.jdt.core.dom.Expression 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)

Aggregations

Expression (org.eclipse.jdt.core.dom.Expression)552 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)263 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)213 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)187 CastExpression (org.eclipse.jdt.core.dom.CastExpression)185 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)135 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)126 ASTNode (org.eclipse.jdt.core.dom.ASTNode)125 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)122 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)121 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)112 AST (org.eclipse.jdt.core.dom.AST)101 PostfixExpression (org.eclipse.jdt.core.dom.PostfixExpression)95 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)88 SimpleName (org.eclipse.jdt.core.dom.SimpleName)83 InstanceofExpression (org.eclipse.jdt.core.dom.InstanceofExpression)76 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)73 Type (org.eclipse.jdt.core.dom.Type)70 ArrayList (java.util.ArrayList)69 Block (org.eclipse.jdt.core.dom.Block)63