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 Project: netbeans   Author: apache   File: ConvertToARM.java    License: 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 #2
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: JavacTrees.java    License: 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 #3
Source Project: netbeans   Author: apache   File: CreateElementUtilities.java    License: 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 #4
Source Project: netbeans   Author: apache   File: JavadocUtilities.java    License: 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 Project: netbeans   Author: apache   File: SendEmailCodeGenerator.java    License: 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 Project: netbeans   Author: apache   File: Flow.java    License: 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 Project: netbeans   Author: apache   File: Flow.java    License: 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 Project: netbeans   Author: apache   File: PreconditionsChecker.java    License: 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 #9
Source Project: netbeans   Author: apache   File: AnnoProcessorGenerator.java    License: 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 Project: netbeans   Author: apache   File: Tiny.java    License: 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 #11
Source Project: netbeans   Author: apache   File: MagicSurroundWithTryCatchFix.java    License: 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 #12
Source Project: netbeans   Author: apache   File: ImportClass.java    License: 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 #13
Source Project: TencentKona-8   Author: Tencent   File: DocCommentTester.java    License: 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 #14
Source Project: netbeans   Author: apache   File: CompilationInfo.java    License: 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 #15
Source Project: netbeans   Author: apache   File: JavadocCompletionQuery.java    License: 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 #16
Source Project: netbeans   Author: apache   File: CreateElementUtilities.java    License: 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 #17
Source Project: netbeans   Author: apache   File: AddCast.java    License: 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 #18
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Env.java    License: 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 #19
Source Project: jdk8u60   Author: chenghanpeng   File: DocImpl.java    License: 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 Project: netbeans   Author: apache   File: TryCatchFinally.java    License: 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 #21
Source Project: netbeans   Author: apache   File: JavaSourceHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static TypeElement getTopLevelClassElement(CompilationController controller) {
    ClassTree classTree = getTopLevelClassTree(controller);
    if (classTree == null) {
        return null;
    }
    Trees trees = controller.getTrees();
    TreePath path = trees.getPath(controller.getCompilationUnit(), classTree);

    return (TypeElement) trees.getElement(path);
}
 
Example #22
Source Project: netbeans   Author: apache   File: AssignComments.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void scan(Tree tree, Void p) {
    if (tree == null) {
        return null;
    } else {
        //XXX:
        boolean oldMapComments = mapComments;
        try {
            limit = -1;
            mapComments |= tree == commentMapTarget;
            if ((commentMapTarget != null) && info.getTreeUtilities().isSynthetic(new TreePath(new TreePath(unit), tree)))
                return null;
            limit = setupLimit(tree);
            if (commentMapTarget != null) {
                mapComments2(tree, true, false);
            }
            Tree oldParent = parent;
            try {
                parent = tree;
                super.scan(tree, p);
            } finally {
                parent = oldParent;
            }
            if (commentMapTarget != null) {
                mapComments2(tree, false, tree.getKind() != Tree.Kind.BLOCK || parent == null || parent.getKind() != Tree.Kind.METHOD);
                if (mapComments) {
                    ((CommentSetImpl) createCommentSet(tree)).commentsMapped();
                }
            }
            return null;
        } finally {
            mapComments = oldMapComments;
        }
    }
}
 
Example #23
Source Project: netbeans   Author: apache   File: GoToOppositeAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 */
public void run(CompilationController controller) throws IOException {
    controller.toPhase(Phase.RESOLVED);     //cursor position needed
    if (cancelled) {
        return;
    }

    TreePath treePath = controller.getTreeUtilities()
                                  .pathFor(caretPosition);
    if (treePath != null) {
        if (cancelled) {
            return;
        }
        
        TreePath parent = treePath.getParentPath();
        while (parent != null) {
            Tree.Kind parentKind = parent.getLeaf().getKind();
            if ((TreeUtilities.CLASS_TREE_KINDS.contains(parentKind))
                    || (parentKind == Tree.Kind.COMPILATION_UNIT)) {
                break;
            }
            treePath = parent;
            parent = treePath.getParentPath();
        }

    }

    if (treePath != null) {
        if (cancelled) {
            return;
        }

        try {
            element = controller.getTrees().getElement(treePath);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger("global").log(Level.WARNING, null, ex);
        }
    }
}
 
Example #24
Source Project: netbeans   Author: apache   File: Tiny.java    License: Apache License 2.0 5 votes vote down vote up
private static VariableElement attributeThis(CompilationInfo info, TreePath tp) {
    //XXX:
    VariableElement thisVE = Hacks.attributeThis(info, tp);
    
    if (thisVE == null) {
        Logger.getLogger(Tiny.class.getName()).log(Level.WARNING, "m.localEnv == null");
        return null;
    }

    return thisVE;
}
 
Example #25
Source Project: netbeans   Author: apache   File: ReplaceBufferByString.java    License: Apache License 2.0 5 votes vote down vote up
@TriggerPatterns({
    @TriggerPattern(value = "java.lang.StringBuffer $x = $expr;"),
    @TriggerPattern(value = "java.lang.StringBuilder $x = $expr;"),
})
public static ErrorDescription checkReplace(HintContext ctx) {
    CompilationInfo ci = ctx.getInfo();
    TreePath vp = ctx.getVariables().get("$x"); // NOI18N
    TreePath initP = ctx.getVariables().get("$expr"); // NOI18N
    Element el = ci.getTrees().getElement(vp);
    if (el == null || el.getKind() != ElementKind.LOCAL_VARIABLE) {
        return null;
    }
    
    StringBufferUsageScanner scanner = new StringBufferUsageScanner(ci, ((VariableElement)el));
    TreePath declRoot = ctx.getPath().getParentPath();
    scanner.scan(declRoot, null);
    if (scanner.isIncompatible()) {
        return null;
    }
    NewAppendScanner newScan = new NewAppendScanner(ci);
    if (newScan.scan(initP, null) != Boolean.TRUE || !newScan.hasContents) {
        return null;
    }
    
    return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.TEXT_ReplaceStringBufferByString(), 
            new RewriteToStringFix(
                TreePathHandle.create(vp, ci),
                TreePathHandle.create(declRoot, ci)
            ).toEditorFix());
}
 
Example #26
Source Project: netbeans   Author: apache   File: IntroduceParameterPlugin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns list of problems. For the change method signature, there are two
 * possible warnings - if the method is overriden or if it overrides
 * another method.
 * @return  overrides or overriden problem or both
 */
@Override
protected Problem preCheck(CompilationController info) throws IOException {
    fireProgressListenerStart(refactoring.PRE_CHECK, 4);
    Problem preCheckProblem = null;
    info.toPhase(JavaSource.Phase.RESOLVED);

    TreePath tp = treePathHandle.resolve(info);
    TreePath method = JavaPluginUtils.findMethod(tp);
    if (method == null) {
        preCheckProblem = createProblem(preCheckProblem, true, NbBundle.getMessage(IntroduceParameterPlugin.class, "ERR_ChangeParamsWrongType")); //NOI18N
        return preCheckProblem;
    }

    Element el = info.getTrees().getElement(method);
    if (!RefactoringUtils.isExecutableElement(el)) {
        preCheckProblem = createProblem(preCheckProblem, true, NbBundle.getMessage(IntroduceParameterPlugin.class, "ERR_ChangeParamsWrongType")); //NOI18N
        return preCheckProblem;
    }

    preCheckProblem = JavaPluginUtils.isSourceElement(el, info);
    if (preCheckProblem != null) {
        return preCheckProblem;
    }

    if (info.getElementUtilities().enclosingTypeElement(el).getKind() == ElementKind.ANNOTATION_TYPE) {
        preCheckProblem = new Problem(true, NbBundle.getMessage(IntroduceParameterPlugin.class, "ERR_MethodsInAnnotationsNotSupported")); //NOI18N
        return preCheckProblem;
    }

    for (ExecutableElement e : JavaRefactoringUtils.getOverriddenMethods((ExecutableElement) el, info)) {
        ElementHandle<ExecutableElement> handle = ElementHandle.create(e);
        if (RefactoringUtils.isFromLibrary(handle, info.getClasspathInfo())) {
            preCheckProblem = createProblem(preCheckProblem, true, NbBundle.getMessage(IntroduceParameterPlugin.class, "ERR_CannnotRefactorLibrary", el)); //NOI18N
        }
    }

    fireProgressListenerStop();
    return preCheckProblem;
}
 
Example #27
Source Project: netbeans   Author: apache   File: DeclarationForInstanceOf.java    License: Apache License 2.0 5 votes vote down vote up
public ChangeInfo implement() throws Exception {
    js.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy wc) throws Exception {
            wc.toPhase(Phase.RESOLVED);
            
            TreePath ifTP = ifHandle.resolve(wc);
            TreePath resolvedExpression = expression.resolve(wc);
            TypeMirror resolvedType = type.resolve(wc);
            
            if (ifTP == null || resolvedType == null || resolvedExpression == null) {
                return ;
            }
            
            IfTree ift = (IfTree) ifTP.getLeaf();
            StatementTree then = ift.getThenStatement();
            
            if (then.getKind() == Kind.ERRONEOUS) {
                return ; //TODO.
            }
            
            List<StatementTree> statements = new LinkedList<StatementTree>();
            
            if (then.getKind() == Kind.BLOCK) {
                statements.addAll(((BlockTree) then).getStatements());
            } else {
                statements.add(then);
            }
            
            TreeMaker make = wc.getTreeMaker();
            VariableTree decl = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(resolvedType), make.TypeCast(make.Type(resolvedType), (ExpressionTree) resolvedExpression.getLeaf()));
            
            statements.add(0, decl);
            
            BlockTree nue = make.Block(statements, false);
            
            wc.rewrite(then, nue);
        }
    }).commit();
    return null;
}
 
Example #28
Source Project: netbeans   Author: apache   File: ThrowableNotThrown.java    License: 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 #29
Source Project: netbeans   Author: apache   File: Utilities.java    License: 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 #30
Source Project: netbeans   Author: apache   File: CopyFinder.java    License: 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));
}