Search in sources :

Example 56 with ContextSensitiveImportRewriteContext

use of org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext in project che by eclipse.

the class SurroundWithTryCatchRefactoring method createTryCatchStatement.

private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter) throws CoreException {
    List<Statement> result = new ArrayList<Statement>(1);
    TryStatement tryStatement = getAST().newTryStatement();
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite);
    if (!fIsMultiCatch) {
        for (int i = 0; i < exceptions.length; i++) {
            ITypeBinding exception = exceptions[i];
            CatchClause catchClause = getAST().newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
            String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
            String name = fScope.createName(varName, false);
            decl.setName(getAST().newSimpleName(name));
            Type type = fImportRewrite.addImport(exception, getAST(), context);
            decl.setType(type);
            catchClause.setException(decl);
            Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter);
            if (st != null) {
                catchClause.getBody().statements().add(st);
            }
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(decl.getType()), i == 0);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + i, true).addPosition(fRewriter.track(decl.getName()), false);
        }
    } else {
        List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions);
        CatchClause catchClause = getAST().newCatchClause();
        SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
        String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
        String name = fScope.createName(varName, false);
        decl.setName(getAST().newSimpleName(name));
        UnionType unionType = getAST().newUnionType();
        List<Type> types = unionType.types();
        int i = 0;
        for (ITypeBinding exception : filteredExceptions) {
            Type type = fImportRewrite.addImport(exception, getAST(), context);
            types.add(type);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(type), i == 0);
            i++;
        }
        decl.setType(unionType);
        catchClause.setException(decl);
        fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + 0, true).addPosition(fRewriter.track(decl.getName()), false);
        //$NON-NLS-1$
        Statement st = getCatchBody("Exception", name, lineDelimiter);
        if (st != null) {
            catchClause.getBody().statements().add(st);
        }
        tryStatement.catchClauses().add(catchClause);
    }
    List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements();
    ListRewrite statements = fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
    boolean selectedNodeRemoved = false;
    ASTNode expressionStatement = null;
    for (int i = 0; i < fSelectedNodes.length; i++) {
        ASTNode node = fSelectedNodes[i];
        if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
            AST ast = getAST();
            VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
            // Create a copy and remove the initializer
            VariableDeclarationStatement copy = (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement);
            List<IExtendedModifier> modifiers = copy.modifiers();
            for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) {
                IExtendedModifier modifier = iter.next();
                if (modifier.isModifier() && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) {
                    iter.remove();
                }
            }
            List<VariableDeclarationFragment> fragments = copy.fragments();
            for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                VariableDeclarationFragment fragment = iter.next();
                fragment.setInitializer(null);
            }
            CompilationUnit root = (CompilationUnit) statement.getRoot();
            int extendedStart = root.getExtendedStartPosition(statement);
            // we have a leading comment and the comment is covered by the selection
            if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) {
                String commentToken = buffer.getText(extendedStart, statement.getStartPosition() - extendedStart);
                commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
                Type type = statement.getType();
                String typeName = buffer.getText(type.getStartPosition(), type.getLength());
                copy.setType((Type) fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
            }
            result.add(copy);
            // convert the fragments into expression statements
            fragments = statement.fragments();
            if (!fragments.isEmpty()) {
                List<ExpressionStatement> newExpressionStatements = new ArrayList<ExpressionStatement>();
                for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                    VariableDeclarationFragment fragment = iter.next();
                    Expression initializer = fragment.getInitializer();
                    if (initializer != null) {
                        Assignment assignment = ast.newAssignment();
                        assignment.setLeftHandSide((Expression) fRewriter.createCopyTarget(fragment.getName()));
                        assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer));
                        newExpressionStatements.add(ast.newExpressionStatement(assignment));
                    }
                }
                if (!newExpressionStatements.isEmpty()) {
                    if (fSelectedNodes.length == 1) {
                        expressionStatement = fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
                    } else {
                        fRewriter.replace(statement, fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])), null);
                    }
                } else {
                    fRewriter.remove(statement, null);
                    selectedNodeRemoved = true;
                }
            } else {
                fRewriter.remove(statement, null);
                selectedNodeRemoved = true;
            }
        }
    }
    result.add(tryStatement);
    ASTNode replacementNode;
    if (result.size() == 1) {
        replacementNode = result.get(0);
    } else {
        replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()]));
    }
    if (fSelectedNodes.length == 1) {
        if (expressionStatement != null) {
            statements.insertLast(expressionStatement, null);
        } else {
            if (!selectedNodeRemoved)
                statements.insertLast(fRewriter.createMoveTarget(fSelectedNodes[0]), null);
        }
        fRewriter.replace(fSelectedNodes[0], replacementNode, null);
    } else {
        ListRewrite source = fRewriter.getListRewrite(fSelectedNodes[0].getParent(), (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent());
        ASTNode toMove = source.createMoveTarget(fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null);
        statements.insertLast(toMove, null);
    }
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Assignment(org.eclipse.jdt.core.dom.Assignment) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement)

Example 57 with ContextSensitiveImportRewriteContext

use of org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext in project flux by eclipse.

the class AdvancedQuickAssistProcessor method getReplaceIfElseWithConditionalProposals.

private static boolean getReplaceIfElseWithConditionalProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    if (!(node instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) node;
    Statement thenStatement = getSingleStatement(ifStatement.getThenStatement());
    Statement elseStatement = getSingleStatement(ifStatement.getElseStatement());
    if (thenStatement == null || elseStatement == null) {
        return false;
    }
    Expression assigned = null;
    Expression thenExpression = null;
    Expression elseExpression = null;
    ITypeBinding exprBinding = null;
    if (thenStatement instanceof ReturnStatement && elseStatement instanceof ReturnStatement) {
        thenExpression = ((ReturnStatement) thenStatement).getExpression();
        elseExpression = ((ReturnStatement) elseStatement).getExpression();
        MethodDeclaration declaration = ASTResolving.findParentMethodDeclaration(node);
        if (declaration == null || declaration.isConstructor()) {
            return false;
        }
        exprBinding = declaration.getReturnType2().resolveBinding();
    } else if (thenStatement instanceof ExpressionStatement && elseStatement instanceof ExpressionStatement) {
        Expression inner1 = ((ExpressionStatement) thenStatement).getExpression();
        Expression inner2 = ((ExpressionStatement) elseStatement).getExpression();
        if (inner1 instanceof Assignment && inner2 instanceof Assignment) {
            Assignment assign1 = (Assignment) inner1;
            Assignment assign2 = (Assignment) inner2;
            Expression left1 = assign1.getLeftHandSide();
            Expression left2 = assign2.getLeftHandSide();
            if (left1 instanceof Name && left2 instanceof Name && assign1.getOperator() == assign2.getOperator()) {
                IBinding bind1 = ((Name) left1).resolveBinding();
                IBinding bind2 = ((Name) left2).resolveBinding();
                if (bind1 == bind2 && bind1 instanceof IVariableBinding) {
                    assigned = left1;
                    exprBinding = ((IVariableBinding) bind1).getType();
                    thenExpression = assign1.getRightHandSide();
                    elseExpression = assign2.getRightHandSide();
                }
            }
        }
    }
    if (thenExpression == null || elseExpression == null) {
        return false;
    }
    // we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    // 
    AST ast = node.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // TightSourceRangeComputer sourceRangeComputer= new TightSourceRangeComputer();
    // sourceRangeComputer.addTightSourceNode(ifStatement);
    // rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_replaceIfWithConditional;
    // Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_IF_ELSE_WITH_CONDITIONAL);
    // prepare conditional expression
    ConditionalExpression conditionalExpression = ast.newConditionalExpression();
    Expression conditionCopy = (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
    conditionalExpression.setExpression(conditionCopy);
    Expression thenCopy = (Expression) rewrite.createCopyTarget(thenExpression);
    Expression elseCopy = (Expression) rewrite.createCopyTarget(elseExpression);
    IJavaProject project = context.getCompilationUnit().getJavaProject();
    if (!JavaModelUtil.is50OrHigher(project)) {
        ITypeBinding thenBinding = thenExpression.resolveTypeBinding();
        ITypeBinding elseBinding = elseExpression.resolveTypeBinding();
        if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) {
            CastExpression castException = ast.newCastExpression();
            ImportRewrite importRewrite = proposal.createImportRewrite(context.getASTRoot());
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, importRewrite);
            castException.setType(importRewrite.addImport(exprBinding, ast, importRewriteContext));
            castException.setExpression(elseCopy);
            elseCopy = castException;
        }
    } else if (JavaModelUtil.is17OrHigher(project)) {
        addExplicitTypeArgumentsIfNecessary(rewrite, proposal, thenExpression);
        addExplicitTypeArgumentsIfNecessary(rewrite, proposal, elseExpression);
    }
    conditionalExpression.setThenExpression(thenCopy);
    conditionalExpression.setElseExpression(elseCopy);
    // replace 'if' statement with conditional expression
    if (assigned == null) {
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(conditionalExpression);
        rewrite.replace(ifStatement, returnStatement, null);
    } else {
        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide((Expression) rewrite.createCopyTarget(assigned));
        assignment.setRightHandSide(conditionalExpression);
        assignment.setOperator(((Assignment) assigned.getParent()).getOperator());
        ExpressionStatement expressionStatement = ast.newExpressionStatement(assignment);
        rewrite.replace(ifStatement, expressionStatement, null);
    }
    // add correction proposal
    resultingCollections.add(proposal);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) AssertStatement(org.eclipse.jdt.core.dom.AssertStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IBinding(org.eclipse.jdt.core.dom.IBinding) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) Assignment(org.eclipse.jdt.core.dom.Assignment) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) CastExpression(org.eclipse.jdt.core.dom.CastExpression)

Aggregations

ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)57 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)47 AST (org.eclipse.jdt.core.dom.AST)33 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)32 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)30 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)26 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)23 ASTNode (org.eclipse.jdt.core.dom.ASTNode)21 Type (org.eclipse.jdt.core.dom.Type)19 SimpleName (org.eclipse.jdt.core.dom.SimpleName)18 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)17 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)15 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)15 Image (org.eclipse.swt.graphics.Image)14 Expression (org.eclipse.jdt.core.dom.Expression)13 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)13 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)12 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)11 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)9 Assignment (org.eclipse.jdt.core.dom.Assignment)8