Java Code Examples for com.sun.source.tree.Tree

The following are top voted examples for showing how to use com.sun.source.tree.Tree. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: ScanningCancellableTask.java   Source Code and License 6 votes vote down vote up
protected <R, P> R scan(CancellableTreePathScanner<R, P> scanner, Tree toScan, P p) {
    if (isCancelled())
        return null;
    
    try {
        synchronized (this) {
            this.pathScanner = scanner;
        }
        
        if (isCancelled())
            return null;
        
        return scanner.scan(toScan, p);
    } finally {
        synchronized (this) {
            this.pathScanner = null;
        }
    }
}
 
Example 2
Project: incubator-netbeans   File: RefactoringVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public Tree scan(Tree tree, Element p) {
    final TreePath currentPath = getCurrentPath();
    if(docScanner != null && tree != null && currentPath != null) {
        switch(tree.getKind()) {
            case METHOD:
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
            case VARIABLE:
                TreePath path = new TreePath(currentPath, tree);
                scanJavadoc(path, p);
            default:
                break;
        }
    }
    return super.scan(tree, p);
}
 
Example 3
Project: incubator-netbeans   File: Utilities.java   Source Code and License 6 votes vote down vote up
@Override
public Boolean visitThrow(ThrowTree node, Void p) {
    TypeMirror type = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
    boolean isCaught = false;

    OUTER: for (Pair<Set<TypeMirror>, Tree> pair : caughtExceptions) {
        Set<TypeMirror> caught = pair.first();
        for (TypeMirror c : caught) {
            if (info.getTypes().isSubtype(type, c)) {
                isCaught = true;
                targetTrees.add(pair.second());
                break OUTER;
            }
        }
    }

    return super.visitThrow(node, p) == Boolean.TRUE || !isCaught;
}
 
Example 4
Project: incubator-netbeans   File: RenameRefactoringPlugin.java   Source Code and License 6 votes vote down vote up
@Override
protected JavaSource getJavaSource(Phase p) {
    if (treePathHandle == null && docTreePathHandle == null) {
        return null;
    }
    switch (p) {
        case PRECHECK:
        case FASTCHECKPARAMETERS:
            return JavaSource.forFileObject(docTreePathHandle != null? docTreePathHandle.getTreePathHandle().getFileObject()
                                                                     : treePathHandle.getFileObject());
        case PREPARE:
        case CHECKPARAMETERS:
            if(treePathHandle != null && treePathHandle.getKind() == Tree.Kind.LABELED_STATEMENT) {
                return JavaSource.forFileObject(treePathHandle.getFileObject());
            }
            ClasspathInfo cpInfo = getClasspathInfo(refactoring);
            JavaSource source = JavaSource.create(cpInfo, docTreePathHandle != null? docTreePathHandle.getTreePathHandle().getFileObject()
                                                                     : treePathHandle.getFileObject());
            return source;
            
    }
    throw new IllegalStateException();
}
 
Example 5
Project: incubator-netbeans   File: DiffContext.java   Source Code and License 6 votes vote down vote up
/**
 * Note: the constructor is only used when creating new compilation units; a special flag will be set up, so an initial comment is not skipped.
 */
public DiffContext(CompilationInfo copy, CompilationUnitTree cut, String code, PositionConverter positionConverter, FileObject file, Set<Tree> syntheticTrees, CompilationUnitTree mainUnit, String mainCode) {
    this.tokenSequence = TokenHierarchy.create(code, JavaTokenId.language()).tokenSequence(JavaTokenId.language());
    this.origText = code;
    this.style = getCodeStyle(copy);
    this.context = JavaSourceAccessor.getINSTANCE().getJavacTask(copy).getContext();
    this.origUnit = (JCCompilationUnit) cut;
    this.trees = copy.getTrees();
    this.doc = null;
    this.positionConverter = positionConverter;
    this.file = file;
    this.syntheticTrees = syntheticTrees;
    this.mainUnit = (JCCompilationUnit) mainUnit;
    this.mainCode = mainCode;
    
    this.textLength = copy.getSnapshot() == null ? Integer.MAX_VALUE : copy.getSnapshot().getOriginalOffset(copy.getSnapshot().getText().length());
    this.blockSequences = new BlockSequences(this.tokenSequence, doc, textLength);
    this.forceInitialComment = true;
}
 
Example 6
Project: incubator-netbeans   File: TreePathHandle.java   Source Code and License 6 votes vote down vote up
public TreePath resolve(CompilationInfo compilationInfo) throws IllegalArgumentException {
    TreePath p = parent.resolve(compilationInfo);

    if (p == null) return null;

    List<Tree> children = listChildren(p.getLeaf());

    if (index < children.size()) {
        Tree t = children.get(index);

        if (t.getKind() == kind) {
            return new TreePath(p, t);
        }
    }

    return null;
}
 
Example 7
Project: incubator-netbeans   File: Utilities.java   Source Code and License 6 votes vote down vote up
public static boolean isFakeClass(Tree t) {
    if (!(t instanceof ClassTree)) {
        return false;
    }

    ClassTree ct = (ClassTree) t;

    if (ct.getMembers().isEmpty()) {
        return false;
    }

    CharSequence wildcardTreeName = Utilities.getWildcardTreeName(ct.getMembers().get(0));

    if (wildcardTreeName == null) {
        return false;
    }

    return wildcardTreeName.toString().startsWith("$$");
}
 
Example 8
Project: incubator-netbeans   File: GoToSupport.java   Source Code and License 6 votes vote down vote up
private static boolean isCaretInsideDeclarationName(CompilationInfo info, Tree t, TreePath path, int caret) {
    try {
        switch (t.getKind()) {
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
            case METHOD:
            case VARIABLE:
                int[] span = org.netbeans.modules.java.editor.base.semantic.Utilities.findIdentifierSpan(path, info, info.getDocument());

                if (span == null || span[0] == (-1) || span[1] == (-1)) {
                    return false;
                }

                return span[0] <= caret && caret <= span[1];
            default:
                return false;
        }

    } catch (IOException iOException) {
        Exceptions.printStackTrace(iOException);
        return false;
    }
}
 
Example 9
Project: incubator-netbeans   File: TooStrongCast.java   Source Code and License 6 votes vote down vote up
/**
 * Checks whether a method or constructor call would become ambiguous if the parameter type changes.
 * 
 * @param info compilation context
 * @param parentExec path to the constructor or method invocation
 * @param argIndex
 * @param casteeType
 * @return 
 */
private static boolean checkAmbiguous(CompilationInfo info, final TreePath parentExec, int argIndex, TypeMirror casteeType, TreePath realArgTree) {
    CharSequence altType = info.getTypeUtilities().getTypeName(casteeType, TypeUtilities.TypeNameOptions.PRINT_FQN);
    String prefix = null;
    if (casteeType != null && !(casteeType.getKind() == TypeKind.NULL || casteeType.getKind() == TypeKind.INTERSECTION)) {
        prefix = "(" + altType + ")"; // NOI18N
    }
    Tree leaf = parentExec.getLeaf();
    List<? extends Tree> arguments;
    if (leaf instanceof MethodInvocationTree) {
        MethodInvocationTree mi = (MethodInvocationTree)leaf;
        arguments = mi.getArguments();
    } else {
        arguments = ((NewClassTree)leaf).getArguments();
    }
    Tree argTree = arguments.get(argIndex);
    TreePath argPath = new TreePath(parentExec, argTree);
    return !Utilities.checkAlternativeInvocation(info, parentExec, argPath, realArgTree, prefix);
}
 
Example 10
Project: incubator-netbeans   File: StringBufferCharConstructor.java   Source Code and License 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath p = ctx.getPath();
    if (p.getLeaf().getKind() != Tree.Kind.NEW_CLASS) {
        return;
    }
    NewClassTree origNct = (NewClassTree)p.getLeaf();
    if (origNct.getArguments().size() != 1) {
        return;
    }
    NewClassTree nct = GeneratorUtilities.get(ctx.getWorkingCopy()).importComments(origNct, ctx.getWorkingCopy().getCompilationUnit());
    ExpressionTree charArg = nct.getArguments().get(0);
    TreeMaker mk = ctx.getWorkingCopy().getTreeMaker();
    
    ExpressionTree newExpr = mk.NewClass(nct.getEnclosingExpression(), (List<ExpressionTree>)nct.getTypeArguments(), nct.getIdentifier(), 
            Collections.<ExpressionTree>emptyList(), nct.getClassBody());

    Tree replace = mk.MethodInvocation(
            Collections.<ExpressionTree>emptyList(), 
            mk.MemberSelect(newExpr, "append"), // NOI18N
            Collections.singletonList(charArg));
    ctx.getWorkingCopy().rewrite(nct, replace);
}
 
Example 11
Project: incubator-netbeans   File: IntroduceMethodFix.java   Source Code and License 6 votes vote down vote up
private void generateMethodContents(List<StatementTree> methodStatements) {
    Iterator<TypeMirrorHandle> additionalType = additionalLocalTypes.iterator();
    Iterator<String> additionalName = additionalLocalNames.iterator();
    while (additionalType.hasNext() && additionalName.hasNext()) {
        TypeMirror tm = additionalType.next().resolve(copy);
        if (tm == null) {
            //XXX:
            return;
        }
        Tree type = make.Type(tm);
        methodStatements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), additionalName.next(), type, null));
    }
    if (from == to && statements.get(from).getKind() == Tree.Kind.BLOCK) {
        methodStatements.addAll(((BlockTree) statements.get(from)).getStatements());
    } else {
        methodStatements.addAll(statements.subList(from, to + 1));
    }
}
 
Example 12
Project: incubator-netbeans   File: TokenList.java   Source Code and License 6 votes vote down vote up
public void moveToEnd(Tree t) {
    if (t == null) {
        return ;
    }

    long end = sourcePositions.getEndPosition(info.getCompilationUnit(), t);

    if (end == (-1))
        return ;

    if (t.getKind() == Kind.ARRAY_TYPE) {
        moveToEnd(((ArrayTypeTree) t).getType());
        return ;
    }
    moveToOffset(end);
}
 
Example 13
Project: incubator-netbeans   File: MathRandomCast.java   Source Code and License 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    // path should be the typecast expression
    TreePath path = ctx.getPath();
    TreePath exprPath = exprHandle.resolve(ctx.getWorkingCopy());
    
    if (path.getLeaf().getKind() != Tree.Kind.TYPE_CAST || exprPath == null || !EXPRESSION_KINDS.contains(exprPath.getLeaf().getKind())) {
        // PENDING - some message ?
        return;
    }
    WorkingCopy copy = ctx.getWorkingCopy();
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    TypeCastTree cast = (TypeCastTree)path.getLeaf();
    // rewrite the type cast to the casted Math.random()
    copy.rewrite(path.getLeaf(), cast.getExpression());
    // rewrite the outermost expression to a typecast of it
    ExpressionTree expr = (ExpressionTree)exprPath.getLeaf();
    if (expr.getKind() != Tree.Kind.PARENTHESIZED) {
        expr = make.Parenthesized(expr);
    }
    copy.rewrite(exprPath.getLeaf(), make.TypeCast(cast.getType(), (ExpressionTree)expr));
}
 
Example 14
Project: incubator-netbeans   File: CreateElementUtilities.java   Source Code and License 6 votes vote down vote up
private static List<? extends TypeMirror> computeMethodInvocation(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    MethodInvocationTree nat = (MethodInvocationTree) parent.getLeaf();
    boolean errorInRealArguments = false;
    
    for (Tree param : nat.getArguments()) {
        errorInRealArguments |= param == error;
    }
    
    if (errorInRealArguments) {
        List<TypeMirror> proposedTypes = new ArrayList<TypeMirror>();
        int[] proposedIndex = new int[1];
        List<ExecutableElement> ee = fuzzyResolveMethodInvocation(info, parent, proposedTypes, proposedIndex);
        
        if (ee.isEmpty()) { //cannot be resolved
            return null;
        }
        
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return proposedTypes;
    }
    
    return null;
}
 
Example 15
Project: incubator-netbeans   File: ElementNode.java   Source Code and License 6 votes vote down vote up
public int getStart() {
    final int[] result = new int[] {-1};

    try {
        JavaSource.create(info.getClasspathInfo()).runUserActionTask(new Task<CompilationController>() {
            public void run(CompilationController parameter) throws Exception {
                Tree tree = info.getTrees().getTree(element);
                if (tree != null) {
                    result[0] = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), tree);
                }
            }
        }, true);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

    return result[0];
}
 
Example 16
Project: incubator-netbeans   File: Utilities.java   Source Code and License 6 votes vote down vote up
/**
 * Attempts to resolve a method or a constructor call with an altered argument tree.
 * 
 * @param ci the context
 * @param invPath path to the method invocation node
 * @param origPath path to the Tree within method's arguments which should be replaced
 * @param valPath the replacement tree
 * @return 
 */
public static boolean checkAlternativeInvocation(CompilationInfo ci, TreePath invPath, 
        TreePath origPath,
        TreePath valPath, String customPrefix) {
    Tree l = invPath.getLeaf();
    Tree sel;
    
    if (l.getKind() == Tree.Kind.NEW_CLASS) {
        NewClassTree nct = (NewClassTree)invPath.getLeaf();
        sel = nct.getIdentifier();
    } else if (l.getKind() == Tree.Kind.METHOD_INVOCATION) {
        MethodInvocationTree mit = (MethodInvocationTree)invPath.getLeaf();
        sel = mit.getMethodSelect();
    } else {
        return false;
    }
    
    return resolveAlternativeInvocation(ci, invPath, 
            origPath, sel, valPath, customPrefix);
}
 
Example 17
Project: incubator-netbeans   File: GeneratorUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * Copy comments from source tree to target tree. Copying a given comment twice will be ignored.
 *
 * @param source tree to copy comments from
 * @param target tree to copy comments to
 * @param preceding true iff preceding comments should be copied
 * @since 0.51
 */
public void copyComments(Tree source, Tree target, boolean preceding) {
    CommentHandlerService handler = CommentHandlerService.instance(copy.impl.getJavacTask().getContext());
    CommentSetImpl s = handler.getComments(source);

    TreeUtilities.ensureCommentsMapped(copy, source, s);

    CommentSetImpl t = handler.getComments(target);

    if (preceding) {
        t.addComments(RelativePosition.PRECEDING, copy.useComments(s.getComments(RelativePosition.PRECEDING)));
        t.addComments(RelativePosition.INNER, copy.useComments(s.getComments(RelativePosition.INNER)));
    } else {
        t.addComments(RelativePosition.INLINE, copy.useComments(s.getComments(RelativePosition.INLINE)));
        t.addComments(RelativePosition.TRAILING, copy.useComments(s.getComments(RelativePosition.TRAILING)));
    }
}
 
Example 18
Project: incubator-netbeans   File: ConvertToARM.java   Source Code and License 6 votes vote down vote up
private static boolean hasNonCleanUpUsages(
        final Collection<? extends TreePath> usages,
        final Collection<? super TreePath> cleanupStatements) {
    for (TreePath usage : usages) {
        final TreePath parentPath = usage.getParentPath();
        final Tree parent = parentPath.getLeaf();
        if (parent.getKind() != Tree.Kind.ASSIGNMENT) {
            return true;
        }
        final AssignmentTree assign = (AssignmentTree) parent;
        if (assign.getVariable() != usage.getLeaf()) {
            return true;
        }
        if (assign.getExpression().getKind() != Tree.Kind.NULL_LITERAL) {
            return true;
        }
        final TreePath parentParent = parentPath.getParentPath();
        if (parentParent.getLeaf().getKind() != Tree.Kind.EXPRESSION_STATEMENT) {
            return true;
        }
        cleanupStatements.add(parentParent);
    }
    return false;
}
 
Example 19
Project: incubator-netbeans   File: VeryPretty.java   Source Code and License 6 votes vote down vote up
@Override
   public void visitIf(JCIf tree) {
print("if");
       print(cs.spaceBeforeIfParen() ? " (" : "(");
       if (cs.spaceWithinIfParens())
           print(' ');
printNoParenExpr(tree.cond);
print(cs.spaceWithinIfParens() ? " )" : ")");
       boolean prevblock = tree.thenpart.getKind() == Tree.Kind.BLOCK && cs.redundantIfBraces() != BracesGenerationStyle.ELIMINATE || cs.redundantIfBraces() == BracesGenerationStyle.GENERATE;
if (tree.elsepart != null && danglingElseChecker.hasDanglingElse(tree.thenpart)) {
    printBlock(tree.thenpart, cs.getOtherBracePlacement(), cs.spaceBeforeIfLeftBrace());
    prevblock = true;
} else
    printIndentedStat(tree.thenpart, cs.redundantIfBraces(), cs.spaceBeforeIfLeftBrace(), cs.wrapIfStatement());
if (tree.elsepart != null) {
       printElse(tree, prevblock);
}
   }
 
Example 20
Project: incubator-netbeans   File: CreateElementUtilities.java   Source Code and License 6 votes vote down vote up
private static List<? extends TypeMirror> computeClass(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ClassTree ct = (ClassTree) parent.getLeaf();
    
    if (ct.getExtendsClause() == error) {
        types.add(ElementKind.CLASS);
        return null;
    }
    
    for (Tree t : ct.getImplementsClause()) {
        if (t == error) {
            types.add(ElementKind.INTERFACE);
            return null;
        }
    }
    
    //XXX: annotation types...
    
    return null;
}
 
Example 21
Project: incubator-netbeans   File: BoxedIdentityComparison.java   Source Code and License 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TreePath p = ctx.getPath();
    if (p.getLeaf().getKind() != Tree.Kind.EQUAL_TO  && p.getLeaf().getKind() != Tree.Kind.NOT_EQUAL_TO) {
        // TODO - report ?
        return;
    }
    BinaryTree bt = (BinaryTree)p.getLeaf();
    TreeMaker mk = ctx.getWorkingCopy().getTreeMaker();
    ExpressionTree replace = mk.MethodInvocation(
        Collections.<ExpressionTree>emptyList(),
        mk.MemberSelect(
            mk.QualIdent(JU_OBJECTS), "equals" // NOI18N
        ), 
        Arrays.asList(bt.getLeftOperand(), bt.getRightOperand())
    );
    if (bt.getKind() == Tree.Kind.NOT_EQUAL_TO) {
        replace = mk.Unary(Tree.Kind.LOGICAL_COMPLEMENT, replace);
    }
    ctx.getWorkingCopy().rewrite(bt, replace);
}
 
Example 22
Project: incubator-netbeans   File: Flow.java   Source Code and License 6 votes vote down vote up
private void resumeAfter(Tree target, Map< Element, State> state) {
    for (TreePath tp : pendingFinally) {
        boolean shouldBeRun = false;

        for (Tree t : tp) {
            if (t == target) {
                shouldBeRun = true;
                break;
            }
        }

        if (shouldBeRun) {
            recordResume(resumeBefore, tp.getLeaf(), state);
        } else {
            break;
        }
    }

    recordResume(resumeAfter, target, state);
}
 
Example 23
Project: incubator-netbeans   File: ConvertToARM.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <R extends Tree> List<? extends R> asList(final Collection<? extends TreePath> data) {
    if (data == null) {
        return Collections.<R>emptyList();
    }
    final List<R> result = new ArrayList<R>(data.size());
    for (TreePath element : data) {
        result.add((R)element.getLeaf());
    }
    return result;
}
 
Example 24
Project: incubator-netbeans   File: TokenList.java   Source Code and License 5 votes vote down vote up
public void moveToEnd(Collection<? extends Tree> trees) {
    if (trees == null) {
        return ;
    }

    for (Tree t : trees) {
        moveToEnd(t);
    }
}
 
Example 25
Project: incubator-netbeans   File: PullUpTest.java   Source Code and License 5 votes vote down vote up
private void performPullUpIface(FileObject source, final int position, final int iface, final boolean makeAbstract, Problem... expectedProblems) throws IOException, IllegalArgumentException, InterruptedException {
    final PullUpRefactoring[] r = new PullUpRefactoring[1];
    JavaSource.forFileObject(source).runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController info) throws Exception {
            info.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = info.getCompilationUnit();

            final ClassTree classTree = (ClassTree) cut.getTypeDecls().get(0);
            final TreePath classPath = info.getTrees().getPath(cut, classTree);
            TypeElement classEl = (TypeElement) info.getTrees().getElement(classPath);

            TypeMirror superclass = classEl.getInterfaces().get(iface);
            TypeElement superEl = (TypeElement) info.getTypes().asElement(superclass);

            MemberInfo[] members = new MemberInfo[1];
            Tree member = classTree.getMembers().get(position);
            Element el = info.getTrees().getElement(new TreePath(classPath, member));
            members[0] = MemberInfo.create(el, info);
            members[0].setMakeAbstract(makeAbstract);

            r[0] = new PullUpRefactoring(TreePathHandle.create(classEl, info));
            r[0].setTargetType(ElementHandle.create(superEl));
            r[0].setMembers(members);
        }
    }, true);

    RefactoringSession rs = RefactoringSession.create("Session");
    List<Problem> problems = new LinkedList<Problem>();

    addAllProblems(problems, r[0].preCheck());
    if (!problemIsFatal(problems)) {
        addAllProblems(problems, r[0].prepare(rs));
    }
    if (!problemIsFatal(problems)) {
        addAllProblems(problems, rs.doRefactoring(true));
    }

    assertProblems(Arrays.asList(expectedProblems), problems);
}
 
Example 26
Project: incubator-netbeans   File: JoinCatches.java   Source Code and License 5 votes vote down vote up
private void addDisjointType(List<Tree> to, Tree type) {
    if (type == null) return;
    if (type.getKind() == Kind.UNION_TYPE) {
        to.addAll(((UnionTypeTree) type).getTypeAlternatives());
    } else {
        to.add(type);
    }
}
 
Example 27
Project: incubator-netbeans   File: Braces.java   Source Code and License 5 votes vote down vote up
@Hint(displayName="#LBL_Braces_For", description="#DSC_Braces_For", category="braces", id=BRACES_ID + "FOR_LOOP", enabled=false, suppressWarnings={"", "ControlFlowStatementWithoutBraces"})
@TriggerTreeKind({Tree.Kind.FOR_LOOP, Tree.Kind.ENHANCED_FOR_LOOP})
public static ErrorDescription checkFor(HintContext ctx) {
    StatementTree st;
    
    switch (ctx.getPath().getLeaf().getKind()){
        case FOR_LOOP: st = ((ForLoopTree) ctx.getPath().getLeaf()).getStatement(); break;
        case ENHANCED_FOR_LOOP: st = ((EnhancedForLoopTree) ctx.getPath().getLeaf()).getStatement(); break;
        default:
            throw new IllegalStateException();
    }
    return checkStatement(ctx, "LBL_Braces_For", st, ctx.getPath());
}
 
Example 28
Project: incubator-netbeans   File: ExpressionScanner.java   Source Code and License 5 votes vote down vote up
@Override
   public List<Tree> visitMethodInvocation(MethodInvocationTree node, ExpressionScanner.ExpressionsInfo p) {
List<Tree> result = scan(node.getTypeArguments(), p);
       result = reduce(result, scan(node.getMethodSelect(), p));
       result = reduce(result, scan(node.getArguments(), p));
       if (result == null) {
           result = new ArrayList<Tree>();
       }
       result.add(node);
       return result;
   }
 
Example 29
Project: incubator-netbeans   File: InitializerCanBeStatic.java   Source Code and License 5 votes vote down vote up
@TriggerTreeKind(Tree.Kind.BLOCK)
public static ErrorDescription run(HintContext ctx) {
    TreePath path = ctx.getPath();
    if (((BlockTree)path.getLeaf()).isStatic()) {
        return null;
    }
    TreePath parentPath = path.getParentPath();
    if (parentPath == null) {
        return null;
    }
    Tree l = parentPath.getLeaf();
    if (!(l instanceof ClassTree)) {
        return null;
    }
    Element el = ctx.getInfo().getTrees().getElement(parentPath);
    if (el == null || !el.getKind().isClass()) {
        return null;
    }
    TypeElement tel = (TypeElement)el;
    // do not suggest for anonymous classes, local classes or members which are not static.
    if (tel.getNestingKind() != NestingKind.TOP_LEVEL && 
        (tel.getNestingKind() != NestingKind.MEMBER || !tel.getModifiers().contains(Modifier.STATIC))) {
        return null;
    }
    InstanceRefFinder finder = new InstanceRefFinder(ctx.getInfo(), path);
    finder.process();
    if (finder.containsInstanceReferences() || finder.containsReferencesToSuper()) {
        return null;
    }
    
    return ErrorDescriptionFactory.forTree(ctx, path, Bundle.TEXT_InitializerCanBeStatic(),
            new MakeInitStatic(TreePathHandle.create(path, ctx.getInfo())).toEditorFix());
}
 
Example 30
Project: incubator-netbeans   File: ThrowableNotThrown.java   Source Code and License 5 votes vote down vote up
/**
 * Process variable usages. Usages are found by reversing basic Flow data and translated to Paths.
 * Paths are cached in the Flow for other potential uses.
 */
private Boolean processVariables() {
    Collection<Tree> vars = getNewAssignments();
    if (vars.isEmpty()) {
        // unless there's a variable using the Throwable, the value is not properly used
        // and will be reported.
        return Boolean.FALSE;
    }
    FlowResult r = getFlowResult();
    
    for (Tree t : vars) {
        
        Iterable<? extends Tree> usages = r.getValueUsers(t);
        if (usages != null) {
            for (Tree u : usages) {
                TreePath pu = r.findPath(u, info.getCompilationUnit());
                if (pu == null) {
                    continue;
                }
                Boolean result = processEnclosingStatement(pu);
                // accept any usage as a final result
                if (result == Boolean.TRUE) {
                    return result;
                }
            }
        }
    }
    return null;
}
 
Example 31
Project: incubator-netbeans   File: RefactoringVisitor.java   Source Code and License 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 32
Project: incubator-netbeans   File: LegalCombinationOfAnnotations.java   Source Code and License 5 votes vote down vote up
void check(ProblemContext ctx,
        HintContext hc,
        Element elem,
        Collection<ErrorDescription> errorList,
        Collection<String> annotations) {

    for (String ann : annotations) {
        if (set1.contains(ann)) {
            for (String forbiddenAnn : set2) {
                if (annotations.contains(forbiddenAnn)) {
                    Tree elementTree = ctx.getCompilationInfo().getTrees().getTree(elem);

                    Utilities.TextSpan underlineSpan = Utilities.getUnderlineSpan(
                            ctx.getCompilationInfo(), elementTree);

                    ErrorDescription error = ErrorDescriptionFactory.forSpan(
                            hc,
                            underlineSpan.getStartOffset(),
                            underlineSpan.getEndOffset(),
                            NbBundle.getMessage(LegalCombinationOfAnnotations.class, "MSG_IllegalAnnotationCombination", ModelUtils.shortAnnotationName(ann), ModelUtils.shortAnnotationName(forbiddenAnn)));

                    errorList.add(error);
                }
            }
        }
    }
}
 
Example 33
Project: incubator-netbeans   File: ClassStructure.java   Source Code and License 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.markerInterface", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.markerInterface", category = "class_structure", enabled = false, suppressWarnings = {"MarkerInterface"}, options=Options.QUERY) //NOI18N
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static ErrorDescription markerInterface(HintContext context) {
    final ClassTree cls = (ClassTree) context.getPath().getLeaf();
    if (context.getInfo().getTreeUtilities().isInterface(cls) && cls.getMembers().isEmpty() && cls.getImplementsClause().size() < 2) {
        return ErrorDescriptionFactory.forName(context, cls, NbBundle.getMessage(ClassStructure.class, "MSG_MarkerInterface", cls.getSimpleName())); //NOI18N
    }
    return null;
}
 
Example 34
Project: moduletools   File: JavacModuleParser.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("static-method")
public void visitCompilationUnit(CompilationUnitTree node, TreeVisitor<?, ?> visitor) {
  for(Tree decl: node.getTypeDecls()) {
    if (!(decl instanceof ModuleTree)) {  // skip unnecessary nodes: imports, etc
      continue;
    }
    accept(visitor, decl);
  }
}
 
Example 35
Project: incubator-netbeans   File: ClassEncapsulation.java   Source Code and License 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.encapsulation.ClassEncapsulation.publicCls", description = "#DESC_org.netbeans.modules.java.hints.encapsulation.ClassEncapsulation.publicCls", category="encapsulation",suppressWarnings={"PublicInnerClass"}, enabled=false, options=Options.QUERY)   //NOI18N
@UseOptions(ALLOW_ENUMS_KEY)
@TriggerTreeKind({Tree.Kind.ANNOTATION_TYPE, Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE})
public static ErrorDescription publicCls(final HintContext ctx) {
    assert ctx != null;
    return create(ctx, Visibility.PUBLIC,
        NbBundle.getMessage(ClassEncapsulation.class, "TXT_PublicInnerClass"), "PublicInnerClass");  //NOI18N
}
 
Example 36
Project: incubator-netbeans   File: ExpressionScanner.java   Source Code and License 5 votes vote down vote up
@Override
public List<Tree> visitThrow(ThrowTree node, ExpressionScanner.ExpressionsInfo p) {
    List<Tree> result = null;
    if (acceptsTree(node)) {
        result = scan(node.getExpression(), p);
    }
    return result;
}
 
Example 37
Project: incubator-netbeans   File: RemoveSurroundingCodeAction.java   Source Code and License 5 votes vote down vote up
private void addStat(StatementTree stat, List<StatementTree> to) {
    if (stat != null) {
        if (stat.getKind() == Tree.Kind.BLOCK) {
            to.addAll(((BlockTree) stat).getStatements());
        } else {
            to.add(stat);
        }
    }
}
 
Example 38
Project: incubator-netbeans   File: WorkingCopy.java   Source Code and License 5 votes vote down vote up
private Tree resolveRewriteHint(Tree orig) {
    Tree last;
    Tree target = null;
    Tree from = orig;
    do {
        last = target;
        target = from;
        target = rewriteHints.get(target);
        if (target == NOT_LINKED) {
            return target;
        }
        from = target;
    } while (target != null);
    return last;
}
 
Example 39
Project: incubator-netbeans   File: Utilities.java   Source Code and License 5 votes vote down vote up
public static @NonNull Collection<? extends TreePath> resolveFieldGroup(@NonNull CompilationInfo info, @NonNull TreePath variable) {
    Tree leaf = variable.getLeaf();

    if (leaf.getKind() != Kind.VARIABLE) {
        return Collections.singleton(variable);
    }

    TreePath parentPath = variable.getParentPath();
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<TreePath> result = new LinkedList<TreePath>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(new TreePath(parentPath, c));
        }
    }
    
    return result;
}
 
Example 40
Project: incubator-netbeans   File: RenameRefactoringUI.java   Source Code and License 5 votes vote down vote up
@Override
public CustomRefactoringPanel getPanel(ChangeListener parent) {
    if (panel == null) {
        String suffix = "";
        if(handle != null && handle.getKind() == Tree.Kind.LABELED_STATEMENT) {
            suffix = getString("LBL_Label");
        } else if (handle != null && handle.getElementHandle() !=null) {
            ElementKind kind = handle.getElementHandle().getKind();
            if (kind!=null && (kind.isClass() || kind.isInterface())) {
                suffix  = kind.isInterface() ? getString("LBL_Interface") : getString("LBL_Class");
            } else if (kind == ElementKind.METHOD) {
                suffix = getString("LBL_Method");
            } else if (kind == ElementKind.FIELD) {
                suffix = getString("LBL_Field");
            } else if (kind == ElementKind.LOCAL_VARIABLE) {
                suffix = getString("LBL_LocalVar");
            } else if (kind == ElementKind.PACKAGE || (handle == null && fromListener)) {
                suffix = pkgRename ? getString("LBL_Package") : getString("LBL_Folder");
            } else if (kind == ElementKind.PARAMETER) {
                suffix = getString("LBL_Parameter");
            }
        }
        suffix = suffix + " " + this.oldName; // NOI18N
        panel = new RenamePanel(handle, newName, parent, NbBundle.getMessage(RenamePanel.class, "LBL_Rename") + " " + suffix, !fromListener, fromListener && !byPassPakageRename);
    }
    return panel;
}