Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import org.jspecify.annotations.Nullable;
Expand All @@ -28,6 +29,10 @@ interface BaseMethodMatcher {

BaseMethodMatcher METHOD =
tree -> {
if (tree instanceof ParenthesizedTree) {
// A method matcher matches the call, not parentheses around it.
return null;
}
Symbol sym = ASTHelpers.getSymbol(tree);
if (!(sym instanceof MethodSymbol methodSymbol)) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
Expand All @@ -50,6 +51,10 @@ public final class MethodInvocationMatcher {

record Context(MethodSymbol sym, ExpressionTree tree) {
static Optional<Context> create(ExpressionTree tree) {
if (tree instanceof ParenthesizedTree) {
// A method matcher matches the call, not parentheses around it.
return Optional.empty();
}
Symbol sym = ASTHelpers.getSymbol(tree);
if (!(sym instanceof MethodSymbol methodSymbol)) {
return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,14 @@ public static boolean sameVariable(ExpressionTree expr1, ExpressionTree expr2) {
* Gets the symbol for a tree. Returns null if this tree does not have a symbol because it is of
* the wrong type, if {@code tree} is null, or if the symbol cannot be found due to a compilation
* error.
*
* <p>A parenthesized expression has the symbol of the expression inside the parentheses, so
* {@code (x)} and {@code x} return the same symbol.
*/
public static @Nullable Symbol getSymbol(Tree tree) {
if (tree instanceof ParenthesizedTree parenthesizedTree) {
return getSymbol(parenthesizedTree.getExpression());
}
if (tree instanceof AnnotationTree annotationTree) {
return getSymbol(annotationTree.getAnnotationType());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.PackageTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
Expand Down Expand Up @@ -1455,6 +1456,43 @@ public Void visitClass(ClassTree node, VisitorState visitorState) {
assertCompiles(scanner);
}

@Test
public void getSymbol_parenthesizedExpressionHasTheSymbolOfItsOperand() {
writeFile(
"A.java",
"""
class A {
int x;
final Object lock = new Object();

int f() {
return ((x)) + (this.x) + (1 + 2);
}

void g() {
synchronized (lock) {
}
}
}
""");
List<String> symbols = new ArrayList<>();
TestScanner scanner =
new TestScanner() {
@Override
public Void visitParenthesized(ParenthesizedTree tree, VisitorState state) {
symbols.add(tree + " -> " + ASTHelpers.getSymbol(tree));
setAssertionsComplete();
return super.visitParenthesized(tree, state);
}
};
tests.add(scanner);
assertCompiles(scanner);
assertThat(symbols)
.containsExactly(
"((x)) -> x", "(x) -> x", "(this.x) -> x", "(1 + 2) -> null", "(lock) -> lock")
.inOrder();
}

@Test
public void outermostclass_dotClass() {
writeFile(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -469,8 +469,7 @@ public Void visitCompoundAssignment(CompoundAssignmentTree node, Void unused) {
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (NULL_CHECK_MATCH.matches(node, state)) {
Symbol firstArgSymbol =
getSymbol(ASTHelpers.stripParentheses(node.getArguments().getFirst()));
Symbol firstArgSymbol = getSymbol(node.getArguments().getFirst());
if (isBoxed(firstArgSymbol, state)) {
dereferenced.add((VarSymbol) firstArgSymbol);
fixableNullCheckInvocations.put((VarSymbol) firstArgSymbol, getCurrentPath());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ private static boolean methodAlwaysReturnsInputParam(MethodTree methodTree, Visi
public Void visitReturn(ReturnTree returnTree, Void unused) {
// even for cases where getExpression() or getSymbol() returns null, we still want to
// add those to the returnedSymbols set (that's important if there's > 1 returns)
returnedSymbols.add(getSymbol(stripParentheses(returnTree.getExpression())));
returnedSymbols.add(getSymbol(returnTree.getExpression()));
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package com.google.errorprone.bugpatterns.threadsafety;

import static com.google.errorprone.util.ASTHelpers.isStatic;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;

import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
Expand Down Expand Up @@ -51,7 +50,7 @@
public class StaticGuardedByInstance extends BugChecker implements SynchronizedTreeMatcher {
@Override
public Description matchSynchronized(SynchronizedTree tree, VisitorState state) {
Symbol lock = ASTHelpers.getSymbol(stripParentheses(tree.getExpression()));
Symbol lock = ASTHelpers.getSymbol(tree.getExpression());
if (!(lock instanceof VarSymbol)) {
return Description.NO_MATCH;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import static com.google.errorprone.util.ASTHelpers.stripParentheses;
import static com.google.errorprone.util.AnnotationNames.LAZY_INIT_ANNOTATION;

import com.google.errorprone.BugPattern;
Expand Down Expand Up @@ -48,7 +47,7 @@ public class SynchronizeOnNonFinalField extends BugChecker

@Override
public Description matchSynchronized(SynchronizedTree tree, VisitorState state) {
Symbol symbol = ASTHelpers.getSymbol(stripParentheses(tree.getExpression()));
Symbol symbol = ASTHelpers.getSymbol(tree.getExpression());
if (!(symbol instanceof VarSymbol varSymbol)) {
return NO_MATCH;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,9 @@ public UCatch visitCatch(CatchTree tree, Void v) {
}

private @Nullable PlaceholderMethod placeholder(@Nullable ExpressionTree expr) {
return expr != null ? placeholderMethods.get(ASTHelpers.getSymbol(expr)) : null;
return expr instanceof MethodInvocationTree
? placeholderMethods.get(ASTHelpers.getSymbol(expr))
: null;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.method.MethodMatchers.constructor;
Expand All @@ -28,13 +29,15 @@
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ParenthesizedTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.matchers.method.MethodMatchers.MethodNameMatcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParenthesizedTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
Expand Down Expand Up @@ -274,4 +277,48 @@ void f() {
""")
.doTest();
}

/** Flags a call, and parentheses around a call, that a method matcher accepts. */
@BugPattern(summary = "", severity = ERROR)
public static class ParenthesizedCallChecker extends BugChecker
implements MethodInvocationTreeMatcher, ParenthesizedTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
anyOf(
staticMethod().onClass("java.lang.Math").named("abs"),
instanceMethod().onDescendantOf("java.lang.String").named("length"));

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return MATCHER.matches(tree, state)
? buildDescription(tree).setMessage("call").build()
: NO_MATCH;
}

@Override
public Description matchParenthesized(ParenthesizedTree tree, VisitorState state) {
return MATCHER.matches(tree, state)
? buildDescription(tree).setMessage("parentheses").build()
: NO_MATCH;
}
}

@Test
public void methodMatcher_doesNotMatchParenthesesAroundACall() {
CompilationTestHelper.newInstance(ParenthesizedCallChecker.class, getClass())
.addSourceLines(
"Test.java",
"""
class Test {
int f(String s) {
return (
// BUG: Diagnostic contains: call
Math.abs(-1))
+ (
// BUG: Diagnostic contains: call
s.length());
}
}
""")
.doTest();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,24 @@
import static com.google.errorprone.matchers.Matchers.staticMethod;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ParenthesizedTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodInvocationMatcher.Rule;
import com.google.errorprone.matchers.method.MethodInvocationMatcher.Token;
import com.google.errorprone.matchers.method.MethodInvocationMatcher.Token.ReceiverType;
import com.google.errorprone.matchers.method.MethodInvocationMatcher.TokenType;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.ParenthesizedTree;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
Expand Down Expand Up @@ -85,4 +93,48 @@ public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState
return matcher.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH;
}
}

/** Flags a call, and parentheses around a call, that a compiled receiver-type rule accepts. */
@BugPattern(summary = "", severity = ERROR)
public static class ParenthesizedCallChecker extends BugChecker
implements MethodInvocationTreeMatcher, ParenthesizedTreeMatcher {
private static final Matcher<ExpressionTree> MATCHER =
MethodInvocationMatcher.compile(
ImmutableList.of(
Rule.create(
ImmutableMap.of(
TokenType.RECEIVER_TYPE,
ImmutableSet.<Token>of(ReceiverType.create("java.lang.String"))))));

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return MATCHER.matches(tree, state)
? buildDescription(tree).setMessage("call").build()
: Description.NO_MATCH;
}

@Override
public Description matchParenthesized(ParenthesizedTree tree, VisitorState state) {
return MATCHER.matches(tree, state)
? buildDescription(tree).setMessage("parentheses").build()
: Description.NO_MATCH;
}
}

@Test
public void compiledMatcher_doesNotMatchParenthesesAroundACall() {
CompilationTestHelper.newInstance(ParenthesizedCallChecker.class, getClass())
.addSourceLines(
"Test.java",
"""
class Test {
int f(String s) {
return (
// BUG: Diagnostic contains: call
s.length());
}
}
""")
.doTest();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,11 @@ public void expressionPlaceholder() throws IOException {
runTest("PlaceholderTemplate");
}

@Test
public void parenthesizedPlaceholderInReturn() throws IOException {
runTest("ParenthesizedPlaceholderTemplate");
}

@Test
public void expressionPlaceholderAllowsIdentity() throws IOException {
runTest("PlaceholderAllowsIdentityTemplate");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2026 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.refaster.testdata;

import java.util.Iterator;
import java.util.List;

/** Test data for {@code ParenthesizedPlaceholderTemplate}. */
public class ParenthesizedPlaceholderTemplateExample {
public void positiveExample(List<Integer> list) {
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
if (itr.next() < 0) {
itr.remove();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2026 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.errorprone.refaster.testdata;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.Iterator;
import java.util.List;

/** Test data for {@code ParenthesizedPlaceholderTemplate}. */
public class ParenthesizedPlaceholderTemplateExample {
public void positiveExample(List<Integer> list) {
Iterables.removeIf(list, new Predicate<Integer>(){

@Override
public boolean apply(Integer input) {
return (input < 0);
}
});

}
}
Loading
Loading