Search in sources :

Example 41 with ContextSensitiveImportRewriteContext

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

the class AdvancedQuickAssistProcessor method getConvertSwitchToIfProposals.

private static boolean getConvertSwitchToIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections, boolean preserveNPE) {
    final AST ast = covering.getAST();
    final ASTRewrite rewrite = ASTRewrite.create(ast);
    final ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getASTRoot(), true);
    //
    SwitchStatement switchStatement = (SwitchStatement) covering;
    ITypeBinding expressionType = switchStatement.getExpression().resolveTypeBinding();
    //$NON-NLS-1$
    boolean isStringsInSwitch = expressionType != null && "java.lang.String".equals(expressionType.getQualifiedName());
    if (!isStringsInSwitch && preserveNPE)
        return false;
    IfStatement firstIfStatement = null;
    IfStatement currentIfStatement = null;
    Block currentBlock = null;
    boolean hasStopAsLastExecutableStatement = false;
    Block defaultBlock = null;
    Expression currentCondition = null;
    boolean defaultFound = false;
    ArrayList<Block> allBlocks = new ArrayList<Block>();
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(covering), importRewrite);
    Expression switchExpression = switchStatement.getExpression();
    Name varName;
    VariableDeclarationStatement variableDeclarationStatement = null;
    if (switchExpression instanceof Name) {
        varName = (Name) switchExpression;
    } else {
        // Switch expression could have side effects, see bug 252040
        VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
        String[] varNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, context.getCompilationUnit().getJavaProject(), expressionType, switchExpression, null);
        varName = ast.newSimpleName(varNames[0]);
        variableDeclarationFragment.setName((SimpleName) varName);
        variableDeclarationFragment.setStructuralProperty(VariableDeclarationFragment.INITIALIZER_PROPERTY, rewrite.createCopyTarget(switchExpression));
        variableDeclarationStatement = ast.newVariableDeclarationStatement(variableDeclarationFragment);
        Type type = importRewrite.addImport(expressionType, ast, importRewriteContext);
        variableDeclarationStatement.setType(type);
    }
    for (Iterator<Statement> iter = switchStatement.statements().iterator(); iter.hasNext(); ) {
        Statement statement = iter.next();
        if (statement instanceof SwitchCase) {
            SwitchCase switchCase = (SwitchCase) statement;
            // special case: pass through
            if (currentBlock != null) {
                if (!hasStopAsLastExecutableStatement) {
                    return false;
                }
                currentBlock = null;
            }
            if (defaultFound) {
                // This gets too complicated. We only support 'default' as last SwitchCase.
                return false;
            }
            if (switchCase.isDefault()) {
                defaultFound = true;
            }
            // prepare condition (is null for 'default')
            Expression switchCaseCondition = createSwitchCaseCondition(ast, rewrite, importRewrite, importRewriteContext, varName, switchCase, isStringsInSwitch, preserveNPE);
            if (currentCondition == null) {
                currentCondition = switchCaseCondition;
            } else {
                InfixExpression condition = ast.newInfixExpression();
                condition.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
                condition.setLeftOperand(currentCondition);
                if (switchCaseCondition == null)
                    switchCaseCondition = ast.newBooleanLiteral(true);
                condition.setRightOperand(switchCaseCondition);
                currentCondition = condition;
            }
        } else {
            // ensure that current block exists as 'then' statement of 'if'
            if (currentBlock == null) {
                if (currentCondition != null) {
                    IfStatement ifStatement;
                    if (firstIfStatement == null) {
                        firstIfStatement = ast.newIfStatement();
                        ifStatement = firstIfStatement;
                    } else {
                        ifStatement = ast.newIfStatement();
                        currentIfStatement.setElseStatement(ifStatement);
                    }
                    currentIfStatement = ifStatement;
                    ifStatement.setExpression(currentCondition);
                    currentCondition = null;
                    currentBlock = ast.newBlock();
                    ifStatement.setThenStatement(currentBlock);
                    allBlocks.add(currentBlock);
                } else {
                    // case for default:
                    defaultBlock = ast.newBlock();
                    currentBlock = defaultBlock;
                    allBlocks.add(currentBlock);
                // delay adding of default block
                }
            }
            if (statement instanceof BreakStatement) {
                currentBlock = null;
            } else {
                // add current statement in current block
                hasStopAsLastExecutableStatement = hasStopAsLastExecutableStatement(statement);
                Statement copyStatement = copyStatementExceptBreak(ast, rewrite, statement);
                currentBlock.statements().add(copyStatement);
            }
        }
    }
    // check, may be we have delayed default block
    if (defaultBlock != null) {
        currentIfStatement.setElseStatement(defaultBlock);
    }
    // remove unnecessary blocks in blocks
    for (int i = 0; i < allBlocks.size(); i++) {
        Block block = allBlocks.get(i);
        List<Statement> statements = block.statements();
        if (statements.size() == 1 && statements.get(0) instanceof Block) {
            Block innerBlock = (Block) statements.remove(0);
            block.getParent().setStructuralProperty(block.getLocationInParent(), innerBlock);
        }
    }
    if (variableDeclarationStatement == null) {
        // replace 'switch' with single if-else-if statement
        rewrite.replace(switchStatement, firstIfStatement, null);
    } else {
        new StatementRewrite(rewrite, new ASTNode[] { switchStatement }).replace(new ASTNode[] { variableDeclarationStatement, firstIfStatement }, null);
    }
    // add correction proposal
    //$NON-NLS-1$ //$NON-NLS-2$
    String source = ASTNodes.asString(switchExpression).replaceAll("\r\n?|\n", " ");
    String label = preserveNPE ? Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf_preserveNPE, source) : CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf;
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_SWITCH_TO_IF_ELSE);
    proposal.setImportRewrite(importRewrite);
    resultingCollections.add(proposal);
    return true;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ArrayList(java.util.ArrayList) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) StatementRewrite(org.eclipse.jdt.internal.corext.dom.StatementRewrite) 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)

Example 42 with ContextSensitiveImportRewriteContext

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

the class LocalCorrectionsSubProcessor method addMissingHashCodeProposals.

public static void addMissingHashCodeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    final ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (!(selectedNode instanceof Name)) {
        return;
    }
    AbstractTypeDeclaration typeDeclaration = null;
    StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
    if (locationInParent != TypeDeclaration.NAME_PROPERTY && locationInParent != EnumDeclaration.NAME_PROPERTY) {
        return;
    }
    typeDeclaration = (AbstractTypeDeclaration) selectedNode.getParent();
    ITypeBinding binding = typeDeclaration.resolveBinding();
    if (binding == null || binding.getSuperclass() == null) {
        return;
    }
    final IType type = (IType) binding.getJavaElement();
    boolean hasInstanceFields = false;
    IVariableBinding[] declaredFields = binding.getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        if (!Modifier.isStatic(declaredFields[i].getModifiers())) {
            hasInstanceFields = true;
            break;
        }
    }
    if (hasInstanceFields) {
        //Generate hashCode() and equals()... proposal
        String label = CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ChangeCorrectionProposal proposal = new ChangeCorrectionProposal(label, null, IProposalRelevance.GENERATE_HASHCODE_AND_EQUALS, image) {

            @Override
            public void apply(IDocument document) {
                // should never happened
                throw new UnsupportedOperationException();
            }

            @Override
            public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
                return CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_additional_info;
            }

            @Override
            public String getActionId() {
                return "javaGenerateHashCodeEquals";
            }
        };
        proposals.add(proposal);
    }
    //Override hashCode() proposal
    //$NON-NLS-1$
    IMethodBinding superHashCode = Bindings.findMethodInHierarchy(binding, "hashCode", new ITypeBinding[0]);
    if (superHashCode == null) {
        return;
    }
    String label = CorrectionMessages.LocalCorrectionsSubProcessor_override_hashCode_description;
    Image image = JavaPluginImages.get(JavaPluginImages.DESC_MISC_PUBLIC);
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
    LinkedCorrectionProposal proposal2 = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.OVERRIDE_HASHCODE, image);
    ImportRewrite importRewrite = proposal2.createImportRewrite(astRoot);
    String typeQualifiedName = type.getTypeQualifiedName('.');
    final CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaProject());
    try {
        ImportRewriteContext importContext = new ContextSensitiveImportRewriteContext(astRoot, problem.getOffset(), importRewrite);
        MethodDeclaration hashCode = StubUtility2.createImplementationStub(cu, rewrite, importRewrite, importContext, superHashCode, typeQualifiedName, settings, false);
        BodyDeclarationRewrite.create(rewrite, typeDeclaration).insert(hashCode, null);
        proposal2.setEndPosition(rewrite.track(hashCode));
    } catch (CoreException e) {
        JavaPlugin.log(e);
    }
    proposals.add(proposal2);
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) Image(org.eclipse.swt.graphics.Image) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) IType(org.eclipse.jdt.core.IType) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) 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) CoreException(org.eclipse.core.runtime.CoreException) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) IDocument(org.eclipse.jface.text.IDocument)

Example 43 with ContextSensitiveImportRewriteContext

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

the class AdvancedQuickAssistProcessor method getConvertIfElseToSwitchProposals.

private static boolean getConvertIfElseToSwitchProposals(IInvocationContext context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections, boolean handleNullArg) {
    final AST ast = coveringNode.getAST();
    final ASTRewrite rewrite = ASTRewrite.create(ast);
    final ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getASTRoot(), true);
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(coveringNode), importRewrite);
    IfStatement ifStatement = (IfStatement) coveringNode;
    IfStatement currentIf = ifStatement;
    Statement currentStatement = ifStatement;
    Expression currentExpression = currentIf.getExpression();
    SwitchStatement switchStatement = ast.newSwitchStatement();
    Expression switchExpression = null;
    boolean executeDefaultOnNullExpression = false;
    Statement defaultStatement = null;
    while (currentStatement != null) {
        Expression expression = null;
        List<Expression> caseExpressions = new ArrayList<Expression>();
        if (currentIf != null) {
            while (currentExpression != null) {
                // loop for fall through cases - multiple expressions with || operator
                Expression leftOperand;
                Expression rightOperand;
                boolean isMethodInvocationCase = false;
                if (currentExpression instanceof MethodInvocation) {
                    isMethodInvocationCase = true;
                    if (//$NON-NLS-1$
                    !(((MethodInvocation) currentExpression).getName().getIdentifier()).equals("equals"))
                        return false;
                    MethodInvocation invocation = (MethodInvocation) currentExpression;
                    leftOperand = invocation.getExpression();
                    if (leftOperand == null)
                        return false;
                    ITypeBinding leftBinding = leftOperand.resolveTypeBinding();
                    if (leftBinding != null) {
                        if (leftBinding.getQualifiedName().equals("java.lang.String")) {
                            //$NON-NLS-1$
                            if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
                                return false;
                        } else if (!leftBinding.isEnum()) {
                            return false;
                        }
                    }
                    List<Expression> arguments = invocation.arguments();
                    if (arguments.size() != 1)
                        return false;
                    rightOperand = arguments.get(0);
                    ITypeBinding rightBinding = leftOperand.resolveTypeBinding();
                    if (rightBinding != null) {
                        if (rightBinding.getQualifiedName().equals("java.lang.String")) {
                            //$NON-NLS-1$
                            if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
                                return false;
                        } else if (!rightBinding.isEnum()) {
                            return false;
                        }
                    }
                } else if (currentExpression instanceof InfixExpression) {
                    InfixExpression infixExpression = (InfixExpression) currentExpression;
                    Operator operator = infixExpression.getOperator();
                    if (!(operator.equals(InfixExpression.Operator.CONDITIONAL_OR) || operator.equals(InfixExpression.Operator.EQUALS)))
                        return false;
                    leftOperand = infixExpression.getLeftOperand();
                    rightOperand = infixExpression.getRightOperand();
                    if (operator.equals(InfixExpression.Operator.EQUALS)) {
                        ITypeBinding typeBinding = leftOperand.resolveTypeBinding();
                        if (typeBinding != null && typeBinding.getQualifiedName().equals("java.lang.String")) {
                            // don't propose quick assist when == is used to compare strings, since switch will use equals()
                            return false;
                        }
                    } else if (operator.equals(InfixExpression.Operator.CONDITIONAL_OR)) {
                        currentExpression = leftOperand;
                        continue;
                    }
                } else {
                    return false;
                }
                if (leftOperand.resolveConstantExpressionValue() != null) {
                    caseExpressions.add(leftOperand);
                    expression = rightOperand;
                    executeDefaultOnNullExpression |= isMethodInvocationCase;
                } else if (rightOperand.resolveConstantExpressionValue() != null) {
                    caseExpressions.add(rightOperand);
                    expression = leftOperand;
                } else if (leftOperand instanceof QualifiedName) {
                    QualifiedName qualifiedName = (QualifiedName) leftOperand;
                    IVariableBinding binding = (IVariableBinding) qualifiedName.resolveBinding();
                    if (binding == null || !binding.isEnumConstant())
                        return false;
                    importRewrite.addImport(binding.getDeclaringClass(), importRewriteContext);
                    caseExpressions.add(qualifiedName.getName());
                    expression = rightOperand;
                    executeDefaultOnNullExpression |= isMethodInvocationCase;
                } else if (rightOperand instanceof QualifiedName) {
                    QualifiedName qualifiedName = (QualifiedName) rightOperand;
                    IVariableBinding binding = (IVariableBinding) qualifiedName.resolveBinding();
                    if (binding == null || !binding.isEnumConstant())
                        return false;
                    importRewrite.addImport(binding.getDeclaringClass(), importRewriteContext);
                    caseExpressions.add(qualifiedName.getName());
                    expression = leftOperand;
                } else {
                    return false;
                }
                if (expression == null) {
                    // paranoidal check: this condition should never be true
                    return false;
                }
                if (currentExpression.getParent() instanceof InfixExpression) {
                    currentExpression = getNextSiblingExpression(currentExpression);
                } else {
                    currentExpression = null;
                }
                if (switchExpression == null) {
                    switchExpression = expression;
                }
                if (!switchExpression.subtreeMatch(new ASTMatcher(), expression)) {
                    return false;
                }
            }
        }
        Statement thenStatement;
        if (currentIf == null) {
            //currentStatement has the default else block
            thenStatement = currentStatement;
            defaultStatement = currentStatement;
        } else {
            thenStatement = currentIf.getThenStatement();
        }
        SwitchCase[] switchCaseStatements = createSwitchCaseStatements(ast, rewrite, caseExpressions);
        for (int i = 0; i < switchCaseStatements.length; i++) {
            switchStatement.statements().add(switchCaseStatements[i]);
        }
        boolean isBreakRequired = true;
        if (thenStatement instanceof Block) {
            Statement statement = null;
            for (Iterator<Statement> iter = ((Block) thenStatement).statements().iterator(); iter.hasNext(); ) {
                statement = iter.next();
                switchStatement.statements().add(rewrite.createCopyTarget(statement));
            }
            if (statement instanceof ReturnStatement || statement instanceof ThrowStatement)
                isBreakRequired = false;
        } else {
            if (thenStatement instanceof ReturnStatement || thenStatement instanceof ThrowStatement)
                isBreakRequired = false;
            switchStatement.statements().add(rewrite.createCopyTarget(thenStatement));
        }
        if (isBreakRequired)
            switchStatement.statements().add(ast.newBreakStatement());
        // advance currentStatement to the next "else if" or "else":
        if (currentIf != null && currentIf.getElseStatement() != null) {
            Statement elseStatement = currentIf.getElseStatement();
            if (elseStatement instanceof IfStatement) {
                currentIf = (IfStatement) elseStatement;
                currentStatement = currentIf;
                currentExpression = currentIf.getExpression();
            } else {
                currentIf = null;
                currentStatement = elseStatement;
                currentExpression = null;
            }
        } else {
            currentStatement = null;
        }
    }
    if (switchExpression == null)
        return false;
    switchStatement.setExpression((Expression) rewrite.createCopyTarget(switchExpression));
    if (handleNullArg) {
        if (executeDefaultOnNullExpression) {
            IfStatement newIfStatement = ast.newIfStatement();
            InfixExpression infixExpression = ast.newInfixExpression();
            infixExpression.setLeftOperand((Expression) rewrite.createCopyTarget(switchExpression));
            infixExpression.setRightOperand(ast.newNullLiteral());
            infixExpression.setOperator(InfixExpression.Operator.EQUALS);
            newIfStatement.setExpression(infixExpression);
            if (defaultStatement == null) {
                Block block = ast.newBlock();
                newIfStatement.setThenStatement(block);
            } else if (defaultStatement instanceof Block) {
                Block block = ast.newBlock();
                for (Iterator<Statement> iter = ((Block) defaultStatement).statements().iterator(); iter.hasNext(); ) {
                    block.statements().add(rewrite.createCopyTarget(iter.next()));
                }
                newIfStatement.setThenStatement(block);
            } else {
                newIfStatement.setThenStatement((Statement) rewrite.createCopyTarget(defaultStatement));
            }
            Block block = ast.newBlock();
            block.statements().add(switchStatement);
            newIfStatement.setElseStatement(block);
            rewrite.replace(ifStatement, newIfStatement, null);
            //$NON-NLS-1$ //$NON-NLS-2$
            String source = ASTNodes.asString(switchExpression).replaceAll("\r\n?|\n", " ");
            String label = Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_convertIfElseToSwitch_handleNullArg, source);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_IF_ELSE_TO_SWITCH);
            proposal.setImportRewrite(importRewrite);
            resultingCollections.add(proposal);
        }
    } else {
        rewrite.replace(ifStatement, switchStatement, null);
        String label = CorrectionMessages.AdvancedQuickAssistProcessor_convertIfElseToSwitch;
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_IF_ELSE_TO_SWITCH);
        proposal.setImportRewrite(importRewrite);
        resultingCollections.add(proposal);
    }
    return true;
}
Also used : Operator(org.eclipse.jdt.core.dom.InfixExpression.Operator) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ArrayList(java.util.ArrayList) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) Iterator(java.util.Iterator) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) 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)

Example 44 with ContextSensitiveImportRewriteContext

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

the class JavaContext method addImport.

/**
	 * Adds an import for type with type name <code>type</code> if possible.
	 * Returns a string which can be used to reference the type.
	 *
	 * @param type the fully qualified name of the type to import
	 * @return returns a type to which the type binding can be assigned to.
	 * 	The returned type contains is unqualified when an import could be added or was already known.
	 * 	It is fully qualified, if an import conflict prevented the import.
	 * @since 3.4
	 */
public String addImport(String type) {
    if (isReadOnly())
        return type;
    ICompilationUnit cu = getCompilationUnit();
    if (cu == null)
        return type;
    try {
        boolean qualified = type.indexOf('.') != -1;
        if (!qualified) {
            IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
            SimpleName nameNode = null;
            TypeNameMatch[] matches = findAllTypes(type, searchScope, nameNode, null, cu);
            if (// only add import if we have a single match
            matches.length != 1)
                return type;
            type = matches[0].getFullyQualifiedName();
        }
        CompilationUnit root = getASTRoot(cu);
        if (fImportRewrite == null) {
            if (root == null) {
                fImportRewrite = StubUtility.createImportRewrite(cu, true);
            } else {
                fImportRewrite = StubUtility.createImportRewrite(root, true);
            }
        }
        ImportRewriteContext context;
        if (root == null)
            context = null;
        else
            context = new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite);
        return fImportRewrite.addImport(type, context);
    } catch (JavaModelException e) {
        handleException(null, e);
        return type;
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SimpleName(org.eclipse.jdt.core.dom.SimpleName)

Example 45 with ContextSensitiveImportRewriteContext

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

the class IntroduceFactoryRefactoring method createFactoryMethod.

/**
	 * Creates and returns a new MethodDeclaration that represents the factory method to be used in
	 * place of direct calls to the constructor in question.
	 * 
	 * @param ast An AST used as a factory for various AST nodes
	 * @param ctorBinding binding for the constructor being wrapped
	 * @param unitRewriter the ASTRewrite to be used
	 * @return the new method declaration
	 * @throws CoreException if an exception occurs while accessing its corresponding resource
	 */
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException {
    MethodDeclaration newMethod = ast.newMethodDeclaration();
    SimpleName newMethodName = ast.newSimpleName(fNewMethodName);
    ClassInstanceCreation newCtorCall = ast.newClassInstanceCreation();
    ReturnStatement ret = ast.newReturnStatement();
    Block body = ast.newBlock();
    List<Statement> stmts = body.statements();
    String retTypeName = ctorBinding.getName();
    createFactoryMethodSignature(ast, newMethod);
    newMethod.setName(newMethodName);
    newMethod.setBody(body);
    ITypeBinding declaringClass = fCtorBinding.getDeclaringClass();
    ITypeBinding[] ctorOwnerTypeParameters = declaringClass.getTypeParameters();
    setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);
    newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));
    setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);
    createFactoryMethodConstructorArgs(ast, newCtorCall);
    if (Modifier.isAbstract(declaringClass.getModifiers())) {
        AnonymousClassDeclaration decl = ast.newAnonymousClassDeclaration();
        IMethodBinding[] unimplementedMethods = getUnimplementedMethods(declaringClass);
        CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
        ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
        for (int i = 0; i < unimplementedMethods.length; i++) {
            IMethodBinding unImplementedMethod = unimplementedMethods[i];
            MethodDeclaration newMethodDecl = StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass().getName(), settings, false);
            decl.bodyDeclarations().add(newMethodDecl);
        }
        newCtorCall.setAnonymousClassDeclaration(decl);
    }
    ret.setExpression(newCtorCall);
    stmts.add(ret);
    return newMethod;
}
Also used : ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) AnonymousClassDeclaration(org.eclipse.jdt.core.dom.AnonymousClassDeclaration) 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) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block)

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