Search in sources :

Example 1 with CUCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal in project che by eclipse.

the class UnresolvedElementsSubProcessor method addSimilarTypeProposals.

private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection<ICommandAccess> proposals) throws CoreException {
    SimilarElement[] elements = SimilarElementsRequestor.findSimilarElement(cu, node, kind);
    // try to resolve type in context -> highest severity
    String resolvedTypeName = null;
    ITypeBinding binding = ASTResolving.guessBindingForTypeReference(node);
    if (binding != null) {
        ITypeBinding simpleBinding = binding;
        if (simpleBinding.isArray()) {
            simpleBinding = simpleBinding.getElementType();
        }
        simpleBinding = simpleBinding.getTypeDeclaration();
        if (!simpleBinding.isRecovered()) {
            resolvedTypeName = simpleBinding.getQualifiedName();
            CUCorrectionProposal proposal = createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2, elements.length);
            proposals.add(proposal);
            if (proposal instanceof AddImportCorrectionProposal)
                proposal.setRelevance(relevance + elements.length + 2);
            if (binding.isParameterizedType() && (node.getParent() instanceof SimpleType || node.getParent() instanceof NameQualifiedType) && !(node.getParent().getParent() instanceof Type)) {
                proposals.add(createTypeRefChangeFullProposal(cu, binding, node, relevance + 5));
            }
        }
    } else {
        ASTNode normalizedNode = ASTNodes.getNormalizedNode(node);
        if (!(normalizedNode.getParent() instanceof Type) && node.getParent() != normalizedNode) {
            ITypeBinding normBinding = ASTResolving.guessBindingForTypeReference(normalizedNode);
            if (normBinding != null && !normBinding.isRecovered()) {
                proposals.add(createTypeRefChangeFullProposal(cu, normBinding, normalizedNode, relevance + 5));
            }
        }
    }
    // add all similar elements
    for (int i = 0; i < elements.length; i++) {
        SimilarElement elem = elements[i];
        if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
            String fullName = elem.getName();
            if (!fullName.equals(resolvedTypeName)) {
                proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance, elements.length));
            }
        }
    }
}
Also used : AddImportCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.AddImportCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) IType(org.eclipse.jdt.core.IType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 2 with CUCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal 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 CUCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal in project che by eclipse.

the class AssistQuickFixTest method testReplaceCatchClauseWithThrowsWithFinally.

@Test
public void testReplaceCatchClauseWithThrowsWithFinally() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("public class E {\n");
    buf.append("    public void foo() {\n");
    buf.append("        try {\n");
    buf.append("            goo();\n");
    buf.append("        } catch (IOException e) {\n");
    buf.append("        } finally {\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
    String str = "(IOException e)";
    AssistContext context = getCorrectionContext(cu, buf.toString().indexOf(str), 0);
    List proposals = collectAssists(context, false);
    assertNumberOfProposals(proposals, 2);
    assertCorrectLabels(proposals);
    CUCorrectionProposal proposal = (CUCorrectionProposal) proposals.get(0);
    String preview1 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("public class E {\n");
    buf.append("    public void foo() throws IOException {\n");
    buf.append("        try {\n");
    buf.append("            goo();\n");
    buf.append("        } finally {\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected1 = buf.toString();
    proposal = (CUCorrectionProposal) proposals.get(1);
    String preview2 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("public class E {\n");
    buf.append("    public void foo() {\n");
    buf.append("        try {\n");
    buf.append("            goo();\n");
    buf.append("        } finally {\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected2 = buf.toString();
    assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) AssistContext(org.eclipse.jdt.internal.ui.text.correction.AssistContext) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 4 with CUCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal in project che by eclipse.

the class AssistQuickFixTest method testInvertEquals6.

@Test
public void testInvertEquals6() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("class A {\n");
    buf.append("    static String get() {\n");
    buf.append("        return \"a\";\n");
    buf.append("    }\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    public void foo() {\n");
    buf.append("        \"a\".equals(A.get());\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
    String str = "equals";
    AssistContext context = getCorrectionContext(cu, buf.toString().indexOf(str), 0);
    List proposals = collectAssists(context, FILTER_EQ);
    assertNumberOfProposals(proposals, 1);
    assertCorrectLabels(proposals);
    cu = pack1.createCompilationUnit("E.java", buf.toString(), true, null);
    CUCorrectionProposal proposal = (CUCorrectionProposal) proposals.get(0);
    String preview = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("class A {\n");
    buf.append("    static String get() {\n");
    buf.append("        return \"a\";\n");
    buf.append("    }\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    public void foo() {\n");
    buf.append("        A.get().equals(\"a\");\n");
    buf.append("    }\n");
    buf.append("}\n");
    assertEqualString(preview, buf.toString());
    cu = pack1.createCompilationUnit("E.java", buf.toString(), true, null);
    context = getCorrectionContext(cu, buf.toString().indexOf(str), 0);
    proposals = collectAssists(context, FILTER_EQ);
    assertNumberOfProposals(proposals, 1);
    assertCorrectLabels(proposals);
    proposal = (CUCorrectionProposal) proposals.get(0);
    preview = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("class A {\n");
    buf.append("    static String get() {\n");
    buf.append("        return \"a\";\n");
    buf.append("    }\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    public void foo() {\n");
    buf.append("        \"a\".equals(A.get());\n");
    buf.append("    }\n");
    buf.append("}\n");
    assertEqualString(preview, buf.toString());
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) AssistContext(org.eclipse.jdt.internal.ui.text.correction.AssistContext) ArrayList(java.util.ArrayList) List(java.util.List) Test(org.junit.Test)

Example 5 with CUCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal in project che by eclipse.

the class LocalCorrectionsQuickFixTest17 method testUncaughtExceptionTryWithResources4.

@Test
public void testUncaughtExceptionTryWithResources4() throws Exception {
    //https://bugs.eclipse.org/bugs/show_bug.cgi?id=351464
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.FileInputStream;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("class MyException extends Exception {\n");
    buf.append("    static final long serialVersionUID = 1L;\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    void bar() throws MyException {\n");
    buf.append("        throw new MyException();\n");
    buf.append("    }\n");
    buf.append("    void foo(String name, boolean b) throws IOException {\n");
    buf.append("        try (FileInputStream fis = new FileInputStream(name)) {\n");
    buf.append("            bar();\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
    CompilationUnit astRoot = getASTRoot(cu);
    ArrayList proposals = collectCorrections(cu, astRoot);
    assertNumberOfProposals(proposals, 3);
    assertCorrectLabels(proposals);
    CUCorrectionProposal proposal = (CUCorrectionProposal) proposals.get(0);
    String preview1 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.FileInputStream;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("class MyException extends Exception {\n");
    buf.append("    static final long serialVersionUID = 1L;\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    void bar() throws MyException {\n");
    buf.append("        throw new MyException();\n");
    buf.append("    }\n");
    buf.append("    void foo(String name, boolean b) throws IOException, MyException {\n");
    buf.append("        try (FileInputStream fis = new FileInputStream(name)) {\n");
    buf.append("            bar();\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected1 = buf.toString();
    proposal = (CUCorrectionProposal) proposals.get(1);
    String preview2 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.FileInputStream;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("class MyException extends Exception {\n");
    buf.append("    static final long serialVersionUID = 1L;\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    void bar() throws MyException {\n");
    buf.append("        throw new MyException();\n");
    buf.append("    }\n");
    buf.append("    void foo(String name, boolean b) throws IOException {\n");
    buf.append("        try (FileInputStream fis = new FileInputStream(name)) {\n");
    buf.append("            bar();\n");
    buf.append("        } catch (MyException e) {\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected2 = buf.toString();
    proposal = (CUCorrectionProposal) proposals.get(2);
    String preview3 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.io.FileInputStream;\n");
    buf.append("import java.io.IOException;\n");
    buf.append("class MyException extends Exception {\n");
    buf.append("    static final long serialVersionUID = 1L;\n");
    buf.append("}\n");
    buf.append("public class E {\n");
    buf.append("    void bar() throws MyException {\n");
    buf.append("        throw new MyException();\n");
    buf.append("    }\n");
    buf.append("    void foo(String name, boolean b) throws IOException {\n");
    buf.append("        try (FileInputStream fis = new FileInputStream(name)) {\n");
    buf.append("            try {\n");
    buf.append("                bar();\n");
    buf.append("            } catch (MyException e) {\n");
    buf.append("            }\n");
    buf.append("        }\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected3 = buf.toString();
    assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Aggregations

CUCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal)292 ArrayList (java.util.ArrayList)287 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)285 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)284 Test (org.junit.Test)284 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)228 AssistContext (org.eclipse.jdt.internal.ui.text.correction.AssistContext)57 List (java.util.List)49 Hashtable (java.util.Hashtable)47 ProblemLocation (org.eclipse.jdt.internal.ui.text.correction.ProblemLocation)7 Ignore (org.junit.Ignore)7 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)6 ChangeCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal)6 IPreferenceStore (org.eclipse.jface.preference.IPreferenceStore)5 CorrectPackageDeclarationProposal (org.eclipse.jdt.internal.ui.text.correction.proposals.CorrectPackageDeclarationProposal)4 IDocument (org.eclipse.jface.text.IDocument)4 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)3 Image (org.eclipse.swt.graphics.Image)3 Iterator (java.util.Iterator)2 IProject (org.eclipse.core.resources.IProject)2