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

The following examples show how to use com.sun.source.tree.Tree.Kind#NEW_CLASS . 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: TreeUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**Returns whether or not the given tree is synthetic - generated by the parser.
 * Please note that this method does not check trees transitively - a child of a syntetic tree
 * may be considered non-syntetic.
 * 
 * @return true if the given tree is synthetic, false otherwise
 * @throws NullPointerException if the given tree is null
 */
public boolean isSynthetic(TreePath path) throws NullPointerException {
    if (path == null)
        throw new NullPointerException();
    
    while (path != null) {
        if (isSynthetic(path.getCompilationUnit(), path.getLeaf()))
            return true;
        if (path.getParentPath() != null &&
            path.getParentPath().getParentPath() != null &&
            path.getParentPath().getParentPath().getLeaf().getKind() == Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) path.getParentPath().getParentPath().getLeaf();
            ClassTree body = nct.getClassBody();

            if (body != null &&
                (body.getExtendsClause() == path.getLeaf() ||
                 body.getImplementsClause().contains(path.getLeaf()))) {
                return true;
            }
        }

        path = path.getParentPath();
    }
    
    return false;
}
 
Example 2
Source File: BreadCrumbsNodeImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static String className(TreePath path) {
    ClassTree ct = (ClassTree) path.getLeaf();
    
    if (path.getParentPath().getLeaf().getKind() == Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree) path.getParentPath().getLeaf();
        
        if (nct.getClassBody() == ct) {
            return simpleName(nct.getIdentifier());
        }
    } else if (path.getParentPath().getLeaf() == path.getCompilationUnit()) {
        ExpressionTree pkg = path.getCompilationUnit().getPackageName();
        String pkgName = pkg != null ? pkg.toString() : null;
        if (pkgName != null && !pkgName.contentEquals(ERR_NAME)) {
            return pkgName + '.' + ct.getSimpleName().toString();
        }
    }
    
    return ct.getSimpleName().toString();
}
 
Example 3
Source File: ConvertToLambda.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws IOException {

    WorkingCopy copy = ctx.getWorkingCopy();
    copy.toPhase(Phase.RESOLVED);

    TreePath tp = ctx.getPath();

    if (tp.getLeaf().getKind() != Kind.NEW_CLASS) {
        //XXX: warning
        return;
    }

    ConvertToLambdaConverter converter = new ConvertToLambdaConverter(tp, copy);
    if (useMemberReference) {
        converter.performRewriteToMemberReference();
    } else {
        converter.performRewriteToLambda();
    }
}
 
Example 4
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static TreePath deepTreePath(CompilationInfo info, int offset) {
    TreePath basic = info.getTreeUtilities().pathFor(offset);
    TreePath plusOne = info.getTreeUtilities().pathFor(offset + 1);
    
    TreePath parent = plusOne.getParentPath();
    if (parent == null) {
        return basic;
    }
    if (plusOne.getLeaf().getKind() == Kind.NEW_CLASS &&
        parent.getLeaf().getKind() == Kind.EXPRESSION_STATEMENT) {
        parent = parent.getParentPath();
        if (parent == null) {
            return basic;
        }
    }
    if (parent.getLeaf() == basic.getLeaf()) {
        return plusOne;
    }
    return basic;
}
 
Example 5
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected boolean generateClassBody(TreePath p) throws Exception {
    Element e = copy.getTrees().getElement(p);
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    if (isUsableElement) {
        return true;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        VariableTree var = (VariableTree) p.getLeaf();
        if (var.getInitializer() != null && var.getInitializer().getKind() == Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) var.getInitializer();
            if (nct.getClassBody() != null) {
                return true;
            }
        }
    }
    return !generateClassBody2(copy, p);
}
 
Example 6
Source File: ComputeImports.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitClass(ClassTree node, Map<String, Object> p) {
    if (getCurrentPath().getParentPath().getLeaf().getKind() != Kind.NEW_CLASS) {
        filterByAcceptedKind(node.getExtendsClause(), ElementKind.CLASS);
        for (Tree intf : node.getImplementsClause()) {
            filterByAcceptedKind(intf, ElementKind.INTERFACE, ElementKind.ANNOTATION_TYPE);
        }
    }

    scan(node.getModifiers(), p);
    scan(node.getTypeParameters(), p, true);
    scan(node.getExtendsClause(), p, true);
    scan(node.getImplementsClause(), p, true);
    scan(node.getMembers(), p);

    return null;
}
 
Example 7
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 8
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 9
Source File: Unbalanced.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPattern(value="$mods$ $type $name = $init$;")
public static ErrorDescription after(HintContext ctx) {
    if (testElement(ctx) == null) return null;

    TreePath init = ctx.getVariables().get("$init$");

    if (init != null) {
        if (init.getLeaf().getKind() != Kind.NEW_CLASS) return null;

        NewClassTree nct = (NewClassTree) init.getLeaf();

        if (nct.getClassBody() != null || nct.getArguments().size() > 1) return null;

        if (nct.getArguments().size() == 1) {
            TypeMirror tm = ctx.getInfo().getTrees().getTypeMirror(new TreePath(init, nct.getArguments().get(0)));

            if (tm == null || tm.getKind() != TypeKind.INT) return null;
        }
    }

    if (   ctx.getPath().getParentPath().getLeaf().getKind() == Kind.ENHANCED_FOR_LOOP
        && ((EnhancedForLoopTree) ctx.getPath().getParentPath().getLeaf()).getVariable() == ctx.getPath().getLeaf()) {
        return null;
    }
    
    return produceWarning(ctx, "ERR_UnbalancedCollection");
}
 
Example 10
Source File: Reindenter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private int getRecordIndent(int startOffset, int endOffset, JavaTokenId nextTokenId, int lastPos, int currentIndent) throws BadLocationException {
    LinkedList<? extends Tree> path = getPath(startOffset);
    Tree last = path.getFirst();
    TokenSequence<JavaTokenId> token = findFirstNonWhitespaceToken(startOffset, endOffset);
    nextTokenId = token != null ? token.token().id() : null;
    if (nextTokenId != null && nextTokenId == JavaTokenId.RBRACE) {
        if (isLeftBraceOnNewLine(lastPos, startOffset)) {
            switch (cs.getClassDeclBracePlacement()) {
                case NEW_LINE_INDENTED:
                    currentIndent += cs.getIndentSize();
                    break;
                case NEW_LINE_HALF_INDENTED:
                    currentIndent += (cs.getIndentSize() / 2);
                    break;
            }
        }
    } else {

        token = findFirstNonWhitespaceToken(startOffset, lastPos);
        JavaTokenId prevTokenId = token != null ? token.token().id() : null;
        if (prevTokenId != null) {
            switch (prevTokenId) {
                case LBRACE:
                    if (path.size() > 1 && path.get(1).getKind() == Kind.NEW_CLASS && isLeftBraceOnNewLine(lastPos, startOffset)) {
                        switch (cs.getClassDeclBracePlacement()) {
                            case SAME_LINE:
                            case NEW_LINE:
                                currentIndent += cs.getIndentSize();
                                break;
                            case NEW_LINE_HALF_INDENTED:
                                currentIndent += (cs.getIndentSize() - cs.getIndentSize() / 2);
                                break;
                        }
                    } else {
                        currentIndent += cs.indentTopLevelClassMembers() ? cs.getIndentSize() : 0;
                    }
                    break;
                case COMMA:
                    List<? extends Tree> implClauses = ((ClassTree) last).getImplementsClause();
                    if (!implClauses.isEmpty() && getStartPosition(implClauses.get(0)) < token.offset()) {
                        currentIndent = getMultilineIndent(implClauses, path, token.offset(), currentIndent, cs.alignMultilineImplements(), true);
                        break;
                    }
                    List<? extends Tree> members = ((ClassTree) last).getMembers();
                    if (!members.isEmpty() && getStartPosition(members.get(0)) < token.offset()) {
                        currentIndent = getMultilineIndent(members, path, token.offset(), currentIndent, cs.alignMultilineMethodParams(), true);
                        break;
                    }
                    List<? extends TypeParameterTree> typeParams = ((ClassTree) last).getTypeParameters();
                    if (!typeParams.isEmpty() && getStartPosition(typeParams.get(0)) < token.offset()) {
                        currentIndent = getMultilineIndent(typeParams, path, token.offset(), currentIndent, cs.alignMultilineMethodParams(), true);
                        break;
                    }
                    break;
                case IDENTIFIER:
                case GT:
                case GTGT:
                case GTGTGT:
                case RPAREN:
                    if (nextTokenId != null && nextTokenId == JavaTokenId.LBRACE) {
                        switch (cs.getClassDeclBracePlacement()) {
                            case NEW_LINE_INDENTED:
                                currentIndent += cs.getIndentSize();
                                break;
                            case NEW_LINE_HALF_INDENTED:
                                currentIndent += (cs.getIndentSize() / 2);
                                break;
                        }
                    } else {
                        currentIndent += cs.getContinuationIndentSize();
                    }
                    break;

                default:
                    Tree t = null;
                    for (Tree member : ((ClassTree) last).getMembers()) {

                        if (member.getKind() == Tree.Kind.VARIABLE && !((VariableTree) member).getModifiers().getFlags().contains(Modifier.STATIC)) {
                            continue;
                        }
                        if (getEndPosition(member) > startOffset) {
                            break;
                        }
                        t = member;
                    }
                    if (t != null) {
                        int i = getCurrentIndent(t, path);
                        currentIndent = i < 0 ? currentIndent + (cs.indentTopLevelClassMembers() ? cs.getIndentSize() : 0) : i;
                        return currentIndent;
                    }

                    currentIndent += cs.getContinuationIndentSize();
            }
        }
    }
    return currentIndent;
}
 
Example 11
Source File: ComputeImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
        public Void visitVariable(VariableTree tree, Map<String, Object> p) {
            scan(tree.getModifiers(), p);
            
            if (tree.getType() != null && tree.getType().getKind() == Kind.IDENTIFIER) {
                p.put("request", null);
            }
            
            scan(tree.getType(), p, true);
            
            Union2<String, DeclaredType> leftSide = (Union2<String, DeclaredType>) p.remove("result");
            
            p.remove("request");
            
            Union2<String, DeclaredType> rightSide = null;
            
            if (leftSide != null && tree.getInitializer() != null) {
                Element el = info.getTrees().getElement(new TreePath(getCurrentPath(),tree.getInitializer()));
                TypeMirror rightType = el != null ? el.asType() : null;
                
//                System.err.println("rightType = " + rightType );
//                System.err.println("tree.getInitializer()=" + tree.getInitializer());
//                System.err.println("rightType.getKind()=" + rightType.getKind());
//                System.err.println("INVALID_TYPES.contains(rightType.getKind())=" + INVALID_TYPES.contains(rightType.getKind()));
                if (rightType != null && rightType.getKind() == TypeKind.DECLARED) {
                    rightSide = Union2.<String, DeclaredType>createSecond((DeclaredType) rightType);
                } else {
                    if (tree.getInitializer().getKind() == Kind.NEW_CLASS || tree.getInitializer().getKind() == Kind.NEW_ARRAY) {
                        p.put("request", null);
                    }
                }
            }
            
            scan(tree.getInitializer(), p);
            
            rightSide = rightSide == null ? (Union2<String, DeclaredType>) p.remove("result") : rightSide;
            
            p.remove("result");
            
//            System.err.println("rightSide = " + rightSide );
            
            p.remove("request");
            
            if (leftSide != null && rightSide != null) {
                if (!(leftSide instanceof TypeMirror) || !(rightSide instanceof TypeMirror)) {
                    hints.add(new TypeHint(leftSide, rightSide));
                }
            }
            
            return null;
        }
 
Example 12
Source File: SourceCodeAnalysisImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private boolean isNewClass(TreePath tp) {
    return tp.getParentPath() != null &&
           tp.getParentPath().getLeaf().getKind() == Kind.NEW_CLASS &&
           ((NewClassTree) tp.getParentPath().getLeaf()).getIdentifier() == tp.getLeaf();
}
 
Example 13
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;
}