Search in sources :

Example 21 with FieldAccess

use of org.eclipse.jdt.core.dom.FieldAccess in project che by eclipse.

the class TypeMismatchSubProcessor method addTypeMismatchProposals.

public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
    String[] args = problem.getProblemArguments();
    if (args.length != 2) {
        return;
    }
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    AST ast = astRoot.getAST();
    ASTNode selectedNode = problem.getCoveredNode(astRoot);
    if (!(selectedNode instanceof Expression)) {
        return;
    }
    Expression nodeToCast = (Expression) selectedNode;
    Name receiverNode = null;
    ITypeBinding castTypeBinding = null;
    int parentNodeType = selectedNode.getParent().getNodeType();
    if (parentNodeType == ASTNode.ASSIGNMENT) {
        Assignment assign = (Assignment) selectedNode.getParent();
        Expression leftHandSide = assign.getLeftHandSide();
        if (selectedNode.equals(leftHandSide)) {
            nodeToCast = assign.getRightHandSide();
        }
        castTypeBinding = assign.getLeftHandSide().resolveTypeBinding();
        if (leftHandSide instanceof Name) {
            receiverNode = (Name) leftHandSide;
        } else if (leftHandSide instanceof FieldAccess) {
            receiverNode = ((FieldAccess) leftHandSide).getName();
        }
    } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
        VariableDeclarationFragment frag = (VariableDeclarationFragment) selectedNode.getParent();
        if (selectedNode.equals(frag.getName()) || selectedNode.equals(frag.getInitializer())) {
            nodeToCast = frag.getInitializer();
            castTypeBinding = ASTNodes.getType(frag).resolveBinding();
            receiverNode = frag.getName();
        }
    } else if (parentNodeType == ASTNode.MEMBER_VALUE_PAIR) {
        receiverNode = ((MemberValuePair) selectedNode.getParent()).getName();
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    } else if (parentNodeType == ASTNode.SINGLE_MEMBER_ANNOTATION) {
        // use the type name
        receiverNode = ((SingleMemberAnnotation) selectedNode.getParent()).getTypeName();
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    } else {
        // try to find the binding corresponding to 'castTypeName'
        castTypeBinding = ASTResolving.guessBindingForReference(nodeToCast);
    }
    if (castTypeBinding == null) {
        return;
    }
    ITypeBinding currBinding = nodeToCast.resolveTypeBinding();
    if (!(nodeToCast instanceof ArrayInitializer)) {
        ITypeBinding castFixType = null;
        if (currBinding == null || castTypeBinding.isCastCompatible(currBinding) || nodeToCast instanceof CastExpression) {
            castFixType = castTypeBinding;
        } else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
            ITypeBinding boxUnboxedTypeBinding = boxUnboxPrimitives(castTypeBinding, currBinding, ast);
            if (boxUnboxedTypeBinding != castTypeBinding && boxUnboxedTypeBinding.isCastCompatible(currBinding)) {
                castFixType = boxUnboxedTypeBinding;
            }
        }
        if (castFixType != null) {
            proposals.add(createCastProposal(context, castFixType, nodeToCast, IProposalRelevance.CREATE_CAST));
        }
    }
    //$NON-NLS-1$
    boolean nullOrVoid = currBinding == null || "void".equals(currBinding.getName());
    // change method return statement to actual type
    if (!nullOrVoid && parentNodeType == ASTNode.RETURN_STATEMENT) {
        BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
        if (decl instanceof MethodDeclaration) {
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            currBinding = Bindings.normalizeTypeBinding(currBinding);
            if (currBinding == null) {
                //$NON-NLS-1$
                currBinding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (currBinding.isWildcardType()) {
                currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
            }
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturntype_description, BasicElementLabels.getJavaElementName(currBinding.getName()));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_METHOD_RETURN_TYPE, image);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
            Type newReturnType = imports.addImport(currBinding, ast, importRewriteContext);
            rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            //$NON-NLS-1$
            String returnKey = "return";
            proposal.addLinkedPosition(rewrite.track(newReturnType), true, returnKey);
            ITypeBinding[] typeSuggestions = ASTResolving.getRelaxingTypes(ast, currBinding);
            for (int i = 0; i < typeSuggestions.length; i++) {
                proposal.addLinkedPositionProposal(returnKey, typeSuggestions[i]);
            }
            proposals.add(proposal);
        }
    }
    if (!nullOrVoid && receiverNode != null) {
        currBinding = Bindings.normalizeTypeBinding(currBinding);
        if (currBinding == null) {
            //$NON-NLS-1$
            currBinding = ast.resolveWellKnownType("java.lang.Object");
        }
        if (currBinding.isWildcardType()) {
            currBinding = ASTResolving.normalizeWildcardType(currBinding, true, ast);
        }
        addChangeSenderTypeProposals(context, receiverNode, currBinding, true, IProposalRelevance.CHANGE_TYPE_OF_RECEIVER_NODE, proposals);
    }
    addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, IProposalRelevance.CHANGE_TYPE_OF_NODE_TO_CAST, proposals);
    if (castTypeBinding == ast.resolveWellKnownType("boolean") && currBinding != null && !currBinding.isPrimitive() && !Bindings.isVoidType(currBinding)) {
        //$NON-NLS-1$
        String label = CorrectionMessages.TypeMismatchSubProcessor_insertnullcheck_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
        InfixExpression expression = ast.newInfixExpression();
        expression.setLeftOperand((Expression) rewrite.createMoveTarget(nodeToCast));
        expression.setRightOperand(ast.newNullLiteral());
        expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
        rewrite.replace(nodeToCast, expression, null);
        proposals.add(new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_NULL_CHECK, image));
    }
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Image(org.eclipse.swt.graphics.Image) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) Assignment(org.eclipse.jdt.core.dom.Assignment) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) 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) SingleMemberAnnotation(org.eclipse.jdt.core.dom.SingleMemberAnnotation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) CastExpression(org.eclipse.jdt.core.dom.CastExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 22 with FieldAccess

use of org.eclipse.jdt.core.dom.FieldAccess in project che by eclipse.

the class UnresolvedElementsSubProcessor method getVariableProposals.

public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, IVariableBinding resolvedField, Collection<ICommandAccess> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveredNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    // type that defines the variable
    ITypeBinding binding = null;
    ITypeBinding declaringTypeBinding = Bindings.getBindingOfParentTypeContext(selectedNode);
    if (declaringTypeBinding == null) {
        return;
    }
    // possible type kind of the node
    boolean suggestVariableProposals = true;
    int typeKind = 0;
    while (selectedNode instanceof ParenthesizedExpression) {
        selectedNode = ((ParenthesizedExpression) selectedNode).getExpression();
    }
    Name node = null;
    switch(selectedNode.getNodeType()) {
        case ASTNode.SIMPLE_NAME:
            node = (SimpleName) selectedNode;
            ASTNode parent = node.getParent();
            StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
            if (locationInParent == ExpressionMethodReference.EXPRESSION_PROPERTY) {
                typeKind = SimilarElementsRequestor.REF_TYPES;
            } else if (locationInParent == MethodInvocation.EXPRESSION_PROPERTY) {
                if (JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
                    typeKind = SimilarElementsRequestor.CLASSES | SimilarElementsRequestor.INTERFACES | SimilarElementsRequestor.ENUMS;
                } else {
                    typeKind = SimilarElementsRequestor.CLASSES;
                }
            } else if (locationInParent == FieldAccess.NAME_PROPERTY) {
                Expression expression = ((FieldAccess) parent).getExpression();
                if (expression != null) {
                    binding = expression.resolveTypeBinding();
                    if (binding == null) {
                        node = null;
                    }
                }
            } else if (parent instanceof SimpleType || parent instanceof NameQualifiedType) {
                suggestVariableProposals = false;
                typeKind = SimilarElementsRequestor.REF_TYPES_AND_VAR;
            } else if (parent instanceof QualifiedName) {
                Name qualifier = ((QualifiedName) parent).getQualifier();
                if (qualifier != node) {
                    binding = qualifier.resolveTypeBinding();
                } else {
                    typeKind = SimilarElementsRequestor.REF_TYPES;
                }
                ASTNode outerParent = parent.getParent();
                while (outerParent instanceof QualifiedName) {
                    outerParent = outerParent.getParent();
                }
                if (outerParent instanceof SimpleType || outerParent instanceof NameQualifiedType) {
                    typeKind = SimilarElementsRequestor.REF_TYPES;
                    suggestVariableProposals = false;
                }
            } else if (locationInParent == SwitchCase.EXPRESSION_PROPERTY) {
                ITypeBinding switchExp = ((SwitchStatement) node.getParent().getParent()).getExpression().resolveTypeBinding();
                if (switchExp != null && switchExp.isEnum()) {
                    binding = switchExp;
                }
            } else if (locationInParent == SuperFieldAccess.NAME_PROPERTY) {
                binding = declaringTypeBinding.getSuperclass();
            }
            break;
        case ASTNode.QUALIFIED_NAME:
            QualifiedName qualifierName = (QualifiedName) selectedNode;
            ITypeBinding qualifierBinding = qualifierName.getQualifier().resolveTypeBinding();
            if (qualifierBinding != null) {
                node = qualifierName.getName();
                binding = qualifierBinding;
            } else {
                node = qualifierName.getQualifier();
                typeKind = SimilarElementsRequestor.REF_TYPES;
                suggestVariableProposals = node.isSimpleName();
            }
            if (selectedNode.getParent() instanceof SimpleType || selectedNode.getParent() instanceof NameQualifiedType) {
                typeKind = SimilarElementsRequestor.REF_TYPES;
                suggestVariableProposals = false;
            }
            break;
        case ASTNode.FIELD_ACCESS:
            FieldAccess access = (FieldAccess) selectedNode;
            Expression expression = access.getExpression();
            if (expression != null) {
                binding = expression.resolveTypeBinding();
                if (binding != null) {
                    node = access.getName();
                }
            }
            break;
        case ASTNode.SUPER_FIELD_ACCESS:
            binding = declaringTypeBinding.getSuperclass();
            node = ((SuperFieldAccess) selectedNode).getName();
            break;
        default:
    }
    if (node == null) {
        return;
    }
    // add type proposals
    if (typeKind != 0) {
        if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
            typeKind &= ~(SimilarElementsRequestor.ANNOTATIONS | SimilarElementsRequestor.ENUMS | SimilarElementsRequestor.VARIABLES);
        }
        int relevance = Character.isUpperCase(ASTNodes.getSimpleNameIdentifier(node).charAt(0)) ? IProposalRelevance.VARIABLE_TYPE_PROPOSAL_1 : IProposalRelevance.VARIABLE_TYPE_PROPOSAL_2;
        addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
        typeKind &= ~SimilarElementsRequestor.ANNOTATIONS;
        addNewTypeProposals(cu, node, typeKind, relevance, proposals);
        ReorgCorrectionsSubProcessor.addProjectSetupFixProposal(context, problem, node.getFullyQualifiedName(), proposals);
    }
    if (!suggestVariableProposals) {
        return;
    }
    SimpleName simpleName = node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
    boolean isWriteAccess = ASTResolving.isWriteAccess(node);
    // similar variables
    addSimilarVariableProposals(cu, astRoot, binding, resolvedField, simpleName, isWriteAccess, proposals);
    if (binding == null) {
        addStaticImportFavoriteProposals(context, simpleName, false, proposals);
    }
    if (resolvedField == null || binding == null || resolvedField.getDeclaringClass() != binding.getTypeDeclaration() && Modifier.isPrivate(resolvedField.getModifiers())) {
        // new fields
        addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
        // new parameters and local variables
        if (binding == null) {
            addNewVariableProposals(cu, node, simpleName, proposals);
        }
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name) SimpleType(org.eclipse.jdt.core.dom.SimpleType) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 23 with FieldAccess

use of org.eclipse.jdt.core.dom.FieldAccess in project che by eclipse.

the class AssignToVariableAssistProposal method doAddField.

private ASTRewrite doAddField() {
    boolean isParamToField = fNodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;
    ASTNode newTypeDecl = ASTResolving.findParentType(fNodeToAssign);
    if (newTypeDecl == null) {
        return null;
    }
    Expression expression = isParamToField ? ((SingleVariableDeclaration) fNodeToAssign).getName() : ((ExpressionStatement) fNodeToAssign).getExpression();
    AST ast = newTypeDecl.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());
    BodyDeclaration bodyDecl = ASTResolving.findParentBodyDeclaration(fNodeToAssign);
    Block body;
    if (bodyDecl instanceof MethodDeclaration) {
        body = ((MethodDeclaration) bodyDecl).getBody();
    } else if (bodyDecl instanceof Initializer) {
        body = ((Initializer) bodyDecl).getBody();
    } else {
        return null;
    }
    IJavaProject project = getCompilationUnit().getJavaProject();
    boolean isAnonymous = newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
    boolean isStatic = Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
    boolean isConstructorParam = isParamToField && fNodeToAssign.getParent() instanceof MethodDeclaration && ((MethodDeclaration) fNodeToAssign.getParent()).isConstructor();
    int modifiers = Modifier.PRIVATE;
    if (isStatic) {
        modifiers |= Modifier.STATIC;
    } else if (isConstructorParam) {
    //			String saveActionsKey= AbstractSaveParticipantPreferenceConfiguration.EDITOR_SAVE_PARTICIPANT_PREFIX + CleanUpPostSaveListener.POSTSAVELISTENER_ID;
    //			IScopeContext[] scopes= { InstanceScope.INSTANCE, new ProjectScope(project.getProject()) };
    //			boolean safeActionsEnabled= Platform.getPreferencesService().getBoolean(JavaPlugin.getPluginId(), saveActionsKey, false, scopes);
    }
    if (/*CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(
					CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.CLEANUP_ON_SAVE_ADDITIONAL_OPTIONS, project))
			&&*/
    CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL, project)) && CleanUpOptions.TRUE.equals(PreferenceConstants.getPreference(CleanUpPreferenceUtil.SAVE_PARTICIPANT_KEY_PREFIX + CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, project))) {
        int constructors = 0;
        if (newTypeDecl instanceof AbstractTypeDeclaration) {
            List<BodyDeclaration> bodyDeclarations = ((AbstractTypeDeclaration) newTypeDecl).bodyDeclarations();
            for (BodyDeclaration decl : bodyDeclarations) {
                if (decl instanceof MethodDeclaration && ((MethodDeclaration) decl).isConstructor()) {
                    constructors++;
                }
            }
        }
        if (constructors == 1) {
            modifiers |= Modifier.FINAL;
        }
    }
    VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression);
    String varName = newDeclFrag.getName().getIdentifier();
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));
    boolean needsThis = StubUtility.useThisForFieldAccess(project);
    if (isParamToField) {
        needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
    }
    SimpleName accessName = ast.newSimpleName(varName);
    if (needsThis) {
        FieldAccess fieldAccess = ast.newFieldAccess();
        fieldAccess.setName(accessName);
        if (isStatic) {
            String typeName = ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
            fieldAccess.setExpression(ast.newSimpleName(typeName));
        } else {
            fieldAccess.setExpression(ast.newThisExpression());
        }
        assignment.setLeftHandSide(fieldAccess);
    } else {
        assignment.setLeftHandSide(accessName);
    }
    ASTNode selectionNode;
    if (isParamToField) {
        // assign parameter to field
        ExpressionStatement statement = ast.newExpressionStatement(assignment);
        int insertIdx = findAssignmentInsertIndex(body.statements());
        rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
        selectionNode = statement;
    } else {
        if (needsSemicolon(expression)) {
            rewrite.replace(expression, ast.newExpressionStatement(assignment), null);
        } else {
            rewrite.replace(expression, assignment, null);
        }
        selectionNode = fNodeToAssign;
    }
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
    if (!isParamToField) {
        FieldDeclaration fieldDeclaration = (FieldDeclaration) newDeclFrag.getParent();
        addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
    }
    addLinkedPosition(rewrite.track(accessName), true, KEY_NAME);
    IVariableBinding variableBinding = newDeclFrag.resolveBinding();
    if (variableBinding != null) {
        SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(fNodeToAssign.getRoot(), variableBinding);
        for (int i = 0; i < linkedNodes.length; i++) {
            addLinkedPosition(rewrite.track(linkedNodes[i]), false, KEY_NAME);
        }
    }
    setEndPosition(rewrite.track(selectionNode));
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) Assignment(org.eclipse.jdt.core.dom.Assignment) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Initializer(org.eclipse.jdt.core.dom.Initializer) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 24 with FieldAccess

use of org.eclipse.jdt.core.dom.FieldAccess in project che by eclipse.

the class ConvertIterableLoopOperation method satisfiesPreconditions.

/**
	 * Is this proposal applicable?
	 *
	 * @return A status with severity <code>IStatus.Error</code> if not
	 *         applicable
	 */
@Override
public final IStatus satisfiesPreconditions() {
    IStatus resultStatus = StatusInfo.OK_STATUS;
    if (JavaModelUtil.is50OrHigher(getJavaProject())) {
        resultStatus = checkExpressionCondition();
        if (resultStatus.getSeverity() == IStatus.ERROR)
            return resultStatus;
        List<Expression> updateExpressions = getForStatement().updaters();
        if (updateExpressions.size() == 1) {
            resultStatus = new StatusInfo(IStatus.WARNING, Messages.format(FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpression_Warning, BasicElementLabels.getJavaCodeString(updateExpressions.get(0).toString())));
        } else if (updateExpressions.size() > 1) {
            resultStatus = new StatusInfo(IStatus.WARNING, FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning);
        }
        for (final Iterator<Expression> outer = getForStatement().initializers().iterator(); outer.hasNext(); ) {
            final Expression initializer = outer.next();
            if (initializer instanceof VariableDeclarationExpression) {
                final VariableDeclarationExpression declaration = (VariableDeclarationExpression) initializer;
                List<VariableDeclarationFragment> fragments = declaration.fragments();
                if (fragments.size() != 1) {
                    //$NON-NLS-1$
                    return new StatusInfo(IStatus.ERROR, "");
                } else {
                    final VariableDeclarationFragment fragment = fragments.get(0);
                    fragment.accept(new ASTVisitor() {

                        @Override
                        public final boolean visit(final MethodInvocation node) {
                            final IMethodBinding binding = node.resolveMethodBinding();
                            if (binding != null) {
                                final ITypeBinding type = binding.getReturnType();
                                if (type != null) {
                                    final String qualified = type.getQualifiedName();
                                    if (qualified.startsWith("java.util.Enumeration<") || qualified.startsWith("java.util.Iterator<")) {
                                        //$NON-NLS-1$ //$NON-NLS-2$
                                        final Expression qualifier = node.getExpression();
                                        if (qualifier != null) {
                                            final ITypeBinding resolved = qualifier.resolveTypeBinding();
                                            if (resolved != null) {
                                                //$NON-NLS-1$
                                                final ITypeBinding iterable = getSuperType(resolved, "java.lang.Iterable");
                                                if (iterable != null) {
                                                    fExpression = qualifier;
                                                    fIterable = resolved;
                                                }
                                            }
                                        } else {
                                            final ITypeBinding declaring = binding.getDeclaringClass();
                                            if (declaring != null) {
                                                //$NON-NLS-1$
                                                final ITypeBinding superBinding = getSuperType(declaring, "java.lang.Iterable");
                                                if (superBinding != null) {
                                                    fIterable = superBinding;
                                                    fThis = true;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            return true;
                        }

                        @Override
                        public final boolean visit(final VariableDeclarationFragment node) {
                            final IVariableBinding binding = node.resolveBinding();
                            if (binding != null) {
                                final ITypeBinding type = binding.getType();
                                if (type != null) {
                                    //$NON-NLS-1$
                                    ITypeBinding iterator = getSuperType(type, "java.util.Iterator");
                                    if (iterator != null)
                                        fIteratorVariable = binding;
                                    else {
                                        //$NON-NLS-1$
                                        iterator = getSuperType(type, "java.util.Enumeration");
                                        if (iterator != null)
                                            fIteratorVariable = binding;
                                    }
                                }
                            }
                            return true;
                        }
                    });
                }
            }
        }
        final Statement statement = getForStatement().getBody();
        final boolean[] otherInvocationThenNext = new boolean[] { false };
        final int[] nextInvocationCount = new int[] { 0 };
        if (statement != null && fIteratorVariable != null) {
            final ITypeBinding elementType = getElementType(fIteratorVariable.getType());
            statement.accept(new ASTVisitor() {

                @Override
                public boolean visit(SimpleName node) {
                    IBinding nodeBinding = node.resolveBinding();
                    if (fElementVariable != null && fElementVariable.equals(nodeBinding)) {
                        fMakeFinal = false;
                    }
                    if (nodeBinding == fIteratorVariable) {
                        if (node.getLocationInParent() == MethodInvocation.EXPRESSION_PROPERTY) {
                            MethodInvocation invocation = (MethodInvocation) node.getParent();
                            String name = invocation.getName().getIdentifier();
                            if (name.equals("next") || name.equals("nextElement")) {
                                //$NON-NLS-1$ //$NON-NLS-2$
                                nextInvocationCount[0]++;
                                Expression left = null;
                                if (invocation.getLocationInParent() == Assignment.RIGHT_HAND_SIDE_PROPERTY) {
                                    left = ((Assignment) invocation.getParent()).getLeftHandSide();
                                } else if (invocation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
                                    left = ((VariableDeclarationFragment) invocation.getParent()).getName();
                                }
                                return visitElementVariable(left);
                            }
                        }
                        otherInvocationThenNext[0] = true;
                    }
                    return true;
                }

                private boolean visitElementVariable(final Expression node) {
                    if (node != null) {
                        final ITypeBinding binding = node.resolveTypeBinding();
                        if (binding != null && elementType.equals(binding)) {
                            if (node instanceof Name) {
                                final Name name = (Name) node;
                                final IBinding result = name.resolveBinding();
                                if (result != null) {
                                    fOccurrences.add(node);
                                    fElementVariable = result;
                                    return false;
                                }
                            } else if (node instanceof FieldAccess) {
                                final FieldAccess access = (FieldAccess) node;
                                final IBinding result = access.resolveFieldBinding();
                                if (result != null) {
                                    fOccurrences.add(node);
                                    fElementVariable = result;
                                    return false;
                                }
                            }
                        }
                    }
                    return true;
                }
            });
            if (otherInvocationThenNext[0])
                return ERROR_STATUS;
            if (nextInvocationCount[0] > 1)
                return ERROR_STATUS;
            if (fElementVariable != null) {
                statement.accept(new ASTVisitor() {

                    @Override
                    public final boolean visit(final VariableDeclarationFragment node) {
                        if (node.getInitializer() instanceof NullLiteral) {
                            SimpleName name = node.getName();
                            if (elementType.equals(name.resolveTypeBinding()) && fElementVariable.equals(name.resolveBinding())) {
                                fOccurrences.add(name);
                            }
                        }
                        return true;
                    }
                });
            }
        }
        final ASTNode root = getForStatement().getRoot();
        if (root != null) {
            root.accept(new ASTVisitor() {

                @Override
                public final boolean visit(final ForStatement node) {
                    return false;
                }

                @Override
                public final boolean visit(final SimpleName node) {
                    final IBinding binding = node.resolveBinding();
                    if (binding != null && binding.equals(fElementVariable))
                        fAssigned = true;
                    return false;
                }
            });
        }
    }
    if ((fExpression != null || fThis) && fIterable != null && fIteratorVariable != null && !fAssigned) {
        return resultStatus;
    } else {
        return ERROR_STATUS;
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) IStatus(org.eclipse.core.runtime.IStatus) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) 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) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) Statement(org.eclipse.jdt.core.dom.Statement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) StatusInfo(org.eclipse.jdt.internal.ui.dialogs.StatusInfo) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) NullLiteral(org.eclipse.jdt.core.dom.NullLiteral)

Example 25 with FieldAccess

use of org.eclipse.jdt.core.dom.FieldAccess in project che by eclipse.

the class InlineConstantRefactoring method findConstantNameNode.

private Name findConstantNameNode() {
    ASTNode node = NodeFinder.perform(fSelectionCuRewrite.getRoot(), fSelectionStart, fSelectionLength);
    if (node == null)
        return null;
    if (node instanceof FieldAccess)
        node = ((FieldAccess) node).getName();
    if (!(node instanceof Name))
        return null;
    Name name = (Name) node;
    IBinding binding = name.resolveBinding();
    if (!(binding instanceof IVariableBinding))
        return null;
    IVariableBinding variableBinding = (IVariableBinding) binding;
    if (!variableBinding.isField() || variableBinding.isEnumConstant())
        return null;
    int modifiers = binding.getModifiers();
    if (!(Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)))
        return null;
    return name;
}
Also used : IBinding(org.eclipse.jdt.core.dom.IBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name)

Aggregations

FieldAccess (org.eclipse.jdt.core.dom.FieldAccess)30 SimpleName (org.eclipse.jdt.core.dom.SimpleName)20 Expression (org.eclipse.jdt.core.dom.Expression)18 ASTNode (org.eclipse.jdt.core.dom.ASTNode)17 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)14 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)12 IBinding (org.eclipse.jdt.core.dom.IBinding)11 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)11 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)10 Name (org.eclipse.jdt.core.dom.Name)10 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)8 AST (org.eclipse.jdt.core.dom.AST)7 Assignment (org.eclipse.jdt.core.dom.Assignment)7 Block (org.eclipse.jdt.core.dom.Block)7 SuperFieldAccess (org.eclipse.jdt.core.dom.SuperFieldAccess)7 CastExpression (org.eclipse.jdt.core.dom.CastExpression)6 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)6 ArrayList (java.util.ArrayList)5