Java Code Examples for com.sun.source.tree.Tree.Kind#METHOD_INVOCATION

The following examples show how to use com.sun.source.tree.Tree.Kind#METHOD_INVOCATION . 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: WorkingCopy.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addSyntheticTrees(DiffContext diffContext, Tree node) {
    if (node == null) return ;
    
    if (((JCTree) node).pos == (-1)) {
        diffContext.syntheticTrees.add(node);
        return ;
    }
    
    if (node.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionTree est = ((ExpressionStatementTree) node).getExpression();

        if (est.getKind() == Kind.METHOD_INVOCATION) {
            ExpressionTree select = ((MethodInvocationTree) est).getMethodSelect();

            if (select.getKind() == Kind.IDENTIFIER && ((IdentifierTree) select).getName().contentEquals("super")) {
                if (getTreeUtilities().isSynthetic(diffContext.origUnit, node)) {
                    diffContext.syntheticTrees.add(node);
                }
            }
        }
    }
}
 
Example 2
Source File: TreePruner.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static boolean delegatingConstructor(List<JCStatement> stats) {
  if (stats.isEmpty()) {
    return false;
  }
  JCStatement stat = stats.get(0);
  if (stat.getKind() != Kind.EXPRESSION_STATEMENT) {
    return false;
  }
  JCExpression expr = ((JCExpressionStatement) stat).getExpression();
  if (expr.getKind() != Kind.METHOD_INVOCATION) {
    return false;
  }
  JCExpression method = ((JCMethodInvocation) expr).getMethodSelect();
  Name name;
  switch (method.getKind()) {
    case IDENTIFIER:
      name = ((JCIdent) method).getName();
      break;
    case MEMBER_SELECT:
      name = ((JCFieldAccess) method).getIdentifier();
      break;
    default:
      return false;
  }
  return name.contentEquals("this") || name.contentEquals("super");
}
 
Example 3
Source File: UncaughtException.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
    * Detects if we are parameter of this() or super() call
    * @return true if yes
    */ 
   private boolean isThisParameter(TreePath path) {
//anonymous class must not be on the path to top
while(!TreeUtilities.CLASS_TREE_KINDS.contains(path.getLeaf().getKind()) && path.getLeaf().getKind() != Kind.COMPILATION_UNIT) {
    if (path.getParentPath().getLeaf().getKind() == Kind.METHOD_INVOCATION) {
	MethodInvocationTree mi = (MethodInvocationTree) path.getParentPath().getLeaf();
	if(mi.getMethodSelect().getKind() == Kind.IDENTIFIER) {
	    String id = ((IdentifierTree) mi.getMethodSelect()).getName().toString();
	    if ("super".equals(id) || "this".equals(id))
		return true;
	}
    }
    path = path.getParentPath();
}
return false;
   }
 
Example 4
Source File: FileToURL.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Kind.METHOD_INVOCATION)
public static ErrorDescription computeTreeKind(HintContext ctx) {
    MethodInvocationTree mit = (MethodInvocationTree) ctx.getPath().getLeaf();

    if (!mit.getArguments().isEmpty() || !mit.getTypeArguments().isEmpty()) {
        return null;
    }

    CompilationInfo info = ctx.getInfo();
    Element e = info.getTrees().getElement(new TreePath(ctx.getPath(), mit.getMethodSelect()));

    if (e == null || e.getKind() != ElementKind.METHOD) {
        return null;
    }

    if (e.getSimpleName().contentEquals("toURL") && info.getElementUtilities().enclosingTypeElement(e).getQualifiedName().contentEquals("java.io.File")) {
        ErrorDescription w = ErrorDescriptionFactory.forName(ctx, mit, "Use of java.io.File.toURL()");

        return w;
    }

    return null;
}
 
Example 5
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
boolean isSynthetic(CompilationUnitTree cut, Tree leaf) throws NullPointerException {
    JCTree tree = (JCTree) leaf;
    
    if (tree.pos == (-1))
        return true;
    
    if (leaf.getKind() == Kind.METHOD) {
        //check for synthetic constructor:
        return (((JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L;
    }
    
    //check for synthetic superconstructor call:
    if (leaf.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionStatementTree est = (ExpressionStatementTree) leaf;
        
        if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();
            
            if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) {
                IdentifierTree it = (IdentifierTree) mit.getMethodSelect();
                
                if ("super".equals(it.getName().toString())) {
                    SourcePositions sp = info.getTrees().getSourcePositions();
                    
                    return sp.getEndPosition(cut, leaf) == (-1);
                }
            }
        }
    }
    
    return false;
}
 
Example 6
Source File: ComputeImports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitMemberSelect(MemberSelectTree tree, Map<String, Object> p) {
    if (tree.getExpression().getKind() == Kind.IDENTIFIER) {
        p.put("request", null);
    }
    
    scan(tree.getExpression(), p);
    
    Union2<String, DeclaredType> leftSide = (Union2<String, DeclaredType>) p.remove("result");
    
    p.remove("request");
    
    if (leftSide != null && leftSide.hasFirst()) {
        String rightSide = tree.getIdentifier().toString();
        
        if (ERROR.equals(rightSide))
            rightSide = "";
        
        boolean isMethodInvocation = getCurrentPath().getParentPath().getLeaf().getKind() == Kind.METHOD_INVOCATION;
        
        //Ignore .class (which will not help us much):
        if (!"class".equals(rightSide))
            hints.add(new EnclosedHint(leftSide.first(), rightSide, !isMethodInvocation));
    }
    
    return null;
}
 
Example 7
Source File: VarArgsCast.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    TreePath call = treePath;//.getParentPath();
    
    if (call.getLeaf().getKind() != Kind.METHOD_INVOCATION) {
        call = call.getParentPath();
        if (call.getLeaf().getKind() != Kind.METHOD_INVOCATION) {
            return null;
        }
    }
    
    MethodInvocationTree mit = (MethodInvocationTree) call.getLeaf();
    TypeMirror mType = info.getTrees().getTypeMirror(new TreePath(call, mit.getMethodSelect()));
    
    if (mType == null || mType.getKind() != TypeKind.EXECUTABLE) {
        return null;
    }
    
    ExecutableType methodType = (ExecutableType) mType;
    
    if (methodType.getParameterTypes().isEmpty() || methodType.getParameterTypes().get(methodType.getParameterTypes().size() - 1).getKind() != TypeKind.ARRAY) {
        return null;
    }
    
    ArrayType targetArray = (ArrayType) methodType.getParameterTypes().get(methodType.getParameterTypes().size() - 1);
    TreePath target = new TreePath(call, mit.getArguments().get(mit.getArguments().size() - 1));
    
    return Arrays.asList(new FixImpl(info, target, targetArray.getComponentType()).toEditorFix(),
                         new FixImpl(info, target, targetArray).toEditorFix());
}
 
Example 8
Source File: Unbalanced.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerTreeKind({Kind.IDENTIFIER, Kind.MEMBER_SELECT})
@TriggerOptions(TriggerOptions.PROCESS_GUARDED)
public static ErrorDescription before(HintContext ctx) {
    TreePath tp = ctx.getPath();
    VariableElement var = testElement(ctx);

    if (var == null) return null;

    if (tp.getParentPath().getLeaf().getKind() == Kind.MEMBER_SELECT && tp.getParentPath().getParentPath().getLeaf().getKind() == Kind.METHOD_INVOCATION) {
        String methodName = ((MemberSelectTree) tp.getParentPath().getLeaf()).getIdentifier().toString();
        if (READ_METHODS.contains(methodName)) {
            if (tp.getParentPath().getParentPath().getParentPath().getLeaf().getKind() != Kind.EXPRESSION_STATEMENT) {
                record(ctx.getInfo(), var, State.READ);
            }
            return null;
        } else if (WRITE_METHODS.contains(methodName)) {
            if (tp.getParentPath().getParentPath().getParentPath().getLeaf().getKind() != Kind.EXPRESSION_STATEMENT) {
                record(ctx.getInfo(), var, State.WRITE, State.READ);
            } else {
                record(ctx.getInfo(), var, State.WRITE);
            }
            return null;
        }
    }

    record(ctx.getInfo(), var, State.WRITE, State.READ);

    return null;
}
 
Example 9
Source File: JavaPluginUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static boolean isSynthetic(CompilationInfo info, CompilationUnitTree cut, Tree leaf) throws NullPointerException {
    JCTree tree = (JCTree) leaf;
    
    if (tree.pos == (-1))
        return true;
    
    if (leaf.getKind() == Kind.METHOD) {
        //check for synthetic constructor:
        return (((JCTree.JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L;
    }
    
    //check for synthetic superconstructor call:
    if (leaf.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionStatementTree est = (ExpressionStatementTree) leaf;
        
        if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();
            
            if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) {
                IdentifierTree it = (IdentifierTree) mit.getMethodSelect();
                
                if ("super".equals(it.getName().toString())) {
                    SourcePositions sp = info.getTrees().getSourcePositions();
                    
                    return sp.getEndPosition(cut, leaf) == (-1);
                }
            }
        }
    }
    
    return false;
}
 
Example 10
Source File: CallHierarchyTasks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void run(CompilationController javac) throws Exception {
    TreePath tpath = null;
    Element method = null;
    
    javac.toPhase(JavaSource.Phase.RESOLVED);
    if (tHandle == null) {
        tpath = javac.getTreeUtilities().pathFor(offset);
    } else {
        tpath = tHandle.resolve(javac);
    }
    
    while (tpath != null) {
        Kind kind = tpath.getLeaf().getKind();
        if (kind == Kind.METHOD || kind == Kind.METHOD_INVOCATION || kind == Kind.MEMBER_SELECT || kind == Kind.NEW_CLASS) {
            method = ScanUtils.checkElement(javac, javac.getTrees().getElement(tpath));
            if (RefactoringUtils.isExecutableElement(method)) {
                break;
            }
            method = null;
        }
        tpath = tpath.getParentPath();
    }
    
    if (method != null) {
        if(isCallerGraph && this.searchFromBase) {
            Collection<ExecutableElement> overriddenMethods = JavaRefactoringUtils.getOverriddenMethods((ExecutableElement)method, javac);
            if(!overriddenMethods.isEmpty()) {
                method = overriddenMethods.iterator().next();
            }
        }
        root = Call.createRoot(javac, tpath, method, isCallerGraph);
    }
}
 
Example 11
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isSynthetic(CompilationUnitTree cut, Tree leaf) throws NullPointerException {
    JCTree tree = (JCTree) leaf;

    if (tree.pos == (-1))
        return true;

    if (leaf.getKind() == Kind.METHOD) {
        //check for synthetic constructor:
        return (((JCMethodDecl)leaf).mods.flags & Flags.GENERATEDCONSTR) != 0L;
    }

    //check for synthetic superconstructor call:
    if (cut != null && leaf.getKind() == Kind.EXPRESSION_STATEMENT) {
        ExpressionStatementTree est = (ExpressionStatementTree) leaf;

        if (est.getExpression().getKind() == Kind.METHOD_INVOCATION) {
            MethodInvocationTree mit = (MethodInvocationTree) est.getExpression();

            if (mit.getMethodSelect().getKind() == Kind.IDENTIFIER) {
                IdentifierTree it = (IdentifierTree) mit.getMethodSelect();

                if ("super".equals(it.getName().toString())) {
                    return ((JCCompilationUnit) cut).endPositions.getEndPos(tree) == (-1);
                }
            }
        }
    }

    return false;
}
 
Example 12
Source File: SemanticHighlighterBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addParameterInlineHint(Tree tree) {
    TreePath pp = getCurrentPath().getParentPath();
    Tree leaf = pp.getLeaf();
    if (leaf != null &&
        (leaf.getKind() == Kind.METHOD_INVOCATION || leaf.getKind() == Kind.NEW_CLASS)) {
        int pos = -1;
        if (leaf.getKind() == Kind.METHOD_INVOCATION) {
            pos = MethodInvocationTree.class.cast(leaf).getArguments().indexOf(tree);
        } else if (leaf.getKind() == Kind.NEW_CLASS) {
            pos = NewClassTree.class.cast(leaf).getArguments().indexOf(tree);
        }
        if (pos != (-1)) {
            Element invoked = info.getTrees().getElement(pp);
            if (invoked != null && (invoked.getKind() == ElementKind.METHOD || invoked.getKind() == ElementKind.CONSTRUCTOR)) {
                long start = sourcePositions.getStartPosition(info.getCompilationUnit(), tree);
                long end = start + 1;
                ExecutableElement invokedMethod = (ExecutableElement) invoked;
                pos = Math.min(pos, invokedMethod.getParameters().size() - 1);
                if (pos != (-1)) {
                    boolean shouldBeAdded = true;
                    if (tree.getKind() == Kind.IDENTIFIER &&
                            invokedMethod.getParameters().get(pos).getSimpleName().equals(
                                    IdentifierTree.class.cast(tree).getName())) {
                        shouldBeAdded = false;
                    }
                    if (shouldBeAdded) {
                        preText.put(new int[] {(int) start, (int) end},
                                    invokedMethod.getParameters().get(pos).getSimpleName() + ":");
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: StaticImport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.MEMBER_SELECT)
public static List<ErrorDescription> run(HintContext ctx) {
    CompilationInfo info = ctx.getInfo();
    TreePath treePath = ctx.getPath();

    Element e = info.getTrees().getElement(treePath);
    EnumSet<ElementKind> supportedTypes = EnumSet.of(ElementKind.METHOD, ElementKind.ENUM_CONSTANT, ElementKind.FIELD);
    if (e == null || !e.getModifiers().contains(Modifier.STATIC) || !supportedTypes.contains(e.getKind())) {
        return null;
    }

    if (ElementKind.METHOD.equals(e.getKind())) {
        TreePath mitp = treePath.getParentPath();
        if (mitp == null || mitp.getLeaf().getKind() != Kind.METHOD_INVOCATION) {
        return null;
    }
        if (((MethodInvocationTree) mitp.getLeaf()).getMethodSelect() != treePath.getLeaf()) {
        return null;
    }
        List<? extends Tree> typeArgs = ((MethodInvocationTree) mitp.getLeaf()).getTypeArguments();
        if (typeArgs != null && !typeArgs.isEmpty()) {
        return null;
    }
    }
    Element enclosingEl = e.getEnclosingElement();
    if (enclosingEl == null) {
        return null;
    }
    String sn = e.getSimpleName().toString();
    // rules out .class, but who knows what keywords will be abused in the future.
    if (SourceVersion.isKeyword(sn)) {
        return null;
    }
    TreePath cc = getContainingClass(treePath);
    if (cc == null){
        return null;
    }
    Element klass = info.getTrees().getElement(cc);
    if (klass == null || klass.getKind() != ElementKind.CLASS) {
        return null;
    }
    String fqn = null;
    String fqn1 = getFqn(info, e);
    if (!isSubTypeOrInnerOfSubType(info, klass, enclosingEl) && !isStaticallyImported(info, fqn1)) {
        if (hasMethodNameClash(info, klass, sn) || hasStaticImportSimpleNameClash(info, sn)) {
            return null;
        }
        fqn = fqn1;
    }
    Scope currentScope = info.getTrees().getScope(treePath);
    TypeMirror enclosingType = e.getEnclosingElement().asType();
    if (enclosingType == null || enclosingType.getKind() != TypeKind.DECLARED || !info.getTrees().isAccessible(currentScope, e, (DeclaredType) enclosingType)) {
        return null;
    }
    String desc = NbBundle.getMessage(StaticImport.class, "ERR_StaticImport");
    ErrorDescription ed = ErrorDescriptionFactory.forTree(ctx, treePath, desc, new FixImpl(TreePathHandle.create(treePath, info), fqn, sn).toEditorFix());
    if (ctx.isCanceled()) {
        return null;
    }
    return Collections.singletonList(ed);
}
 
Example 14
Source File: CodeHintProviderImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind(Kind.METHOD_INVOCATION)
public static ErrorDescription hintPattern2(HintContext ctx) {
    return null;
}
 
Example 15
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String simpleName(Tree t) {
    if (t == null) {
        return Bundle.DisplayName_Unknown();
    }
    if (t.getKind() == Kind.IDENTIFIER) {
        return ((IdentifierTree) t).getName().toString();
    }

    if (t.getKind() == Kind.MEMBER_SELECT) {
        return ((MemberSelectTree) t).getIdentifier().toString();
    }

    if (t.getKind() == Kind.METHOD_INVOCATION) {
        return scan(t, null);
    }

    if (t.getKind() == Kind.PARAMETERIZED_TYPE) {
        return simpleName(((ParameterizedTypeTree) t).getType()) + "<...>"; // NOI18N
    }

    if (t.getKind() == Kind.ARRAY_ACCESS) {
        return simpleName(((ArrayAccessTree) t).getExpression()) + "[]"; //NOI18N
    }

    if (t.getKind() == Kind.PARENTHESIZED) {
        return "(" + simpleName(((ParenthesizedTree)t).getExpression()) + ")"; //NOI18N
    }

    if (t.getKind() == Kind.TYPE_CAST) {
        return simpleName(((TypeCastTree)t).getType());
    }

    if (t.getKind() == Kind.ARRAY_TYPE) {
        return simpleName(((ArrayTypeTree)t).getType());
    }

    if (t.getKind() == Kind.PRIMITIVE_TYPE) {
        return ((PrimitiveTypeTree) t).getPrimitiveTypeKind().name().toLowerCase();
    }
    
    throw new IllegalStateException("Currently unsupported kind of tree: " + t.getKind()); // NOI18N
}
 
Example 16
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 17
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;
}
 
Example 18
Source File: TreeConverter.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private TreeNode convertFieldAccess(MemberSelectTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  String fieldName = node.getIdentifier().toString();
  SourcePosition pos = getPosition(node);
  ExpressionTree selected = node.getExpression();
  TreePath selectedPath = getTreePath(path, selected);
  Element element = getElement(path);
  TypeMirror typeMirror = getTypeMirror(path);
  if (fieldName.equals("this")) {
    return new ThisExpression()
        .setQualifier((Name) convert(selected, path))
        .setTypeMirror(typeMirror);
  }
  if ("super".equals(getMemberName(selected))) {
    SuperFieldAccess newNode =
        new SuperFieldAccess()
            .setVariableElement((VariableElement) element)
            .setTypeMirror(typeMirror);
    if (selected.getKind() == Kind.MEMBER_SELECT) {
      newNode.setQualifier(
          (Name) convert(((MemberSelectTree) selected).getExpression(), selectedPath));
    }
    return newNode;
  }
  if (node.getIdentifier().toString().equals("class")) {
    Type type = convertType(getTypeMirror(selectedPath), pos, false);
    type.setPosition(getPosition(node));
    return new TypeLiteral(typeMirror).setType(type);
  }
  if (selected.getKind() == Kind.IDENTIFIER
      && (!element.getKind().isField() || ElementUtil.isConstant((VariableElement) element))) {
    if (selected.toString().equals("this")) {
      // Just return the constant.
      return new SimpleName(element);
    }
    return new QualifiedName()
        .setName(convertSimpleName(element, typeMirror, pos))
        .setQualifier(
            convertSimpleName(getElement(selectedPath), getTypeMirror(selectedPath), pos))
        .setElement(element);
  }
  if (selected.getKind() == Kind.MEMBER_SELECT) {
    TreeNode newSelected = convertFieldAccess((MemberSelectTree) selected, path).setPosition(pos);
    if (newSelected.getKind() == TreeNode.Kind.QUALIFIED_NAME) {
      return new QualifiedName()
          .setName(convertSimpleName(element, typeMirror, pos))
          .setQualifier((QualifiedName) newSelected)
          .setElement(element);
    }
  }
  if (ElementUtil.isConstant((VariableElement) element)
      && ElementUtil.isStatic(element)
      && !(selected.getKind() == Kind.METHOD_INVOCATION)
      && !(selected.getKind() == Kind.MEMBER_SELECT)
      && !(selected.getKind() == Kind.PARENTHESIZED)) {
    return new QualifiedName()
        .setName(convertSimpleName(element, typeMirror, pos))
        .setQualifier((Name) convert(selected, path))
        .setElement(element);
  }
  return new FieldAccess()
      .setVariableElement((VariableElement) element)
      .setExpression((Expression) convert(selected, path))
      .setName(convertSimpleName(element, typeMirror, pos).setTypeMirror(typeMirror));
}