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());
}
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);
}
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;
}
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);
}
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("");
}
}
Aggregations