Skip to content

[java] Fix #6513: SimplifyConditional detects null check separated from instanceof by a && chain - #6946

Merged
UncleOwen merged 6 commits into
pmd:mainfrom
fudianchn:fix/simplifyconditional-and-chain-6513
Sep 12, 2026
Merged

UncleOwen merged 6 commits into
pmd:mainfrom
fudianchn:fix/simplifyconditional-and-chain-6513

Conversation

@fudianchn

@fudianchn fudianchn commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

AI disclosure: this change was prepared with AI coding agents, reviewed and revised line by line by me.

What

Extend SimplifyConditional to detect a redundant null check on the same subject anywhere in the short-circuit chain around an instanceof, not only when directly adjacent: before it (s != null && s2 != null && s instanceof String), after it (s instanceof String && cond && s != null), with the instanceof in the middle, and in the negated || form (s == null || cond || !(s instanceof String)).

Why

The rule previously only fired when the null check was the direct sibling of the instanceof. When the two were separated by other operands in the same short-circuit chain, or the null check followed the instanceof, the rule silently missed the case. Resumes the closed #6558, which @adangel confirmed valid.

Root cause

visit used getOtherOperandIfInInfixExpr to fetch the instanceof's direct sibling. In a chain, that sibling is itself a compound expression, so isNullCheck failed and the violation was dropped.

How

From the instanceof, climb to the root of the surrounding same-operator chain and scan all leaf operands in evaluation order, reusing the existing isNullCheck + StablePathMatcher and the polarity check. Each reported null check gets one of two messages: when an operand between it and the instanceof uses the subject, removing the null check alone could throw a NullPointerException, so the violation asks to move the instanceof first instead ("Move the instanceof check and remove the unnecessary null check to simplify this conditional"); otherwise the default message stays and the null check can simply be removed. Null checks and instanceofs on the subject in between cannot throw, and operands after the instanceof stay guarded by it, so they do not change the message. Several redundant null checks on the same subject are each reported; with several instanceofs on the subject in one chain, only the first one reports. Both && and || (negated instanceof) are covered; null checks beyond operator boundaries (parenthesized subtrees) are not considered.

Testing

  • New cases in SimplifyConditional.xml: && chain, || chain, after-position in both forms, instanceof in the middle, several null checks (each reported), two instanceofs (reported once), the reorder-vs-drop message split pinned with <expected-messages> for both messages, and negatives for unrelated subjects and operator boundaries.
  • Verified each new positive fails on the old code: expected: <1> but was: <0> for the missing positions, expected: <2> but was: <1> for several null checks, expected: <1> but was: <2> for two instanceofs.
  • Verified on the previous commit the reorder-message cases fail with the default message instead.
  • ./mvnw -pl pmd-java -am test -Dtest=SimplifyConditionalTest -Dsurefire.failIfNoSpecifiedTests=false -DfailIfNoTests=false → Tests run: 26, Failures: 0, Errors: 0.
  • Existing cases stay unchanged, including the Bug 2317099 (different subjects) and #1165 multi-|| negatives.

Regression

The 7 new violations are the intended new #6513 detections: 4x the socket != null && socket.isConnected() && socket instanceof SSLSocket idiom in openjdk-11 sun.security.ssl (reported with the move-instanceof message, since isConnected() uses the subject), 2x the adjacent credentials != null && credentials instanceof DigestAuthentication in openjdk-11 HttpURLConnection, and 1x in java-regression-tests GuardedPatterns.java (adjacent form).

Notes

Fixes #6513

@pmd-actions-helper

pmd-actions-helper Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Documentation Preview

Compared to main:
This changeset changes 90 violations,
introduces 7 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 16 errors and 0 configuration errors.
There are 0 changed duplications, 0 new duplications and 0 removed duplications.
There are 0 changed CPD errors, 0 new CPD errors and 0 removed CPD errors.

Regression Tester Report

(comment created at 2026-09-12 12:23:43+00:00 for dcfd604)

@fudianchn
fudianchn marked this pull request as draft August 12, 2026 00:37
… from instanceof by a && chain

The rule only checked the operand directly adjacent to the instanceof for a
null check on the same subject. When additional conditions sit in the same
&& (or || with negated instanceof) chain, the adjacent operand is itself a
compound expression and the redundant null check was missed.

Traverse the whole sibling short-circuit chain, reusing isNullCheck with the
existing StablePathMatcher so null checks on unrelated expressions are still
ignored. Adds && / || chain regression tests plus a negative test.

Signed-off-by: 付典 <[email protected]>
@fudianchn
fudianchn force-pushed the fix/simplifyconditional-and-chain-6513 branch from 01f72cf to 1b55586 Compare August 12, 2026 16:36
@fudianchn
fudianchn marked this pull request as ready for review August 12, 2026 17:04
@UncleOwen

Copy link
Copy Markdown
Member

We're now reporting a violation on this code:

if (socket != null && socket.isConnected() && socket instanceof SSLSocket) { ... }

I'm not sure if we should. Simply removing the null check would lead to a NullPointerException. On the other hand, it should be always possible to reorder the checks, so that the instanceof comes first, avoiding the NPE, correct?

@UncleOwen

Copy link
Copy Markdown
Member

A null check appearing after the instanceof in the chain (s instanceof String && cond && s != null) is not detected by this change; the adjacent form (s instanceof String && s != null) is still reported.

I think that should be detected as well.

@fudianchn
fudianchn marked this pull request as draft August 22, 2026 04:00
@fudianchn

fudianchn commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@UncleOwen

I'm not sure if we should. Simply removing the null check would lead to a NullPointerException. On the other hand, it should be always possible to reorder the checks, so that the instanceof comes first, avoiding the NPE, correct?

I think reordering is the better fix here. s != null && R && s instanceof T and s instanceof T && R are equivalent: with s == null, both short-circuit before evaluating R; otherwise the only change is moving an instanceof, which never throws and has no side effects. This relies on a pure subject, which the rule already enforces via StablePathMatcher. The same holds for the || form.

So the null check is still redundant, but dropping it alone only works when no intermediate operand references the subject. When I generalized the check to chains, I didn't re-check that dropping the null check is still a safe fix.

I think that should be detected as well.

I'll implement that: from the instanceof, climb to the root of the surrounding same-operator chain and scan all leaf operands in evaluation order, so a null check is reported wherever it sits in the chain. Tests are in place: the after-position && and || forms and the middle position fail on the current code (expected: <1> but was: <0>), and null checks beyond operator boundaries (parenthesized subtrees) stay at 0.

One design point: when the same chain contains several redundant null checks on the same subject, e.g. s != null && s instanceof String && s != null, I've implemented reporting each for now, following how the rule reports occurrences elsewhere. I'm not sure whether reporting only the first would be more reasonable in this scenario. Do you have a preference?

@fudianchn
fudianchn marked this pull request as ready for review August 22, 2026 07:03
…in the short-circuit chain

Scan all leaf operands of the surrounding same-operator chain in
evaluation order instead of only the sibling of the instanceof, so the
null check is reported whether it comes before or after the instanceof,
or the instanceof sits in the middle, in both the && and the negated ||
form. Several redundant null checks on the same subject are each
reported; with several instanceofs on the subject in one chain, only
the first one reports, so null checks are not reported once per
instanceof. Describe in the rule that within a chain, the instanceof
must be evaluated before other operands using the subject once the
null check is dropped.
@fudianchn
fudianchn force-pushed the fix/simplifyconditional-and-chain-6513 branch from 439ad33 to 9ba5e99 Compare August 22, 2026 07:12
@adangel

adangel commented Aug 22, 2026

Copy link
Copy Markdown
Member

@UncleOwen

I'm not sure if we should. Simply removing the null check would lead to a NullPointerException. On the other hand, it should be always possible to reorder the checks, so that the instanceof comes first, avoiding the NPE, correct?

I think reordering is the better fix here. ... The same holds for the || form.

So the null check is still redundant, but dropping it alone only works when no intermediate operand references the subject. When I generalized the check to chains, I didn't re-check that dropping the null check is still a safe fix.

Is it possible, that we detect this case and create a violation with a different message? e.g. "Move the instanceof check and remove the unnecessary null check to simplify this conditional".
In the rule tests, you can verify the messages with "..." (https://docs.pmd-code.org/latest/pmd_userdocs_extending_testing.html#test-code-children)

I think that should be detected as well.

I'll implement that...

One design point: when the same chain contains several redundant null checks on the same subject, e.g. s != null && s instanceof String && s != null, I've implemented reporting each for now, following how the rule reports occurrences elsewhere. I'm not sure whether reporting only the first would be more reasonable in this scenario. Do you have a preference?

In this example, the two violations can be fixed independently of each other. In that case, I think, it's ok to report the two "s != null" checks separately. I guess, we need to see real cases first, to decide on this. I'd say: keep it separate for now.

…ot be removed

When an operand evaluated between the null check and the instanceof uses
the subject, removing the null check alone could make it throw a
NullPointerException; report those chains with a message suggesting to
move the instanceof first instead. Null checks and instanceofs on the
subject in between cannot throw, and operands after the instanceof stay
guarded by it, so there the null check can simply be removed and the
default message is kept. Both messages are pinned with expected-messages
in the rule tests.
@fudianchn
fudianchn force-pushed the fix/simplifyconditional-and-chain-6513 branch from aa95d35 to 9ba5e99 Compare August 22, 2026 09:23
@fudianchn
fudianchn marked this pull request as draft August 22, 2026 09:56
@fudianchn

fudianchn commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@adangel Implemented in aa95d35: chains where an operand between the null check and the instanceof uses the subject now get a dedicated message, your wording verbatim ("Move the instanceof check and remove the unnecessary null check to simplify this conditional"). Null checks and instanceofs on the subject in between cannot throw, and operands after the instanceof stay guarded by it, so those keep the default message. Both messages are pinned with <expected-messages> in the rule tests, including the socket example from @UncleOwen above. Several null checks on the same subject: kept reporting each separately, per your call.

One residual imprecision, for the record: both fixes change which operands are evaluated. Removing the null check evaluates the conditions in between for a null subject; moving the instanceof first skips them for a subject that is non-null but not an instance. With pure conditions in between this is unobservable, but not with side-effecting ones:

if (s != null && list.remove(x) && s instanceof String) { ... }

No new detection in the regression corpus has such a gap (the openjdk socket.isConnected() cases are pure queries), and the message is a suggestion the developer applies by hand, so I chose to report anyway.

@fudianchn
fudianchn marked this pull request as ready for review August 22, 2026 09:57
"We don't have bug X anymore" belongs in the changelog, not in the rule
description.
We don't only check for nullchecks before an instanceof, but also for
nullchecks after an instanceof, so the old message didn't fit anymore.
…hain-6513

# Conflicts:
#	docs/pages/release_notes.md
@UncleOwen UncleOwen added this to the 7.28.0 milestone Sep 12, 2026

@UncleOwen UncleOwen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@UncleOwen
UncleOwen merged commit dd5b3e5 into pmd:main Sep 12, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[java] SimplifyConditional: False negative when null check and instanceof are separated by other && conditions

3 participants