Search in sources :

Example 31 with QualifiedName

use of org.eclipse.jdt.core.dom.QualifiedName in project AutoRefactor by JnRouvignac.

the class ObsoleteLambdaExpressionRatherThanComparatorCleanUp method refactor.

private void refactor(final Expression visited, final ITypeBinding typeArgument, final Set<String> classesToUseWithImport, final SimpleName name1, final AtomicReference<Expression> criteria, final AtomicBoolean isForward, final Boolean isNullFirst) {
    String comparatorClassName = addImport(Comparator.class, classesToUseWithImport, new HashSet<>());
    Expression lambda;
    if (criteria.get() instanceof MethodInvocation) {
        lambda = buildMethod(typeArgument, (MethodInvocation) criteria.get());
    } else {
        lambda = buildField(visited, typeArgument, isForward.get(), isNullFirst, (QualifiedName) criteria.get(), name1);
    }
    ASTRewrite rewrite = cuRewrite.getASTRewrite();
    ASTNodeFactory ast = cuRewrite.getASTBuilder();
    TextEditGroup group = new TextEditGroup(MultiFixMessages.ObsoleteLambdaExpressionRatherThanComparatorCleanUp_description);
    MethodInvocation comparingMethod = ast.newMethodInvocation();
    comparingMethod.setExpression(ASTNodeFactory.newName(ast, comparatorClassName));
    // $NON-NLS-1$
    comparingMethod.setName(ast.newSimpleName("comparing"));
    comparingMethod.arguments().add(lambda);
    if (!isForward.get()) {
        MethodInvocation reversedMethod = ast.newMethodInvocation();
        reversedMethod.setExpression(comparingMethod);
        // $NON-NLS-1$
        reversedMethod.setName(ast.newSimpleName("reversed"));
        comparingMethod = reversedMethod;
    }
    if (isNullFirst != null) {
        if (isNullFirst) {
            MethodInvocation nullsFirstMethod = ast.newMethodInvocation();
            nullsFirstMethod.setExpression(ASTNodeFactory.newName(ast, comparatorClassName));
            // $NON-NLS-1$
            nullsFirstMethod.setName(ast.newSimpleName("nullsFirst"));
            nullsFirstMethod.arguments().add(comparingMethod);
            comparingMethod = nullsFirstMethod;
        } else {
            MethodInvocation nullsLastMethod = ast.newMethodInvocation();
            nullsLastMethod.setExpression(ASTNodeFactory.newName(ast, comparatorClassName));
            // $NON-NLS-1$
            nullsLastMethod.setName(ast.newSimpleName("nullsLast"));
            nullsLastMethod.arguments().add(comparingMethod);
            comparingMethod = nullsLastMethod;
        }
    }
    ASTNodes.replaceButKeepComment(rewrite, visited, comparingMethod, group);
}
Also used : Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) OrderedInfixExpression(org.autorefactor.jdt.internal.corext.dom.OrderedInfixExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTNodeFactory(org.autorefactor.jdt.internal.corext.dom.ASTNodeFactory) ASTRewrite(org.autorefactor.jdt.core.dom.ASTRewrite) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) TextEditGroup(org.eclipse.text.edits.TextEditGroup)

Example 32 with QualifiedName

use of org.eclipse.jdt.core.dom.QualifiedName in project AutoRefactor by JnRouvignac.

the class ObsoleteLocalVariableRatherThanFieldCleanUp method isExternalField.

private static boolean isExternalField(final SimpleName occurrence) {
    FieldAccess fieldAccess = ASTNodes.as(occurrence, FieldAccess.class);
    if (fieldAccess != null && ASTNodes.is(fieldAccess.getExpression(), ThisExpression.class)) {
        return true;
    }
    QualifiedName qualifiedName = ASTNodes.as(occurrence, QualifiedName.class);
    return qualifiedName != null;
}
Also used : ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 33 with QualifiedName

use of org.eclipse.jdt.core.dom.QualifiedName in project eclipse.jdt.ls by eclipse.

the class ExtractConstantRefactoring method checkExpression.

private RefactoringStatus checkExpression() throws JavaModelException {
    RefactoringStatus result = new RefactoringStatus();
    result.merge(checkExpressionBinding());
    if (result.hasFatalError()) {
        return result;
    }
    checkAllStaticFinal();
    IExpressionFragment selectedExpression = getSelectedExpression();
    Expression associatedExpression = selectedExpression.getAssociatedExpression();
    if (associatedExpression instanceof NullLiteral) {
        result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
    } else if (!ConstantChecks.isLoadTimeConstant(selectedExpression)) {
        result.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
    } else if (associatedExpression instanceof SimpleName) {
        if (associatedExpression.getParent() instanceof QualifiedName && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || associatedExpression.getParent() instanceof FieldAccess && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY) {
            return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
        }
    }
    return result;
}
Also used : IExpressionFragment(org.eclipse.jdt.internal.corext.dom.fragments.IExpressionFragment) Expression(org.eclipse.jdt.core.dom.Expression) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) NullLiteral(org.eclipse.jdt.core.dom.NullLiteral)

Example 34 with QualifiedName

use of org.eclipse.jdt.core.dom.QualifiedName in project eclipse.jdt.ls by eclipse.

the class ExtractFieldRefactoring method wrapAsFieldAccessExpression.

private Expression wrapAsFieldAccessExpression(SimpleName fieldName) {
    AST ast = fCURewrite.getAST();
    ASTRewrite rewrite = fCURewrite.getASTRewrite();
    List<String> variableNames = Arrays.asList(getExcludedVariableNames());
    if (variableNames.contains(fFieldName)) {
        int modifiers = getModifiers();
        if (Flags.isStatic(modifiers)) {
            try {
                String enclosingTypeName = getEnclosingTypeName();
                SimpleName typeName = ast.newSimpleName(enclosingTypeName);
                if (fLinkedProposalModel != null) {
                    fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(rewrite.track(typeName), false);
                }
                QualifiedName qualifiedName = ast.newQualifiedName(typeName, fieldName);
                return qualifiedName;
            } catch (JavaModelException e) {
                return wrapAsFieldAccess(fieldName, ast);
            }
        } else {
            return wrapAsFieldAccess(fieldName, ast);
        }
    }
    return fieldName;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) JavaModelException(org.eclipse.jdt.core.JavaModelException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 35 with QualifiedName

use of org.eclipse.jdt.core.dom.QualifiedName in project eclipse.jdt.ls by eclipse.

the class UnresolvedElementsSubProcessor method addSimilarVariableProposals.

private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, IVariableBinding resolvedField, SimpleName node, boolean isWriteAccess, Collection<ChangeCorrectionProposal> 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<>(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, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(curr));
                        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite, IProposalRelevance.CHANGE_TO_METHOD);
                        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);
                        }
                        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) Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) 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)

Aggregations

QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)68 SimpleName (org.eclipse.jdt.core.dom.SimpleName)47 ASTNode (org.eclipse.jdt.core.dom.ASTNode)36 Name (org.eclipse.jdt.core.dom.Name)26 FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)22 Expression (org.eclipse.jdt.core.dom.Expression)20 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)18 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)17 IBinding (org.eclipse.jdt.core.dom.IBinding)16 SimpleType (org.eclipse.jdt.core.dom.SimpleType)16 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)14 ArrayList (java.util.ArrayList)13 NameQualifiedType (org.eclipse.jdt.core.dom.NameQualifiedType)12 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)10 Type (org.eclipse.jdt.core.dom.Type)10 CastExpression (org.eclipse.jdt.core.dom.CastExpression)9 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)9 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)9 IType (org.eclipse.jdt.core.IType)8 Assignment (org.eclipse.jdt.core.dom.Assignment)8