Repository navigation
[java] Fix #5441: Resolve interdependent inference variables simultaneously - #6934
Conversation
…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]>
|
Compared to main: (comment created at 2026-08-14 14:58:08+00:00 for fff0ddf) |
|
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]>
|
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
left a comment
There was a problem hiding this comment.
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.
Analyzed and written by Claude Opus 5.
Describe the PR
UseDiamondOperatorreported a false positive on code where javac cannot inferthe type arguments, so following the suggestion did not compile:
The rule itself was fine; the underlying type inference was wrong. PMD inferred
the diamond as
ConcreteCacheLoader<String, List<Integer>>, identical to theexplicit type arguments, so the rule concluded they were redundant. javac infers
ConcreteCacheLoader<Object, List<Integer>>, which is why replacing the typearguments 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
VarWalkStrategymerges strongly connected components of the ivar dependencygraph into a single batch, precisely so that mutually dependent variables are
solved together. But
solveBatchProgressedinstantiated only the firstacceptable 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:
Solved sequentially,
'a := Stringby UPPER; incorporation turns'e >: 'ainto the proper bound
'e >: String, LOWER applies and'e := String. Solvedsimultaneously,
'ehas no proper lower bound, so UPPER gives'e := Objectwhile
'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 — theaffected calls stopped resolving at all, so the rules bailed out. Reduced from
JsonPathAssertions#value:Instantiating the batch simultaneously used LOWER for
'dand UPPER for'ainthe same pass:
'a := Object,'d := Integer. Incorporation then produces'a <: Integer, contradicting'a = Object, so the bound set becomes false andthe 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 itsGraphSolverescalates step sets over the whole batch —{EQ}, then{EQ, LOWER}, then{EQ, LOWER, UPPER, THROWS, CAPTURED}— so LOWER isexhausted batch-wide before UPPER is applied to any variable. PMD's
ReductionStep.WAVESinstead offered LOWER and UPPER to the same variable in asingle pass. This commit splits the waves the same way.
'd := Integeris then the only instantiation of the first productive wave;after incorporation
'a <: Integeris proper and'a := glb(Object, Integer) = Integer. That matches javac, which infersT := Integerhere (verified by probing javac with<T> List<T> value(Matcher<? super T>), which reportsList<Integer>). This isalso more precise than main, which inferred
Matcher<? super Object>.Refs the inference trace and initial analysis in oowekyala/pmd@b2bb215.
Related issues
Ready?
./mvnw clean verifypasses (checked automatically by github actions)