Example usage for org.eclipse.jdt.core.dom MethodInvocation getParent

List of usage examples for org.eclipse.jdt.core.dom MethodInvocation getParent

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom MethodInvocation getParent.

Prototype

public final ASTNode getParent() 

Source Link

Document

Returns this node's parent node, or null if this is the root node.

Usage

From source file:ch.acanda.eclipse.pmd.java.resolution.stringandstringbuffer.StringToStringQuickFix.java

License:Open Source License

/**
 * Removes the <code>.toString()</code> from <code>"foo".toString()</code> if the expression is only a part of an
 * statement. Removes the expression completely if it is the whole statement.
 *//*from   w w w .  j a  v a2  s. c  o  m*/
@Override
protected boolean apply(final MethodInvocation node) {
    if (node.getParent() instanceof ExpressionStatement) {
        // remove "foo".toString() completely if it is a statement as "foo" alone is not a valid statement
        node.getParent().delete();
    } else {
        // remove .toString() if "foo".toString() is only part of a statement
        // e.g. return "foo".toString(); -> return "foo";
        replace(node, copy(node.getExpression()));
    }
    return true;
}

From source file:com.bsiag.eclipse.jdt.java.formatter.linewrap.WrapPreparator.java

License:Open Source License

@Override
public boolean visit(MethodInvocation node) {
    handleArguments(node.arguments(), this.options.alignment_for_arguments_in_method_invocation);

    boolean isInvocationChainRoot = !(node.getParent() instanceof MethodInvocation)
            || node.getLocationInParent() != MethodInvocation.EXPRESSION_PROPERTY;
    if (isInvocationChainRoot) {
        Expression expression = node;
        MethodInvocation invocation = node;
        while (expression instanceof MethodInvocation) {
            invocation = (MethodInvocation) expression;
            expression = invocation.getExpression();
            if (expression != null)
                this.wrapIndexes.add(this.tm.firstIndexBefore(invocation.getName(), TokenNameDOT));
        }//from   w  ww  .  j  a  va 2  s .  co m
        Collections.reverse(this.wrapIndexes);
        this.wrapParentIndex = (expression != null) ? this.tm.lastIndexIn(expression, -1)
                : this.tm.lastIndexIn(invocation, -1);
        this.wrapGroupEnd = this.tm.firstIndexIn(node.getName(), -1);
        handleWrap(this.options.alignment_for_selector_in_method_invocation);
    }
    return true;
}

From source file:com.dnw.depmap.ast.MethodInvocationVisitor.java

License:Open Source License

/**
 * The method will be called when a <code>MethodInvocation</code> node is met.
 * //  w  w w  . j a  v a2  s. c om
 * @author manbaum
 * @since Sep 29, 2014
 * @param node the <code>MethodInvocation</code> node.
 * @param context the visiting context.
 * @see com.dnw.plugin.ast.IVisitor#visit(org.eclipse.jdt.core.dom.ASTNode,
 *      com.dnw.plugin.ast.VisitContext)
 */
@Override
public void visit(MethodInvocation node, VisitContext context) {
    Activator.console.println(" -- Visit MethodInvocation: " + node.toString());
    // find the containing method of this method invocation.
    // TODO: what if a method invocation not happens in a method? i.e. during class initialization.
    ASTNode p = node.getParent();
    while (p != null) {
        if (p instanceof MethodDeclaration) {
            break;
        } else {
            p = p.getParent();
        }
    }
    MethodDeclaration decl = (MethodDeclaration) p;
    Activator.console.println("  . Method is called from: " + make(decl));
    if (p == null)
        return;

    IMethodBinding from = decl.resolveBinding();
    Activator.console.println(AstUtil.infoOf(context, decl, from));
    IMethodBinding to = node.resolveMethodBinding();
    Activator.console.println(AstUtil.infoOf(context, node, to));
    // call DAO to generate the method node and its related relationships.
    Activator.neo().createInvocation(from, to, args(node.arguments()));
}

From source file:com.google.devtools.j2cpp.gen.CppStatementGenerator.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  w ww . j a v  a 2  s.  com*/
public boolean visit(MethodInvocation node) {
    invocations.push(node);
    String methodName = NameTable.getName(node.getName());
    IMethodBinding binding = Types.getMethodBinding(node);
    assert binding != null;
    // Object receiving the message, or null if it's a method in this class.
    Expression receiver = node.getExpression();
    ITypeBinding receiverType = receiver != null ? Types.getTypeBinding(receiver) : null;
    buffer.append(' ');
    if ((receiverType != null) && (receiver instanceof SimpleName)) {
        buffer.append(((SimpleName) receiver).getIdentifier()).append('.');
    }
    if (Types.isFunction(binding)) {
        buffer.append(methodName);
        buffer.append("(");
        for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext();) {
            it.next().accept(this);
            if (it.hasNext()) {
                buffer.append(", ");
            }
        }
        buffer.append(")");
    } else {
        boolean castAttempted = false;
        boolean castReturnValue = false;
        if (node.getParent() instanceof Expression || node.getParent() instanceof ReturnStatement
                || node.getParent() instanceof VariableDeclarationFragment) {
            ITypeBinding actualType = binding.getMethodDeclaration().getReturnType();
            if (actualType.isArray()) {
                actualType = Types.resolveArrayType(actualType.getComponentType());
            }
            ITypeBinding expectedType;
            if (node.getParent() instanceof VariableDeclarationFragment) {
                expectedType = Types.getTypeBinding(node.getParent());
            } else {
                expectedType = binding.getReturnType();
            }
            if (expectedType.isArray()) {
                expectedType = Types.resolveArrayType(expectedType.getComponentType());
            }
            if (!actualType.isAssignmentCompatible(expectedType)) {
                if (!actualType.isEqualTo(node.getAST().resolveWellKnownType("void"))) {
                    // Since type parameters aren't passed to Obj-C, add cast for it.
                    // However, this is only needed with nested invocations.
                    if (invocations.size() > 0) {
                        // avoid a casting again below, and know to print a closing ')'
                        // after the method invocation.
                        castReturnValue = printCast(expectedType);
                        castAttempted = true;
                    }
                }
            }
        }
        ITypeBinding typeBinding = binding.getDeclaringClass();

        if (receiver != null) {
            boolean castPrinted = false;
            IMethodBinding methodReceiver = Types.getMethodBinding(receiver);
            if (methodReceiver != null) {
                if (methodReceiver.isConstructor()) {
                    // gcc sometimes fails to discern the constructor's type when
                    // chaining, so add a cast.
                    if (!castAttempted) {
                        castPrinted = printCast(typeBinding);
                        castAttempted = true;
                    }
                } else {
                    ITypeBinding receiverReturnType = methodReceiver.getReturnType();
                    if (receiverReturnType.isInterface()) {
                        // Add interface cast, so Obj-C knows the type node's receiver is.
                        if (!castAttempted) {
                            castPrinted = printCast(receiverReturnType);
                            castAttempted = true;
                        }
                    }
                }
            } else {
                IVariableBinding var = Types.getVariableBinding(receiver);
                if (var != null) {
                    if (Types.variableHasCast(var)) {
                        castPrinted = printCast(Types.getCastForVariable(var));
                    }
                }
            }
            //        printNilCheck(receiver, !castPrinted);
            if (castPrinted) {
                buffer.append(')');
            }
        } else {
            //        if ((binding.getModifiers() & Modifier.STATIC) > 0) {
            //          buffer.append(NameTable.getFullName(typeBinding));
            //        } else {
            //          buffer.append("self");
            //        }
        }
        if (binding instanceof IOSMethodBinding) {
            buffer.append(binding.getName());
        } else {
            buffer.append(methodName);
        }
        buffer.append("(");
        printArguments(binding, node.arguments());
        buffer.append(")");
        if (castReturnValue) {
            buffer.append(')');
        }
    }
    invocations.pop();
    return false;
}

From source file:com.google.devtools.j2cpp.translate.Rewriter.java

License:Open Source License

/**
 * Rewrites System.out and System.err println calls as NSLog calls.
 *
 * @return true if the node was rewritten
 *//* www  .  j a va  2 s. c om*/
// TODO(user): remove when there is iOS console support.
@SuppressWarnings("unchecked")
private boolean rewriteSystemOut(MethodInvocation node) {
    Expression expression = node.getExpression();
    if (expression instanceof Name) {
        Name expr = (Name) node.getExpression();
        IBinding binding = expr.resolveBinding();
        if (binding instanceof IVariableBinding) {
            IVariableBinding varBinding = (IVariableBinding) binding;
            ITypeBinding type = varBinding.getDeclaringClass();
            if (type == null) {
                return false;
            }
            String clsName = type.getQualifiedName();
            String varName = varBinding.getName();
            if (clsName.equals("java.lang.System") && (varName.equals("out") || varName.equals("err"))) {
                // Change System.out.* or System.err.* to NSLog
                AST ast = node.getAST();
                MethodInvocation newInvocation = ast.newMethodInvocation();
                IMethodBinding methodBinding = new IOSMethodBinding("NSLog", Types.getMethodBinding(node),
                        null);
                Types.addBinding(newInvocation, methodBinding);
                Types.addFunction(methodBinding);
                newInvocation.setName(ast.newSimpleName("NSLog"));
                Types.addBinding(newInvocation.getName(), methodBinding);
                newInvocation.setExpression(null);

                // Insert NSLog format argument
                List<Expression> args = node.arguments();
                if (args.size() == 1) {
                    Expression arg = args.get(0);
                    arg.accept(this);
                    String format = getFormatArgument(arg);
                    StringLiteral literal = ast.newStringLiteral();
                    literal.setLiteralValue(format);
                    Types.addBinding(literal, ast.resolveWellKnownType("java.lang.String"));
                    newInvocation.arguments().add(literal);

                    // JDT won't let nodes be re-parented, so copy and map.
                    ASTNode newArg = NodeCopier.copySubtree(ast, arg);
                    if (arg instanceof MethodInvocation) {
                        IMethodBinding argBinding = ((MethodInvocation) arg).resolveMethodBinding();
                        if (!argBinding.getReturnType().isPrimitive()) {
                            IOSMethodBinding newBinding = new IOSMethodBinding("format", argBinding,
                                    Types.getNSString());
                            Types.addMappedInvocation((MethodInvocation) newArg, newBinding);
                        }
                    }
                    newInvocation.arguments().add(newArg);
                } else if (args.size() > 1 && node.getName().getIdentifier().equals("printf")) {
                    newInvocation.arguments().addAll(NodeCopier.copySubtrees(ast, args));
                } else if (args.size() == 0) {
                    // NSLog requires a format string.
                    StringLiteral literal = ast.newStringLiteral();
                    literal.setLiteralValue("");
                    Types.addBinding(literal, ast.resolveWellKnownType("java.lang.String"));
                    newInvocation.arguments().add(literal);
                }

                // Replace old invocation with new.
                ASTNode parent = node.getParent();
                if (parent instanceof ExpressionStatement) {
                    ExpressionStatement stmt = (ExpressionStatement) parent;
                    stmt.setExpression(newInvocation);
                } else {
                    throw new AssertionError("unknown parent type: " + parent.getClass().getSimpleName());
                }
                return true;
            }
        }
    }
    return false;
}

From source file:com.intel.ide.eclipse.mpt.ast.UnresolvedElementsSubProcessor.java

License:Open Source License

private static void addMissingCastParentsProposal(ICompilationUnit cu, MethodInvocation invocationNode,
        Collection<LinkedCorrectionProposal> proposals) {
    Expression sender = invocationNode.getExpression();
    if (sender instanceof ThisExpression) {
        return;//from ww  w.j a v  a 2 s  . c o  m
    }

    ITypeBinding senderBinding = sender.resolveTypeBinding();
    if (senderBinding == null || Modifier.isFinal(senderBinding.getModifiers())) {
        return;
    }

    if (sender instanceof Name && ((Name) sender).resolveBinding() instanceof ITypeBinding) {
        return; // static access
    }

    ASTNode parent = invocationNode.getParent();
    while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) {
        parent = parent.getParent();
    }
    boolean hasCastProposal = false;
    if (parent instanceof CastExpression) {
        //   (TestCase) x.getName() -> ((TestCase) x).getName
        //         hasCastProposal= useExistingParentCastProposal(cu, (CastExpression) parent, sender, invocationNode.getName(), getArgumentTypes(invocationNode.arguments()), proposals);
    }
    if (!hasCastProposal) {
        // x.getName() -> ((TestCase) x).getName

        Expression target = sender;
        while (target instanceof ParenthesizedExpression) {
            target = ((ParenthesizedExpression) target).getExpression();
        }

        String label;
        if (target.getNodeType() != ASTNode.CAST_EXPRESSION) {
            String targetName = null;
            if (target.getLength() <= 18) {
                targetName = ASTNodes.asString(target);
            }
            if (targetName == null) {
                label = CorrectionMessages.UnresolvedElementsSubProcessor_methodtargetcast_description;
            } else {
                label = Messages.format(
                        CorrectionMessages.UnresolvedElementsSubProcessor_methodtargetcast2_description,
                        BasicElementLabels.getJavaCodeString(targetName));
            }
        } else {
            String targetName = null;
            if (target.getLength() <= 18) {
                targetName = ASTNodes.asString(((CastExpression) target).getExpression());
            }
            if (targetName == null) {
                label = CorrectionMessages.UnresolvedElementsSubProcessor_changemethodtargetcast_description;
            } else {
                label = Messages.format(
                        CorrectionMessages.UnresolvedElementsSubProcessor_changemethodtargetcast2_description,
                        BasicElementLabels.getJavaCodeString(targetName));
            }
        }
        proposals.add(new CastCorrectionProposal(label, cu, target, (ITypeBinding) null,
                IProposalRelevance.CHANGE_CAST));
    }
}

From source file:com.motorola.studio.android.generateviewbylayout.MethodBodyVisitor.java

License:Apache License

private void checkInflatedViewNameOnFields(MethodInvocation node) {
    //check if this method invocation is binded to an assignment
    ASTNode nodeParent = node.getParent();
    while ((nodeParent != null) && (inflatedViewName == null)) {
        if (nodeParent instanceof Assignment) {
            Assignment assignment = (Assignment) nodeParent;
            Expression lhs = assignment.getLeftHandSide();
            ITypeBinding binding = lhs.resolveTypeBinding();
            IJavaElement javaElement = binding.getJavaElement();
            if ((javaElement != null) && (lhs instanceof SimpleName)) {
                IType type = (IType) javaElement.getAdapter(IType.class);
                if (type != null) {
                    try {
                        if (JDTUtils.isSubclass(type, "android.view.View")) {
                            inflatedViewName = ((SimpleName) lhs).getFullyQualifiedName();
                        }/*w w w.j  av  a2 s .c  om*/
                    } catch (JavaModelException e) {
                        // do nothing
                    }
                }

            }
        }
        nodeParent = nodeParent.getParent();
    }

}

From source file:com.motorolamobility.preflighting.core.internal.utils.ProjectUtils.java

License:Apache License

private static void analizeBody(final CompilationUnit javaCompilationUnit, final Method method, Block body) {
    body.accept(new ASTVisitor() {

        @Override//from ww w  .j  a  va2  s.c o m
        public boolean visit(VariableDeclarationFragment node) {
            String varName = node.getName().getIdentifier();
            ITypeBinding typeBinding = node.resolveBinding().getType();
            String typeQualifiedName = typeBinding.getQualifiedName();
            int modifiers = typeBinding.getModifiers();
            boolean isFinal = isFinal(modifiers);
            boolean isStatic = isStatic(modifiers);
            String value = null;
            Expression initializer = node.getInitializer();
            if (initializer != null) {
                value = initializer.toString();
            }
            int lineNumber = javaCompilationUnit.getLineNumber(node.getStartPosition());

            Variable variable = new Variable();
            variable.setName(varName);
            variable.setType(typeQualifiedName);
            variable.setFinal(isFinal);
            variable.setStatic(isStatic);
            variable.setValue(value);
            variable.setLineNumber(lineNumber);

            method.addVariable(variable);

            return super.visit(node);
        }

        @Override
        public boolean visit(MethodInvocation node) {
            // Fill invoked method model.
            MethodInvocation invoked = node;
            IMethodBinding methodBinding = invoked.resolveMethodBinding();
            if (methodBinding != null) {
                IMethodBinding methodDeclaration = methodBinding.getMethodDeclaration();
                ITypeBinding declaringClass = methodDeclaration.getDeclaringClass();
                String declaringClassName = "";
                if (declaringClass != null) {
                    declaringClassName = declaringClass.getQualifiedName();
                }
                String methodSimpleName = methodBinding.getName();
                int lineNumber = javaCompilationUnit.getLineNumber(invoked.getStartPosition());
                String returnType = methodBinding.getReturnType().getQualifiedName();
                int methodModifiers = methodBinding.getModifiers();
                boolean isVirtual = isMethodVirtual(methodModifiers);
                String sourceFileFullPath = ((File) javaCompilationUnit.getProperty(JAVA_FILE_PROPERTY))
                        .getAbsolutePath();

                // Retrieve parameter types and look for R constants used
                // within method arguments
                List arguments = invoked.arguments();
                List<String> parameterTypes = new ArrayList<String>(arguments.size());
                List<String> parameterNames = new ArrayList<String>(arguments.size());
                for (Object argument : arguments) {
                    Expression argumentExpression = (Expression) argument;
                    ITypeBinding typeBinding = argumentExpression.resolveTypeBinding();
                    String parameterType = "";
                    String parameterName = "";
                    if (typeBinding != null) {
                        parameterType = typeBinding.getName();
                        parameterName = argumentExpression.toString();
                    } else {
                        continue;
                    }

                    parameterTypes.add(parameterType);
                    parameterNames.add(parameterName);
                    if (argumentExpression instanceof QualifiedName) /*
                                                                     * Can
                                                                     * be a
                                                                     * constant
                                                                     * access
                                                                     */
                    {
                        QualifiedName qualifiedName = (QualifiedName) argumentExpression;
                        String fullQualifiedName = qualifiedName.getQualifier().getFullyQualifiedName();
                        if (fullQualifiedName.startsWith("R.")) /*
                                                                 * Accessing
                                                                 * a R
                                                                 * constant
                                                                 */
                        {
                            Constant constant = new Constant();
                            constant.setSourceFileFullPath(sourceFileFullPath);
                            constant.setLine(lineNumber);
                            constant.setType(parameterType);
                            Object constantExpressionValue = qualifiedName.resolveConstantExpressionValue();
                            if (constantExpressionValue != null) {
                                String constantValueHex = constantExpressionValue.toString();
                                if (constantExpressionValue instanceof Integer) {
                                    Integer integerValue = (Integer) constantExpressionValue;
                                    constantValueHex = Integer.toHexString(integerValue);
                                }
                                constant.setValue(constantValueHex);
                                method.getInstructions().add(constant);
                            }
                        }

                    }
                }

                // Get the name of the object who owns the method being
                // called.
                Expression expression = invoked.getExpression();
                String objectName = null;
                if ((expression != null) && (expression instanceof SimpleName)) {
                    SimpleName simpleName = (SimpleName) expression;
                    objectName = simpleName.getIdentifier();
                }

                // Get the variable, if any, that received the method
                // returned value
                ASTNode parent = invoked.getParent();
                String assignedVariable = null;
                if (parent instanceof VariableDeclarationFragment) {
                    VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment) parent;
                    assignedVariable = variableDeclarationFragment.getName().getIdentifier();
                } else if (parent instanceof Assignment) {
                    Assignment assignment = (Assignment) parent;
                    Expression leftHandSide = assignment.getLeftHandSide();
                    if (leftHandSide instanceof SimpleName) {
                        SimpleName name = (SimpleName) leftHandSide;
                        assignedVariable = name.getIdentifier();
                    }
                }

                // Fill Invoke object and add to the method model.
                Invoke invoke = new Invoke();
                invoke.setLine(lineNumber);
                invoke.setMethodName(methodSimpleName);
                invoke.setObjectName(objectName);
                invoke.setType(getMethodTypeString(isVirtual));
                invoke.setReturnType(returnType);
                invoke.setClassCalled(declaringClassName);
                invoke.setParameterTypes(parameterTypes);
                invoke.setParameterNames(parameterNames);
                invoke.setSourceFileFullPath(sourceFileFullPath);
                invoke.setAssignedVariable(assignedVariable);

                method.getInstructions().add(invoke);
            }
            return super.visit(node);
        }

        @Override
        public boolean visit(VariableDeclarationExpression node) {

            return super.visit(node);
        }

        @Override
        public boolean visit(Assignment node) {
            Expression lhs = node.getLeftHandSide();
            String name = "";
            if (lhs instanceof SimpleName) {
                SimpleName simpleName = (SimpleName) lhs;
                name = simpleName.getIdentifier();
            }
            ITypeBinding typeBinding = lhs.resolveTypeBinding();
            String type = typeBinding.getName();
            // method.addAssigment(assignment);

            // TODO Auto-generated method stub
            return super.visit(node);
        }
    });
}

From source file:com.motorolamobility.preflighting.samplechecker.findviewbyid.implementation.FindViewByIdVisitor.java

License:Apache License

/**
 * Visit method invocations to find invocation of <code>findViewById</code>.
 * //  w w  w .  j  a va 2s. co m
 * @param invoked method that is being called and will be analyzed to check if it is a <code>findViewById</code> call. 
 */
@Override
public boolean visit(MethodInvocation invoked) {
    //find the signature of the method that is being called
    IMethodBinding methodBinding = invoked.resolveMethodBinding();
    if (methodBinding != null) {
        if (methodBinding.toString().trim().equalsIgnoreCase(FIND_VIEW_BY_ID_METHOD_BINDING)) {
            //according to the signature, findViewById was called
            ASTNode parentNode = invoked.getParent();
            Object firstElement = invoked.arguments().get(0);
            if (firstElement != null && firstElement.toString() != null
                    && firstElement.toString().startsWith(R_CONSTANT)) {
                //argument has a constant R. (indicating access that could be possibly done outside the loop)
                if (hasLoopStatementAsParent(parentNode)) {
                    //print in the console (if DEBUG level set for verbosity of App Validator output)
                    PreflightingLogger.debug("Found findViewById invocation inside loop statement");

                    //call is inside a loop statement - raise issue                            
                    ValidationResultData validationResult = createResult(invoked);
                    results.addValidationResult(validationResult);
                }
            }
        }
    }
    return super.visit(invoked);
}

From source file:com.motorolamobility.preflighting.samplechecker.findviewbyid.quickfix.FindViewByIdMarkerResolution.java

License:Apache License

private ASTNode getInvokedStatement(MethodInvocation invokedMethod) {
    boolean found = false;
    ASTNode parent = invokedMethod.getParent();
    do {/*from   w ww  .j a  v a  2  s.com*/
        if ((parent instanceof Statement)) {
            found = true;
        } else {
            parent = parent.getParent();
        }
    } while (!found);
    return parent;
}