Skip to content

ASTHelpers.getSymbol returns null for a parenthesized expression, while javac's TreeInfo.symbol returns the symbol inside #6223

Closed

Description

@vlsi

A check that looks up the symbol of an operand stops working as soon as the user writes that operand in redundant parentheses: ASTHelpers.getSymbol returns null for (x), for (this.x), and for the (lock) of every synchronized statement, where javac's own TreeInfo.symbol returns the field. The null reads as "not a variable", so the check neither crashes nor reports; it silently does nothing.

Versions: Error Prone 2.50.0 (error_prone_check_api-2.50.0.jar) on OpenJDK 21.0.9, and master at 0a97086 built locally, on OpenJDK 25.0.4; both print the output below.

What happens today

The program below compiles a class with javac and, for every ParenthesizedTree, prints ASTHelpers.getSymbol of the tree, getSymbol of the stripped tree, and TreeInfo.symbol of the tree.

import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeInfo;
import java.net.URI;
import java.util.List;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

public class GetSymbolParens {
  public static void main(String[] args) throws Exception {
    String src = "class T { int x; final Object lock = new Object(); int f() { return (x) + (this.x); } void g() { synchronized (lock) {} } }";
    JavaFileObject file =
        new SimpleJavaFileObject(URI.create("string:///T.java"), JavaFileObject.Kind.SOURCE) {
          @Override
          public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return src;
          }
        };
    JavacTask task =
        (JavacTask)
            ToolProvider.getSystemJavaCompiler().getTask(null, null, null, null, null, List.of(file));
    Iterable<? extends CompilationUnitTree> units = task.parse();
    task.analyze();
    for (CompilationUnitTree unit : units) {
      new TreeScanner<Void, Void>() {
        @Override
        public Void visitParenthesized(ParenthesizedTree tree, Void unused) {
          System.out.printf(
              "%-10s getSymbol=%s  getSymbol(stripParentheses)=%s  TreeInfo.symbol=%s%n",
              tree,
              ASTHelpers.getSymbol(tree),
              ASTHelpers.getSymbol(ASTHelpers.stripParentheses(tree)),
              TreeInfo.symbol((JCTree) tree));
          return super.visitParenthesized(tree, unused);
        }

        @Override
        public Void visitSynchronized(SynchronizedTree tree, Void unused) {
          System.out.printf(
              "synchronized: getExpression() is %s%n", tree.getExpression().getKind());
          return super.visitSynchronized(tree, unused);
        }
      }.scan(unit, null);
    }
  }
}

Run with error_prone_check_api-2.50.0.jar, guava-33.5.0-jre.jar, error_prone_annotation-2.50.0.jar, and caffeine-3.3.0.jar on the class path, and --add-exports jdk.compiler/com.sun.tools.javac.{tree,code,util,api,parser,comp,main,model,processing,file}=ALL-UNNAMED:

(x)        getSymbol=null  getSymbol(stripParentheses)=x  TreeInfo.symbol=x
(this.x)   getSymbol=null  getSymbol(stripParentheses)=x  TreeInfo.symbol=x
synchronized: getExpression() is PARENTHESIZED
(lock)     getSymbol=null  getSymbol(stripParentheses)=lock  TreeInfo.symbol=lock

Expected

ASTHelpers.getSymbol(tree) for a ParenthesizedTree returns the same symbol as getSymbol of the expression inside it, so in the output above the getSymbol column reads x, x, lock, the same as the TreeInfo.symbol column.

Grounding:

  • JLS §15.8.5 (https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.8.5): if the contained expression denotes a variable, the parenthesized expression denotes that variable too.
  • javac's TreeInfo.symbol calls skipParens before its switch: https://github.com/openjdk/jdk/blob/d63b981776ec2258023f54d8c5bfdbf52b074f4f/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeInfo.java#L1059-L1077
  • ASTHelpers.getSymbol(Tree) has no case for ParenthesizedTree and falls through to getDeclaredSymbol, which returns null for anything that is not a declaration:
    public static @Nullable Symbol getDeclaredSymbol(Tree tree) {
    if (tree instanceof PackageTree packageTree) {
    return getSymbol(packageTree);
    }
    if (tree instanceof TypeParameterTree) {
    Type type = ((JCTypeParameter) tree).type;
    return type == null ? null : type.tsym;
    }
    if (tree instanceof ClassTree classTree) {
    return getSymbol(classTree);
    }
    if (tree instanceof MethodTree methodTree) {
    return getSymbol(methodTree);
    }
    if (tree instanceof VariableTree variableTree) {
    return getSymbol(variableTree);
    }
    return null;
    }
    /**
    * 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.
    */
    public static @Nullable Symbol getSymbol(Tree tree) {
    if (tree instanceof AnnotationTree annotationTree) {
    return getSymbol(annotationTree.getAnnotationType());
    }
    if (tree instanceof JCFieldAccess jcFieldAccess) {
    return jcFieldAccess.sym;
    }
    if (tree instanceof JCIdent jcIdent) {
    // You might reasonably expect that IdentifierTrees always have a non-null symbol, but a few
    // cases don't, including module names and identifiers resolved from Javadoc (sometimes).
    return jcIdent.sym;
    }
    if (tree instanceof JCMethodInvocation jcMethodInvocation) {
    return getSymbol(jcMethodInvocation);
    }
    if (tree instanceof JCNewClass jcNewClass) {
    return getSymbol(jcNewClass);
    }
    if (tree instanceof MemberReferenceTree memberReferenceTree) {
    return getSymbol(memberReferenceTree);
    }
    if (tree instanceof JCAnnotatedType jcAnnotatedType) {
    return getSymbol(jcAnnotatedType.underlyingType);
    }
    if (tree instanceof ParameterizedTypeTree parameterizedTypeTree) {
    return getSymbol(parameterizedTypeTree.getType());
    }
    if (tree instanceof ClassTree classTree) {
    return getSymbol(classTree);
    }
    return getDeclaredSymbol(tree);
    }

Who else hits this

Every caller has to remember stripParentheses, and the ones that forget fail silently.

Scope

This asks only about the symbol lookup. It does not cover matchers that compare trees or test instanceof on an operand, which #5845 and its split-out issues track; a parenthesized operand breaks those for a different reason. A cast is not a parenthesized expression and stays out of scope: getSymbol((Object) x) returning null is not part of this request.

Compatibility

A caller that relies on getSymbol returning null for a parenthesized tree would change behavior. To look for one, I applied the shape below to master (0a97086) and ran mvn test -pl check_api,core on OpenJDK 25.0.4: 189 tests in check_api and 7447 in core pass, 135 skipped, none failed.

The tests do not exercise every one of the roughly 1000 getSymbol calls in check_api and core, so I also read the three scanners in core that call getSymbol on every node they visit, where a parenthesized identifier would now yield its symbol twice, once for the parentheses and once for the identifier. MockNotUsedInProduction merges the deletion ranges it collects, so a range found twice is deleted once. UnnecessaryBoxedVariable stops scanning at the parentheses instead of at the identifier inside them. UnusedTypeParameter counts only type variables, and a type variable is never a parenthesized expression. I did not read the other call sites one by one.

One possible shape

Not the requirement, only an illustration: a case at the top of getSymbol(Tree).

if (tree instanceof ParenthesizedTree parenthesizedTree) {
  return getSymbol(parenthesizedTree.getExpression());
}

A separate method such as getSymbolSkippingParentheses would leave every existing caller to opt in, which is the step the current callers already forget.

Prior reports

Searched the tracker, open and closed, issues and PRs, for getSymbol parentheses, getSymbol ParenthesizedTree, getSymbol stripParentheses, getSymbol parenthesized, parentheses ASTHelpers, parenthesized expression symbol, and stripParentheses. The nearest hits are #5845 (checks that are not invariant under parentheses, split into #6213 to #6218) and PR #5889 (per-check fixes). Both fix individual checks; this issue asks for the fix in ASTHelpers.getSymbol, so that checks written later get it too.

Activity

  1. added a commit that references this issue on Oct 21, 2026
    37fc792
  2. cushon commented on Nov 4, 2026

    @cushon
    Collaborator

    Thanks for the detailed analysis and PR. In general, Error Prone checks do not aim to be invariant under arbitrary redundant parenthesization like (x) or (this.x) (see https://errorprone.info/docs/criteria#false-positives-false-negatives-and-bug-reports). Making ASTHelpers.getSymbol(Tree) look through ParenthesizedTree also creates a hazard for the many callers and matchers that treat getSymbol(tree) != null as implying that tree itself is the identifier, member select, or invocation node rather than an enclosing ParenthesizedTree (for example, ASTHelpersSuggestions calls getReceiver(receiver) after SYMBOL_OWNER.matches(receiver, state), which throws IllegalStateException on (sym.owner).enclClass(), and TreeScanners visiting every node see the same symbol multiple times for ((x))). Turning potential false negatives on parenthesized expressions into crashes or duplicate matches is a worse trade-off, so we prefer to keep getSymbol(ParenthesizedTree) returning null and call stripParentheses explicitly where needed.

  3. vlsi commented on Nov 4, 2026

    @vlsi
    ContributorAuthor

    Thanks, the (sym.owner).enclClass() case convinced me: a caller that casts the tree or calls getReceiver after a non-null getSymbol would crash. I'll handle this in NullAway instead, by making each call site choose explicitly (apache/nullaway#2133).

    Would a one-line Javadoc note on getSymbol(Tree) that it returns null for a ParenthesizedTree be welcome?

  4. cushon commented on Nov 4, 2026

    @cushon
    Collaborator

    Would a one-line Javadoc note on getSymbol(Tree) that it returns null for a ParenthesizedTree be welcome?

    Yes, I'd be happy to take a PR for that, thanks!

  5. vlsi commented on Nov 4, 2026

    @vlsi
    ContributorAuthor

    Here's the PR along with the test for getSymbol(ParenthesizedTree): #6295

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions