Search in sources :

Example 1 with ForLoopTree

use of com.sun.source.tree.ForLoopTree in project error-prone by google.

the class FindIdentifiers method findUnusedIdentifiers.

/**
 * Finds all variable declarations which are unused at this point in the AST (i.e. they might be
 * used further on).
 */
public static ImmutableSet<VarSymbol> findUnusedIdentifiers(VisitorState state) {
    ImmutableSet.Builder<VarSymbol> definedVariables = ImmutableSet.builder();
    ImmutableSet.Builder<Symbol> usedSymbols = ImmutableSet.builder();
    Tree prev = state.getPath().getLeaf();
    for (Tree curr : state.getPath().getParentPath()) {
        createFindIdentifiersScanner(usedSymbols, prev).scan(curr, null);
        switch(curr.getKind()) {
            case BLOCK:
                // If we see a block then walk over each statement to see if it defines a variable
                for (StatementTree statement : ((BlockTree) curr).getStatements()) {
                    if (statement.equals(prev)) {
                        // declared/used before us in the tree
                        break;
                    }
                    addIfVariable(statement, definedVariables);
                }
                break;
            case FOR_LOOP:
                ForLoopTree forLoop = (ForLoopTree) curr;
                forLoop.getInitializer().stream().forEach(t -> addIfVariable(t, definedVariables));
                break;
            case ENHANCED_FOR_LOOP:
                EnhancedForLoopTree enhancedFor = (EnhancedForLoopTree) curr;
                addIfVariable(enhancedFor.getVariable(), definedVariables);
                break;
            default:
                break;
        }
        prev = curr;
    }
    return ImmutableSet.copyOf(Sets.difference(definedVariables.build(), usedSymbols.build()));
}
Also used : StatementTree(com.sun.source.tree.StatementTree) ImmutableSet(com.google.common.collect.ImmutableSet) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) ForLoopTree(com.sun.source.tree.ForLoopTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) TryTree(com.sun.source.tree.TryTree) BlockTree(com.sun.source.tree.BlockTree) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree)

Example 2 with ForLoopTree

use of com.sun.source.tree.ForLoopTree in project error-prone by google.

the class VarChecker method forLoopVariable.

boolean forLoopVariable(VariableTree tree, TreePath path) {
    Tree parent = path.getParentPath().getLeaf();
    if (!(parent instanceof ForLoopTree)) {
        return false;
    }
    ForLoopTree forLoop = (ForLoopTree) parent;
    return forLoop.getInitializer().contains(tree);
}
Also used : ForLoopTree(com.sun.source.tree.ForLoopTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ForLoopTree(com.sun.source.tree.ForLoopTree) JCTree(com.sun.tools.javac.tree.JCTree)

Example 3 with ForLoopTree

use of com.sun.source.tree.ForLoopTree in project error-prone by google.

the class IncrementInForLoopAndHeader method matchForLoop.

@Override
public Description matchForLoop(ForLoopTree forLoopTree, VisitorState visitorState) {
    List<? extends ExpressionStatementTree> updates = forLoopTree.getUpdate();
    // keep track of all the symbols that are updated in the for loop header
    final Set<Symbol> incrementedSymbols = updates.stream().filter(expStateTree -> expStateTree.getExpression() instanceof UnaryTree).map(expStateTree -> ASTHelpers.getSymbol(((UnaryTree) expStateTree.getExpression()).getExpression())).collect(Collectors.toCollection(HashSet::new));
    // track if they are updated in the body without a conditional surrounding them
    StatementTree body = forLoopTree.getStatement();
    List<? extends StatementTree> statementTrees = body instanceof BlockTree ? ((BlockTree) body).getStatements() : ImmutableList.of(body);
    for (StatementTree s : statementTrees) {
        if (!CONDITIONALS.contains(s.getKind())) {
            Optional<Symbol> opSymbol = returnUnarySym(s);
            if (opSymbol.isPresent() && incrementedSymbols.contains(opSymbol.get())) {
                // both ++ and --
                return describeMatch(forLoopTree);
            }
        }
    }
    return Description.NO_MATCH;
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) UnaryTree(com.sun.source.tree.UnaryTree) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Collectors(java.util.stream.Collectors) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) HashSet(java.util.HashSet) VisitorState(com.google.errorprone.VisitorState) ForLoopTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.ForLoopTreeMatcher) List(java.util.List) Kind(com.sun.source.tree.Tree.Kind) ImmutableList(com.google.common.collect.ImmutableList) Description(com.google.errorprone.matchers.Description) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) BugPattern(com.google.errorprone.BugPattern) Optional(java.util.Optional) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) JDK(com.google.errorprone.BugPattern.Category.JDK) ForLoopTree(com.sun.source.tree.ForLoopTree) ASTHelpers(com.google.errorprone.util.ASTHelpers) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) StatementTree(com.sun.source.tree.StatementTree) Symbol(com.sun.tools.javac.code.Symbol) BlockTree(com.sun.source.tree.BlockTree) UnaryTree(com.sun.source.tree.UnaryTree)

Example 4 with ForLoopTree

use of com.sun.source.tree.ForLoopTree in project groovy-cps by cloudbees.

the class Translator method translateMethod.

/**
 * @param e
 *      Method in {@code fqcn} to translate.
 */
private void translateMethod(final CompilationUnitTree cut, ExecutableElement e, JDefinedClass $output, String fqcn, String overloadResolved) {
    String methodName = n(e);
    boolean isPublic = e.getModifiers().contains(Modifier.PUBLIC);
    JMethod delegating = $output.method(isPublic ? JMod.PUBLIC | JMod.STATIC : JMod.STATIC, (JType) null, methodName);
    JMethod m = $output.method(JMod.PRIVATE | JMod.STATIC, (JType) null, overloadResolved);
    Map<String, JTypeVar> typeVars = new HashMap<>();
    e.getTypeParameters().forEach(p -> {
        String name = n(p);
        JTypeVar typeVar = delegating.generify(name);
        JTypeVar typeVar2 = m.generify(name);
        p.getBounds().forEach(b -> {
            JClass binding = (JClass) t(b, typeVars);
            typeVar.bound(binding);
            typeVar2.bound(binding);
        });
        typeVars.put(name, typeVar);
    });
    JType type = t(e.getReturnType(), typeVars);
    delegating.type(type);
    m.type(type);
    List<JVar> delegatingParams = new ArrayList<>();
    List<JVar> params = new ArrayList<>();
    e.getParameters().forEach(p -> {
        JType paramType = t(p.asType(), typeVars);
        delegatingParams.add(e.isVarArgs() && p == e.getParameters().get(e.getParameters().size() - 1) ? delegating.varParam(paramType.elementType(), n(p)) : delegating.param(paramType, n(p)));
        params.add(m.param(paramType, n(p)));
    });
    e.getThrownTypes().forEach(ex -> {
        delegating._throws((JClass) t(ex));
        m._throws((JClass) t(ex));
    });
    boolean returnsVoid = e.getReturnType().getKind() == TypeKind.VOID;
    if (isPublic) {
        // preamble
        /*
                If the call to this method happen outside CPS code, execute normally via DefaultGroovyMethods
             */
        delegating.body()._if(JOp.cand(JOp.not($Caller.staticInvoke("isAsynchronous").tap(inv -> {
            inv.arg(delegatingParams.get(0));
            inv.arg(methodName);
            for (int i = 1; i < delegatingParams.size(); i++) inv.arg(delegatingParams.get(i));
        })), JOp.not($Caller.staticInvoke("isAsynchronous").arg($output.dotclass()).arg(methodName).args(params))))._then().tap(blk -> {
            JClass $WhateverGroovyMethods = codeModel.ref(fqcn);
            JInvocation forward = $WhateverGroovyMethods.staticInvoke(methodName).args(delegatingParams);
            if (returnsVoid) {
                blk.add(forward);
                blk._return();
            } else {
                blk._return(forward);
            }
        });
    }
    JInvocation delegateCall = $output.staticInvoke(overloadResolved);
    if (returnsVoid) {
        delegating.body().add(delegateCall);
    } else {
        delegating.body()._return(delegateCall);
    }
    delegatingParams.forEach(p -> delegateCall.arg(p));
    JVar $b = m.body().decl($Builder, "b", JExpr._new($Builder).arg(JExpr.invoke("loc").arg(methodName)).invoke("contextualize").arg(codeModel.ref("com.cloudbees.groovy.cps.sandbox.Trusted").staticRef("INSTANCE")));
    JInvocation f = JExpr._new($CpsFunction);
    // parameter names
    f.arg(codeModel.ref(Arrays.class).staticInvoke("asList").tap(inv -> {
        e.getParameters().forEach(p -> inv.arg(n(p)));
    }));
    // translate the method body into an expression that invokes Builder
    f.arg(trees.getTree(e).getBody().accept(new SimpleTreeVisitor<JExpression, Void>() {

        private JExpression visit(Tree t) {
            if (t == null)
                return JExpr._null();
            return visit(t, null);
        }

        /**
         * Maps a symbol to its source location.
         */
        private JExpression loc(Tree t) {
            long pos = trees.getSourcePositions().getStartPosition(cut, t);
            return JExpr.lit((int) cut.getLineMap().getLineNumber(pos));
        }

        @Override
        public JExpression visitWhileLoop(WhileLoopTree wt, Void __) {
            return $b.invoke("while_").arg(// TODO: label
            JExpr._null()).arg(visit(wt.getCondition())).arg(visit(wt.getStatement()));
        }

        @Override
        public JExpression visitMethodInvocation(MethodInvocationTree mt, Void __) {
            ExpressionTree ms = mt.getMethodSelect();
            JInvocation inv;
            if (ms instanceof MemberSelectTree) {
                MemberSelectTree mst = (MemberSelectTree) ms;
                // of the other known translated classes.
                if (mst.getExpression() instanceof JCIdent && !((JCIdent) mst.getExpression()).sym.toString().equals(fqcn) && otherTranslated.containsKey(((JCIdent) mst.getExpression()).sym.toString())) {
                    inv = $b.invoke("functionCall").arg(loc(mt)).arg($b.invoke("constant").arg(otherTranslated.get(((JCIdent) mst.getExpression()).sym.toString()).dotclass())).arg(n(mst.getIdentifier()));
                } else {
                    inv = $b.invoke("functionCall").arg(loc(mt)).arg(visit(mst.getExpression())).arg(n(mst.getIdentifier()));
                }
            } else if (ms instanceof JCIdent) {
                // invocation without object selection, like  foo(bar,zot)
                JCIdent it = (JCIdent) ms;
                if (!it.sym.owner.toString().equals(fqcn)) {
                    if (otherTranslated.containsKey(it.sym.owner.toString())) {
                        // static import from transformed class
                        inv = $b.invoke("functionCall").arg(loc(mt)).arg($b.invoke("constant").arg(otherTranslated.get(it.sym.owner.toString()).dotclass())).arg(n(it));
                    } else {
                        // static import from non-transformed class
                        inv = $b.invoke("functionCall").arg(loc(mt)).arg($b.invoke("constant").arg(t(it.sym.owner.type).dotclass())).arg(n(it));
                    }
                } else {
                    // invocation on this class
                    String overloadResolved = mangledName((Symbol.MethodSymbol) it.sym);
                    Optional<? extends Element> callSite = elements.getTypeElement(fqcn).getEnclosedElements().stream().filter(e -> e.getKind() == ElementKind.METHOD && mangledName((ExecutableElement) e).equals(overloadResolved)).findAny();
                    if (callSite.isPresent()) {
                        ExecutableElement e = (ExecutableElement) callSite.get();
                        if (e.getModifiers().contains(Modifier.PUBLIC) && !e.isVarArgs() && !e.getParameters().stream().anyMatch(p -> types.isAssignable(p.asType(), closureType))) {
                            // Delegate to the standard version.
                            inv = $b.invoke("staticCall").arg(loc(mt)).arg(t(it.sym.owner.type).dotclass()).arg(n(e));
                        } else if (overloadsResolved.containsKey(overloadResolved)) {
                            // Private, so delegate to our mangled version.
                            // TODO add a String parameter to each internal helper method for the expected methodName to pass to CpsCallableInvocation.<init>
                            // (It could be improved to take a parameter for the name under which we expect methodCall to be invoking it.
                            // Usually just `each`, but might be `$each__java_util_Iterable__groovy_lang_Closure` for the case that one DGM method is delegating to another.
                            // See comment in ContinuationGroup, where we are unable to enforce continuation name mismatches in this case.)
                            inv = $b.invoke("staticCall").arg(loc(mt)).arg($output.dotclass()).arg(overloadResolved);
                        } else {
                            throw new IllegalStateException("Not yet translating a " + e.getModifiers() + " method; translatable.txt might need to include: " + fqcn + "." + e);
                        }
                    } else {
                        throw new IllegalStateException("Could not find self-call site " + overloadResolved + " for " + mt);
                    }
                }
            } else {
                // TODO: figure out what can come here
                throw new UnsupportedOperationException(ms.toString());
            }
            mt.getArguments().forEach(a -> inv.arg(visit(a)));
            return inv;
        }

        @Override
        public JExpression visitVariable(VariableTree vt, Void __) {
            return $b.invoke("declareVariable").arg(loc(vt)).arg(cpsTypeTranslation(erasure(vt))).arg(n(vt)).arg(visit(vt.getInitializer()));
        }

        @Override
        public JExpression visitIdentifier(IdentifierTree it, Void __) {
            JCIdent idt = (JCIdent) it;
            return idt.sym.accept(new DefaultSymbolVisitor<JExpression, Void>() {

                @Override
                public JExpression visitClassSymbol(ClassSymbol cs, Void __) {
                    return $b.invoke("constant").arg(t(cs.asType()).dotclass());
                }

                @Override
                public JExpression visitVarSymbol(VarSymbol s, Void __) {
                    return $b.invoke("localVariable").arg(n(s.name));
                }

                @Override
                public JExpression visitSymbol(Symbol s, Void __) {
                    throw new UnsupportedOperationException(s.toString());
                }
            }, __);
        }

        @Override
        public JExpression visitBlock(BlockTree bt, Void __) {
            JInvocation inv = $b.invoke("block");
            bt.getStatements().forEach(s -> inv.arg(visit(s)));
            return inv;
        }

        @Override
        public JExpression visitReturn(ReturnTree rt, Void __) {
            return $b.invoke("return_").arg(visit(rt.getExpression()));
        }

        /**
         * When used outside {@link MethodInvocationTree}, this is property access.
         */
        @Override
        public JExpression visitMemberSelect(MemberSelectTree mt, Void __) {
            return $b.invoke("property").arg(loc(mt)).arg(visit(mt.getExpression())).arg(n(mt.getIdentifier()));
        }

        @Override
        public JExpression visitTypeCast(TypeCastTree tt, Void __) {
            return $b.invoke("cast").arg(loc(tt)).arg(visit(tt.getExpression())).arg(erasure(tt.getType()).dotclass()).arg(JExpr.lit(false));
        }

        @Override
        public JExpression visitIf(IfTree it, Void __) {
            JInvocation inv = $b.invoke("if_").arg(visit(it.getCondition())).arg(visit(it.getThenStatement()));
            if (it.getElseStatement() != null)
                inv.arg(visit(it.getElseStatement()));
            return inv;
        }

        @Override
        public JExpression visitNewClass(NewClassTree nt, Void __) {
            // TODO: outer class
            if (nt.getEnclosingExpression() != null)
                throw new UnsupportedOperationException();
            return $b.invoke("new_").tap(inv -> {
                inv.arg(loc(nt));
                inv.arg(cpsTypeTranslation(t(((JCTree) nt).type)));
                nt.getArguments().forEach(et -> inv.arg(visit(et)));
            });
        }

        @Override
        public JExpression visitExpressionStatement(ExpressionStatementTree et, Void __) {
            return visit(et.getExpression());
        }

        @Override
        public JExpression visitLiteral(LiteralTree lt, Void __) {
            return $b.invoke("constant").arg(JExpr.literal(lt.getValue()));
        }

        @Override
        public JExpression visitParenthesized(ParenthesizedTree pt, Void __) {
            return visit(pt.getExpression());
        }

        @Override
        public JExpression visitBinary(BinaryTree bt, Void __) {
            return $b.invoke(opName(bt.getKind())).arg(loc(bt)).arg(visit(bt.getLeftOperand())).arg(visit(bt.getRightOperand()));
        }

        @Override
        public JExpression visitUnary(UnaryTree ut, Void __) {
            return $b.invoke(opName(ut.getKind())).arg(loc(ut)).arg(visit(ut.getExpression()));
        }

        @Override
        public JExpression visitCompoundAssignment(CompoundAssignmentTree ct, Void __) {
            return $b.invoke(opName(ct.getKind())).arg(loc(ct)).arg(visit(ct.getVariable())).arg(visit(ct.getExpression()));
        }

        private String opName(Kind kind) {
            switch(kind) {
                case EQUAL_TO:
                    return "compareEqual";
                case NOT_EQUAL_TO:
                    return "compareNotEqual";
                case LESS_THAN_EQUAL:
                    return "lessThanEqual";
                case LESS_THAN:
                    return "lessThan";
                case GREATER_THAN_EQUAL:
                    return "greaterThanEqual";
                case GREATER_THAN:
                    return "greaterThan";
                case PREFIX_INCREMENT:
                    return "prefixInc";
                case POSTFIX_INCREMENT:
                    return "postfixInc";
                case POSTFIX_DECREMENT:
                    return "postfixDec";
                case LOGICAL_COMPLEMENT:
                    return "not";
                case CONDITIONAL_OR:
                    return "logicalOr";
                case CONDITIONAL_AND:
                    return "logicalAnd";
                case PLUS:
                    return "plus";
                case PLUS_ASSIGNMENT:
                    return "plusEqual";
                case MINUS:
                    return "minus";
                case MINUS_ASSIGNMENT:
                    return "minusEqual";
            }
            throw new UnsupportedOperationException(kind.toString());
        }

        @Override
        public JExpression visitAssignment(AssignmentTree at, Void __) {
            return $b.invoke("assign").arg(loc(at)).arg(visit(at.getVariable())).arg(visit(at.getExpression()));
        }

        /**
         * This is needed to handle cases like {@code Object[].class}.
         */
        @Override
        public JExpression visitArrayType(ArrayTypeTree at, Void __) {
            if (at.getType() instanceof IdentifierTree) {
                return visitIdentifier((IdentifierTree) at.getType(), __);
            } else {
                return defaultAction(at, __);
            }
        }

        @Override
        public JExpression visitNewArray(NewArrayTree nt, Void __) {
            if (nt.getInitializers() != null) {
                return $b.invoke("newArrayFromInitializers").tap(inv -> {
                    nt.getInitializers().forEach(d -> inv.arg(visit(d)));
                });
            } else {
                return $b.invoke("newArray").tap(inv -> {
                    inv.arg(loc(nt));
                    inv.arg(t(nt.getType()).dotclass());
                    nt.getDimensions().forEach(d -> inv.arg(visit(d)));
                });
            }
        }

        @Override
        public JExpression visitForLoop(ForLoopTree ft, Void __) {
            return $b.invoke("forLoop").arg(JExpr._null()).arg($b.invoke("sequence").tap(inv -> ft.getInitializer().forEach(i -> inv.arg(visit(i))))).arg(visit(ft.getCondition())).arg($b.invoke("sequence").tap(inv -> ft.getUpdate().forEach(i -> inv.arg(visit(i))))).arg(visit(ft.getStatement()));
        }

        @Override
        public JExpression visitEnhancedForLoop(EnhancedForLoopTree et, Void __) {
            return $b.invoke("forInLoop").arg(loc(et)).arg(JExpr._null()).arg(erasure(et.getVariable()).dotclass()).arg(n(et.getVariable())).arg(visit(et.getExpression())).arg(visit(et.getStatement()));
        }

        @Override
        public JExpression visitArrayAccess(ArrayAccessTree at, Void __) {
            return $b.invoke("array").arg(loc(at)).arg(visit(at.getExpression())).arg(visit(at.getIndex()));
        }

        @Override
        public JExpression visitBreak(BreakTree node, Void __) {
            if (node.getLabel() != null)
                throw new UnsupportedOperationException();
            return $b.invoke("break_").arg(JExpr._null());
        }

        @Override
        public JExpression visitContinue(ContinueTree node, Void aVoid) {
            if (node.getLabel() != null)
                throw new UnsupportedOperationException();
            return $b.invoke("continue_").arg(JExpr._null());
        }

        @Override
        public JExpression visitInstanceOf(InstanceOfTree it, Void __) {
            return $b.invoke("instanceOf").arg(loc(it)).arg(visit(it.getExpression())).arg($b.invoke("constant").arg(t(it.getType()).dotclass()));
        }

        @Override
        public JExpression visitThrow(ThrowTree tt, Void __) {
            return $b.invoke("throw_").arg(loc(tt)).arg(visit(tt.getExpression()));
        }

        @Override
        public JExpression visitDoWhileLoop(DoWhileLoopTree dt, Void __) {
            return $b.invoke("doWhile").arg(JExpr._null()).arg(visit(dt.getStatement())).arg(visit(dt.getCondition()));
        }

        @Override
        public JExpression visitConditionalExpression(ConditionalExpressionTree ct, Void __) {
            return $b.invoke("ternaryOp").arg(visit(ct.getCondition())).arg(visit(ct.getTrueExpression())).arg(visit(ct.getFalseExpression()));
        }

        @Override
        public JExpression visitTry(TryTree tt, Void __) {
            return $b.invoke("tryCatch").arg(visit(tt.getBlock())).arg(visit(tt.getFinallyBlock())).tap(inv -> tt.getCatches().forEach(ct -> JExpr._new($CatchExpression).arg(t(ct.getParameter()).dotclass()).arg(n(ct.getParameter())).arg(visit(ct.getBlock()))));
        }

        @Override
        protected JExpression defaultAction(Tree node, Void aVoid) {
            throw new UnsupportedOperationException(node.toString());
        }
    }, null));
    JVar $f = m.body().decl($CpsFunction, "f", f);
    m.body()._throw(JExpr._new($CpsCallableInvocation).arg(JExpr.lit(methodName)).arg($f).arg(JExpr._null()).args(params));
}
Also used : CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) Arrays(java.util.Arrays) LiteralTree(com.sun.source.tree.LiteralTree) JCodeModel(com.sun.codemodel.JCodeModel) Modifier(javax.lang.model.element.Modifier) Closure(groovy.lang.Closure) TypeElement(javax.lang.model.element.TypeElement) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) Elements(javax.lang.model.util.Elements) JExpr(com.sun.codemodel.JExpr) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) Map(java.util.Map) ForLoopTree(com.sun.source.tree.ForLoopTree) Trees(com.sun.source.util.Trees) InstanceOfTree(com.sun.source.tree.InstanceOfTree) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ArrayType(javax.lang.model.type.ArrayType) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) DefaultSymbolVisitor(com.sun.tools.javac.code.Types.DefaultSymbolVisitor) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Element(javax.lang.model.element.Element) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) StandardCharsets(java.nio.charset.StandardCharsets) ThrowTree(com.sun.source.tree.ThrowTree) BlockTree(com.sun.source.tree.BlockTree) JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) ReturnTree(com.sun.source.tree.ReturnTree) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) UnaryTree(com.sun.source.tree.UnaryTree) JInvocation(com.sun.codemodel.JInvocation) VariableTree(com.sun.source.tree.VariableTree) ArrayList(java.util.ArrayList) Kind(com.sun.source.tree.Tree.Kind) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) DeclaredType(javax.lang.model.type.DeclaredType) BreakTree(com.sun.source.tree.BreakTree) Tree(com.sun.source.tree.Tree) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) JClassAlreadyExistsException(com.sun.codemodel.JClassAlreadyExistsException) Resources(com.google.common.io.Resources) JDefinedClass(com.sun.codemodel.JDefinedClass) ExpressionTree(com.sun.source.tree.ExpressionTree) IOException(java.io.IOException) TreeMap(java.util.TreeMap) WildcardTree(com.sun.source.tree.WildcardTree) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) JVar(com.sun.codemodel.JVar) SimpleTypeVisitor6(javax.lang.model.util.SimpleTypeVisitor6) Date(java.util.Date) JMethod(com.sun.codemodel.JMethod) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) JExpression(com.sun.codemodel.JExpression) Generated(javax.annotation.Generated) CompilationTask(javax.tools.JavaCompiler.CompilationTask) IdentifierTree(com.sun.source.tree.IdentifierTree) NewArrayTree(com.sun.source.tree.NewArrayTree) WildcardType(javax.lang.model.type.WildcardType) JMod(com.sun.codemodel.JMod) JOp(com.sun.codemodel.JOp) JavacTask(com.sun.source.util.JavacTask) ContinueTree(com.sun.source.tree.ContinueTree) SimpleTreeVisitor(com.sun.source.util.SimpleTreeVisitor) Types(javax.lang.model.util.Types) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) TypeKind(javax.lang.model.type.TypeKind) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol) List(java.util.List) ElementScanner7(javax.lang.model.util.ElementScanner7) JType(com.sun.codemodel.JType) PrimitiveTypeTree(com.sun.source.tree.PrimitiveTypeTree) TypeVariable(javax.lang.model.type.TypeVariable) Optional(java.util.Optional) WhileLoopTree(com.sun.source.tree.WhileLoopTree) BinaryTree(com.sun.source.tree.BinaryTree) HashMap(java.util.HashMap) JTypeVar(com.sun.codemodel.JTypeVar) HashSet(java.util.HashSet) CodeWriter(com.sun.codemodel.CodeWriter) ClassTree(com.sun.source.tree.ClassTree) Name(javax.lang.model.element.Name) IfTree(com.sun.source.tree.IfTree) ElementKind(javax.lang.model.element.ElementKind) NoType(javax.lang.model.type.NoType) ExecutableElement(javax.lang.model.element.ExecutableElement) JCTree(com.sun.tools.javac.tree.JCTree) TypeMirror(javax.lang.model.type.TypeMirror) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) TryTree(com.sun.source.tree.TryTree) PrimitiveType(javax.lang.model.type.PrimitiveType) JClass(com.sun.codemodel.JClass) Collections(java.util.Collections) TypeCastTree(com.sun.source.tree.TypeCastTree) HashMap(java.util.HashMap) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ArrayList(java.util.ArrayList) BinaryTree(com.sun.source.tree.BinaryTree) IdentifierTree(com.sun.source.tree.IdentifierTree) ReturnTree(com.sun.source.tree.ReturnTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) JTypeVar(com.sun.codemodel.JTypeVar) Kind(com.sun.source.tree.Tree.Kind) TypeKind(javax.lang.model.type.TypeKind) ElementKind(javax.lang.model.element.ElementKind) ThrowTree(com.sun.source.tree.ThrowTree) InstanceOfTree(com.sun.source.tree.InstanceOfTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) LiteralTree(com.sun.source.tree.LiteralTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) TypeCastTree(com.sun.source.tree.TypeCastTree) ForLoopTree(com.sun.source.tree.ForLoopTree) InstanceOfTree(com.sun.source.tree.InstanceOfTree) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) ThrowTree(com.sun.source.tree.ThrowTree) BlockTree(com.sun.source.tree.BlockTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) ReturnTree(com.sun.source.tree.ReturnTree) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) UnaryTree(com.sun.source.tree.UnaryTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) BreakTree(com.sun.source.tree.BreakTree) Tree(com.sun.source.tree.Tree) ExpressionTree(com.sun.source.tree.ExpressionTree) WildcardTree(com.sun.source.tree.WildcardTree) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) IdentifierTree(com.sun.source.tree.IdentifierTree) NewArrayTree(com.sun.source.tree.NewArrayTree) ContinueTree(com.sun.source.tree.ContinueTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) PrimitiveTypeTree(com.sun.source.tree.PrimitiveTypeTree) WhileLoopTree(com.sun.source.tree.WhileLoopTree) BinaryTree(com.sun.source.tree.BinaryTree) ClassTree(com.sun.source.tree.ClassTree) IfTree(com.sun.source.tree.IfTree) JCTree(com.sun.tools.javac.tree.JCTree) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) TryTree(com.sun.source.tree.TryTree) CompoundAssignmentTree(com.sun.source.tree.CompoundAssignmentTree) AssignmentTree(com.sun.source.tree.AssignmentTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) JType(com.sun.codemodel.JType) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) JCIdent(com.sun.tools.javac.tree.JCTree.JCIdent) Optional(java.util.Optional) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) IfTree(com.sun.source.tree.IfTree) Arrays(java.util.Arrays) TryTree(com.sun.source.tree.TryTree) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) ArrayAccessTree(com.sun.source.tree.ArrayAccessTree) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) Symbol(com.sun.tools.javac.code.Symbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) TypeVariableSymbol(com.sun.tools.javac.code.Symbol.TypeVariableSymbol) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableTree(com.sun.source.tree.VariableTree) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) NewClassTree(com.sun.source.tree.NewClassTree) BreakTree(com.sun.source.tree.BreakTree) LiteralTree(com.sun.source.tree.LiteralTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) ExpressionTree(com.sun.source.tree.ExpressionTree) BlockTree(com.sun.source.tree.BlockTree) ContinueTree(com.sun.source.tree.ContinueTree) UnaryTree(com.sun.source.tree.UnaryTree) JVar(com.sun.codemodel.JVar) SimpleTreeVisitor(com.sun.source.util.SimpleTreeVisitor) JClass(com.sun.codemodel.JClass) ForLoopTree(com.sun.source.tree.ForLoopTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) JInvocation(com.sun.codemodel.JInvocation) JExpression(com.sun.codemodel.JExpression) NewArrayTree(com.sun.source.tree.NewArrayTree) WhileLoopTree(com.sun.source.tree.WhileLoopTree) DoWhileLoopTree(com.sun.source.tree.DoWhileLoopTree) JMethod(com.sun.codemodel.JMethod)

Example 5 with ForLoopTree

use of com.sun.source.tree.ForLoopTree in project error-prone by google.

the class FindIdentifiers method findAllIdents.

/**
 * Finds the set of all bare variable identifiers in scope at the current location. Identifiers
 * are ordered by ascending distance/scope count from the current location to match shadowing
 * rules. That is, if two variables with the same simple names appear in the set, the one that
 * appears first in iteration order is the one you get if you use the bare name in the source
 * code.
 *
 * <p>We do not report variables that would require a qualfied access. We also do not handle
 * wildcard imports.
 */
public static LinkedHashSet<VarSymbol> findAllIdents(VisitorState state) {
    ImmutableSet.Builder<VarSymbol> result = new ImmutableSet.Builder<>();
    Tree prev = state.getPath().getLeaf();
    for (Tree curr : state.getPath().getParentPath()) {
        switch(curr.getKind()) {
            case BLOCK:
                for (StatementTree stmt : ((BlockTree) curr).getStatements()) {
                    if (stmt.equals(prev)) {
                        break;
                    }
                    addIfVariable(stmt, result);
                }
                break;
            case METHOD:
                for (VariableTree param : ((MethodTree) curr).getParameters()) {
                    result.add(ASTHelpers.getSymbol(param));
                }
                break;
            case CATCH:
                result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter()));
                break;
            case CLASS:
            case INTERFACE:
            case ENUM:
            case ANNOTATION_TYPE:
                // field is referred to by qualified name, but we don't support that.
                for (Tree member : ((ClassTree) curr).getMembers()) {
                    if (member.equals(prev)) {
                        break;
                    }
                    addIfVariable(member, result);
                }
                // Collect inherited fields.
                Type classType = ASTHelpers.getType(curr);
                List<Type> classTypeClosure = state.getTypes().closure(classType);
                List<Type> superTypes = classTypeClosure.size() <= 1 ? Collections.emptyList() : classTypeClosure.subList(1, classTypeClosure.size());
                for (Type type : superTypes) {
                    Scope scope = type.tsym.members();
                    ImmutableList.Builder<VarSymbol> varsList = ImmutableList.builder();
                    for (Symbol var : scope.getSymbols(VarSymbol.class::isInstance)) {
                        varsList.add((VarSymbol) var);
                    }
                    result.addAll(varsList.build().reverse());
                }
                break;
            case FOR_LOOP:
                addAllIfVariable(((ForLoopTree) curr).getInitializer(), result);
                break;
            case ENHANCED_FOR_LOOP:
                result.add(ASTHelpers.getSymbol(((EnhancedForLoopTree) curr).getVariable()));
                break;
            case TRY:
                TryTree tryTree = (TryTree) curr;
                boolean inResources = false;
                for (Tree resource : tryTree.getResources()) {
                    if (resource.equals(prev)) {
                        inResources = true;
                        break;
                    }
                }
                if (inResources) {
                    // Case 1: we're in one of the resource declarations
                    for (Tree resource : tryTree.getResources()) {
                        if (resource.equals(prev)) {
                            break;
                        }
                        addIfVariable(resource, result);
                    }
                } else if (tryTree.getBlock().equals(prev)) {
                    // Case 2: We're in the block (not a catch or finally)
                    addAllIfVariable(tryTree.getResources(), result);
                }
                break;
            case COMPILATION_UNIT:
                for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) {
                    if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) {
                        MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier();
                        Scope scope = state.getTypes().membersClosure(ASTHelpers.getType(memberSelectTree.getExpression()), /* skipInterface= */
                        false);
                        for (Symbol var : scope.getSymbols(sym -> sym instanceof VarSymbol && sym.getSimpleName().equals(memberSelectTree.getIdentifier()))) {
                            result.add((VarSymbol) var);
                        }
                    }
                }
                break;
            default:
                // other node types don't introduce variables
                break;
        }
        prev = curr;
    }
    // TODO(eaftan): switch out collector for ImmutableSet.toImmutableSet()
    return result.build().stream().filter(var -> isVisible(var, state.getPath())).collect(Collectors.toCollection(LinkedHashSet::new));
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassType(com.sun.tools.javac.code.Type.ClassType) Modifier(javax.lang.model.element.Modifier) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) Method(java.lang.reflect.Method) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) TreePath(com.sun.source.util.TreePath) ImmutableSet(com.google.common.collect.ImmutableSet) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) MemberSelectTree(com.sun.source.tree.MemberSelectTree) Env(com.sun.tools.javac.comp.Env) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) TreeScanner(com.sun.source.util.TreeScanner) Objects(java.util.Objects) List(java.util.List) WriteableScope(com.sun.tools.javac.code.Scope.WriteableScope) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) Flags(com.sun.tools.javac.code.Flags) Name(com.sun.tools.javac.util.Name) Scope(com.sun.tools.javac.code.Scope) Type(com.sun.tools.javac.code.Type) MethodTree(com.sun.source.tree.MethodTree) MemberEnter(com.sun.tools.javac.comp.MemberEnter) VariableTree(com.sun.source.tree.VariableTree) AttrContext(com.sun.tools.javac.comp.AttrContext) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) BiPredicate(java.util.function.BiPredicate) Kind(com.sun.source.tree.Tree.Kind) ImmutableList(com.google.common.collect.ImmutableList) NewClassTree(com.sun.source.tree.NewClassTree) StreamSupport(java.util.stream.StreamSupport) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) Enter(com.sun.tools.javac.comp.Enter) ElementKind(javax.lang.model.element.ElementKind) KindSelector(com.sun.tools.javac.code.Kinds.KindSelector) TryTree(com.sun.source.tree.TryTree) Collections(java.util.Collections) Resolve(com.sun.tools.javac.comp.Resolve) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) MethodTree(com.sun.source.tree.MethodTree) CatchTree(com.sun.source.tree.CatchTree) ImmutableList(com.google.common.collect.ImmutableList) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ClassSymbol(com.sun.tools.javac.code.Symbol.ClassSymbol) TypeSymbol(com.sun.tools.javac.code.Symbol.TypeSymbol) Symbol(com.sun.tools.javac.code.Symbol) PackageSymbol(com.sun.tools.javac.code.Symbol.PackageSymbol) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) MemberSelectTree(com.sun.source.tree.MemberSelectTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ClassTree(com.sun.source.tree.ClassTree) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) StatementTree(com.sun.source.tree.StatementTree) ClassType(com.sun.tools.javac.code.Type.ClassType) Type(com.sun.tools.javac.code.Type) ImmutableSet(com.google.common.collect.ImmutableSet) WriteableScope(com.sun.tools.javac.code.Scope.WriteableScope) Scope(com.sun.tools.javac.code.Scope) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) IdentifierTree(com.sun.source.tree.IdentifierTree) CatchTree(com.sun.source.tree.CatchTree) ForLoopTree(com.sun.source.tree.ForLoopTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) BlockTree(com.sun.source.tree.BlockTree) StatementTree(com.sun.source.tree.StatementTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) NewClassTree(com.sun.source.tree.NewClassTree) ImportTree(com.sun.source.tree.ImportTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) TryTree(com.sun.source.tree.TryTree) BlockTree(com.sun.source.tree.BlockTree) EnhancedForLoopTree(com.sun.source.tree.EnhancedForLoopTree) TryTree(com.sun.source.tree.TryTree) ImportTree(com.sun.source.tree.ImportTree)

Aggregations

ForLoopTree (com.sun.source.tree.ForLoopTree)5 BlockTree (com.sun.source.tree.BlockTree)4 Tree (com.sun.source.tree.Tree)4 VariableTree (com.sun.source.tree.VariableTree)4 Symbol (com.sun.tools.javac.code.Symbol)4 ImmutableSet (com.google.common.collect.ImmutableSet)3 ClassTree (com.sun.source.tree.ClassTree)3 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)3 EnhancedForLoopTree (com.sun.source.tree.EnhancedForLoopTree)3 IdentifierTree (com.sun.source.tree.IdentifierTree)3 MemberSelectTree (com.sun.source.tree.MemberSelectTree)3 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)3 NewClassTree (com.sun.source.tree.NewClassTree)3 StatementTree (com.sun.source.tree.StatementTree)3 Kind (com.sun.source.tree.Tree.Kind)3 TryTree (com.sun.source.tree.TryTree)3 ClassSymbol (com.sun.tools.javac.code.Symbol.ClassSymbol)3 VarSymbol (com.sun.tools.javac.code.Symbol.VarSymbol)3 ImmutableList (com.google.common.collect.ImmutableList)2 VisitorState (com.google.errorprone.VisitorState)2