Search in sources :

Example 1 with LinkedCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.

the class ReturnTypeSubProcessor method addMissingReturnTypeProposals.

public static void addMissingReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
        ReturnStatementCollector eval = new ReturnStatementCollector();
        decl.accept(eval);
        AST ast = astRoot.getAST();
        ITypeBinding typeBinding = eval.getTypeBinding(decl.getAST());
        typeBinding = Bindings.normalizeTypeBinding(typeBinding);
        if (typeBinding == null) {
            //$NON-NLS-1$
            typeBinding = ast.resolveWellKnownType("void");
        }
        if (typeBinding.isWildcardType()) {
            typeBinding = ASTResolving.normalizeWildcardType(typeBinding, true, ast);
        }
        ASTRewrite rewrite = ASTRewrite.create(ast);
        String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_missingreturntype_description, BindingLabelProvider.getBindingLabel(typeBinding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.MISSING_RETURN_TYPE, image);
        ImportRewrite imports = proposal.createImportRewrite(astRoot);
        ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
        Type type = imports.addImport(typeBinding, ast, importRewriteContext);
        rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null);
        rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
        Javadoc javadoc = methodDeclaration.getJavadoc();
        if (javadoc != null && typeBinding != null) {
            TagElement newTag = ast.newTagElement();
            newTag.setTagName(TagElement.TAG_RETURN);
            TextElement commentStart = ast.newTextElement();
            newTag.fragments().add(commentStart);
            JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
            //$NON-NLS-1$
            proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
        }
        //$NON-NLS-1$
        String key = "return_type";
        proposal.addLinkedPosition(rewrite.track(type), true, key);
        if (typeBinding != null) {
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, typeBinding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
        }
        proposals.add(proposal);
        // change to constructor
        ASTNode parentType = ASTResolving.findParentType(decl);
        if (parentType instanceof AbstractTypeDeclaration) {
            boolean isInterface = parentType instanceof TypeDeclaration && ((TypeDeclaration) parentType).isInterface();
            if (!isInterface) {
                String constructorName = ((AbstractTypeDeclaration) parentType).getName().getIdentifier();
                ASTNode nameNode = methodDeclaration.getName();
                label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_wrongconstructorname_description, BasicElementLabels.getJavaElementName(constructorName));
                proposals.add(new ReplaceCorrectionProposal(label, cu, nameNode.getStartPosition(), nameNode.getLength(), constructorName, IProposalRelevance.CHANGE_TO_CONSTRUCTOR));
            }
        }
    }
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Image(org.eclipse.swt.graphics.Image) TextElement(org.eclipse.jdt.core.dom.TextElement) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) ReplaceCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposal)

Example 2 with LinkedCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.

the class UnresolvedElementsSubProcessor method addSimilarVariableProposals.

private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, IVariableBinding resolvedField, SimpleName node, boolean isWriteAccess, Collection<ICommandAccess> proposals) {
    int kind = ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
    if (!isWriteAccess) {
        // also try to find similar methods
        kind |= ScopeAnalyzer.METHODS;
    }
    IBinding[] varsAndMethodsInScope = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
    if (varsAndMethodsInScope.length > 0) {
        // avoid corrections like int i= i;
        String otherNameInAssign = null;
        // help with x.getString() -> y.getString()
        String methodSenderName = null;
        String fieldSenderName = null;
        ASTNode parent = node.getParent();
        switch(parent.getNodeType()) {
            case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
                // node must be initializer
                otherNameInAssign = ((VariableDeclarationFragment) parent).getName().getIdentifier();
                break;
            case ASTNode.ASSIGNMENT:
                Assignment assignment = (Assignment) parent;
                if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getRightHandSide()).getIdentifier();
                } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
                }
                break;
            case ASTNode.METHOD_INVOCATION:
                MethodInvocation inv = (MethodInvocation) parent;
                if (inv.getExpression() == node) {
                    methodSenderName = inv.getName().getIdentifier();
                }
                break;
            case ASTNode.QUALIFIED_NAME:
                QualifiedName qualName = (QualifiedName) parent;
                if (qualName.getQualifier() == node) {
                    fieldSenderName = qualName.getName().getIdentifier();
                }
                break;
        }
        ITypeBinding guessedType = ASTResolving.guessBindingForReference(node);
        //$NON-NLS-1$
        ITypeBinding objectBinding = astRoot.getAST().resolveWellKnownType("java.lang.Object");
        String identifier = node.getIdentifier();
        boolean isInStaticContext = ASTResolving.isInStaticContext(node);
        ArrayList<CUCorrectionProposal> newProposals = new ArrayList<CUCorrectionProposal>(51);
        loop: for (int i = 0; i < varsAndMethodsInScope.length && newProposals.size() <= 50; i++) {
            IBinding varOrMeth = varsAndMethodsInScope[i];
            if (varOrMeth instanceof IVariableBinding) {
                IVariableBinding curr = (IVariableBinding) varOrMeth;
                String currName = curr.getName();
                if (currName.equals(otherNameInAssign)) {
                    continue loop;
                }
                if (resolvedField != null && Bindings.equals(resolvedField, curr)) {
                    continue loop;
                }
                boolean isFinal = Modifier.isFinal(curr.getModifiers());
                if (isFinal && curr.isField() && isWriteAccess) {
                    continue loop;
                }
                if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
                    continue loop;
                }
                int relevance = IProposalRelevance.SIMILAR_VARIABLE_PROPOSAL;
                if (NameMatcher.isSimilarName(currName, identifier)) {
                    // variable with a similar name than the unresolved variable
                    relevance += 3;
                }
                if (currName.equalsIgnoreCase(identifier)) {
                    relevance += 5;
                }
                ITypeBinding varType = curr.getType();
                if (varType != null) {
                    if (guessedType != null && guessedType != objectBinding) {
                        // variable type is compatible with the guessed type
                        if (!isWriteAccess && canAssign(varType, guessedType) || isWriteAccess && canAssign(guessedType, varType)) {
                            // unresolved variable can be assign to this variable
                            relevance += 2;
                        }
                    }
                    if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
                        relevance += 2;
                    }
                    if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
                        relevance += 2;
                    }
                }
                if (relevance > 0) {
                    String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, BasicElementLabels.getJavaElementName(currName));
                    newProposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
                }
            } else if (varOrMeth instanceof IMethodBinding) {
                IMethodBinding curr = (IMethodBinding) varOrMeth;
                if (!curr.isConstructor() && guessedType != null && canAssign(curr.getReturnType(), guessedType)) {
                    if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
                        AST ast = astRoot.getAST();
                        ASTRewrite rewrite = ASTRewrite.create(ast);
                        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description, ASTResolving.getMethodSignature(curr));
                        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_METHOD, image);
                        newProposals.add(proposal);
                        MethodInvocation newInv = ast.newMethodInvocation();
                        newInv.setName(ast.newSimpleName(curr.getName()));
                        ITypeBinding[] parameterTypes = curr.getParameterTypes();
                        for (int k = 0; k < parameterTypes.length; k++) {
                            ASTNode arg = ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
                            newInv.arguments().add(arg);
                            proposal.addLinkedPosition(rewrite.track(arg), false, null);
                        }
                        rewrite.replace(node, newInv, null);
                    }
                }
            }
        }
        if (newProposals.size() <= 50)
            proposals.addAll(newProposals);
    }
    if (binding != null && binding.isArray()) {
        //$NON-NLS-1$
        String idLength = "length";
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
        proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, IProposalRelevance.CHANGE_VARIABLE));
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Image(org.eclipse.swt.graphics.Image) Assignment(org.eclipse.jdt.core.dom.Assignment) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 3 with LinkedCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.

the class QuickAssistProcessor method getConvertEnhancedForLoopProposal.

private static boolean getConvertEnhancedForLoopProposal(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    EnhancedForStatement enhancedForStatement = getEnclosingHeader(node, EnhancedForStatement.class, EnhancedForStatement.PARAMETER_PROPERTY, EnhancedForStatement.EXPRESSION_PROPERTY);
    if (enhancedForStatement == null) {
        return false;
    }
    SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
    IVariableBinding parameterBinding = parameter.resolveBinding();
    if (parameterBinding == null) {
        return false;
    }
    Expression initializer = enhancedForStatement.getExpression();
    ITypeBinding initializerTypeBinding = initializer.resolveTypeBinding();
    if (initializerTypeBinding == null) {
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    Statement topLabelStatement = enhancedForStatement;
    while (topLabelStatement.getLocationInParent() == LabeledStatement.BODY_PROPERTY) {
        topLabelStatement = (Statement) topLabelStatement.getParent();
    }
    IJavaProject project = context.getCompilationUnit().getJavaProject();
    AST ast = node.getAST();
    Statement enhancedForBody = enhancedForStatement.getBody();
    Collection<String> usedVarNames = Arrays.asList(ASTResolving.getUsedVariableNames(enhancedForBody));
    boolean initializerIsArray = initializerTypeBinding.isArray();
    //$NON-NLS-1$
    ITypeBinding initializerListType = Bindings.findTypeInHierarchy(initializerTypeBinding, "java.util.List");
    //$NON-NLS-1$
    ITypeBinding initializerIterableType = Bindings.findTypeInHierarchy(initializerTypeBinding, "java.lang.Iterable");
    if (initializerIterableType != null) {
        String label = CorrectionMessages.QuickAssistProcessor_convert_to_iterator_for_loop;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        //$NON-NLS-1$
        String iterNameKey = "iterName";
        ASTRewrite rewrite = ASTRewrite.create(ast);
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_ITERATOR_FOR_LOOP, image);
        // convert 'for' statement
        ForStatement forStatement = ast.newForStatement();
        // create initializer
        MethodInvocation iterInitializer = ast.newMethodInvocation();
        //$NON-NLS-1$
        iterInitializer.setName(ast.newSimpleName("iterator"));
        ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
        ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
        //$NON-NLS-1$
        Type iterType = ast.newSimpleType(ast.newName(imports.addImport("java.util.Iterator", importRewriteContext)));
        if (initializerIterableType.getTypeArguments().length == 1) {
            Type iterTypeArgument = imports.addImport(Bindings.normalizeTypeBinding(initializerIterableType.getTypeArguments()[0]), ast, importRewriteContext);
            ParameterizedType parameterizedIterType = ast.newParameterizedType(iterType);
            parameterizedIterType.typeArguments().add(iterTypeArgument);
            iterType = parameterizedIterType;
        }
        String[] iterNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, iterType, iterInitializer, usedVarNames);
        String iterName = iterNames[0];
        SimpleName initializerIterName = ast.newSimpleName(iterName);
        VariableDeclarationFragment iterFragment = ast.newVariableDeclarationFragment();
        iterFragment.setName(initializerIterName);
        proposal.addLinkedPosition(rewrite.track(initializerIterName), 0, iterNameKey);
        for (int i = 0; i < iterNames.length; i++) {
            proposal.addLinkedPositionProposal(iterNameKey, iterNames[i], null);
        }
        Expression initializerExpression = (Expression) rewrite.createCopyTarget(initializer);
        iterInitializer.setExpression(initializerExpression);
        iterFragment.setInitializer(iterInitializer);
        VariableDeclarationExpression iterVariable = ast.newVariableDeclarationExpression(iterFragment);
        iterVariable.setType(iterType);
        forStatement.initializers().add(iterVariable);
        // create condition
        MethodInvocation condition = ast.newMethodInvocation();
        //$NON-NLS-1$
        condition.setName(ast.newSimpleName("hasNext"));
        SimpleName conditionExpression = ast.newSimpleName(iterName);
        proposal.addLinkedPosition(rewrite.track(conditionExpression), LinkedPositionGroup.NO_STOP, iterNameKey);
        condition.setExpression(conditionExpression);
        forStatement.setExpression(condition);
        // create 'for' body element variable
        VariableDeclarationFragment elementFragment = ast.newVariableDeclarationFragment();
        elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite));
        elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName()));
        SimpleName elementIterName = ast.newSimpleName(iterName);
        proposal.addLinkedPosition(rewrite.track(elementIterName), LinkedPositionGroup.NO_STOP, iterNameKey);
        MethodInvocation getMethodInvocation = ast.newMethodInvocation();
        //$NON-NLS-1$
        getMethodInvocation.setName(ast.newSimpleName("next"));
        getMethodInvocation.setExpression(elementIterName);
        elementFragment.setInitializer(getMethodInvocation);
        VariableDeclarationStatement elementVariable = ast.newVariableDeclarationStatement(elementFragment);
        ModifierRewrite.create(rewrite, elementVariable).copyAllModifiers(parameter, null);
        elementVariable.setType((Type) rewrite.createCopyTarget(parameter.getType()));
        Block newBody = ast.newBlock();
        List<Statement> statements = newBody.statements();
        statements.add(elementVariable);
        if (enhancedForBody instanceof Block) {
            List<Statement> oldStatements = ((Block) enhancedForBody).statements();
            if (oldStatements.size() > 0) {
                ListRewrite statementsRewrite = rewrite.getListRewrite(enhancedForBody, Block.STATEMENTS_PROPERTY);
                Statement oldStatementsCopy = (Statement) statementsRewrite.createCopyTarget(oldStatements.get(0), oldStatements.get(oldStatements.size() - 1));
                statements.add(oldStatementsCopy);
            }
        } else {
            statements.add((Statement) rewrite.createCopyTarget(enhancedForBody));
        }
        forStatement.setBody(newBody);
        rewrite.replace(enhancedForStatement, forStatement, null);
        resultingCollections.add(proposal);
    }
    if (initializerIsArray || initializerListType != null) {
        String label = CorrectionMessages.QuickAssistProcessor_convert_to_indexed_for_loop;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        //$NON-NLS-1$
        String varNameKey = "varName";
        //$NON-NLS-1$
        String indexNameKey = "indexName";
        ASTRewrite rewrite = ASTRewrite.create(ast);
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_INDEXED_FOR_LOOP, image);
        // create temp variable from initializer if necessary
        String varName;
        boolean varNameGenerated;
        if (initializer instanceof SimpleName) {
            varName = ((SimpleName) initializer).getIdentifier();
            varNameGenerated = false;
        } else {
            VariableDeclarationFragment varFragment = ast.newVariableDeclarationFragment();
            String[] varNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, initializerTypeBinding, initializer, usedVarNames);
            varName = varNames[0];
            usedVarNames = new ArrayList<String>(usedVarNames);
            usedVarNames.add(varName);
            varNameGenerated = true;
            SimpleName varNameNode = ast.newSimpleName(varName);
            varFragment.setName(varNameNode);
            proposal.addLinkedPosition(rewrite.track(varNameNode), 0, varNameKey);
            for (int i = 0; i < varNames.length; i++) {
                proposal.addLinkedPositionProposal(varNameKey, varNames[i], null);
            }
            varFragment.setInitializer((Expression) rewrite.createCopyTarget(initializer));
            VariableDeclarationStatement varDeclaration = ast.newVariableDeclarationStatement(varFragment);
            Type varType;
            if (initializerIsArray) {
                Type copiedType = DimensionRewrite.copyTypeAndAddDimensions(parameter.getType(), parameter.extraDimensions(), rewrite);
                varType = ASTNodeFactory.newArrayType(copiedType);
            } else {
                ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
                varType = imports.addImport(Bindings.normalizeForDeclarationUse(initializerTypeBinding, ast), ast, importRewriteContext);
            }
            varDeclaration.setType(varType);
            if (!(topLabelStatement.getParent() instanceof Block)) {
                Block block = ast.newBlock();
                List<Statement> statements = block.statements();
                statements.add(varDeclaration);
                statements.add((Statement) rewrite.createCopyTarget(topLabelStatement));
                rewrite.replace(topLabelStatement, block, null);
            } else {
                rewrite.getListRewrite(topLabelStatement.getParent(), Block.STATEMENTS_PROPERTY).insertBefore(varDeclaration, topLabelStatement, null);
            }
        }
        // convert 'for' statement
        ForStatement forStatement = ast.newForStatement();
        // create initializer
        VariableDeclarationFragment indexFragment = ast.newVariableDeclarationFragment();
        NumberLiteral indexInitializer = ast.newNumberLiteral();
        indexFragment.setInitializer(indexInitializer);
        PrimitiveType indexType = ast.newPrimitiveType(PrimitiveType.INT);
        String[] indexNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, indexType, indexInitializer, usedVarNames);
        String indexName = indexNames[0];
        SimpleName initializerIndexName = ast.newSimpleName(indexName);
        indexFragment.setName(initializerIndexName);
        proposal.addLinkedPosition(rewrite.track(initializerIndexName), 0, indexNameKey);
        for (int i = 0; i < indexNames.length; i++) {
            proposal.addLinkedPositionProposal(indexNameKey, indexNames[i], null);
        }
        VariableDeclarationExpression indexVariable = ast.newVariableDeclarationExpression(indexFragment);
        indexVariable.setType(indexType);
        forStatement.initializers().add(indexVariable);
        // create condition
        InfixExpression condition = ast.newInfixExpression();
        condition.setOperator(InfixExpression.Operator.LESS);
        SimpleName conditionLeft = ast.newSimpleName(indexName);
        proposal.addLinkedPosition(rewrite.track(conditionLeft), LinkedPositionGroup.NO_STOP, indexNameKey);
        condition.setLeftOperand(conditionLeft);
        SimpleName conditionRightName = ast.newSimpleName(varName);
        if (varNameGenerated) {
            proposal.addLinkedPosition(rewrite.track(conditionRightName), LinkedPositionGroup.NO_STOP, varNameKey);
        }
        Expression conditionRight;
        if (initializerIsArray) {
            //$NON-NLS-1$
            conditionRight = ast.newQualifiedName(conditionRightName, ast.newSimpleName("length"));
        } else {
            MethodInvocation sizeMethodInvocation = ast.newMethodInvocation();
            //$NON-NLS-1$
            sizeMethodInvocation.setName(ast.newSimpleName("size"));
            sizeMethodInvocation.setExpression(conditionRightName);
            conditionRight = sizeMethodInvocation;
        }
        condition.setRightOperand(conditionRight);
        forStatement.setExpression(condition);
        // create updater
        SimpleName indexUpdaterName = ast.newSimpleName(indexName);
        proposal.addLinkedPosition(rewrite.track(indexUpdaterName), LinkedPositionGroup.NO_STOP, indexNameKey);
        PostfixExpression indexUpdater = ast.newPostfixExpression();
        indexUpdater.setOperator(PostfixExpression.Operator.INCREMENT);
        indexUpdater.setOperand(indexUpdaterName);
        forStatement.updaters().add(indexUpdater);
        // create 'for' body element variable
        VariableDeclarationFragment elementFragment = ast.newVariableDeclarationFragment();
        elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite));
        elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName()));
        SimpleName elementVarName = ast.newSimpleName(varName);
        if (varNameGenerated) {
            proposal.addLinkedPosition(rewrite.track(elementVarName), LinkedPositionGroup.NO_STOP, varNameKey);
        }
        SimpleName elementIndexName = ast.newSimpleName(indexName);
        proposal.addLinkedPosition(rewrite.track(elementIndexName), LinkedPositionGroup.NO_STOP, indexNameKey);
        Expression elementAccess;
        if (initializerIsArray) {
            ArrayAccess elementArrayAccess = ast.newArrayAccess();
            elementArrayAccess.setArray(elementVarName);
            elementArrayAccess.setIndex(elementIndexName);
            elementAccess = elementArrayAccess;
        } else {
            MethodInvocation getMethodInvocation = ast.newMethodInvocation();
            //$NON-NLS-1$
            getMethodInvocation.setName(ast.newSimpleName("get"));
            getMethodInvocation.setExpression(elementVarName);
            getMethodInvocation.arguments().add(elementIndexName);
            elementAccess = getMethodInvocation;
        }
        elementFragment.setInitializer(elementAccess);
        VariableDeclarationStatement elementVariable = ast.newVariableDeclarationStatement(elementFragment);
        ModifierRewrite.create(rewrite, elementVariable).copyAllModifiers(parameter, null);
        elementVariable.setType((Type) rewrite.createCopyTarget(parameter.getType()));
        Block newBody = ast.newBlock();
        List<Statement> statements = newBody.statements();
        statements.add(elementVariable);
        if (enhancedForBody instanceof Block) {
            List<Statement> oldStatements = ((Block) enhancedForBody).statements();
            if (oldStatements.size() > 0) {
                ListRewrite statementsRewrite = rewrite.getListRewrite(enhancedForBody, Block.STATEMENTS_PROPERTY);
                Statement oldStatementsCopy = (Statement) statementsRewrite.createCopyTarget(oldStatements.get(0), oldStatements.get(oldStatements.size() - 1));
                statements.add(oldStatementsCopy);
            }
        } else {
            statements.add((Statement) rewrite.createCopyTarget(enhancedForBody));
        }
        forStatement.setBody(newBody);
        rewrite.replace(enhancedForStatement, forStatement, null);
        resultingCollections.add(proposal);
    }
    return true;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Image(org.eclipse.swt.graphics.Image) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal)

Example 4 with LinkedCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.

the class QuickAssistProcessor method getAddBlockProposals.

private static boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    if (!(node instanceof Statement)) {
        return false;
    }
    /*
		 * only show the quick assist when the selection is of the control statement keywords (if, else, while,...)
		 * but not inside the statement or the if expression.
		 */
    if (!isControlStatementWithBlock(node) && isControlStatementWithBlock(node.getParent())) {
        int statementStart = node.getStartPosition();
        int statementEnd = statementStart + node.getLength();
        int offset = context.getSelectionOffset();
        int length = context.getSelectionLength();
        if (length == 0) {
            if (offset != statementEnd) {
                // cursor at end
                return false;
            }
        } else {
            if (offset > statementStart || offset + length < statementEnd) {
                // statement selected
                return false;
            }
        }
        node = node.getParent();
    }
    StructuralPropertyDescriptor childProperty = null;
    ASTNode child = null;
    switch(node.getNodeType()) {
        case ASTNode.IF_STATEMENT:
            ASTNode then = ((IfStatement) node).getThenStatement();
            ASTNode elseStatement = ((IfStatement) node).getElseStatement();
            if ((then instanceof Block) && (elseStatement instanceof Block || elseStatement == null)) {
                break;
            }
            int thenEnd = then.getStartPosition() + then.getLength();
            int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
            if (!(then instanceof Block)) {
                if (selectionEnd <= thenEnd) {
                    childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
                    child = then;
                    break;
                } else if (elseStatement != null && selectionEnd < elseStatement.getStartPosition()) {
                    // find out if we are before or after the 'else' keyword
                    try {
                        TokenScanner scanner = new TokenScanner(context.getCompilationUnit());
                        int elseTokenStart = scanner.getNextStartOffset(thenEnd, true);
                        if (selectionEnd < elseTokenStart) {
                            childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
                            child = then;
                            break;
                        }
                    } catch (CoreException e) {
                    // ignore
                    }
                }
            }
            if (elseStatement != null && !(elseStatement instanceof Block) && context.getSelectionOffset() >= thenEnd) {
                childProperty = IfStatement.ELSE_STATEMENT_PROPERTY;
                child = elseStatement;
            }
            break;
        case ASTNode.WHILE_STATEMENT:
            ASTNode whileBody = ((WhileStatement) node).getBody();
            if (!(whileBody instanceof Block)) {
                childProperty = WhileStatement.BODY_PROPERTY;
                child = whileBody;
            }
            break;
        case ASTNode.FOR_STATEMENT:
            ASTNode forBody = ((ForStatement) node).getBody();
            if (!(forBody instanceof Block)) {
                childProperty = ForStatement.BODY_PROPERTY;
                child = forBody;
            }
            break;
        case ASTNode.ENHANCED_FOR_STATEMENT:
            ASTNode enhancedForBody = ((EnhancedForStatement) node).getBody();
            if (!(enhancedForBody instanceof Block)) {
                childProperty = EnhancedForStatement.BODY_PROPERTY;
                child = enhancedForBody;
            }
            break;
        case ASTNode.DO_STATEMENT:
            ASTNode doBody = ((DoStatement) node).getBody();
            if (!(doBody instanceof Block)) {
                childProperty = DoStatement.BODY_PROPERTY;
                child = doBody;
            }
            break;
        default:
    }
    if (child == null) {
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    AST ast = node.getAST();
    {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        ASTNode childPlaceholder = rewrite.createMoveTarget(child);
        Block replacingBody = ast.newBlock();
        replacingBody.statements().add(childPlaceholder);
        rewrite.set(node, childProperty, replacingBody, null);
        String label;
        if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
            label = CorrectionMessages.QuickAssistProcessor_replacethenwithblock_description;
        } else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
            label = CorrectionMessages.QuickAssistProcessor_replaceelsewithblock_description;
        } else {
            label = CorrectionMessages.QuickAssistProcessor_replacebodywithblock_description;
        }
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_BLOCK, image);
        proposal.setCommandId(ADD_BLOCK_ID);
        proposal.setEndPosition(rewrite.track(child));
        resultingCollections.add(proposal);
    }
    if (node.getNodeType() == ASTNode.IF_STATEMENT) {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        while (node.getLocationInParent() == IfStatement.ELSE_STATEMENT_PROPERTY) {
            node = node.getParent();
        }
        boolean missingBlockFound = false;
        boolean foundElse = false;
        IfStatement ifStatement;
        Statement thenStatment;
        Statement elseStatment;
        do {
            ifStatement = (IfStatement) node;
            thenStatment = ifStatement.getThenStatement();
            elseStatment = ifStatement.getElseStatement();
            if (!(thenStatment instanceof Block)) {
                ASTNode childPlaceholder1 = rewrite.createMoveTarget(thenStatment);
                Block replacingBody1 = ast.newBlock();
                replacingBody1.statements().add(childPlaceholder1);
                rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, replacingBody1, null);
                if (thenStatment != child) {
                    missingBlockFound = true;
                }
            }
            if (elseStatment != null) {
                foundElse = true;
            }
            node = elseStatment;
        } while (elseStatment instanceof IfStatement);
        if (elseStatment != null && !(elseStatment instanceof Block)) {
            ASTNode childPlaceholder2 = rewrite.createMoveTarget(elseStatment);
            Block replacingBody2 = ast.newBlock();
            replacingBody2.statements().add(childPlaceholder2);
            rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, replacingBody2, null);
            if (elseStatment != child) {
                missingBlockFound = true;
            }
        }
        if (missingBlockFound && foundElse) {
            String label = CorrectionMessages.QuickAssistProcessor_replacethenelsewithblock_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_IF_ELSE_TO_BLOCK, image);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : TokenScanner(org.eclipse.jdt.internal.corext.dom.TokenScanner) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) CoreException(org.eclipse.core.runtime.CoreException) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 5 with LinkedCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal in project che by eclipse.

the class LocalCorrectionsSubProcessor method addUncaughtExceptionProposals.

public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    while (selectedNode != null && !(selectedNode instanceof Statement) && !(selectedNode instanceof VariableDeclarationExpression)) {
        selectedNode = selectedNode.getParent();
    }
    if (selectedNode == null) {
        return;
    }
    int offset = selectedNode.getStartPosition();
    int length = selectedNode.getLength();
    int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
    if (selectionEnd > offset + length) {
        // extend the selection if more than one statement is selected (bug 72149)
        length = selectionEnd - offset;
    }
    //Surround with proposals
    SurroundWithTryCatchRefactoring refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length);
    if (refactoring == null)
        return;
    refactoring.setLeaveDirty(true);
    if (refactoring.checkActivationBasics(astRoot).isOK()) {
        String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_CATCH, image);
        proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
        proposals.add(proposal);
    }
    if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
        refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length, true);
        if (refactoring == null)
            return;
        refactoring.setLeaveDirty(true);
        if (refactoring.checkActivationBasics(astRoot).isOK()) {
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
            RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_MULTICATCH, image);
            proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
            proposals.add(proposal);
        }
    }
    //Catch exception
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl == null) {
        return;
    }
    ITypeBinding[] uncaughtExceptions = ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(offset, length));
    if (uncaughtExceptions.length == 0) {
        return;
    }
    TryStatement surroundingTry = ASTResolving.findParentTryStatement(selectedNode);
    AST ast = astRoot.getAST();
    if (surroundingTry != null && (ASTNodes.isParent(selectedNode, surroundingTry.getBody()) || selectedNode.getLocationInParent() == TryStatement.RESOURCES_PROPERTY)) {
        {
            ASTRewrite rewrite = ASTRewrite.create(surroundingTry.getAST());
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_CATCH, image);
            ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
            CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
            scope.setCursor(offset);
            ListRewrite clausesRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                ITypeBinding excBinding = uncaughtExceptions[i];
                String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
                String name = scope.createName(varName, false);
                SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
                var.setName(ast.newSimpleName(name));
                var.setType(imports.addImport(excBinding, ast, importRewriteContext));
                CatchClause newClause = ast.newCatchClause();
                newClause.setException(var);
                String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), name, selectedNode, String.valueOf('\n'));
                if (catchBody != null) {
                    ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
                    newClause.getBody().statements().add(node);
                }
                clausesRewrite.insertLast(newClause, null);
                //$NON-NLS-1$
                String typeKey = "type" + i;
                //$NON-NLS-1$
                String nameKey = "name" + i;
                proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey);
                proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
                addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
            }
            proposals.add(proposal);
        }
        if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
            List<CatchClause> catchClauses = surroundingTry.catchClauses();
            if (catchClauses != null && catchClauses.size() == 1) {
                List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(uncaughtExceptions);
                String label = filteredExceptions.size() > 1 ? CorrectionMessages.LocalCorrectionsSubProcessor_addexceptionstoexistingcatch_description : CorrectionMessages.LocalCorrectionsSubProcessor_addexceptiontoexistingcatch_description;
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
                ASTRewrite rewrite = ASTRewrite.create(ast);
                LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH, image);
                ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
                CatchClause catchClause = catchClauses.get(0);
                Type type = catchClause.getException().getType();
                if (type instanceof UnionType) {
                    UnionType unionType = (UnionType) type;
                    ListRewrite listRewrite = rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY);
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
                        listRewrite.insertLast(type2, null);
                        //$NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                } else {
                    UnionType newUnionType = ast.newUnionType();
                    List<Type> types = newUnionType.types();
                    types.add((Type) rewrite.createCopyTarget(type));
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
                        types.add(type2);
                        //$NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                    rewrite.replace(type, newUnionType, null);
                }
                proposals.add(proposal);
            } else if (catchClauses != null && catchClauses.size() == 0 && uncaughtExceptions.length > 1) {
                String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalmulticatch_description;
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
                ASTRewrite rewrite = ASTRewrite.create(ast);
                LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_MULTI_CATCH, image);
                ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
                CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
                scope.setCursor(offset);
                CatchClause newCatchClause = ast.newCatchClause();
                String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
                String name = scope.createName(varName, false);
                SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
                var.setName(ast.newSimpleName(name));
                UnionType newUnionType = ast.newUnionType();
                List<Type> types = newUnionType.types();
                for (int i = 0; i < uncaughtExceptions.length; i++) {
                    ITypeBinding excBinding = uncaughtExceptions[i];
                    Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
                    types.add(type2);
                    //$NON-NLS-1$
                    String typeKey = "type" + i;
                    proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                    addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                }
                //$NON-NLS-1$
                String nameKey = "name";
                proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
                var.setType(newUnionType);
                newCatchClause.setException(var);
                //$NON-NLS-1$
                String catchBody = StubUtility.getCatchBodyContent(cu, "Exception", name, selectedNode, String.valueOf('\n'));
                if (catchBody != null) {
                    ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
                    newCatchClause.getBody().statements().add(node);
                }
                ListRewrite listRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
                listRewrite.insertFirst(newCatchClause, null);
                proposals.add(proposal);
            }
        }
    }
    //Add throws declaration
    if (decl instanceof MethodDeclaration) {
        MethodDeclaration methodDecl = (MethodDeclaration) decl;
        IMethodBinding binding = methodDecl.resolveBinding();
        boolean isApplicable = (binding != null);
        if (isApplicable) {
            IMethodBinding overriddenMethod = Bindings.findOverriddenMethod(binding, true);
            if (overriddenMethod != null) {
                isApplicable = overriddenMethod.getDeclaringClass().isFromSource();
                if (!isApplicable) {
                    // bug 349051
                    ITypeBinding[] exceptionTypes = overriddenMethod.getExceptionTypes();
                    ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<ITypeBinding>(uncaughtExceptions.length);
                    for (int i = 0; i < uncaughtExceptions.length; i++) {
                        ITypeBinding curr = uncaughtExceptions[i];
                        if (isSubtype(curr, exceptionTypes)) {
                            unhandledExceptions.add(curr);
                        }
                    }
                    uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
                    isApplicable |= uncaughtExceptions.length > 0;
                }
            }
        }
        if (isApplicable) {
            ITypeBinding[] methodExceptions = binding.getExceptionTypes();
            ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<ITypeBinding>(uncaughtExceptions.length);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                ITypeBinding curr = uncaughtExceptions[i];
                if (!isSubtype(curr, methodExceptions)) {
                    unhandledExceptions.add(curr);
                }
            }
            uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
            List<Type> exceptions = methodDecl.thrownExceptionTypes();
            int nExistingExceptions = exceptions.size();
            ChangeDescription[] desc = new ChangeDescription[nExistingExceptions + uncaughtExceptions.length];
            for (int i = 0; i < exceptions.size(); i++) {
                Type elem = exceptions.get(i);
                if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) {
                    desc[i] = new RemoveDescription();
                }
            }
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                //$NON-NLS-1$
                desc[i + nExistingExceptions] = new InsertDescription(uncaughtExceptions[i], "");
            }
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
            ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, IProposalRelevance.ADD_THROWS_DECLARATION, image);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions));
            }
            proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID);
            proposals.add(proposal);
        }
    }
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) InsertDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.InsertDescription) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Image(org.eclipse.swt.graphics.Image) RefactoringCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal) SurroundWithTryCatchRefactoring(org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring) ChangeDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.ChangeDescription) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) List(java.util.List) ArrayList(java.util.ArrayList) RemoveDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.RemoveDescription) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ChangeMethodSignatureProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal)

Aggregations

LinkedCorrectionProposal (org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal)29 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)27 Image (org.eclipse.swt.graphics.Image)18 AST (org.eclipse.jdt.core.dom.AST)13 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)11 ASTNode (org.eclipse.jdt.core.dom.ASTNode)10 Expression (org.eclipse.jdt.core.dom.Expression)9 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)9 CastExpression (org.eclipse.jdt.core.dom.CastExpression)8 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)8 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)8 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)8 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)8 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)7 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)7 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)7 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)7 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)7 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)7 ArrayList (java.util.ArrayList)6