Java Code Examples for com.sun.source.util.TreePath#getLeaf()

The following examples show how to use com.sun.source.util.TreePath#getLeaf() . 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: IntroduceHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static boolean needsStaticRelativeTo(CompilationInfo info, TreePath targetClass, TreePath occurrence) {
    while (occurrence != null && targetClass.getLeaf() != occurrence.getLeaf()) {
        switch (occurrence.getLeaf().getKind()) {
            case METHOD:
                if (((MethodTree) occurrence.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC)) {
                    return true;
                }
                break;
            case BLOCK:
                if (((BlockTree) occurrence.getLeaf()).isStatic()) {
                    return true;
                }
                break;
            case INTERFACE:
                return true;
        }

        occurrence = occurrence.getParentPath();
    }

    return false;
}
 
Example 2
Source File: CopyFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean visitMemberReference(MemberReferenceTree node, TreePath p) {
    if (p == null)
        return super.visitMemberReference(node, p);

    MemberReferenceTree t = (MemberReferenceTree) p.getLeaf();
    
    if (!node.getMode().equals(t.getMode()))
        return false;

    if (!scan(node.getQualifierExpression(), t.getQualifierExpression(), p))
        return false;

    String ident = t.getName().toString();

    if (ident.startsWith("$")) { //XXX: there should be a utility method for this check
        if (bindState.variables2Names.containsKey(ident)) {
            return node.getName().contentEquals(bindState.variables2Names.get(ident));
        } else {
            bindState.variables2Names.put(ident, node.getName().toString());
        }
        return true;
    }

    return node.getName().contentEquals(t.getName());
}
 
Example 3
Source File: AnnotationProcessors.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath cpath = ctx.getPath();
    if (cpath.getLeaf().getKind() != Tree.Kind.CLASS) {
        return;
    }
    WorkingCopy wc = ctx.getWorkingCopy();
    TreeMaker make = wc.getTreeMaker();
    ClassTree ct = (ClassTree)cpath.getLeaf();
    ModifiersTree mt = ct.getModifiers();
    ModifiersTree nmt = make.Modifiers(mt, Collections.singletonList(
            make.Annotation(
                    make.QualIdent(SUPPORTED_SOURCE_TYPE),
                    Collections.singletonList(
                            make.MemberSelect(
                                    make.QualIdent(SOURCE_VERSION_TYPE), 
                                    wc.getSourceVersion().name()
                            )
                    )
            )
    ));
    wc.rewrite(mt, nmt);
}
 
Example 4
Source File: SuspiciousNamesCombination.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<ErrorDescription> handleAssignment(CompilationInfo info, TreePath treePath) {
    AssignmentTree at = (AssignmentTree) treePath.getLeaf();
    
    String declarationName = getName(at.getVariable());
    String actualName      = getName(at.getExpression());
    
    if (isConflicting(info, declarationName, actualName)) {
        long start = info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), at.getVariable());
        long end   = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), at.getVariable());
        
        if (start != (-1) && end != (-1)) {
            return Collections.singletonList(ErrorDescriptionFactory.createErrorDescription(getSeverity().toEditorSeverity(), "Suspicious names combination", info.getFileObject(), (int) start, (int) end));
        }
    }
    
    return null;
}
 
Example 5
Source File: SourceCodeAnalysisImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Iterable<Pair<ExecutableElement, ExecutableType>> newClassCandidates(AnalyzeTask at, TreePath newClassPath) {
    NewClassTree nct = (NewClassTree) newClassPath.getLeaf();
    Element type = at.trees().getElement(new TreePath(newClassPath.getParentPath(), nct.getIdentifier()));
    TypeMirror targetType = at.trees().getTypeMirror(newClassPath);
    if (targetType == null || targetType.getKind() != TypeKind.DECLARED) {
        Iterable<TypeMirror> targetTypes = findTargetType(at, newClassPath);
        if (targetTypes == null)
            targetTypes = Collections.emptyList();
        targetType =
                StreamSupport.stream(targetTypes.spliterator(), false)
                             .filter(t -> at.getTypes().asElement(t) == type)
                             .findAny()
                             .orElse(at.getTypes().erasure(type.asType()));
    }
    List<Pair<ExecutableElement, ExecutableType>> candidateConstructors = new ArrayList<>();
    Predicate<Element> accessibility = createAccessibilityFilter(at, newClassPath);

    if (targetType != null &&
        targetType.getKind() == TypeKind.DECLARED &&
        type != null &&
        (type.getKind().isClass() || type.getKind().isInterface())) {
        for (ExecutableElement constr : ElementFilter.constructorsIn(type.getEnclosedElements())) {
            if (accessibility.test(constr)) {
                ExecutableType constrType =
                        (ExecutableType) at.getTypes().asMemberOf((DeclaredType) targetType, constr);
                candidateConstructors.add(Pair.of(constr, constrType));
            }
        }
    }

    return candidateConstructors;
}
 
Example 6
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isIfWithContinueOnly(ContinueTree that) {
    TreePath currentTreePath = this.getCurrentPath();
    TreePath parentPath = currentTreePath.getParentPath();
    Tree parentTree = parentPath.getLeaf();
    if (parentTree.getKind() == Tree.Kind.IF) {
        return true;
    } else if (parentTree.getKind() == Tree.Kind.BLOCK) {
        BlockTree parentBlock = (BlockTree) parentTree;
        if (parentBlock.getStatements().size() == 1) {
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: MethodMetrics.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitReturn(ReturnTree node, Object p) {
    TreePath path = getCurrentPath();
    TreePath parentPath = path.getParentPath();
    if (suppress) {
        return  super.visitReturn(node, p);
    }
    if (ignoreGuards && parentPath != null) {
        Tree parentTree = parentPath.getLeaf();
        TreePath branchPath = path;
        while (parentTree.getKind() == Tree.Kind.BLOCK) {
            branchPath = parentPath;
            parentPath = parentPath.getParentPath();
            parentTree = parentPath.getLeaf();
        }
        if (parentTree.getKind() == Tree.Kind.IF) {
            IfTree ifTree = (IfTree)parentTree;
            StatementTree trueTree = ifTree.getThenStatement() == branchPath.getLeaf() ? 
                    ifTree.getThenStatement() : ifTree.getElseStatement();
            if (trueTree == node) {
                return  super.visitReturn(node, p);
            }
            if (trueTree.getKind() == Tree.Kind.BLOCK) {
                BlockTree bt = (BlockTree)trueTree;
                if (bt.getStatements().size() == 1) {
                    return  super.visitReturn(node, p);
                }
            }
        }
    }
    returnCount++;
    return super.visitReturn(node, p);
}
 
Example 8
Source File: ProgramElementDocImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
protected ProgramElementDocImpl(DocEnv env, Symbol sym, TreePath treePath) {
    super(env, treePath);
    this.sym = sym;
    if (treePath != null) {
        tree = (JCTree) treePath.getLeaf();
        lineMap = ((JCCompilationUnit) treePath.getCompilationUnit()).lineMap;
    }
}
 
Example 9
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testFindNameSpanUnicode() throws Exception {
    String code = "package test; public class Test {private int test\\u0061;}";
    prepareTest("Test", code);
    
    TreePath tp = info.getTreeUtilities().pathFor(71 - 24);
    VariableTree ct = (VariableTree) tp.getLeaf();
    
    int[] span = info.getTreeUtilities().findNameSpan(ct);
    
    assertTrue(Arrays.toString(span), Arrays.equals(span, new int[] {69 - 24, 79 - 24}));
}
 
Example 10
Source File: FinalizeNotProtected.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    final Tree tree = tp.getLeaf();
    if (tree.getKind() != Tree.Kind.METHOD) {
        return;
    }
    final TreeMaker tm = wc.getTreeMaker();
    wc.rewrite(((MethodTree)tree).getModifiers(), tm.addModifiersModifier(
            tm.removeModifiersModifier(((MethodTree)tree).getModifiers(), Modifier.PUBLIC),
            Modifier.PROTECTED));
}
 
Example 11
Source File: RefactoringVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param oldTree 
 * @param newTree 
 */
protected void rewrite(Tree oldTree, Tree newTree) {
    workingCopy.rewrite(oldTree, newTree);
    TreePath current = getCurrentPath();
    if (current.getLeaf() == oldTree) {
        JavaRefactoringUtils.cacheTreePathInfo(current, workingCopy);
    } else {
        if (oldTree!=null) {
            TreePath tp = workingCopy.getTrees().getPath(current.getCompilationUnit(), oldTree);
            if(tp != null) {
                JavaRefactoringUtils.cacheTreePathInfo(tp, workingCopy);
            }
        }
    }
}
 
Example 12
Source File: GoToSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static GoToTarget computeGoToTarget(CompilationController controller, Context resolved, int offset) {
    TreePath elpath = getPath(controller, resolved.resolved);

    if (elpath != null) {
        Tree tree = elpath.getLeaf();
        long startPos = controller.getTrees().getSourcePositions().getStartPosition(controller.getCompilationUnit(), tree);

        if (startPos != (-1)) {
            //check if the caret is inside the declaration itself, as jump in this case is not very usefull:
            if (isCaretInsideDeclarationName(controller, tree, elpath, offset)) {
                return new GoToTarget(-1, null, null, null, false);
            } else {
                //#71272: it is necessary to translate the offset:
                return new GoToTarget(controller.getSnapshot().getOriginalOffset((int) startPos),
                                      null,
                                      null,
                                      controller.getElementUtilities().getElementName(resolved.resolved, false).toString(),
                                      true);
            }
        } else {
            return new GoToTarget(-1, null, null, null, false);
        }
    } else {
        return new GoToTarget(-1,
                              controller.getClasspathInfo(),
                              ElementHandle.create(resolved.resolved),
                              controller.getElementUtilities().getElementName(resolved.resolved, false).toString(),
                              true);
    }
}
 
Example 13
Source File: JavacTrees.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
private Env<AttrContext> getAttrContext(TreePath path) {
        if (!(path.getLeaf() instanceof JCTree))  // implicit null-check
            throw new IllegalArgumentException();

        // if we're being invoked via from a JSR199 client, we need to make sure
        // all the classes have been entered; if we're being invoked from JSR269,
        // then the classes will already have been entered.
        if (javacTaskImpl != null) {
            try {
                javacTaskImpl.enter(null);
            } catch (IOException e) {
                throw new Error("unexpected error while entering symbols: " + e);
            }
        }


        JCCompilationUnit unit = (JCCompilationUnit) path.getCompilationUnit();
        Copier copier = new Copier(treeMaker.forToplevel(unit));

        Env<AttrContext> env = null;
        JCMethodDecl method = null;
        JCVariableDecl field = null;

        List<Tree> l = List.nil();
        TreePath p = path;
        while (p != null) {
            l = l.prepend(p.getLeaf());
            p = p.getParentPath();
        }

        for ( ; l.nonEmpty(); l = l.tail) {
            Tree tree = l.head;
            switch (tree.getKind()) {
                case COMPILATION_UNIT:
//                    System.err.println("COMP: " + ((JCCompilationUnit)tree).sourcefile);
                    env = enter.getTopLevelEnv((JCCompilationUnit)tree);
                    break;
                case ANNOTATION_TYPE:
                case CLASS:
                case ENUM:
                case INTERFACE:
//                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
                    env = enter.getClassEnv(((JCClassDecl)tree).sym);
                    break;
                case METHOD:
//                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
                    method = (JCMethodDecl)tree;
                    break;
                case VARIABLE:
//                    System.err.println("FIELD: " + ((JCVariableDecl)tree).sym.getSimpleName());
                    field = (JCVariableDecl)tree;
                    break;
                case BLOCK: {
//                    System.err.println("BLOCK: ");
                    if (method != null)
                        env = memberEnter.getMethodEnv(method, env);
                    JCTree body = copier.copy((JCTree)tree, (JCTree) path.getLeaf());
                    env = attribStatToTree(body, env, copier.leafCopy);
                    return env;
                }
                default:
//                    System.err.println("DEFAULT: " + tree.getKind());
                    if (field != null && field.getInitializer() == tree) {
                        env = memberEnter.getInitEnv(field, env);
                        JCExpression expr = copier.copy((JCExpression)tree, (JCTree) path.getLeaf());
                        env = attribExprToTree(expr, env, copier.leafCopy);
                        return env;
                    }
            }
        }
        return field != null ? memberEnter.getInitEnv(field, env) : env;
    }
 
Example 14
Source File: ClassStructure.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean testClassMayBeInterface(Trees trees, TreeUtilities treeUtilities, TreePath path) {
    final ClassTree cls = (ClassTree) path.getLeaf();
    if (!treeUtilities.isClass(cls)) {
        return true;
    }
    final Element element = trees.getElement(path);
    if (element == null) return false; //see bug #221820
    final TypeMirror superclass = element.getKind().isClass() ? ((TypeElement) element).getSuperclass() : null;
    if (superclass == null || superclass.getKind() != TypeKind.DECLARED
            || !"java.lang.Object".contentEquals(((TypeElement) ((DeclaredType) superclass).asElement()).getQualifiedName())) { //NOI18N
        return false;
    }
    for (Tree member : cls.getMembers()) {
        TreePath memberPath = TreePath.getPath(path, member);
        if (!treeUtilities.isSynthetic(memberPath)) {
            switch (member.getKind()) {
                case VARIABLE:
                    if (!((VariableTree) member).getModifiers().getFlags().containsAll(EnumSet.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL))) {
                        return false;
                    }
                    break;
                case METHOD:
                    if (!((MethodTree) member).getModifiers().getFlags().containsAll(EnumSet.of(Modifier.PUBLIC, Modifier.ABSTRACT))) {
                        return false;
                    }
                    break;
                case ANNOTATION_TYPE:
                case CLASS:
                case ENUM:
                case INTERFACE:
                    if (!testClassMayBeInterface(trees, treeUtilities, memberPath)) {
                        return false;
                    }
                    break;
                default:
                    return false;
            }
        }
    }
    return true;
}
 
Example 15
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 16
Source File: OperatorPrecedence.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Check to see if parentheses are needed for substitution.
 * @param location, the location to substitute
 * @param elementToFind, the element to substitute
 * @param expression, the expression to substitute with
 * @return false when certain not needed, true otherwise
 */
public static boolean needsParentheses(TreePath location, Element elementToFind, ExpressionTree expression, WorkingCopy workingcopy) {
    Trees trees = workingcopy.getTrees();
    CompilationUnitTree cut = workingcopy.getCompilationUnit();
    
    if (!needsParentheses(expression)) {
        return false;
    }

    TreePath parentPath = location.getParentPath();
    Tree parent = parentPath.getLeaf();
    switch (parent.getKind()) {
        case PARENTHESIZED:
        case METHOD_INVOCATION:
        case VARIABLE:
        case RETURN:
        case ASSIGNMENT:
            return false;
    }
    if(parent.getKind().equals(Tree.Kind.PLUS) && expression.getKind().equals(Tree.Kind.PLUS)) {
        if (((BinaryTree) expression).getLeftOperand().getKind().equals(Tree.Kind.STRING_LITERAL)
                || ((BinaryTree) parent).getLeftOperand().getKind().equals(Tree.Kind.STRING_LITERAL)
                || ((BinaryTree) expression).getRightOperand().getKind().equals(Tree.Kind.STRING_LITERAL)
                || ((BinaryTree) parent).getRightOperand().getKind().equals(Tree.Kind.STRING_LITERAL)) {
            return true;
        }
    }
    if(parent.getKind().equals(Tree.Kind.MINUS)) {
        ExpressionTree rightOperand = ((BinaryTree) parent).getRightOperand();
        Element rightElement = trees.getElement(trees.getPath(cut, rightOperand));
        
        if(elementToFind != null && elementToFind.equals(rightElement)) {
            return true;
        }
    }

    switch (parent.getKind()) {
        case PLUS:
        case AND:
        case BITWISE_COMPLEMENT:
        case CONDITIONAL_AND:
        case CONDITIONAL_EXPRESSION:
        case CONDITIONAL_OR:
        case DIVIDE:
        case EQUAL_TO:
        case GREATER_THAN:
        case INSTANCE_OF:
        case LEFT_SHIFT:
        case LESS_THAN:
        case LESS_THAN_EQUAL:
        case LOGICAL_COMPLEMENT:
        case MINUS:
        case MULTIPLY:
        case NOT_EQUAL_TO:
        case OR:
        case POSTFIX_DECREMENT:
        case POSTFIX_INCREMENT:
        case PREFIX_DECREMENT:
        case PREFIX_INCREMENT:
        case REMAINDER:
        case RIGHT_SHIFT:
        case UNARY_MINUS:
        case UNARY_PLUS:
        case UNSIGNED_RIGHT_SHIFT:
        case XOR:
            int substitutePrecedence = OperatorPrecedence.getOperatorPrecedence(expression.getKind());
            int locationPrecedence = OperatorPrecedence.getOperatorPrecedence(parent.getKind());
            if (substitutePrecedence >= locationPrecedence) {
                return false;
            }
    }
    return true;
}
 
Example 17
Source File: OptionalEE7APIsHint.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@TriggerTreeKind({Kind.MEMBER_SELECT, Kind.IDENTIFIER})
public static List<ErrorDescription> run(HintContext context) {
    CompilationInfo info = context.getInfo();
    TreePath treePath = context.getPath();
    Element el = info.getTrees().getElement(treePath);
    if (el == null) {
        return null;
    }
    TypeMirror type = el.asType();
    if (type == null) {
        return null;
    }
    String name = type.toString();
    if (!(name.startsWith("javax.xml.rpc") || name.startsWith("javax.xml.registry") || name.startsWith("javax.enterprise.deploy"))) { // NOI18N
        return null;
    }
    boolean optional = false;
    for (String opt : optionalPackages) {
        if (name.startsWith(opt)) {
            optional = true;
            break;
        }
    }
    
    if (!optional) {
        return null;
    }
    Tree t = treePath.getLeaf();
    int start = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), t);
    int end = (int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), t);
    // #205936
    if (start == -1 || end == -1 || end < start) {
        return null;
    }
    List<Fix> fixes = new ArrayList<Fix>();
    return Collections.<ErrorDescription>singletonList(
            ErrorDescriptionFactory.createErrorDescription(
            context.getSeverity(),
            Bundle.OptionalEE7APIsHint_DisplayName(),
            fixes,
            info.getFileObject(),
            start,
            end));
}
 
Example 18
Source File: UncaughtException.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private List<? extends TypeMirror> findUncaughtExceptions(CompilationInfo info, TreePath path, List<? extends TypeMirror> exceptions) {
    List<TypeMirror> result = new ArrayList<TypeMirror>();
    
    result.addAll(exceptions);
    
    Tree lastTree = null;
    
    while (path != null) {
        Tree currentTree = path.getLeaf();

        if (currentTree.getKind() == Tree.Kind.METHOD) {
            TypeMirror tm = info.getTrees().getTypeMirror(path);
            if (tm != null && tm.getKind() == TypeKind.EXECUTABLE) {
                for (TypeMirror mirr : ((ExecutableType) tm).getThrownTypes()) {
                    for (Iterator<TypeMirror> it = result.iterator(); it.hasNext();)
                        if (info.getTypes().isSameType(it.next(), mirr))
                            it.remove();
                }
                break;
            }
        }            
        
        if (currentTree.getKind() == Tree.Kind.LAMBDA_EXPRESSION) {
            // no checked exceptions can be thrown out of Lambda, #243106
            break;
        }
        
        if (currentTree.getKind() == Kind.TRY) {
            TryTree tt = (TryTree) currentTree;
            
            if (tt.getBlock() == lastTree) {
                for (CatchTree c : tt.getCatches()) {
                    TreePath catchPath = new TreePath(new TreePath(path, c), c.getParameter());
                    VariableElement variable = (VariableElement) info.getTrees().getElement(catchPath);
                    if (variable == null) {
                        continue;
                    }
                    TypeMirror variableType = variable.asType();
                    if (variableType.getKind() == TypeKind.UNION) {
                        result.removeAll(((UnionType)variableType).getAlternatives());
                    } else {
                        result.remove(variableType);
                    }
                }
            }
        }
        
        lastTree = path.getLeaf();
        path = path.getParentPath();
    }
    
    List<TypeMirror> filtered = new ArrayList<>();
    
    OUTER: for (Iterator<TypeMirror> sourceIt = result.iterator(); sourceIt.hasNext(); ) {
        TypeMirror sourceType = sourceIt.next();
        
        for (Iterator<TypeMirror> filteredIt = filtered.iterator(); filteredIt.hasNext(); ) {
            TypeMirror filteredType = filteredIt.next();
            
            if (info.getTypes().isSubtype(sourceType, filteredType)) {
                sourceIt.remove();
                continue OUTER;
            }
            
            if (info.getTypes().isSubtype(filteredType, sourceType)) {
                filteredIt.remove();
                break;
            }
        }
        
        filtered.add(sourceType);
    }
    
    return filtered;
}
 
Example 19
Source File: CopyFinder.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public Boolean visitMethod(MethodTree node, TreePath p) {
    if (p == null)
        return super.visitMethod(node, p);

    MethodTree t = (MethodTree) p.getLeaf();

    if (!scan(node.getModifiers(), t.getModifiers(), p))
        return false;

    if (!checkLists(node.getTypeParameters(), t.getTypeParameters(), p))
        return false;

    if (!scan(node.getReturnType(), t.getReturnType(), p))
        return false;

    String name = t.getName().toString();

    if (name.startsWith("$")) { //XXX: there should be a utility method for this check
        String existingName = bindState.variables2Names.get(name);
        String currentName = node.getName().toString();

        if (existingName != null) {
            if (!existingName.equals(currentName)) {
                return false;
            }
            bindState.variables.put(name + "$" + ++bindState.matchCount, currentPath);
        } else {
            //XXX: putting the variable into both variables and variable2Names.
            //variables is needed by the declarative hints to support conditions like
            //referencedIn($variable, $statements$):
            //causes problems in JavaFix, see visitIdentifier there.
            bindState.variables.put(name, getCurrentPath());
            bindState.variables2Names.put(name, currentName);
        }
    } else {
        if (!node.getName().contentEquals(name))
            return false;
    }

    if (!checkLists(node.getParameters(), t.getParameters(), p))
        return false;

    if (!checkLists(node.getThrows(), t.getThrows(), p))
        return false;

    if (!scan(node.getBody(), t.getBody(), p))
        return false;

    return scan(node.getDefaultValue(), t.getDefaultValue(), p);
}
 
Example 20
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 3 votes vote down vote up
public void testFindNameSpan2() throws Exception {
    prepareTest("Test", "package test; public /*dsfasfd*/   class   /*laksdjflk*/   /**asdff*/ //    \n Test {}");
    
    TreePath tp = info.getTreeUtilities().pathFor(109 - 30);
    ClassTree ct = (ClassTree) tp.getLeaf();
    
    int[] span = info.getTreeUtilities().findNameSpan(ct);
    
    assertTrue(Arrays.toString(span), Arrays.equals(span, new int[] {108 - 30, 112 - 30}));
}