Skip to content

[java] Fix #5441: Resolve interdependent inference variables simultaneously - #6934

Merged
adangel merged 3 commits into
pmd:mainfrom
slovdahl:fix-UseDiamondOperator
Aug 14, 2026
Merged

adangel merged 3 commits into
pmd:mainfrom
slovdahl:fix-UseDiamondOperator

Conversation

@slovdahl

@slovdahl slovdahl commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Analyzed and written by Claude Opus 5.

Describe the PR

UseDiamondOperator reported a false positive on code where javac cannot infer
the type arguments, so following the suggestion did not compile:

Cache<String, List<Integer>> cache =
    provider.<String, List<Integer>>newCacheBuilder("test")
            .buildAsync(new ConcreteCacheLoader<String, List<Integer>>() { ... })
            .synchronous();

The rule itself was fine; the underlying type inference was wrong. PMD inferred
the diamond as ConcreteCacheLoader<String, List<Integer>>, identical to the
explicit type arguments, so the rule concluded they were redundant. javac infers
ConcreteCacheLoader<Object, List<Integer>>, which is why replacing the type
arguments with a diamond breaks compilation ("does not override abstract method
fetch(Object)").

Two commits, both in net.sourceforge.pmd.lang.java.types.internal.infer.

1. Resolve interdependent inference variables simultaneously

VarWalkStrategy merges strongly connected components of the ivar dependency
graph into a single batch, precisely so that mutually dependent variables are
solved together. But solveBatchProgressed instantiated only the first
acceptable variable of the batch and returned, so incorporation ran again before
the rest of the batch was solved. JLS 18.4 requires the instantiations of such a
batch to all be computed from the same bound set and only then incorporated,
because the resolution rules may only use proper bounds. For the snippet above:

'a { 'a <: String, 'a <: 'e }     # K1 of buildAsync
'e { 'e <: Object, 'e >: 'a }     # K of the diamond

Solved sequentially, 'a := String by UPPER; incorporation turns 'e >: 'a
into the proper bound 'e >: String, LOWER applies and 'e := String. Solved
simultaneously, 'e has no proper lower bound, so UPPER gives 'e := Object
while 'a := String — matching javac.

2. Exhaust lower bounds before upper bounds within a batch

The first commit alone caused a regression that the regression tester caught:
5 violations removed from spring-framework (4 LawOfDemeter,
1 UnnecessaryFullyQualifiedName). Those removals were not valid — the
affected calls stopped resolving at all, so the rules bailed out. Reduced from
JsonPathAssertions#value:

<T> BodyContentSpec value(Matcher<? super T> matcher);
static <T> Matcher<T> equalTo(T operand);

a.value(equalTo(42));

'a { 'a <: Object, 'a <: 'd }     # T of value
'd { 'd >: Integer, 'd >: 'a }    # T of equalTo

Instantiating the batch simultaneously used LOWER for 'd and UPPER for 'a in
the same pass: 'a := Object, 'd := Integer. Incorporation then produces
'a <: Integer, contradicting 'a = Object, so the bound set becomes false and
the invocation is rejected.

JLS 18.4 prescribes a recovery for exactly this — when the simultaneous
instantiation yields false, a second attempt is made with fresh type variables.
PMD does not implement that fallback. javac has it
(Infer.instantiateAsUninferredVars) but never needs it here, because its
GraphSolver escalates step sets over the whole batch — {EQ}, then
{EQ, LOWER}, then {EQ, LOWER, UPPER, THROWS, CAPTURED} — so LOWER is
exhausted batch-wide before UPPER is applied to any variable. PMD's
ReductionStep.WAVES instead offered LOWER and UPPER to the same variable in a
single pass. This commit splits the waves the same way.

'd := Integer is then the only instantiation of the first productive wave;
after incorporation 'a <: Integer is proper and
'a := glb(Object, Integer) = Integer. That matches javac, which infers
T := Integer here (verified by probing javac with
<T> List<T> value(Matcher<? super T>), which reports List<Integer>). This is
also more precise than main, which inferred Matcher<? super Object>.

Refs the inference trace and initial analysis in oowekyala/pmd@b2bb215.

Related issues

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

…taneously

UseDiamondOperator reported a false positive on code where javac cannot
infer the type arguments, so following the suggestion did not compile:

    Cache<String, List<Integer>> cache =
        provider.<String, List<Integer>>newCacheBuilder("test")
                .buildAsync(new ConcreteCacheLoader<String, List<Integer>>() { ... })
                .synchronous();

The rule itself was fine; the underlying type inference was wrong. PMD
inferred the diamond as ConcreteCacheLoader<String, List<Integer>>, which
is identical to the explicit type arguments, so the rule concluded they
were redundant. javac infers ConcreteCacheLoader<Object, List<Integer>>
instead, which is why replacing the type arguments with a diamond breaks
compilation ("does not override abstract method fetch(Object)").

Cause: VarWalkStrategy merges strongly connected components of the ivar
dependency graph into a single batch, precisely so that mutually dependent
variables are solved together. But solveBatchProgressed instantiated only
the first acceptable variable of the batch and returned, so incorporation
ran again before the rest of the batch was solved.

That violates JLS 18.4, which requires the instantiations of such a batch
to all be *computed* from the same bound set and only then be incorporated.
The distinction matters because the resolution rules may only use proper
bounds, i.e. bounds that do not mention an inference variable. For the
snippet above the relevant context is

    'a { 'a <: String, 'a <: 'e }     # K1 of buildAsync
    'e { 'e <: Object, 'e >: 'a }     # K of the diamond

Solved sequentially, 'a := String by rule UPPER; incorporation then turns
'e >: 'a into the proper bound 'e >: String, rule LOWER applies and
'e := String. Solved simultaneously, 'e has no proper lower bound (its only
lower bound 'a still mentions an ivar), so rule UPPER gives 'e := Object
while 'a := String — matching javac.

Note that the JLS does pin this down, via the proper-bound requirement; it
is not merely an unspecified resolution order.

Fix: compute the instantiation of every acceptable variable of the batch
before applying any of them, then instantiate them all and let incorporation
run once. This is behaviourally identical to the previous code for the
common case of a batch holding a single variable.

Verified that the change is inert elsewhere: running the full all-java
ruleset before and after yields byte-identical reports for Guava, Caffeine
and RxJava (109615 violations) and for PMD's own src/main/java (41174
violations). The whole pmd-java suite passes unchanged.

Refs the inference trace and initial analysis in oowekyala/pmd@b2bb215.

Fixes pmd#5441

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@pmd-actions-helper

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

Copy link
Copy Markdown
Contributor

Documentation Preview

Compared to main:
This changeset changes 8 violations,
introduces 0 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 0 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-08-14 14:58:08+00:00 for fff0ddf)

@UncleOwen

Copy link
Copy Markdown
Member

Could you please have a look at the regression report? This PR removes 5 violations from spring-framework. Those violations seem to be valid on first glance.

The previous commit made the interdependent variables of a batch be
instantiated simultaneously, as JLS 18.4 requires. The regression tester
then reported 5 violations removed from spring-framework (4 LawOfDemeter,
1 UnnecessaryFullyQualifiedName). Those removals were not valid: the
affected calls stopped resolving altogether, so the rules bailed out
(UnnecessaryFullyQualifiedNameRule returns early when
getOverloadSelectionInfo().isFailed(), LawOfDemeter cannot compute a
degree without a receiver type).

The smallest of the two shapes, reduced from JsonPathAssertions#value:

    <T> BodyContentSpec value(Matcher<? super T> matcher);
    static <T> Matcher<T> equalTo(T operand);

    a.value(equalTo(42));

gives the bound set

    'a { 'a <: Object, 'a <: 'd }     # T of value
    'd { 'd >: Integer, 'd >: 'a }    # T of equalTo

Instantiating the batch simultaneously used LOWER for 'd and UPPER for
'a in the same pass, yielding 'a := Object and 'd := Integer.
Incorporating both produces 'a <: Integer, which contradicts
'a = Object, so the bound set becomes false and the invocation is
rejected:

    Failed: Incompatible bounds: 'a = Object and 'a <: Integer
    [WARNING] Compile-time declaration resolution failed. Expr: a.value(equalTo(42))

JLS 18.4 does prescribe a recovery for exactly this: when the
simultaneous instantiation yields false, a second attempt is made with
fresh type variables. We do not implement that fallback, so the false
bound is terminal. Javac has the fallback (Infer.instantiateAsUninferredVars)
but never needs it here, because its GraphSolver escalates *step sets*
over the whole batch - {EQ}, then {EQ, LOWER}, then
{EQ, LOWER, UPPER, THROWS, CAPTURED} - so LOWER is exhausted batch-wide
before UPPER is applied to any variable. Our WAVES instead offered LOWER
and UPPER to the same variable in a single pass.

Fix: split the waves the way javac does. 'd := Integer is then the only
instantiation of the first productive wave; after incorporation
'a <: Integer is a proper bound and 'a := glb(Object, Integer) = Integer.
That matches javac, which infers T := Integer here (verified by probing
javac with `<T> List<T> value(Matcher<? super T>)`, which reports
List<Integer>). Note this is also more precise than before pmd#5441: main
inferred Matcher<? super Object> for this call.

The pmd#5441 case is unaffected, because there both variables fall through
to UPPER in the same wave anyway, and UPPER ignores the lower bound that
incorporation would have made proper.

Add regression tests for both spring-framework shapes. Each fails
without this commit (the call resolves to *unknown*) and passes with it.
Full pmd-java suite: 9806 tests, 0 failures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@slovdahl

slovdahl commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Ah, yes, great point. Nice way of detecting regressions 👌

Claude agrees. I pushed a second commit with a fix that should fix the regression.

@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, this looks good to me. But since this is changing the type resolution code (which is very important and with which I'm not very familiar), I'd like another set of eyes.

@UncleOwen
UncleOwen requested a review from adangel August 6, 2026 13:46
@adangel adangel added this to the 7.27.0 milestone Aug 14, 2026

@adangel adangel 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!

@adangel
adangel merged commit a9b6520 into pmd:main Aug 14, 2026
13 checks passed
@slovdahl
slovdahl deleted the fix-UseDiamondOperator branch August 14, 2026 15:05
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] UseDiamondOperator: False positive with interdependent generic vars

3 participants