Skip to content

PatternMatchingInstanceof misses casts with a parenthesized operand (T)(x) #5843

@Chordrain

Description

@Chordrain

Error Prone version

Error Prone 2.49.0 (javac plugin) — javac 21.0.8, source/target 21.

Check name

PatternMatchingInstanceof

Description

PatternMatchingInstanceof flags if (x instanceof T) { ... (T) x ... } blocks that could be rewritten with a pattern binding if (x instanceof T t). The matcher inspects the cast expression (T) x to decide applicability. Wrapping the cast operand in parentheses — (T) x(T)(x) — is syntactically inert (JLS §15.16: parentheses around an operand do not change value or type), but the rule no longer recognizes the cast and drops the suggestion.

Reproducer

// BEFORE — 1 finding on the cast
public class Sample {
  public int f(Object o) {
    if (o instanceof String) {  // PatternMatchingInstanceof reported here
      String s = (String) o;
      return s.length();
    }
    return o.hashCode();
  }
}
// AFTER — parenthesized cast operand, 0 findings
public class Sample {
  public int f(Object o) {
    if (o instanceof String) {
      String s = (String)(o);    // semantically identical, no warning
      return s.length();
    }
    return o.hashCode();
  }
}

Expected behavior

PatternMatchingInstanceof should produce the same finding on BEFORE and AFTER. (String) o and (String)(o) are the same cast with the same operand, type, and runtime value.

Actual behavior

  • BEFORE: 1 finding.
  • AFTER: 0 findings.

The matcher only inspects the bare-operand cast form and does not look through enclosing parentheses on the cast operand.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions