Java Code Examples for com.sun.source.tree.MethodInvocationTree#getArguments()

The following examples show how to use com.sun.source.tree.MethodInvocationTree#getArguments() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeMethodInvocation(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    MethodInvocationTree nat = (MethodInvocationTree) parent.getLeaf();
    boolean errorInRealArguments = false;
    
    for (Tree param : nat.getArguments()) {
        errorInRealArguments |= param == error;
    }
    
    if (errorInRealArguments) {
        List<TypeMirror> proposedTypes = new ArrayList<TypeMirror>();
        int[] proposedIndex = new int[1];
        List<ExecutableElement> ee = fuzzyResolveMethodInvocation(info, parent, proposedTypes, proposedIndex);
        
        if (ee.isEmpty()) { //cannot be resolved
            return null;
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return proposedTypes;
    }
    
    return null;
}
 
Example 2
Source File: ReplaceBufferByString.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean visitMethodInvocation(MethodInvocationTree node, Void p) {
    Boolean expr = scan(node.getMethodSelect(), p);
    if (expr == Boolean.TRUE) {
        // check invoked methods
        incompatibleMethodCalled = true;
        return expr;
    } else {
        for (ExpressionTree et : node.getArguments()) {
            Boolean used = scan(et, p);
            if (used == Boolean.TRUE) {
                passedToMethod = true;
            }
        }
    }
    
    return false;
}
 
Example 3
Source File: TooStrongCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a method or constructor call would become ambiguous if the parameter type changes.
 * 
 * @param info compilation context
 * @param parentExec path to the constructor or method invocation
 * @param argIndex
 * @param casteeType
 * @return 
 */
private static boolean checkAmbiguous(CompilationInfo info, final TreePath parentExec, int argIndex, TypeMirror casteeType, TreePath realArgTree) {
    CharSequence altType = info.getTypeUtilities().getTypeName(casteeType, TypeUtilities.TypeNameOptions.PRINT_FQN);
    String prefix = null;
    if (casteeType != null && !(casteeType.getKind() == TypeKind.NULL || casteeType.getKind() == TypeKind.INTERSECTION)) {
        prefix = "(" + altType + ")"; // NOI18N
    }
    Tree leaf = parentExec.getLeaf();
    List<? extends Tree> arguments;
    if (leaf instanceof MethodInvocationTree) {
        MethodInvocationTree mi = (MethodInvocationTree)leaf;
        arguments = mi.getArguments();
    } else {
        arguments = ((NewClassTree)leaf).getArguments();
    }
    Tree argTree = arguments.get(argIndex);
    TreePath argPath = new TreePath(parentExec, argTree);
    return !Utilities.checkAlternativeInvocation(info, parentExec, argPath, realArgTree, prefix);
}
 
Example 4
Source File: MethodArgumentsScanner.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public MethodArgument[] visitMethodInvocation(MethodInvocationTree node, Object p) {
    if (!methodInvocation || offset != positions.getEndPosition(tree, node.getMethodSelect())) {
        return super.visitMethodInvocation(node, p);
        /*MethodArgument[] r = scan(node.getTypeArguments(), p);
        r = scanAndReduce(node.getMethodSelect(), p, r);
        r = scanAndReduce(node.getArguments(), p, r);
        return r;*/
    }
    List<? extends ExpressionTree> args = node.getArguments();
    List<? extends Tree> argTypes = node.getTypeArguments();
    /*int n = args.size();
    arguments = new MethodArgument[n];
    for (int i = 0; i < n; i++) {
        arguments[i] = new MethodArgument(args.get(i).toString(), argTypes.get(i).toString());
    }
    return arguments;*/
    arguments = composeArguments(args, argTypes);
    return arguments;
}
 
Example 5
Source File: ConvertToLambdaPreconditionChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int getLambdaIndexFromInvokingTree(Tree invokingTree) {
    List<? extends ExpressionTree> invokingArgs;
    if (invokingTree.getKind() == Tree.Kind.METHOD_INVOCATION) {
        MethodInvocationTree invokingMethTree = ((MethodInvocationTree) invokingTree);
        invokingArgs = invokingMethTree.getArguments();
    } else if (invokingTree.getKind() == Tree.Kind.NEW_CLASS) {
        NewClassTree invokingConstrTree = (NewClassTree) invokingTree;
        invokingArgs = invokingConstrTree.getArguments();
    } else {
        return -1;
    }

    return getIndexOfLambdaInArgs(newClassTree, invokingArgs);
}
 
Example 6
Source File: InfiniteRecursion.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public State visitMethodInvocation(MethodInvocationTree node, Void p) {
    Element target = ci.getTrees().getElement(getCurrentPath());
    if (target == null) {
        return State.NO;
    }
    State r = null;
    if (target == checkMethod && breakContinueJumps.isEmpty()) {
        if (node.getMethodSelect().getKind() != Tree.Kind.IDENTIFIER) {
            this.thisTree = null;

            returnIfRecurse(r = scan(node.getMethodSelect(), p));
            if (this.thisTree != null) {
                r = State.MUST;
            }
        } else {
            r = State.MUST;
        }
    } else {
        r = scan(node.getMethodSelect(), p);
    }
    if (r == null) {
        for (Tree arg : node.getArguments()) {
            if (returnIfRecurse(r = scan(arg, p))) {
                break;
            }
        }
    }
    this.thisTree = null;
    if (r == null || r == State.NO) {
        return State.NO;
    }
    recursionPoints.add(getCurrentPath());
    return knownResult = State.MUST;
}
 
Example 7
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeMethodInvocation(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    MethodInvocationTree nat = (MethodInvocationTree) parent.getLeaf();
    int realArgumentError = -1;
    int i = 0;
    for (Tree param : nat.getArguments()) {
        if (param == error) {
            realArgumentError = i;
            break;
        }
        i++;
    }
    
    if (realArgumentError != (-1)) {
        List<TypeMirror> proposedTypes = new ArrayList<TypeMirror>();
        int[] proposedIndex = new int[1];
        List<ExecutableElement> ee = org.netbeans.modules.editor.java.Utilities.fuzzyResolveMethodInvocation(info, parent, proposedTypes, proposedIndex);
        
        if (ee.isEmpty()) { //cannot be resolved
            TypeMirror executable = info.getTrees().getTypeMirror(new TreePath(parent, nat.getMethodSelect()));
            
            if (executable == null || executable.getKind() != TypeKind.EXECUTABLE) return null;
            
            ExecutableType et = (ExecutableType) executable;
            
            if (realArgumentError >= et.getParameterTypes().size()) {
                return null;
            }
            
            proposedTypes.add(et.getParameterTypes().get(realArgumentError));
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return proposedTypes;
    }
    
    return null;
}
 
Example 8
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  final Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
  if (methodSymbol == null) {
    throw new RuntimeException("not expecting unresolved method here");
  }
  handler.onMatchMethodInvocation(this, tree, state, methodSymbol);
  // assuming this list does not include the receiver
  List<? extends ExpressionTree> actualParams = tree.getArguments();
  return handleInvocation(tree, state, methodSymbol, actualParams);
}
 
Example 9
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * @param path tree path to read operation
 * @return true if it is permissible to perform this read before the field has been initialized,
 *     false otherwise
 */
private boolean okToReadBeforeInitialized(TreePath path) {
  TreePath parentPath = path.getParentPath();
  Tree leaf = path.getLeaf();
  Tree parent = parentPath.getLeaf();
  if (parent instanceof AssignmentTree) {
    // ok if it's actually a write
    AssignmentTree assignment = (AssignmentTree) parent;
    return assignment.getVariable().equals(leaf);
  } else if (parent instanceof BinaryTree) {
    // ok if we're comparing to null
    BinaryTree binaryTree = (BinaryTree) parent;
    Tree.Kind kind = binaryTree.getKind();
    if (kind.equals(Tree.Kind.EQUAL_TO) || kind.equals(Tree.Kind.NOT_EQUAL_TO)) {
      ExpressionTree left = binaryTree.getLeftOperand();
      ExpressionTree right = binaryTree.getRightOperand();
      return (left.equals(leaf) && right.getKind().equals(Tree.Kind.NULL_LITERAL))
          || (right.equals(leaf) && left.getKind().equals(Tree.Kind.NULL_LITERAL));
    }
  } else if (parent instanceof MethodInvocationTree) {
    // ok if it's invoking castToNonNull and the read is the argument
    MethodInvocationTree methodInvoke = (MethodInvocationTree) parent;
    Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(methodInvoke);
    String qualifiedName =
        ASTHelpers.enclosingClass(methodSymbol) + "." + methodSymbol.getSimpleName().toString();
    if (qualifiedName.equals(config.getCastToNonNullMethod())) {
      List<? extends ExpressionTree> arguments = methodInvoke.getArguments();
      return arguments.size() == 1 && leaf.equals(arguments.get(0));
    }
  }
  return false;
}
 
Example 10
Source File: UnnecessaryBoxing.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean checkMethodInvocation(HintContext ctx, TreePath invPath, TreePath valPath) {
    Trees trees = ctx.getInfo().getTrees();
    Tree invLeaf = invPath.getLeaf();
    List<? extends ExpressionTree> arguments;
    TypeMirror m;
    
    switch (invLeaf.getKind()) {
        case METHOD_INVOCATION: {
            MethodInvocationTree mit = (MethodInvocationTree)invLeaf;
            arguments = mit.getArguments();
            m = trees.getTypeMirror(new TreePath(invPath, mit.getMethodSelect()));
            break;
        }
        case NEW_CLASS: {
            NewClassTree nct = (NewClassTree)invLeaf;
            arguments = nct.getArguments();
            Element e = trees.getElement(invPath);
            TypeMirror cl = trees.getTypeMirror(invPath);
            if (!Utilities.isValidType(cl) || cl.getKind().isPrimitive()) {
                return false;
            }
            m = ctx.getInfo().getTypes().asMemberOf((DeclaredType)cl, e);
            break;
        }
        default:
            return false;
    }
    
    if (!Utilities.isValidType(m) || m.getKind() != TypeKind.EXECUTABLE) {
        return false;
    }
    ExecutableType execType = (ExecutableType)m;
    int idx = arguments.indexOf(ctx.getPath().getLeaf());
    if (idx < 0 || idx >= execType.getParameterTypes().size()) {
        return false;
    }
    TypeMirror paramType = execType.getParameterTypes().get(idx);
    TypeMirror curType = trees.getTypeMirror(ctx.getPath());
    TypeMirror valType = trees.getTypeMirror(valPath);
    
    if (!paramType.getKind().isPrimitive() && valType.getKind().isPrimitive()) {
        valType = ctx.getInfo().getTypes().boxedClass((PrimitiveType)valType).asType();
        // ensure that the passed INSTANCE type will not change when the boxing is removed
        if (!ctx.getInfo().getTypes().isSameType(curType, valType)) {
            return false;
        }
    }
            
    return Utilities.checkAlternativeInvocation(ctx.getInfo(), invPath, ctx.getPath(), valPath, null);
}
 
Example 11
Source File: UseNbBundleMessages.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath treePath = ctx.getPath();
            TreeMaker make = wc.getTreeMaker();
            if (treePath.getLeaf().getKind() == Kind.METHOD_INVOCATION) {
                MethodInvocationTree mit = (MethodInvocationTree) treePath.getLeaf();
                CompilationUnitTree cut = wc.getCompilationUnit();
                boolean imported = false;
                String importBundleStar = cut.getPackageName() + ".Bundle.*";
                for (ImportTree it : cut.getImports()) {
                    if (it.isStatic() && it.getQualifiedIdentifier().toString().equals(importBundleStar)) {
                        imported = true;
                        break;
                    }
                }
                if (!imported) {
                    wc.rewrite(cut, make.addCompUnitImport(cut, make.Import(make.Identifier(importBundleStar), true)));
                }
                List<? extends ExpressionTree> args = mit.getArguments();
                List<? extends ExpressionTree> params;
                if (args.size() == 3 && args.get(2).getKind() == Kind.NEW_ARRAY) {
                    params = ((NewArrayTree) args.get(2)).getInitializers();
                } else {
                    params = args.subList(2, args.size());
                }
                wc.rewrite(mit, make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.Identifier(toIdentifier(key)), params));
            } // else annotation value, nothing to change
            if (!isAlreadyRegistered) {
                EditableProperties ep = new EditableProperties(true);
                InputStream is = ctx.getResourceContent(bundleProperties);
                try {
                    ep.load(is);
                } finally {
                    is.close();
                }
                List<ExpressionTree> lines = new ArrayList<ExpressionTree>();
                for (String comment : ep.getComment(key)) {
                    lines.add(make.Literal(comment));
                }
                lines.add(make.Literal(key + '=' + ep.remove(key)));
                TypeElement nbBundleMessages = wc.getElements().getTypeElement("org.openide.util.NbBundle.Messages");
                if (nbBundleMessages == null) {
                    throw new IllegalArgumentException("cannot resolve org.openide.util.NbBundle.Messages");
                }
                GeneratorUtilities gu = GeneratorUtilities.get(wc);
                Tree enclosing = findEnclosingElement(wc, treePath);
                Tree modifiers;
                Tree nueModifiers;
                ExpressionTree[] linesA = lines.toArray(new ExpressionTree[lines.size()]);
                switch (enclosing.getKind()) {
                case METHOD:
                    modifiers = wc.resolveRewriteTarget(((MethodTree) enclosing).getModifiers());
                    nueModifiers = gu.appendToAnnotationValue((ModifiersTree) modifiers, nbBundleMessages, "value", linesA);
                    break;
                case VARIABLE:
                    modifiers = wc.resolveRewriteTarget(((VariableTree) enclosing).getModifiers());
                    nueModifiers = gu.appendToAnnotationValue((ModifiersTree) modifiers, nbBundleMessages, "value", linesA);
                    break;
                case COMPILATION_UNIT:
                    modifiers = wc.resolveRewriteTarget(enclosing);
                    nueModifiers = gu.appendToAnnotationValue((CompilationUnitTree) modifiers, nbBundleMessages, "value", linesA);
                    break;
                default:
                    modifiers = wc.resolveRewriteTarget(((ClassTree) enclosing).getModifiers());
                    nueModifiers = gu.appendToAnnotationValue((ModifiersTree) modifiers, nbBundleMessages, "value", linesA);
                }
                wc.rewrite(modifiers, nueModifiers);
            // XXX remove NbBundle import if now unused
            OutputStream os = ctx.getResourceOutput(bundleProperties);
            try {
                ep.store(os);
            } finally {
                os.close();
            }
        }
    // XXX after JavaFix rewrite, Savable.save (on DataObject.find(src)) no longer works (JG13 again)
}
 
Example 12
Source File: SourceCodeAnalysisImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private List<Documentation> documentationImpl(String code, int cursor, boolean computeJavadoc) {
    code = code.substring(0, cursor);
    if (code.trim().isEmpty()) { //TODO: comment handling
        code += ";";
    }

    if (guessKind(code) == Kind.IMPORT)
        return Collections.emptyList();

    OuterWrap codeWrap = proc.outerMap.wrapInTrialClass(Wrap.methodWrap(code));
    AnalyzeTask at = proc.taskFactory.new AnalyzeTask(codeWrap, keepParameterNames);
    SourcePositions sp = at.trees().getSourcePositions();
    CompilationUnitTree topLevel = at.firstCuTree();
    TreePath tp = pathFor(topLevel, sp, codeWrap.snippetIndexToWrapIndex(cursor));

    if (tp == null)
        return Collections.emptyList();

    TreePath prevPath = null;
    while (tp != null && tp.getLeaf().getKind() != Kind.METHOD_INVOCATION &&
           tp.getLeaf().getKind() != Kind.NEW_CLASS && tp.getLeaf().getKind() != Kind.IDENTIFIER &&
           tp.getLeaf().getKind() != Kind.MEMBER_SELECT) {
        prevPath = tp;
        tp = tp.getParentPath();
    }

    if (tp == null)
        return Collections.emptyList();

    Stream<Element> elements;
    Iterable<Pair<ExecutableElement, ExecutableType>> candidates;
    List<? extends ExpressionTree> arguments;

    if (tp.getLeaf().getKind() == Kind.METHOD_INVOCATION || tp.getLeaf().getKind() == Kind.NEW_CLASS) {
        if (tp.getLeaf().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) tp.getLeaf();
            candidates = methodCandidates(at, tp);
            arguments = mit.getArguments();
        } else {
            NewClassTree nct = (NewClassTree) tp.getLeaf();
            candidates = newClassCandidates(at, tp);
            arguments = nct.getArguments();
        }

        if (!isEmptyArgumentsContext(arguments)) {
            List<TypeMirror> actuals = computeActualInvocationTypes(at, arguments, prevPath);
            List<TypeMirror> fullActuals = actuals != null ? actuals : Collections.emptyList();

            candidates =
                    this.filterExecutableTypesByArguments(at, candidates, fullActuals)
                        .stream()
                        .filter(method -> parameterType(method.fst, method.snd, fullActuals.size(), true).findAny().isPresent())
                        .collect(Collectors.toList());
        }

        elements = Util.stream(candidates).map(method -> method.fst);
    } else if (tp.getLeaf().getKind() == Kind.IDENTIFIER || tp.getLeaf().getKind() == Kind.MEMBER_SELECT) {
        Element el = at.trees().getElement(tp);

        if (el == null ||
            el.asType().getKind() == TypeKind.ERROR ||
            (el.getKind() == ElementKind.PACKAGE && el.getEnclosedElements().isEmpty())) {
            //erroneous element:
            return Collections.emptyList();
        }

        elements = Stream.of(el);
    } else {
        return Collections.emptyList();
    }

    List<Documentation> result = Collections.emptyList();

    try (JavadocHelper helper = JavadocHelper.create(at.task, findSources())) {
        result = elements.map(el -> constructDocumentation(at, helper, el, computeJavadoc))
                         .filter(Objects::nonNull)
                         .collect(Collectors.toList());
    } catch (IOException ex) {
        proc.debug(ex, "JavadocHelper.close()");
    }

    return result;
}