com.sun.source.util.TreePath Java Examples

The following examples show how to use com.sun.source.util.TreePath. 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: Env.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/** Set the current declaration and its doc comment. */
void setCurrent(TreePath path, DocCommentTree comment) {
    currPath = path;
    currDocComment = comment;
    currElement = trees.getElement(currPath);
    currOverriddenMethods = ((JavacTypes) types).getOverriddenMethods(currElement);

    AccessKind ak = AccessKind.PUBLIC;
    for (TreePath p = path; p != null; p = p.getParentPath()) {
        Element e = trees.getElement(p);
        if (e != null && e.getKind() != ElementKind.PACKAGE && e.getKind() != ElementKind.MODULE) {
            ak = min(ak, AccessKind.of(e.getModifiers()));
        }
    }
    currAccess = ak;
}
 
Example #2
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeParenthesis(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ParenthesizedTree pt = (ParenthesizedTree) parent.getLeaf();
    
    if (pt.getExpression() != error) {
        return null;
    }
    
    TreePath parentParent = parent.getParentPath();
    List<? extends TypeMirror> upperTypes = resolveType(types, info, parentParent, pt, offset, null, null);
    
    if (upperTypes == null) {
        return null;
    }
    
    return upperTypes;
}
 
Example #3
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private Symbol attributeParamIdentifier(TreePath path, DCParam ptag) {
    Symbol javadocSymbol = getElement(path);
    if (javadocSymbol == null)
        return null;
    ElementKind kind = javadocSymbol.getKind();
    List<? extends Symbol> params = List.nil();
    if (kind == ElementKind.METHOD || kind == ElementKind.CONSTRUCTOR) {
        MethodSymbol ee = (MethodSymbol) javadocSymbol;
        params = ptag.isTypeParameter()
                ? ee.getTypeParameters()
                : ee.getParameters();
    } else if (kind.isClass() || kind.isInterface()) {
        ClassSymbol te = (ClassSymbol) javadocSymbol;
        params = te.getTypeParameters();
    }

    for (Symbol param : params) {
        if (param.getSimpleName() == ptag.getName().getName()) {
            return param;
        }
    }
    return null;
}
 
Example #4
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 #5
Source File: SendEmailCodeGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<? extends CodeGenerator> create(Lookup context) {
    ArrayList<CodeGenerator> ret = new ArrayList<CodeGenerator>();
    JTextComponent component = context.lookup(JTextComponent.class);
    CompilationController controller = context.lookup(CompilationController.class);
    TreePath path = context.lookup(TreePath.class);
    path = path != null ? getPathElementOfKind(Tree.Kind.CLASS, path) : null;
    if (component == null || controller == null || path == null)
        return ret;
    try {
        controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
        Element elem = controller.getTrees().getElement(path);
        if (elem != null) {
            SendEmailCodeGenerator gen = createSendEmailGenerator(component, controller, elem);
            if (gen != null)
                ret.add(gen);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return ret;
}
 
Example #6
Source File: Flow.java    From netbeans with Apache License 2.0 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 #7
Source File: Flow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Boolean visitBlock(BlockTree node, ConstructorData p) {
    List<? extends StatementTree> statements = new ArrayList<StatementTree>(node.getStatements());
    
    for (int i = 0; i < statements.size(); i++) {
        StatementTree st = statements.get(i);
        
        if (st.getKind() == Kind.IF) {
            IfTree it = (IfTree) st; 
            if (it.getElseStatement() == null && Utilities.exitsFromAllBranchers(info, new TreePath(new TreePath(getCurrentPath(), it), it.getThenStatement()))) {
                generalizedIf(it.getCondition(), it.getThenStatement(), statements.subList(i + 1, statements.size()), false);
                break;
            }
        }
        
        scan(st, null);
    }
    
    return null;
}
 
Example #8
Source File: ConvertToARM.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isAssigned(
        final Element what,
        final Iterable<? extends TreePath> where,
        final Trees trees) {
    ErrorAwareTreePathScanner<Boolean, Void> scanner = new ErrorAwareTreePathScanner<Boolean, Void>() {
        @Override public Boolean visitAssignment(AssignmentTree node, Void p) {
            if (trees.getElement(new TreePath(getCurrentPath(), node.getVariable())) == what) {
                return true;
            }
            return super.visitAssignment(node, p);
        }
        @Override
        public Boolean reduce(Boolean r1, Boolean r2) {
            return r1 == Boolean.TRUE || r2 == Boolean.TRUE;
        }
    };
    
    for (TreePath usage : where) {
        if (scanner.scan(usage, null) == Boolean.TRUE) {
            return true;
        }
    }
    return false;
}
 
Example #9
Source File: AnnoProcessorGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void run(WorkingCopy parameter) throws Exception {
    parameter.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
    TypeElement resolved = handle.resolve(parameter);
    if (!Utilities.isValidElement(resolved)) {
        return;
    }
    TreePath path = parameter.getTrees().getPath(resolved);
    if (path == null) {
        return;
    }
    
    ProcessorHintSupport supp = new ProcessorHintSupport(parameter, path);
    if (!supp.initialize() || !supp.canOverrideProcessor(true)) {
        return;
    }
    supp.makeGetSupportedOverride(parameter, null, true);
}
 
Example #10
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static CatchTree createCatch(WorkingCopy info, TreeMaker make, TreePath statement, String name, TypeMirror type) {
    StatementTree logStatement = createExceptionsStatement(info, make, name);

    if (logStatement == null) {
        logStatement = createLogStatement(info, make, statement, name);
    }
    
    if (logStatement == null) {
        logStatement = createRethrowAsRuntimeExceptionStatement(info, make, name);
    }
    
    if (logStatement == null) {
        logStatement = createRethrow(info, make, name);
    }

    if (logStatement == null) {
        logStatement = createPrintStackTraceStatement(info, make, name);
    }

    return make.Catch(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(type), null), make.Block(Collections.singletonList(logStatement), false));
}
 
Example #11
Source File: ImportClass.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public FixImport(FileObject file, String fqn, ElementHandle<Element> toImport, String sortText, boolean isValid, CompilationInfo info, @NullAllowed TreePath replacePath, @NullAllowed String replaceSuffix, 
        boolean doOrganize) {
    super(file, fqn, toImport, sortText, isValid);
    if (replacePath != null) {
        this.replacePathHandle = TreePathHandle.create(replacePath, info);
        this.suffix = replaceSuffix;
        while (replacePath != null && replacePath.getLeaf().getKind() != Kind.IMPORT) {
            replacePath = replacePath.getParentPath();
        }
        this.statik = replacePath != null ? ((ImportTree) replacePath.getLeaf()).isStatic() : false;
    } else {
        this.replacePathHandle = null;
        this.suffix = null;
        this.statik = false;
    }
    this.doOrganize = doOrganize;
}
 
Example #12
Source File: DocCommentTester.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
    void check(TreePath path, Name name) throws Exception {
        String raw = trees.getDocComment(path);
        String normRaw = normalize(raw);

        StringWriter out = new StringWriter();
        DocPretty dp = new DocPretty(out);
        dp.print(trees.getDocCommentTree(path));
        String pretty = out.toString();

        if (!pretty.equals(normRaw)) {
            error("mismatch");
            System.err.println("*** expected:");
            System.err.println(normRaw.replace(" ", "_"));
            System.err.println("*** found:");
            System.err.println(pretty.replace(" ", "_"));
//            throw new Error();
        }
    }
 
Example #13
Source File: CompilationInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns tree which was reparsed by an incremental reparse.
 * When the source file wasn't parsed yet or the parse was a full parse
 * this method returns null.
 * <p class="nonnormative">
 * Currently the leaf tree is a MethodTree but this may change in the future.
 * Client of this method is responsible to check the corresponding TreeKind
 * to find out if it may perform on the changed subtree or it needs to
 * reprocess the whole tree.
 * </p>
 * @return {@link TreePath} or null
 * @since 0.31
 */
public @CheckForNull @CheckReturnValue TreePath getChangedTree () {
    checkConfinement();
    if (JavaSource.Phase.PARSED.compareTo (impl.getPhase())>0) {
        return null;
    }
    final Pair<DocPositionRegion,MethodTree> changedTree = impl.getChangedTree();
    if (changedTree == null) {
        return null;
    }
    final CompilationUnitTree cu = impl.getCompilationUnit();
    if (cu == null) {
        return null;
    }
    return TreePath.getPath(cu, changedTree.second());
}
 
Example #14
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addPackageContent(PackageElement pe, EnumSet<ElementKind> kinds, DeclaredType baseType, Set<? extends Element> toExclude, String prefix, int substitutionOffset, JavadocContext jdctx) {
    CompilationInfo controller = jdctx.javac;
    Element srcEl = jdctx.handle.resolve(controller);
    Elements elements = controller.getElements();
    Types types = controller.getTypes();
    Trees trees = controller.getTrees();
    TreeUtilities tu = controller.getTreeUtilities();
    ElementUtilities eu = controller.getElementUtilities();
    TreePath docpath = srcEl != null ? trees.getPath(srcEl) : null;
    Scope scope = docpath != null ? trees.getScope(docpath) : tu.scopeFor(caretOffset);
    for(Element e : pe.getEnclosedElements()) {
        if ((e.getKind().isClass() || e.getKind().isInterface()) && (toExclude == null || !toExclude.contains(e))) {
            String name = e.getSimpleName().toString();
                if (Utilities.startsWith(name, prefix) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e))
                    && trees.isAccessible(scope, (TypeElement)e)
                    && isOfKindAndType(e.asType(), e, kinds, baseType, scope, trees, types)
                    && !Utilities.isExcluded(eu.getElementName(e, true))) {
                    items.add(JavadocCompletionItem.createTypeItem(jdctx.javac, (TypeElement) e, substitutionOffset, null, elements.isDeprecated(e)/*, isOfSmartType(env, e.asType(), smartTypes)*/));
            }
        }
    }
}
 
Example #15
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 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 #16
Source File: Tiny.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean isSynced(HintContext ctx, TreePath inspect) {
    while (inspect != null && !TreeUtilities.CLASS_TREE_KINDS.contains(inspect.getLeaf().getKind())) {
        if (inspect.getLeaf().getKind() == Kind.SYNCHRONIZED) {
            return true;
        }

        if (inspect.getLeaf().getKind() == Kind.METHOD) {
            if (((MethodTree) inspect.getLeaf()).getModifiers().getFlags().contains(Modifier.SYNCHRONIZED)) {
                return true;
            }

            break;
        }

        inspect = inspect.getParentPath();
    }

    return false;
}
 
Example #17
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean isLastInControlFlow(TreePath pathToInstruction) {
    Tree currentTree = pathToInstruction.getLeaf();
    Tree parentTree = pathToInstruction.getParentPath().getLeaf();
    if (parentTree.equals(this.loop)) {
        return true;
    } else if (parentTree.getKind() == Tree.Kind.BLOCK) {
        List<? extends StatementTree> ls = ((BlockTree) parentTree).getStatements();
        if (ls.get(ls.size() - 1).equals(currentTree)) {
            return isLastInControlFlow(pathToInstruction.getParentPath());
        } else {
            return false;
        }

    } else if (parentTree.getKind() == Tree.Kind.AND.IF && ((IfTree) parentTree).getElseStatement() != null) {
        return false;
    } else {
        return this.isLastInControlFlow(pathToInstruction.getParentPath());
    }


}
 
Example #18
Source File: AddCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public List<Fix> run(CompilationInfo info, String diagnosticKey, int offset, TreePath treePath, Data<Void> data) {
    List<Fix> result = new ArrayList<Fix>();
    List<TypeMirror> targetType = new ArrayList<TypeMirror>();
    TreePath[] tmTree = new TreePath[1];
    ExpressionTree[] expression = new ExpressionTree[1];
    Tree[] leaf = new Tree[1];
    
    computeType(info, offset, targetType, tmTree, expression, leaf);
    
    if (!targetType.isEmpty()) {
        TreePath expressionPath = TreePath.getPath(info.getCompilationUnit(), expression[0]); //XXX: performance
        for (TypeMirror type : targetType) {
            if (type.getKind() != TypeKind.NULL) {
                result.add(new AddCastFix(info, expressionPath, tmTree[0], type).toEditorFix());
            }
        }
    }
    
    return result;
}
 
Example #19
Source File: DocImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static String getCommentText(TreePath p) {
    if (p == null)
        return null;

    JCCompilationUnit topLevel = (JCCompilationUnit) p.getCompilationUnit();
    JCTree tree = (JCTree) p.getLeaf();
    return topLevel.docComments.getCommentText(tree);
}
 
Example #20
Source File: JavaPluginUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TreePath findStatement(TreePath statementPath) {
    while (statementPath != null
            && (!StatementTree.class.isAssignableFrom(statementPath.getLeaf().getKind().asInterface())
            || (statementPath.getParentPath() != null
            && statementPath.getParentPath().getLeaf().getKind() != Kind.BLOCK))) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(statementPath.getLeaf().getKind())) {
            return null;
        }

        statementPath = statementPath.getParentPath();
    }

    return statementPath;
}
 
Example #21
Source File: SourceUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all elements of the given scope that are declared after given position in a source.
 * @param path to the given search scope
 * @param pos position in the source
 * @param sourcePositions
 * @param trees
 * @return collection of forward references
 * 
 * @since 0.136
 */
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) {
    HashSet<Element> refs = new HashSet<>();
    Element el;
    
    while(path != null) {
        switch(path.getLeaf().getKind()) {
            case VARIABLE:
                el = trees.getElement(path);
                if (el != null) {
                    refs.add(el);
                }
                TreePath parent = path.getParentPath();
                if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) {
                    boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC);
                    for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) {
                        if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos &&
                                (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC))) {
                            el = trees.getElement(new TreePath(parent, member));
                            if (el != null) {
                                refs.add(el);
                            }
                        }
                    }
                }
                break;
            case ENHANCED_FOR_LOOP:
                EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf();
                if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos) {
                    el = trees.getElement(new TreePath(path, efl.getVariable()));
                    if (el != null) {
                        refs.add(el);
                    }
                }                        
        }
        path = path.getParentPath();
    }
    return refs;
}
 
Example #22
Source File: ClassStructure.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.protectedMemberInFinalClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.protectedMemberInFinalClass", category = "class_structure", enabled = false, suppressWarnings = {"ProtectedMemberInFinalClass"}) //NOI18N
@TriggerTreeKind({Kind.METHOD, Kind.VARIABLE})
public static ErrorDescription protectedMemberInFinalClass(HintContext context) {
    final Tree tree = context.getPath().getLeaf();
    final Tree parent = context.getPath().getParentPath().getLeaf();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind())) {
        if (tree.getKind() == Kind.METHOD) {
            final MethodTree mth = (MethodTree) tree;
            if (mth.getModifiers().getFlags().contains(Modifier.PROTECTED) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) {
                Element el = context.getInfo().getTrees().getElement(context.getPath());
                if (el == null || el.getKind() != ElementKind.METHOD) {
                    return null;
                }
                List<ElementDescription> overrides = new LinkedList<ElementDescription>();
                ComputeOverriding.detectOverrides(context.getInfo(), (TypeElement) el.getEnclosingElement(), (ExecutableElement) el, overrides);
                for (ElementDescription ed : overrides) {
                    Element res = ed.getHandle().resolve(context.getInfo());
                    if (res == null) {
                        continue; //XXX: log
                    }
                    if (   res.getModifiers().contains(Modifier.PROTECTED)
                        || /*to prevent reports for broken sources:*/ res.getModifiers().contains(Modifier.PUBLIC)) {
                        return null;
                    }
                }
                return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_ProtectedMethodInFinalClass", mth.getName()), //NOI18N
                        FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), mth.getModifiers()), EnumSet.of(Modifier.PROTECTED), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveProtectedFromMethod", mth.getName()))); //NOI18N
            }
        } else {
            final VariableTree var = (VariableTree) tree;
            if (var.getModifiers().getFlags().contains(Modifier.PROTECTED) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.FINAL)) {
                return ErrorDescriptionFactory.forName(context, var, NbBundle.getMessage(ClassStructure.class, "MSG_ProtectedFieldInFinalClass", var.getName()), //NOI18N
                        FixFactory.removeModifiersFix(context.getInfo(), TreePath.getPath(context.getPath(), var.getModifiers()), EnumSet.of(Modifier.PROTECTED), NbBundle.getMessage(ClassStructure.class, "FIX_RemoveProtectedFromField", var.getName()))); //NOI18N
            }
        }
    }
    return null;
}
 
Example #23
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<? extends Element> getForwardReferences(TreePath path, int pos, SourcePositions sourcePositions, Trees trees) {
    HashSet<Element> refs = new HashSet<Element>();
    while(path != null) {
        switch(path.getLeaf().getKind()) {
            case BLOCK:
                if (path.getParentPath().getLeaf().getKind() == Tree.Kind.LAMBDA_EXPRESSION)
                    break;
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
                return refs;
            case VARIABLE:
                refs.add(trees.getElement(path));
                TreePath parent = path.getParentPath();
                if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getLeaf().getKind())) {
                    boolean isStatic = ((VariableTree)path.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC);
                    for(Tree member : ((ClassTree)parent.getLeaf()).getMembers()) {
                        if (member.getKind() == Tree.Kind.VARIABLE && sourcePositions.getStartPosition(path.getCompilationUnit(), member) >= pos &&
                                (isStatic || !((VariableTree)member).getModifiers().getFlags().contains(Modifier.STATIC)))
                            refs.add(trees.getElement(new TreePath(parent, member)));
                    }
                }
                return refs;
            case ENHANCED_FOR_LOOP:
                EnhancedForLoopTree efl = (EnhancedForLoopTree)path.getLeaf();
                if (sourcePositions.getEndPosition(path.getCompilationUnit(), efl.getExpression()) >= pos)
                    refs.add(trees.getElement(new TreePath(path, efl.getVariable())));                        
        }
        path = path.getParentPath();
    }
    return refs;
}
 
Example #24
Source File: BIGuardedBlockHandlerFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean checkChange(CompilationController javac, PositionBounds span) throws IOException, BadLocationException {
    final int begin = span.getBegin().getOffset();
    final Trees trees = javac.getTrees();
    TreePath path = javac.getTreeUtilities().pathFor(begin + 1);
    if (path == null) {
        return false;
    }
    
    Element element = trees.getElement(path);
    if (element == null) {
        return false;
    }

    TreePath decl = trees.getPath(element);
    if (decl != null) {
        SourcePositions sourcePositions = trees.getSourcePositions();
        long declBegin = sourcePositions.getStartPosition(decl.getCompilationUnit(), decl.getLeaf());
        FileObject fo = SourceUtils.getFile(element, javac.getClasspathInfo());
        Document doc = javac.getDocument();
        GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc);
        
        if (fo != javac.getFileObject() || guards != null && !isGuarded(guards, doc.createPosition((int) declBegin))) {
            // tree being refactored is declared outside of this file
            // or out of guarded sections. It should be safe to make change
            return true;
        }
    } else {
        // e.g. package; change is OK
            return true;
    }
    return false;
}
 
Example #25
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 #26
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Boolean scan(Tree node, Tree p, TreePath pOrigin) {
    if (node == null && p == null)
        return true;

    if (node != null && p == null)
        return false;
    
    return scan(node, new TreePath(pOrigin, p));
}
 
Example #27
Source File: TryCatchFinally.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitContinue(ContinueTree node, Collection<TreePath> trees) {
    if (!analyzeThrows && !seenTrees.contains(info.getTreeUtilities().getBreakContinueTarget(getCurrentPath()))) {
        trees.add(getCurrentPath());
    }
    return null;
}
 
Example #28
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * @param tp tested {@link TreePath}
 * @return true if <code>tp</code> is an IDENTIFIER in a VARIABLE in an ENHANCED_FOR_LOOP
 */
public static boolean isEnhancedForLoopIdentifier(TreePath tp) {
    if (tp == null || tp.getLeaf().getKind() != Kind.IDENTIFIER)
        return false;
    TreePath parent = tp.getParentPath();
    if (parent == null || parent.getLeaf().getKind() != Kind.VARIABLE)
        return false;
    TreePath context = parent.getParentPath();
    if (context == null || context.getLeaf().getKind() != Kind.ENHANCED_FOR_LOOP)
        return false;
    return true;
}
 
Example #29
Source File: ThrowableNotThrown.java    From netbeans with Apache License 2.0 5 votes vote down vote up
boolean traceThrowable(TreePath path) {
    Boolean b = processEnclosingStatement(path);
    if (b != null) {
        return b;
    }
    // recursively process pass through variables.
    while ((b = processVariables()) == null) {
        // OK
    }
        
    return b;
}
 
Example #30
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);
            }
        }
    }
}