Search in sources :

Example 56 with TreePath

use of com.sun.source.util.TreePath in project error-prone by google.

the class JdkObsolete method stringBufferFix.

// Rewrite StringBuffers that are immediately assigned to a variable which does not escape the
// current method.
private static Optional<Fix> stringBufferFix(VisitorState state) {
    Tree tree = state.getPath().getLeaf();
    // expect `new StringBuffer()`
    if (!(tree instanceof NewClassTree)) {
        return Optional.empty();
    }
    // expect e.g. `StringBuffer sb = new StringBuffer();`
    NewClassTree newClassTree = (NewClassTree) tree;
    Tree parent = state.getPath().getParentPath().getLeaf();
    if (!(parent instanceof VariableTree)) {
        return Optional.empty();
    }
    VariableTree varTree = (VariableTree) parent;
    VarSymbol varSym = ASTHelpers.getSymbol(varTree);
    TreePath methodPath = findEnclosingMethod(state);
    if (methodPath == null) {
        return Optional.empty();
    }
    // Expect all uses to be of the form `sb.<method>` (append, toString, etc.)
    // We don't want to refactor StringBuffers that escape the current method.
    // Use an array to get a boxed boolean that we can update in the anonymous class.
    boolean[] escape = { false };
    new TreePathScanner<Void, Void>() {

        @Override
        public Void visitIdentifier(IdentifierTree tree, Void unused) {
            if (varSym.equals(ASTHelpers.getSymbol(tree))) {
                Tree parent = getCurrentPath().getParentPath().getLeaf();
                if (parent == varTree) {
                    // the use of the variable in its declaration gets a pass
                    return null;
                }
                // the LHS of a select (e.g. in `sb.append(...)`) does not escape
                if (!(parent instanceof MemberSelectTree) || ((MemberSelectTree) parent).getExpression() != tree) {
                    escape[0] = true;
                }
            }
            return null;
        }
    }.scan(methodPath, null);
    if (escape[0]) {
        return Optional.empty();
    }
    return Optional.of(SuggestedFix.builder().replace(newClassTree.getIdentifier(), "StringBuilder").replace(varTree.getType(), "StringBuilder").build());
}
Also used : TreePath(com.sun.source.util.TreePath) MemberSelectTree(com.sun.source.tree.MemberSelectTree) VariableTree(com.sun.source.tree.VariableTree) ReturnTree(com.sun.source.tree.ReturnTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) AssignmentTree(com.sun.source.tree.AssignmentTree) NewClassTree(com.sun.source.tree.NewClassTree) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) ParameterizedTypeTree(com.sun.source.tree.ParameterizedTypeTree) IdentifierTree(com.sun.source.tree.IdentifierTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ExpressionTree(com.sun.source.tree.ExpressionTree) MemberReferenceTree(com.sun.source.tree.MemberReferenceTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree) IdentifierTree(com.sun.source.tree.IdentifierTree) NewClassTree(com.sun.source.tree.NewClassTree) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol)

Example 57 with TreePath

use of com.sun.source.util.TreePath in project error-prone by google.

the class InputStreamSlowMultibyteRead method maybeMatchReadByte.

private Description maybeMatchReadByte(MethodTree readByteMethod, VisitorState state) {
    if (readByteMethod.getBody() != null) {
        // Null-check for native/abstract overrides of read()
        List<? extends StatementTree> statements = readByteMethod.getBody().getStatements();
        if (statements.size() == 1) {
            Tree tree = statements.get(0);
            if (tree.getKind() == Kind.RETURN && ASTHelpers.constValue(((ReturnTree) tree).getExpression()) != null) {
                return Description.NO_MATCH;
            }
        }
    }
    // Streams within JUnit test cases are likely to be OK as well.
    TreePath enclosingPath = ASTHelpers.findPathFromEnclosingNodeToTopLevel(state.getPath(), ClassTree.class);
    while (enclosingPath != null) {
        ClassTree klazz = (ClassTree) enclosingPath.getLeaf();
        if (JUnitMatchers.isTestCaseDescendant.matches(klazz, state) || hasAnnotation(JUnitMatchers.JUNIT4_RUN_WITH_ANNOTATION).matches(klazz, state)) {
            return Description.NO_MATCH;
        }
        enclosingPath = ASTHelpers.findPathFromEnclosingNodeToTopLevel(enclosingPath, ClassTree.class);
    }
    return describeMatch(readByteMethod);
}
Also used : TreePath(com.sun.source.util.TreePath) ClassTree(com.sun.source.tree.ClassTree) ReturnTree(com.sun.source.tree.ReturnTree) MethodTree(com.sun.source.tree.MethodTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) StatementTree(com.sun.source.tree.StatementTree)

Example 58 with TreePath

use of com.sun.source.util.TreePath in project error-prone by google.

the class MultipleParallelOrSequentialCalls method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) {
    if (STREAM.matches(t, state) || PARALLELSTREAM.matches(t, state)) {
        int appropriateAmount = STREAM.matches(t, state) ? 1 : 0;
        SuggestedFix.Builder builder = SuggestedFix.builder();
        TreePath pathToMet = ASTHelpers.findPathFromEnclosingNodeToTopLevel(state.getPath(), MethodInvocationTree.class);
        // counts how many instances of parallel / sequential
        int count = 0;
        String toReplace = "empty";
        while (pathToMet != null) {
            MethodInvocationTree methodInvocationTree = (MethodInvocationTree) pathToMet.getLeaf();
            // this check makes it so that we stop iterating up once it's done
            if (methodInvocationTree.getArguments().stream().map(m -> m.toString()).anyMatch(m -> m.contains(t.toString()))) {
                break;
            }
            if (methodInvocationTree.getMethodSelect() instanceof MemberSelectTree) {
                MemberSelectTree memberSelectTree = (MemberSelectTree) methodInvocationTree.getMethodSelect();
                String memberSelectIdentifier = memberSelectTree.getIdentifier().toString();
                // checks for the first instance of parallel / sequential
                if (toReplace.equals("empty") && (memberSelectIdentifier.equals("parallel") || memberSelectIdentifier.equals("sequential"))) {
                    toReplace = memberSelectIdentifier.equals("parallel") ? "parallel" : "sequential";
                }
                // immediately removes any instances of the appropriate string
                if (memberSelectIdentifier.equals(toReplace)) {
                    int endOfExpression = state.getEndPosition(memberSelectTree.getExpression());
                    builder.replace(endOfExpression, state.getEndPosition(methodInvocationTree), "");
                    count++;
                }
            }
            pathToMet = ASTHelpers.findPathFromEnclosingNodeToTopLevel(pathToMet, MethodInvocationTree.class);
        }
        // use the builder's replacements and add a postfix
        if (count > appropriateAmount) {
            // parallel stream doesn't need a postfix
            if (appropriateAmount == 1) {
                builder.postfixWith(t, "." + toReplace + "()");
            }
            return describeMatch(t, builder.build());
        }
    }
    return Description.NO_MATCH;
}
Also used : MethodInvocationTreeMatcher(com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher) TreePath(com.sun.source.util.TreePath) MemberSelectTree(com.sun.source.tree.MemberSelectTree) Matchers.instanceMethod(com.google.errorprone.matchers.Matchers.instanceMethod) VisitorState(com.google.errorprone.VisitorState) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) Description(com.google.errorprone.matchers.Description) BugPattern(com.google.errorprone.BugPattern) WARNING(com.google.errorprone.BugPattern.SeverityLevel.WARNING) ProvidesFix(com.google.errorprone.BugPattern.ProvidesFix) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) JDK(com.google.errorprone.BugPattern.Category.JDK) ASTHelpers(com.google.errorprone.util.ASTHelpers) MethodNameMatcher(com.google.errorprone.matchers.method.MethodMatchers.MethodNameMatcher) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) TreePath(com.sun.source.util.TreePath) MethodInvocationTree(com.sun.source.tree.MethodInvocationTree) MemberSelectTree(com.sun.source.tree.MemberSelectTree)

Example 59 with TreePath

use of com.sun.source.util.TreePath in project ceylon-compiler by ceylon.

the class T6852595 method main.

public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"), Kind.SOURCE) {

        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask) tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree) cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl) cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) TreePath(com.sun.source.util.TreePath) JavaCompiler(javax.tools.JavaCompiler) JavacTask(com.sun.source.util.JavacTask)

Example 60 with TreePath

use of com.sun.source.util.TreePath in project ceylon-compiler by ceylon.

the class T6598108 method main.

public static void main(String[] args) throws Exception {
    // NOI18N
    final String bootPath = System.getProperty("sun.boot.class.path");
    final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    assert tool != null;
    final JavacTask ct = (JavacTask) tool.getTask(null, null, null, Arrays.asList("-bootclasspath", bootPath), null, Arrays.asList(new MyFileObject()));
    CompilationUnitTree cut = ct.parse().iterator().next();
    TreePath tp = new TreePath(new TreePath(cut), cut.getTypeDecls().get(0));
    Scope s = Trees.instance(ct).getScope(tp);
    TypeElement type = ct.getElements().getTypeElement("com.sun.java.util.jar.pack.Package.File");
    if (Trees.instance(ct).isAccessible(s, type)) {
        // "false" would be expected here.
        throw new IllegalStateException("");
    }
}
Also used : CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) TreePath(com.sun.source.util.TreePath) Scope(com.sun.source.tree.Scope) TypeElement(javax.lang.model.element.TypeElement) JavaCompiler(javax.tools.JavaCompiler) JavacTask(com.sun.source.util.JavacTask)

Aggregations

TreePath (com.sun.source.util.TreePath)151 ExpressionTree (com.sun.source.tree.ExpressionTree)60 Tree (com.sun.source.tree.Tree)60 VariableTree (com.sun.source.tree.VariableTree)50 MethodInvocationTree (com.sun.source.tree.MethodInvocationTree)46 MethodTree (com.sun.source.tree.MethodTree)46 ClassTree (com.sun.source.tree.ClassTree)45 MemberSelectTree (com.sun.source.tree.MemberSelectTree)39 IdentifierTree (com.sun.source.tree.IdentifierTree)37 BlockTree (com.sun.source.tree.BlockTree)36 NewClassTree (com.sun.source.tree.NewClassTree)32 StatementTree (com.sun.source.tree.StatementTree)32 JCTree (com.sun.tools.javac.tree.JCTree)31 AssignmentTree (com.sun.source.tree.AssignmentTree)27 BinaryTree (com.sun.source.tree.BinaryTree)27 TypeCastTree (com.sun.source.tree.TypeCastTree)26 ExpressionStatementTree (com.sun.source.tree.ExpressionStatementTree)25 LambdaExpressionTree (com.sun.source.tree.LambdaExpressionTree)25 LiteralTree (com.sun.source.tree.LiteralTree)25 CompoundAssignmentTree (com.sun.source.tree.CompoundAssignmentTree)23