Repository navigation
[java] Fix #6513: SimplifyConditional detects null check separated from instanceof by a && chain - #6946
Conversation
|
Compared to main: (comment created at 2026-09-12 12:23:43+00:00 for dcfd604) |
… 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]>
01f72cf to
1b55586
Compare
|
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? |
I think that should be detected as well. |
I think reordering is the better fix here. 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'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 One design point: when the same chain contains several redundant null checks on the same subject, e.g. |
…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.
439ad33 to
9ba5e99
Compare
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 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.
aa95d35 to
9ba5e99
Compare
|
@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 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 |
"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
AI disclosure: this change was prepared with AI coding agents, reviewed and revised line by line by me.
What
Extend
SimplifyConditionalto detect a redundant null check on the same subject anywhere in the short-circuit chain around aninstanceof, not only when directly adjacent: before it (s != null && s2 != null && s instanceof String), after it (s instanceof String && cond && s != null), with theinstanceofin the middle, and in the negated||form (s == null || cond || !(s instanceof String)).Why
The rule previously only fired when the
nullcheck was the direct sibling of theinstanceof. 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
visitusedgetOtherOperandIfInInfixExprto fetch theinstanceof's direct sibling. In a chain, that sibling is itself a compound expression, soisNullCheckfailed 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 existingisNullCheck+StablePathMatcherand the polarity check. Each reported null check gets one of two messages: when an operand between it and theinstanceofuses 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 severalinstanceofs on the subject in one chain, only the first one reports. Both&&and||(negatedinstanceof) are covered; null checks beyond operator boundaries (parenthesized subtrees) are not considered.Testing
SimplifyConditional.xml:&&chain,||chain, after-position in both forms,instanceofin the middle, several null checks (each reported), twoinstanceofs (reported once), the reorder-vs-drop message split pinned with<expected-messages>for both messages, and negatives for unrelated subjects and operator boundaries.expected: <1> but was: <0>for the missing positions,expected: <2> but was: <1>for several null checks,expected: <1> but was: <2>for twoinstanceofs../mvnw -pl pmd-java -am test -Dtest=SimplifyConditionalTest -Dsurefire.failIfNoSpecifiedTests=false -DfailIfNoTests=false→Tests run: 26, Failures: 0, Errors: 0.Bug 2317099(different subjects) and#1165multi-||negatives.Regression
The 7 new violations are the intended new #6513 detections: 4x the
socket != null && socket.isConnected() && socket instanceof SSLSocketidiom in openjdk-11sun.security.ssl(reported with the move-instanceof message, sinceisConnected()uses the subject), 2x the adjacentcredentials != null && credentials instanceof DigestAuthenticationin openjdk-11HttpURLConnection, and 1x injava-regression-testsGuardedPatterns.java(adjacent form).Notes
UselessParentheses.Fixes #6513