Java Code Examples for com.sun.source.tree.Tree#getKind()

The following examples show how to use com.sun.source.tree.Tree#getKind() . 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: TypeArgumentCriterion.java    From annotation-tools with MIT License 6 votes vote down vote up
@Override
public boolean isSatisfiedBy(TreePath path) {
  if (path == null || path.getParentPath() == null) { return false; }

  TreePath parentPath = path.getParentPath();
  Tree parent = parentPath.getLeaf();
  List<? extends Tree> typeArgs;

  switch (parent.getKind()) {
  case MEMBER_REFERENCE:
    typeArgs = ((JCTree.JCMemberReference) parent).getTypeArguments();
    break;
  case METHOD_INVOCATION:
    typeArgs = ((JCTree.JCMethodInvocation) parent).getTypeArguments();
    break;
  default:
    return isSatisfiedBy(parentPath);
  }

  return typeArgs != null
      && loc.index >= 0 && loc.index < typeArgs.size()
      && typeArgs.get(loc.index) == path.getLeaf();
}
 
Example 2
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static boolean isValid(CompilationInfo javac, TreePath path, Severity severity, Access access, int caret) {
    Tree leaf = path.getLeaf();
    boolean onLine = severity == Severity.HINT && caret > -1;
    switch (leaf.getKind()) {
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            return access.isAccessible(javac, path, false) && (!onLine || isInHeader(javac, (ClassTree) leaf, caret));
        case METHOD:
            return access.isAccessible(javac, path, false) && (!onLine || isInHeader(javac, (MethodTree) leaf, caret));
        case VARIABLE:
            return access.isAccessible(javac, path, false);
    }
    return false;
}
 
Example 3
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void doMoveComments(WorkingCopy wc, Tree from,  Tree to, int offset, List<Comment> comments, int fromIdx, int toIdx) {
    if (comments.isEmpty()) {
        return;
    }
    TreeMaker tm = wc.getTreeMaker();
    Tree tree = from;
    switch (from.getKind()) {
        case METHOD:
            tree = tm.setLabel(from, ((MethodTree)from).getName());
            break;
        case VARIABLE:
            tree = tm.setLabel(from, ((VariableTree)from).getName());
            break;
        case BLOCK:
            tree = tm.Block(((BlockTree)from).getStatements(), ((BlockTree)from).isStatic());
            GeneratorUtilities gu = GeneratorUtilities.get(wc);
            gu.copyComments(from, tree, true);
            gu.copyComments(from, tree, false);
            break;
    }
    boolean before = (int)wc.getTrees().getSourcePositions().getStartPosition(wc.getCompilationUnit(), from) >= offset;
    if (fromIdx >=0 && toIdx >= 0 && toIdx - fromIdx > 0) {
        for (int i = toIdx - 1; i >= fromIdx; i--) {
            tm.removeComment(tree, i, before);
        }
    }
    wc.rewrite(from, tree);
    for (Comment comment : comments) {
        tm.addComment(to, comment, comment.pos() <= offset);
    }
}
 
Example 4
Source File: JavacJ2ObjCIncompatibleStripper.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private String getLastComponent(Tree name) {
  switch (name.getKind()) {
    case IDENTIFIER:
      return ((IdentifierTree) name).getName().toString();
    case MEMBER_SELECT:
      return ((MemberSelectTree) name).getIdentifier().toString();
    default:
      return "";
  }
}
 
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: 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 7
Source File: ComputeImports.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void filterByKind(Tree toFilter, Set<ElementKind> acceptedKinds, Set<ElementKind> notAcceptedKinds) {
    if (toFilter == null) return;
    switch (toFilter.getKind()) {
        case IDENTIFIER:
            hints.add(new KindHint(((IdentifierTree) toFilter).getName().toString(), acceptedKinds, notAcceptedKinds));
            break;
        case PARAMETERIZED_TYPE:
            filterByKind(((ParameterizedTypeTree) toFilter).getType(), acceptedKinds, notAcceptedKinds);
            break;
    }
}
 
Example 8
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean thisIsMatcherReturn(Tree that, TreePath currentTreePath) {
    TreePath parentPath = currentTreePath.getParentPath();
    Tree parent = parentPath.getLeaf();
    if (parent.getKind() == Tree.Kind.BLOCK && ((BlockTree) parent).getStatements().size() == 1) {
        return thisIsMatcherReturn(parent, parentPath);
    } else if (parent.getKind() == Tree.Kind.IF && ((IfTree) parent).getElseStatement() == null) {
        return true;
    }
    return false;


}
 
Example 9
Source File: Insertions.java    From annotation-tools with MIT License 5 votes vote down vote up
/**
   * Returns the depth of type nesting of the innermost nested type of a type AST.
   * For example, both {@code A.B.C} and {@code A.B<D.E.F.G>.C} have depth 3.
   */
  private int localDepth(Tree node) {
    Tree t = node;
    int result = 0;
loop:
    while (t != null) {
      switch (t.getKind()) {
      case ANNOTATED_TYPE:
        t = ((AnnotatedTypeTree) t).getUnderlyingType();
        break;
      case MEMBER_SELECT:
        if (t instanceof JCTree.JCFieldAccess) {
          JCTree.JCFieldAccess jfa = (JCTree.JCFieldAccess) t;
          if (jfa.sym.kind == Kinds.Kind.PCK) {
            t = jfa.getExpression();
            continue;
          }
        }
        t = ((MemberSelectTree) t).getExpression();
        ++result;
        break;
      default:
        break loop;
      }
    }
    return result;
  }
 
Example 10
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean executeRound(Element el, int round) throws Exception {
    if (el.getKind() != ElementKind.ENUM) {
        return false;
    }
    ClassTree ct = (ClassTree)path.getLeaf();
    for (ListIterator<? extends Tree> it = ct.getMembers().listIterator(ct.getMembers().size()); it.hasPrevious(); ) {
        Tree t = it.previous();
        
        if (t.getKind() != Tree.Kind.VARIABLE) {
            continue;
        }
        TreePath p = new TreePath(path, t);
        Element e = copy.getTrees().getElement(p);
        if (e == null || e.getKind() != ElementKind.ENUM_CONSTANT) {
            continue;
        }

        switch (round) {
            case 0:
                if (!generateClassBody(p)) {
                    return false;
                }
                break;
            case 1:
                if (!generateImplementation(el, p)) {
                    return false;
                }
                break;
            default:
                throw new IllegalStateException();
        }
    }
    return true;
}
 
Example 11
Source File: SnakeYAMLMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private static String fullyQualifiedPath(TreePath path) {
    ExpressionTree packageNameExpr = path.getCompilationUnit().getPackageName();
    MemberSelectTree packageID = packageNameExpr.getKind() == Tree.Kind.MEMBER_SELECT
            ? ((MemberSelectTree) packageNameExpr) : null;

    StringBuilder result = new StringBuilder();
    if (packageID != null) {
        result.append(packageID.getExpression().toString())
                .append(".")
                .append(packageID.getIdentifier().toString());
    }
    Tree.Kind kind = path.getLeaf().getKind();
    String leafName = null;
    if (kind == Tree.Kind.CLASS || kind == Tree.Kind.INTERFACE) {
        leafName = ((ClassTree) path.getLeaf()).getSimpleName().toString();
    } else if (kind == Tree.Kind.ENUM) {
        if (path.getParentPath() != null) {
            Tree parent = path.getParentPath().getLeaf();
            if (parent.getKind() == Tree.Kind.CLASS || parent.getKind() == Tree.Kind.INTERFACE) {
                result.append(((ClassTree) parent).getSimpleName().toString()).append(".");
            }
            leafName = ((ClassTree) path.getLeaf()).getSimpleName().toString();
        }
    }

    // leafName can be empty for anonymous inner classes, for example.
    boolean isUsefulLeaf = leafName != null && !leafName.isEmpty();
    if (isUsefulLeaf) {
        result.append(".").append(leafName);
    }
    return isUsefulLeaf ? result.toString() : null;
}
 
Example 12
Source File: ConvertToLambdaPreconditionChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ExpressionTree getSelector(Tree tree) {
    switch (tree.getKind()) {
        case MEMBER_SELECT:
            return ((MemberSelectTree) tree).getExpression();
        case METHOD_INVOCATION:
            return getSelector(((MethodInvocationTree) tree).getMethodSelect());
        case NEW_CLASS:
            return getSelector(((NewClassTree) tree).getIdentifier());
        default:
            return null;
    }
}
 
Example 13
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isGetter(Tree member) {
    return member.getKind() == Tree.Kind.METHOD
            && name(member).startsWith("get") //NOI18N
            && ((MethodTree)member).getParameters().isEmpty()
            && (((MethodTree)member).getReturnType().getKind() != Tree.Kind.PRIMITIVE_TYPE
            || ((PrimitiveTypeTree)((MethodTree)member).getReturnType()).getPrimitiveTypeKind() != TypeKind.VOID);
}
 
Example 14
Source File: JavaMoveCodeElementAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private TreePath widenToElementBounds(CompilationInfo cInfo, BaseDocument doc, int[] bounds) {
    SourcePositions sp = cInfo.getTrees().getSourcePositions();
    TreeUtilities tu = cInfo.getTreeUtilities();
    int startOffset = getLineStart(doc, bounds[0]);
    int endOffset = getLineEnd(doc, bounds[1]);
    while (true) {
        TokenSequence<JavaTokenId> ts = SourceUtils.getJavaTokenSequence(cInfo.getTokenHierarchy(), startOffset);
        if (ts != null && (ts.moveNext() || ts.movePrevious())) {
            if (ts.offset() < startOffset && ts.token().id() != JavaTokenId.WHITESPACE) {
                startOffset = getLineStart(doc, ts.offset());
                continue;
            }
        }
        ts = SourceUtils.getJavaTokenSequence(cInfo.getTokenHierarchy(), endOffset);
        if (ts != null && (ts.moveNext() || ts.movePrevious())) {
            if (ts.offset() < endOffset && ts.token().id() != JavaTokenId.WHITESPACE) {
                endOffset = getLineEnd(doc, ts.offset() + ts.token().length());
                continue;
            }
        }
        boolean finish = true;
        TreePath tp = tu.pathFor(startOffset);
        while (tp != null) {
            Tree leaf = tp.getLeaf();
            List<? extends Tree> children = null;
            switch (leaf.getKind()) {
                case BLOCK:
                    if (endOffset < sp.getEndPosition(tp.getCompilationUnit(), leaf)) {
                        children = ((BlockTree) leaf).getStatements();
                    }
                    break;
                case CLASS:
                case INTERFACE:
                case ANNOTATION_TYPE:
                case ENUM:
                    if (endOffset < sp.getEndPosition(tp.getCompilationUnit(), leaf)) {
                        children = ((ClassTree) leaf).getMembers();
                    }
                    break;
            }
            if (children != null) {
                for (Tree tree : children) {
                    int startPos = (int) sp.getStartPosition(tp.getCompilationUnit(), tree);
                    int endPos = (int) sp.getEndPosition(tp.getCompilationUnit(), tree);
                    if (endPos > startOffset) {
                        if (startPos < startOffset) {
                            startOffset = getLineStart(doc, startPos);
                            finish = false;
                        }
                        if (startPos < endOffset && endOffset < endPos) {
                            endOffset = getLineEnd(doc, endPos);
                            finish = false;
                        }
                    }
                }
                break;
            }
            tp = tp.getParentPath();
        }
        if (finish) {
            bounds[0] = startOffset;
            bounds[1] = endOffset;
            return tp;
        }
    }
}
 
Example 15
Source File: Lambda.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Hint(displayName="#DN_lambda2MemberReference", description="#DESC_lambda2MemberReference", category="suggestions", hintKind=Hint.Kind.ACTION,
        minSourceVersion = "8")
@Messages({
    "DN_lambda2MemberReference=Convert Lambda Expression to Member Reference",
    "DESC_lambda2MemberReference=Converts lambda expressions to member references",
    "ERR_lambda2MemberReference=Member reference can be used",
    "FIX_lambda2MemberReference=Use member reference"
})
@TriggerTreeKind(Kind.LAMBDA_EXPRESSION)
public static ErrorDescription lambda2MemberReference(HintContext ctx) {
    TypeMirror samType = ctx.getInfo().getTrees().getTypeMirror(ctx.getPath());        
    if (samType == null || samType.getKind() != TypeKind.DECLARED) {
        return null;
    }

    LambdaExpressionTree lambda = (LambdaExpressionTree) ctx.getPath().getLeaf();
    Tree tree = lambda.getBody();
    if (tree == null) {
        return null;
    }
    if (tree.getKind() == Tree.Kind.BLOCK) {
        if (((BlockTree)tree).getStatements().size() == 1) {
            tree = ((BlockTree)tree).getStatements().get(0);
            if (tree.getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
                tree = ((ExpressionStatementTree)tree).getExpression();
            } else if (tree.getKind() == Tree.Kind.RETURN) {
                tree = ((ReturnTree)tree).getExpression();
            } else {
                return null;
            }
            if (tree == null) {
                return null;
            }
        } else {
            return null;
        }
    }

    if (tree.getKind() != Tree.Kind.METHOD_INVOCATION) {
        return null;
    }

    boolean check = true;
    Iterator<? extends VariableTree> paramsIt = lambda.getParameters().iterator();
    ExpressionTree methodSelect = ((MethodInvocationTree)tree).getMethodSelect();
    if (paramsIt.hasNext() && methodSelect.getKind() == Tree.Kind.MEMBER_SELECT) {
        ExpressionTree expr = ((MemberSelectTree) methodSelect).getExpression();
        if (expr.getKind() == Tree.Kind.IDENTIFIER) {
            if (!((IdentifierTree)expr).getName().contentEquals(paramsIt.next().getName())) {
                paramsIt = lambda.getParameters().iterator();
            }
        }
    }
    Iterator<? extends ExpressionTree> argsIt = ((MethodInvocationTree)tree).getArguments().iterator();
    while (check && argsIt.hasNext() && paramsIt.hasNext()) {
        ExpressionTree arg = argsIt.next();
        if (arg.getKind() != Tree.Kind.IDENTIFIER || !paramsIt.next().getName().contentEquals(((IdentifierTree)arg).getName())) {
            check = false;
        }
    }
    if (!check || paramsIt.hasNext() || argsIt.hasNext()) {
        return null;
    }

    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.ERR_lambda2MemberReference(), new Lambda2MemberReference(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
 
Example 16
Source File: StaticAccess.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected static Fix computeFixes(CompilationInfo info, TreePath treePath, int[] bounds, int[] kind, String[] simpleName) {
    if (treePath.getLeaf().getKind() != Kind.MEMBER_SELECT) {
        return null;
    }
    MemberSelectTree mst = (MemberSelectTree)treePath.getLeaf();
    Tree expression = mst.getExpression();
    TreePath expr = new TreePath(treePath, expression);
    
    TypeMirror tm = info.getTrees().getTypeMirror(expr);
    if (!Utilities.isValidType(tm)) {
        return null;
    }
    Element el = info.getTypes().asElement(tm);
    if (el == null || (!el.getKind().isClass() && !el.getKind().isInterface())) {
        return null;
    }
    
    TypeElement type = (TypeElement)el;
    
    if (isError(type)) {
        return null;
    }
    
    Name idName = null;
    
    if (expression.getKind() == Kind.MEMBER_SELECT) {
        MemberSelectTree exprSelect = (MemberSelectTree)expression;
        idName = exprSelect.getIdentifier();
    }
    
    if (expression.getKind() == Kind.IDENTIFIER) {
        IdentifierTree idt = (IdentifierTree)expression;
        idName = idt.getName();
    }
    
    if (idName != null) {
        if (idName.equals(type.getSimpleName())) {
            return null;
        }
        if (idName.equals(type.getQualifiedName())) {
            return null;
        }
    }
    
    Element used = info.getTrees().getElement(treePath);
    
    if (used == null || !used.getModifiers().contains(Modifier.STATIC)) {
        return null;
    }
    
    if (isError(used)) {
        return null;
    }
    
    if (used.getKind().isField()) {
        kind[0] = 0;
    } else {
        if (used.getKind() == ElementKind.METHOD) {
            kind[0] = 1;
        } else {
            kind[0] = 2;
        }
    }
    
    simpleName[0] = used.getSimpleName().toString();
    
    return new FixImpl(info, expr, type).toEditorFix();
}
 
Example 17
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
@Override
public Void visitCompilationUnit(CompilationUnitTree node, Void unused) {
    boolean first = true;
    if (node.getPackageName() != null) {
        markForPartialFormat();
        visitPackage(node.getPackageName(), node.getPackageAnnotations());
        builder.forcedBreak();
        first = false;
    }
    if (!node.getImports().isEmpty()) {
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.YES);
        }
        for (ImportTree importDeclaration : node.getImports()) {
            markForPartialFormat();
            builder.blankLineWanted(PRESERVE);
            scan(importDeclaration, null);
            builder.forcedBreak();
        }
        first = false;
    }
    dropEmptyDeclarations();
    for (Tree type : node.getTypeDecls()) {
        if (type.getKind() == Tree.Kind.IMPORT) {
            // javac treats extra semicolons in the import list as type declarations
            // TODO(cushon): remove this if https://bugs.openjdk.java.net/browse/JDK-8027682 is fixed
            continue;
        }
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.YES);
        }
        markForPartialFormat();
        scan(type, null);
        builder.forcedBreak();
        first = false;
        dropEmptyDeclarations();
    }
    // set a partial format marker at EOF to make sure we can format the entire file
    markForPartialFormat();
    return null;
}
 
Example 18
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Computes possible types for throw expression. Throw can safely throw an exception, which is
 * either declared by method as a thrown type, or catched within method, by an upper try-catch block.
 * Unchecked exceptions are permitted (derivatives of RuntimeException or Error).
 */
@Override
public List<? extends TypeMirror> visitThrow(ThrowTree node, Object p) {
    List<TypeMirror> result = new ArrayList<TypeMirror>();
    TreePath parents = getCurrentPath();
    Tree prev = null;
    while (parents != null && parents.getLeaf().getKind() != Tree.Kind.METHOD) {
        Tree l = parents.getLeaf();
        if (l.getKind() == Tree.Kind.TRY) {
            TryTree tt = (TryTree) l;
            if (prev == tt.getBlock()) {
                for (CatchTree ct : tt.getCatches()) {
                    TypeMirror ex = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), ct.getParameter().getType()));
                    if (ex != null) {
                        switch (ex.getKind()) {
                            case DECLARED:
                                if (!result.contains(ex)) {
                                    result.add(ex);
                                }
                                break;
                            case UNION:
                                for (TypeMirror t : ((UnionType) ex).getAlternatives()) {
                                    if (!result.contains(t)) {
                                        result.add(t);
                                    }
                                }
                                break;
                        }
                    }
                }
            }
        }
        prev = l;
        parents = parents.getParentPath();
    }
    if (parents != null) {
        MethodTree mt = (MethodTree) parents.getLeaf();
        for (ExpressionTree etree : mt.getThrows()) {
            TypeMirror m = info.getTrees().getTypeMirror(new TreePath(parents, etree));
            if (m != null && !result.contains(m)) {
                result.add(m);
            }
        }
    }
    TypeMirror jlre = info.getElements().getTypeElement("java.lang.RuntimeException").asType(); // NOI18N
    TypeMirror jler = info.getElements().getTypeElement("java.lang.Error").asType(); // NOI18N
    for (TypeMirror em : result) {
        if (jlre != null && info.getTypes().isAssignable(jlre, em)) {
            jlre = null;
        }
        if (jler != null && info.getTypes().isAssignable(jler, em)) {
            jler = null;
        }
        if (jlre == null && jler == null) {
            break;
        }
    }
    if (jlre != null) {
        result.add(jlre);
    }
    if (jler != null) {
        result.add(jler);
    }
    return result;
}
 
Example 19
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 20
Source File: CdiEditorAnalysisFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static List<Integer> getElementPosition(CompilationInfo info, Tree tree){
    SourcePositions srcPos = info.getTrees().getSourcePositions();
    
    int startOffset = (int) srcPos.getStartPosition(info.getCompilationUnit(), tree);
    int endOffset = (int) srcPos.getEndPosition(info.getCompilationUnit(), tree);
    
    Tree startTree = null;
    
    if (TreeUtilities.CLASS_TREE_KINDS.contains(tree.getKind())){
        startTree = ((ClassTree)tree).getModifiers();
        
    } else if (tree.getKind() == Tree.Kind.METHOD){
        startTree = ((MethodTree)tree).getReturnType();
    } else if (tree.getKind() == Tree.Kind.VARIABLE){
        startTree = ((VariableTree)tree).getType();
    }
    
    if (startTree != null){
        int searchStart = (int) srcPos.getEndPosition(info.getCompilationUnit(),
                startTree);
        
        TokenSequence<?> tokenSequence = info.getTreeUtilities().tokensFor(tree);
        
        if (tokenSequence != null){
            boolean eob = false;
            tokenSequence.move(searchStart);
            
            do{
                eob = !tokenSequence.moveNext();
            }
            while (!eob && tokenSequence.token().id() != JavaTokenId.IDENTIFIER);
            
            if (!eob){
                Token<?> identifier = tokenSequence.token();
                startOffset = identifier.offset(info.getTokenHierarchy());
                endOffset = startOffset + identifier.length();
            }
        }
    }
    
    List<Integer> result = new ArrayList<Integer>(2);
    result.add(startOffset);
    result.add(endOffset );
    return result;
}