Skip to content
Merged
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 @@ -232,9 +232,13 @@ 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.
* Gets the symbol that a tree declares or refers to.
*
* <p>Returns null if {@code tree} is null, if it is a kind of tree that has no symbol, or if
* javac attached no symbol to an identifier or member select, as for some module names. A {@link
* ParenthesizedTree} has no symbol, so {@code getSymbol((x))} returns null where {@code
* getSymbol(x)} returns the symbol of {@code x}. Call {@link #stripParentheses(Tree)} first where
* the parentheses do not matter.
*/
public static @Nullable Symbol getSymbol(Tree tree) {
if (tree instanceof AnnotationTree annotationTree) {
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 @@ -1483,6 +1484,38 @@ public Void visitMemberSelect(MemberSelectTree tree, VisitorState state) {
assertCompiles(scanner);
}

// Callers treat a non-null symbol as a sign that the tree itself is an identifier, member select,
// or invocation, and some cast it or pass it to getReceiver, which throws IllegalStateException
// when given a parenthesized expression. See https://github.com/google/error-prone/issues/6223.
@Test
public void getSymbol_parenthesizedExpressionHasNoSymbol() {
writeFile(
"Foo.java",
"""
class Foo {
int x;

int f() {
return (x) + 1;
}
}
""");

TestScanner scanner =
new TestScanner() {
@Override
public Void visitParenthesized(ParenthesizedTree tree, VisitorState state) {
assertThat(getSymbol(tree)).isNull();
assertThat(String.valueOf(getSymbol(tree.getExpression()))).isEqualTo("x");
setAssertionsComplete();
return super.visitParenthesized(tree, state);
}
};
tests.add(scanner);

assertCompiles(scanner);
}

/** Replaces all throws clauses with more specific exceptions. */
@BugPattern(
summary = "Replaces all throws clauses with more specific exceptions.",
Expand Down
Loading