Search in sources :

Example 6 with ArrayAccess

use of org.eclipse.jdt.core.dom.ArrayAccess in project xtext-xtend by eclipse.

the class JavaASTFlattener method visit.

@Override
public boolean visit(final PrefixExpression node) {
    final Expression operand = node.getOperand();
    PrefixExpression.Operator _operator = node.getOperator();
    boolean _matched = false;
    if (Objects.equal(_operator, PrefixExpression.Operator.DECREMENT)) {
        _matched = true;
    }
    if (!_matched) {
        if (Objects.equal(_operator, PrefixExpression.Operator.INCREMENT)) {
            _matched = true;
        }
    }
    if (_matched) {
        if ((operand instanceof ArrayAccess)) {
            final String arrayName = this.computeArrayName(((ArrayAccess) operand));
            StringConcatenation _builder = new StringConcatenation();
            _builder.append("_tPreInx_");
            _builder.append(arrayName);
            final String idxName = _builder.toString();
            String op = "-";
            PrefixExpression.Operator _operator_1 = node.getOperator();
            boolean _equals = Objects.equal(_operator_1, PrefixExpression.Operator.INCREMENT);
            if (_equals) {
                op = "+";
            }
            StringConcatenation _builder_1 = new StringConcatenation();
            _builder_1.append("{val ");
            _builder_1.append(idxName);
            _builder_1.append("=");
            this.appendToBuffer(_builder_1.toString());
            ((ArrayAccess) operand).getIndex().accept(this);
            StringConcatenation _builder_2 = new StringConcatenation();
            _builder_2.append(" ");
            _builder_2.append("val ");
            _builder_2.append(idxName, " ");
            _builder_2.append("_res=");
            _builder_2.append(arrayName, " ");
            _builder_2.append(".get(");
            _builder_2.append(idxName, " ");
            _builder_2.append(")");
            _builder_2.append(op, " ");
            _builder_2.append("1");
            this.appendToBuffer(_builder_2.toString());
            StringConcatenation _builder_3 = new StringConcatenation();
            _builder_3.append(" ");
            _builder_3.append(arrayName, " ");
            _builder_3.append(".set(");
            _builder_3.append(idxName, " ");
            _builder_3.append(", ");
            _builder_3.append(idxName, " ");
            _builder_3.append("_res)  ");
            _builder_3.append(idxName, " ");
            _builder_3.append("_res}");
            this.appendToBuffer(_builder_3.toString());
            return false;
        } else {
            final AST dummyAST = AST.newAST(node.getAST().apiLevel());
            final Assignment assigment = dummyAST.newAssignment();
            final InfixExpression infixOp = dummyAST.newInfixExpression();
            ASTNode _copySubtree = ASTNode.copySubtree(dummyAST, operand);
            infixOp.setLeftOperand(((Expression) _copySubtree));
            PrefixExpression.Operator _operator_2 = node.getOperator();
            boolean _equals_1 = Objects.equal(_operator_2, PrefixExpression.Operator.DECREMENT);
            if (_equals_1) {
                infixOp.setOperator(InfixExpression.Operator.MINUS);
            } else {
                infixOp.setOperator(InfixExpression.Operator.PLUS);
            }
            infixOp.setRightOperand(dummyAST.newNumberLiteral("1"));
            ASTNode _copySubtree_1 = ASTNode.copySubtree(dummyAST, operand);
            final Expression leftSide = ((Expression) _copySubtree_1);
            assigment.setLeftHandSide(leftSide);
            assigment.setRightHandSide(infixOp);
            this.appendToBuffer("{");
            Type type = null;
            if ((operand instanceof SimpleName)) {
                type = this._aSTFlattenerUtils.findDeclaredType(((SimpleName) operand));
            }
            this.handleAssignment(assigment, leftSide, type);
            this.appendToBuffer("}");
            return false;
        }
    }
    if (!_matched) {
        if (Objects.equal(_operator, PrefixExpression.Operator.COMPLEMENT)) {
            _matched = true;
            node.getOperand().accept(this);
            this.appendToBuffer(".bitwiseNot");
        }
    }
    if (!_matched) {
        {
            this.appendToBuffer(node.getOperator().toString());
            node.getOperand().accept(this);
        }
    }
    return false;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Assignment(org.eclipse.jdt.core.dom.Assignment) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) WildcardType(org.eclipse.jdt.core.dom.WildcardType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) StringConcatenation(org.eclipse.xtend2.lib.StringConcatenation) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode)

Example 7 with ArrayAccess

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

the class CFGBuilder method addVariableAccess.

/**
 * @return whether the current variable access can throw an exception.
 */
private boolean addVariableAccess(final CFGBasicBlock basicBlock, final Expression node, final int flags, final ThrowerBlocks throwers) {
    if (node == null) {
        return false;
    }
    switch(node.getNodeType()) {
        case ASTNode.ARRAY_ACCESS:
            ArrayAccess aa = (ArrayAccess) node;
            addVariableAccess(basicBlock, aa.getArray(), flags, throwers);
            addVariableAccess(basicBlock, aa.getIndex(), flags, throwers);
            throwers.addThrow(aa, newException(node, ArrayIndexOutOfBoundsException.class.getCanonicalName()));
            return true;
        case ASTNode.ARRAY_CREATION:
            ArrayCreation ac = (ArrayCreation) node;
            boolean acMightThrow1 = addVariableAccess(basicBlock, ac.getInitializer(), flags, throwers);
            boolean acMightThrow2 = addVariableAccesses(basicBlock, ac.dimensions(), flags, throwers);
            return acMightThrow1 || acMightThrow2;
        case ASTNode.ARRAY_INITIALIZER:
            ArrayInitializer ai = (ArrayInitializer) node;
            return addVariableAccesses(basicBlock, ai.expressions(), flags, throwers);
        case ASTNode.ASSIGNMENT:
            Assignment a = (Assignment) node;
            boolean aMightThrow1 = addVariableAccess(basicBlock, a.getLeftHandSide(), VariableAccess.WRITE, throwers);
            boolean aMightThrow2 = addVariableAccess(basicBlock, a.getRightHandSide(), VariableAccess.READ, throwers);
            return aMightThrow1 || aMightThrow2;
        case ASTNode.BOOLEAN_LITERAL:
        case ASTNode.CHARACTER_LITERAL:
        case ASTNode.NULL_LITERAL:
        case ASTNode.NUMBER_LITERAL:
        case ASTNode.STRING_LITERAL:
        case ASTNode.TYPE_LITERAL:
            // Nothing to do
            return false;
        case ASTNode.CAST_EXPRESSION:
            CastExpression cae = (CastExpression) node;
            return addVariableAccess(basicBlock, cae.getExpression(), flags, throwers);
        case ASTNode.CLASS_INSTANCE_CREATION:
            ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) node;
            addVariableAccess(basicBlock, classInstanceCreation.getExpression(), flags, throwers);
            addVariableAccesses(basicBlock, classInstanceCreation.arguments(), flags, throwers);
            IMethodBinding cicBinding = classInstanceCreation.resolveConstructorBinding();
            if (cicBinding != null) {
                ITypeBinding[] declaredThrows = cicBinding.getExceptionTypes();
                throwers.addThrow(classInstanceCreation, declaredThrows);
                return declaredThrows.length > 0;
            }
            return false;
        case ASTNode.CONDITIONAL_EXPRESSION:
            ConditionalExpression coe = (ConditionalExpression) node;
            boolean mightThrow1 = addVariableAccess(basicBlock, coe.getExpression(), flags, throwers);
            boolean mightThrow2 = addVariableAccess(basicBlock, coe.getThenExpression(), flags, throwers);
            boolean mightThrow3 = addVariableAccess(basicBlock, coe.getElseExpression(), flags, throwers);
            return mightThrow1 || mightThrow2 || mightThrow3;
        case ASTNode.FIELD_ACCESS:
            FieldAccess fa = (FieldAccess) node;
            boolean mightThrow = addVariableAccess(basicBlock, fa.getExpression(), flags, throwers);
            basicBlock.addVariableAccess(new VariableAccess(fa, flags));
            if (is(flags, VariableAccess.READ)) {
                throwers.addThrow(fa, newException(node, NullPointerException.class.getCanonicalName()));
                mightThrow = true;
            }
            return mightThrow;
        case ASTNode.INFIX_EXPRESSION:
            InfixExpression infixExpression = (InfixExpression) node;
            boolean ieMightThrow1 = addVariableAccess(basicBlock, infixExpression.getLeftOperand(), flags, throwers);
            boolean ieMightThrow2 = addVariableAccess(basicBlock, infixExpression.getRightOperand(), flags, throwers);
            return ieMightThrow1 || ieMightThrow2;
        case ASTNode.INSTANCEOF_EXPRESSION:
            InstanceofExpression ioe = (InstanceofExpression) node;
            return addVariableAccess(basicBlock, ioe.getLeftOperand(), flags, throwers);
        case ASTNode.METHOD_INVOCATION:
            MethodInvocation methodInvocation = (MethodInvocation) node;
            addVariableAccess(basicBlock, methodInvocation.getExpression(), flags, throwers);
            addVariableAccesses(basicBlock, methodInvocation.arguments(), flags, throwers);
            IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
            if (methodBinding != null) {
                ITypeBinding[] declaredThrows = methodBinding.getExceptionTypes();
                throwers.addThrow(methodInvocation, declaredThrows);
                return declaredThrows.length > 0;
            }
            return false;
        case ASTNode.SIMPLE_NAME:
            SimpleName sn = (SimpleName) node;
            basicBlock.addVariableAccess(new VariableAccess(sn, flags));
            if (is(flags, VariableAccess.READ)) {
                throwers.addThrow(sn, newException(node, NullPointerException.class.getCanonicalName()));
                return true;
            }
            return false;
        case ASTNode.QUALIFIED_NAME:
            QualifiedName qn = (QualifiedName) node;
            basicBlock.addVariableAccess(new VariableAccess(qn, flags));
            throwers.addThrow(qn, newException(node, NullPointerException.class.getCanonicalName()));
            return true;
        case ASTNode.PARENTHESIZED_EXPRESSION:
            ParenthesizedExpression pe = (ParenthesizedExpression) node;
            return addVariableAccess(basicBlock, pe.getExpression(), flags, throwers);
        case ASTNode.POSTFIX_EXPRESSION:
            PostfixExpression poe = (PostfixExpression) node;
            return addVariableAccess(basicBlock, poe.getOperand(), flags, throwers);
        case ASTNode.PREFIX_EXPRESSION:
            PrefixExpression pre = (PrefixExpression) node;
            return addVariableAccess(basicBlock, pre.getOperand(), flags, throwers);
        case ASTNode.SUPER_FIELD_ACCESS:
            SuperFieldAccess sfa = (SuperFieldAccess) node;
            boolean sfaMightThrow1 = addVariableAccess(basicBlock, sfa.getQualifier(), flags, throwers);
            boolean sfaMightThrow2 = addVariableAccess(basicBlock, sfa.getName(), flags, throwers);
            return sfaMightThrow1 || sfaMightThrow2;
        case ASTNode.SUPER_METHOD_INVOCATION:
            SuperMethodInvocation smi = (SuperMethodInvocation) node;
            addVariableAccess(basicBlock, smi.getQualifier(), flags, throwers);
            addVariableAccess(basicBlock, smi.getName(), flags, throwers);
            IMethodBinding sMethodBinding = smi.resolveMethodBinding();
            if (sMethodBinding != null) {
                ITypeBinding[] declaredThrows = sMethodBinding.getExceptionTypes();
                throwers.addThrow(smi, declaredThrows);
                return declaredThrows.length > 0;
            }
            return false;
        case ASTNode.THIS_EXPRESSION:
            ThisExpression te = (ThisExpression) node;
            // TODO JNR remember use of "this" here
            return addVariableAccess(basicBlock, te.getQualifier(), flags, throwers);
        case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
            return addDeclarations(basicBlock, (VariableDeclarationExpression) node, throwers);
        default:
            throw new NotImplementedException(node);
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) NotImplementedException(org.autorefactor.util.NotImplementedException) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) Assignment(org.eclipse.jdt.core.dom.Assignment) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Example 8 with ArrayAccess

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

the class GenerateForLoopAssistProposal method getForBodyAssignment.

/**
	 * Creates an {@link Assignment} as first expression appearing in a <code>for</code> loop's
	 * body. This Assignment declares a local variable and initializes it using the array's current
	 * element identified by the loop index.
	 * 
	 * @param rewrite the current {@link ASTRewrite} instance
	 * @param loopVariableName the name of the index variable in String representation
	 * @return a completed {@link Assignment} containing the mentioned declaration and
	 *         initialization
	 */
private Assignment getForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
    AST ast = rewrite.getAST();
    ITypeBinding loopOverType = extractElementType(ast);
    Assignment assignResolvedVariable = ast.newAssignment();
    // left hand side
    SimpleName resolvedVariableName = resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
    VariableDeclarationFragment resolvedVariableDeclarationFragment = ast.newVariableDeclarationFragment();
    resolvedVariableDeclarationFragment.setName(resolvedVariableName);
    VariableDeclarationExpression resolvedVariableDeclaration = ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
    resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
    assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);
    // right hand side
    ArrayAccess access = ast.newArrayAccess();
    access.setArray((Expression) rewrite.createCopyTarget(fCurrentExpression));
    SimpleName indexName = ast.newSimpleName(loopVariableName.getIdentifier());
    addLinkedPosition(rewrite.track(indexName), LinkedPositionGroup.NO_STOP, indexName.getIdentifier());
    access.setIndex(indexName);
    assignResolvedVariable.setRightHandSide(access);
    assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);
    return assignResolvedVariable;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression)

Example 9 with ArrayAccess

use of org.eclipse.jdt.core.dom.ArrayAccess in project processing by processing.

the class CompletionGenerator method resolveExpression3rdParty.

/**
   * Finds the type of the expression in foo.bar().a().b, this would give me the
   * type of b if it exists in return type of a(). If noCompare is true,
   * it'll return type of a()
   * @param nearestNode
   * @param astNode
   * @return
   */
public static ClassMember resolveExpression3rdParty(PreprocessedSketch ps, ASTNode nearestNode, ASTNode astNode, boolean noCompare) {
    log("Resolve 3rdParty expr-- " + getNodeAsString(astNode) + " nearest node " + getNodeAsString(nearestNode));
    if (astNode == null)
        return null;
    ClassMember scopeParent;
    SimpleType stp;
    if (astNode instanceof SimpleName) {
        ASTNode decl = findDeclaration2(((SimpleName) astNode), nearestNode);
        if (decl != null) {
            // see if locally defined
            log(getNodeAsString(astNode) + " found decl -> " + getNodeAsString(decl));
            {
                if (decl.getNodeType() == ASTNode.TYPE_DECLARATION) {
                    TypeDeclaration td = (TypeDeclaration) decl;
                    return new ClassMember(ps, td);
                }
            }
            {
                // Handle "array." x "array[1]."
                Type type = extracTypeInfo2(decl);
                if (type != null && type.isArrayType() && astNode.getParent().getNodeType() != ASTNode.ARRAY_ACCESS) {
                    // No array access, we want members of the array itself
                    Type elementType = ((ArrayType) type).getElementType();
                    // Get name of the element class
                    String name = "";
                    if (elementType.isSimpleType()) {
                        Class<?> c = findClassIfExists(ps, elementType.toString());
                        if (c != null)
                            name = c.getName();
                    } else if (elementType.isPrimitiveType()) {
                        name = ((PrimitiveType) elementType).getPrimitiveTypeCode().toString();
                    }
                    // Convert element class to array class
                    Class<?> arrayClass = getArrayClass(name, ps.classLoader);
                    return arrayClass == null ? null : new ClassMember(arrayClass);
                }
            }
            return new ClassMember(ps, extracTypeInfo(decl));
        } else {
            // or in a predefined class?
            Class<?> tehClass = findClassIfExists(ps, astNode.toString());
            if (tehClass != null) {
                return new ClassMember(tehClass);
            }
        }
        astNode = astNode.getParent();
    }
    switch(astNode.getNodeType()) {
        //TODO: Notice the redundancy in the 3 cases, you can simplify things even more.
        case ASTNode.FIELD_ACCESS:
            FieldAccess fa = (FieldAccess) astNode;
            if (fa.getExpression() == null) {
                // TODO: Check for existence of 'new' keyword. Could be a ClassInstanceCreation
                // Local code or belongs to super class
                log("FA,Not implemented.");
                return null;
            } else {
                if (fa.getExpression() instanceof SimpleName) {
                    stp = extracTypeInfo(findDeclaration2((SimpleName) fa.getExpression(), nearestNode));
                    if (stp == null) {
                        /*The type wasn't found in local code, so it might be something like
             * log(), or maybe belonging to super class, etc.
             */
                        Class<?> tehClass = findClassIfExists(ps, fa.getExpression().toString());
                        if (tehClass != null) {
                            // so look for method in this class.
                            return definedIn3rdPartyClass(ps, new ClassMember(tehClass), fa.getName().toString());
                        }
                        log("FA resolve 3rd par, Can't resolve " + fa.getExpression());
                        return null;
                    }
                    log("FA, SN Type " + getNodeAsString(stp));
                    scopeParent = definedIn3rdPartyClass(ps, stp.getName().toString(), "THIS");
                } else {
                    scopeParent = resolveExpression3rdParty(ps, nearestNode, fa.getExpression(), noCompare);
                }
                log("FA, ScopeParent " + scopeParent);
                return definedIn3rdPartyClass(ps, scopeParent, fa.getName().toString());
            }
        case ASTNode.METHOD_INVOCATION:
            MethodInvocation mi = (MethodInvocation) astNode;
            ASTNode temp = findDeclaration2(mi.getName(), nearestNode);
            if (temp instanceof MethodDeclaration) {
                // method is locally defined
                log(mi.getName() + " was found locally," + getNodeAsString(extracTypeInfo(temp)));
                {
                    // Handle "array." x "array[1]."
                    Type type = extracTypeInfo2(temp);
                    if (type != null && type.isArrayType() && astNode.getParent().getNodeType() != ASTNode.ARRAY_ACCESS) {
                        // No array access, we want members of the array itself
                        Type elementType = ((ArrayType) type).getElementType();
                        // Get name of the element class
                        String name = "";
                        if (elementType.isSimpleType()) {
                            Class<?> c = findClassIfExists(ps, elementType.toString());
                            if (c != null)
                                name = c.getName();
                        } else if (elementType.isPrimitiveType()) {
                            name = ((PrimitiveType) elementType).getPrimitiveTypeCode().toString();
                        }
                        // Convert element class to array class
                        Class<?> arrayClass = getArrayClass(name, ps.classLoader);
                        return arrayClass == null ? null : new ClassMember(arrayClass);
                    }
                }
                return new ClassMember(ps, extracTypeInfo(temp));
            }
            if (mi.getExpression() == null) {
                //        if()
                //Local code or belongs to super class
                log("MI,Not implemented.");
                return null;
            } else {
                if (mi.getExpression() instanceof SimpleName) {
                    ASTNode decl = findDeclaration2((SimpleName) mi.getExpression(), nearestNode);
                    if (decl != null) {
                        if (decl.getNodeType() == ASTNode.TYPE_DECLARATION) {
                            TypeDeclaration td = (TypeDeclaration) decl;
                            return new ClassMember(ps, td);
                        }
                        stp = extracTypeInfo(decl);
                        if (stp == null) {
                            /*The type wasn't found in local code, so it might be something like
             * System.console()., or maybe belonging to super class, etc.
             */
                            Class<?> tehClass = findClassIfExists(ps, mi.getExpression().toString());
                            if (tehClass != null) {
                                // so look for method in this class.
                                return definedIn3rdPartyClass(ps, new ClassMember(tehClass), mi.getName().toString());
                            }
                            log("MI resolve 3rd par, Can't resolve " + mi.getExpression());
                            return null;
                        }
                        log("MI, SN Type " + getNodeAsString(stp));
                        ASTNode typeDec = findDeclaration2(stp.getName(), nearestNode);
                        if (typeDec == null) {
                            log(stp.getName() + " couldn't be found locally..");
                            Class<?> tehClass = findClassIfExists(ps, stp.getName().toString());
                            if (tehClass != null) {
                                // so look for method in this class.
                                return definedIn3rdPartyClass(ps, new ClassMember(tehClass), mi.getName().toString());
                            }
                        //return new ClassMember(findClassIfExists(stp.getName().toString()));
                        }
                        //scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
                        return definedIn3rdPartyClass(ps, new ClassMember(ps, typeDec), mi.getName().toString());
                    }
                } else {
                    log("MI EXP.." + getNodeAsString(mi.getExpression()));
                    //          return null;
                    scopeParent = resolveExpression3rdParty(ps, nearestNode, mi.getExpression(), noCompare);
                    log("MI, ScopeParent " + scopeParent);
                    return definedIn3rdPartyClass(ps, scopeParent, mi.getName().toString());
                }
            }
            break;
        case ASTNode.QUALIFIED_NAME:
            QualifiedName qn = (QualifiedName) astNode;
            ASTNode temp2 = findDeclaration2(qn.getName(), nearestNode);
            if (temp2 instanceof FieldDeclaration) {
                // field is locally defined
                log(qn.getName() + " was found locally," + getNodeAsString(extracTypeInfo(temp2)));
                return new ClassMember(ps, extracTypeInfo(temp2));
            }
            if (qn.getQualifier() == null) {
                log("QN,Not implemented.");
                return null;
            } else {
                if (qn.getQualifier() instanceof SimpleName) {
                    stp = extracTypeInfo(findDeclaration2(qn.getQualifier(), nearestNode));
                    if (stp == null) {
                        /*The type wasn't found in local code, so it might be something like
             * log(), or maybe belonging to super class, etc.
             */
                        Class<?> tehClass = findClassIfExists(ps, qn.getQualifier().toString());
                        if (tehClass != null) {
                            // note how similar thing is called on line 690. Check check.
                            return definedIn3rdPartyClass(ps, new ClassMember(tehClass), qn.getName().toString());
                        }
                        log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
                        return null;
                    }
                    log("QN, SN Local Type " + getNodeAsString(stp));
                    //scopeParent = definedIn3rdPartyClass(stp.getName().toString(), "THIS");
                    ASTNode typeDec = findDeclaration2(stp.getName(), nearestNode);
                    if (typeDec == null) {
                        log(stp.getName() + " couldn't be found locally..");
                        Class<?> tehClass = findClassIfExists(ps, stp.getName().toString());
                        if (tehClass != null) {
                            // note how similar thing is called on line 690. Check check.
                            return definedIn3rdPartyClass(ps, new ClassMember(tehClass), qn.getName().toString());
                        }
                        log("QN resolve 3rd par, Can't resolve " + qn.getQualifier());
                        return null;
                    }
                    return definedIn3rdPartyClass(ps, new ClassMember(ps, typeDec), qn.getName().toString());
                } else {
                    scopeParent = resolveExpression3rdParty(ps, nearestNode, qn.getQualifier(), noCompare);
                    log("QN, ScopeParent " + scopeParent);
                    return definedIn3rdPartyClass(ps, scopeParent, qn.getName().toString());
                }
            }
        case ASTNode.ARRAY_ACCESS:
            ArrayAccess arac = (ArrayAccess) astNode;
            return resolveExpression3rdParty(ps, nearestNode, arac.getArray(), noCompare);
        default:
            log("Unaccounted type " + getNodeAsString(astNode));
            break;
    }
    return null;
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) SimpleType(org.eclipse.jdt.core.dom.SimpleType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) ASTNode(org.eclipse.jdt.core.dom.ASTNode) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration)

Example 10 with ArrayAccess

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

the class AllInOneMethodRatherThanLoopRefactoring method visit.

@Override
public boolean visit(ForStatement node) {
    final ForLoopContent loopContent = iterateOverContainer(node);
    final List<Statement> stmts = asList(node.getBody());
    if (loopContent != null && loopContent.getLoopVariable() != null && stmts.size() == 1) {
        final SimpleName loopVariable = (SimpleName) loopContent.getLoopVariable();
        final IVariableBinding loopVariableName = (IVariableBinding) loopVariable.resolveBinding();
        // As we replace only one, there should be no more than one occurrence
        if (getVariableUseCount(loopVariableName, node.getBody()) == 1) {
            final MethodInvocation mi = asExpression(stmts.get(0), MethodInvocation.class);
            switch(loopContent.getContainerType()) {
                case COLLECTION:
                    if (isMethod(mi, "java.util.Collection", "add", "java.lang.Object")) {
                        return maybeReplaceWithCollectionMethod(node, loopContent, "addAll", mi);
                    } else if (isMethod(mi, "java.util.Collection", "remove", "java.lang.Object")) {
                        return maybeReplaceWithCollectionMethod(node, loopContent, "removeAll", mi);
                    }
                    break;
                case ARRAY:
                    if (isMethod(mi, "java.util.Collection", "add", "java.lang.Object") && areTypeCompatible(mi.getExpression(), loopContent.getContainerVariable())) {
                        final Expression addArg0 = arg0(mi);
                        final ArrayAccess aa = as(addArg0, ArrayAccess.class);
                        if (isSameVariable(loopContent, aa)) {
                            replaceWithCollectionsAddAll(node, loopContent.getContainerVariable(), mi);
                            return DO_NOT_VISIT_SUBTREE;
                        }
                    }
                    break;
            }
        }
    }
    return VISIT_SUBTREE;
}
Also used : ForLoopContent(org.autorefactor.refactoring.ForLoopHelper.ForLoopContent) ArrayAccess(org.eclipse.jdt.core.dom.ArrayAccess) Expression(org.eclipse.jdt.core.dom.Expression) ASTHelper.asExpression(org.autorefactor.refactoring.ASTHelper.asExpression) Statement(org.eclipse.jdt.core.dom.Statement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding)

Aggregations

ArrayAccess (org.eclipse.jdt.core.dom.ArrayAccess)19 Expression (org.eclipse.jdt.core.dom.Expression)11 SimpleName (org.eclipse.jdt.core.dom.SimpleName)11 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)10 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)10 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)9 Assignment (org.eclipse.jdt.core.dom.Assignment)8 CastExpression (org.eclipse.jdt.core.dom.CastExpression)8 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)6 ArrayType (org.eclipse.jdt.core.dom.ArrayType)6 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)6 PostfixExpression (org.eclipse.jdt.core.dom.PostfixExpression)6 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)6 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)5 InstanceofExpression (org.eclipse.jdt.core.dom.InstanceofExpression)5 ParameterizedType (org.eclipse.jdt.core.dom.ParameterizedType)5 AST (org.eclipse.jdt.core.dom.AST)4