Repository navigation
Description
Affects PMD Version: 7.28.0 (also 7.29.0-SNAPSHOT)
Description:
With f(int, Long) and f(long, long), javac compiles f(value, 2) for an Integer value to f(long, long). PMD resolves it to f(int, Long). For PMD both methods are applicable and f(int, Long) wins as more specific. g(1) for a single g(Long) resolves to g(Long) and h(null) for h(int) to h(int), with getOverloadSelectionInfo().isFailed() false, where javac reports incompatible types: int cannot be converted to Long and incompatible types: <null> cannot be converted to int.
When one side is primitive, Infer.isConvertible boxes both sides first and, when that fails, unboxes both sides (line 1010):
pmd/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/types/internal/infer/Infer.java
Lines 998 to 1015 in 5c9271c
| static Convertibility isConvertible(JTypeMirror exprType, JTypeMirror formalType, boolean canBox) { | |
| if (exprType == formalType) { | |
| // fast path | |
| return Convertibility.SUBTYPING; | |
| } | |
| if (canBox && exprType.isPrimitive() ^ formalType.isPrimitive()) { | |
| // then boxing conversions may be useful | |
| Convertibility result = TypeOps.isConvertible(exprType.box(), formalType.box()); | |
| if (!result.never()) { | |
| return result; | |
| } else { | |
| return TypeOps.isConvertible(exprType.unbox(), formalType.unbox()); | |
| } | |
| } | |
| return TypeOps.isConvertible(exprType, formalType); | |
| } |
For a primitive argument the second step accepts int for Long through the widening int to long, and int for Double through int to double. JLS 5.3 allows a boxing conversion followed by a widening reference conversion, not a widening primitive conversion followed by boxing. The first step accepts the null type for a primitive parameter, because null converts to Integer.
The test "Two overloads with boxed types, widening required, ambiguous" in OverloadResolutionTest.kt (lines 343-367) expects an ambiguity for assertThat(1) with assertThat(Double) and assertThat(Long). javac reports no suitable method found for assertThat(int), because neither method is applicable. Above it, the test for #4557 (lines 304-341) describes int -> Long as widening and then boxing.
Found while working on #7136.
Code Sample demonstrating the issue:
class Loose {
static void f(int x, Long y) { }
static void f(long x, long y) { }
void t(Integer value) {
f(value, 2);
}
}Steps to reproduce:
javac Loose.java, also with--release 8, thenjavap -c -p Loose: the call isf:(JJ)V.- Run PMD on
Loose.javawith the XPath rule//MethodCall[pmd-java:matchesSig("Loose#f(int,java.lang.Long)")]. It reports line 6.
Running PMD through: Other (PmdAnalysis API)
Activity
[java] UnnecessaryBoxing: rerun the overload resolution without the u…
[java] Fix #7146, #7149: Loose invocation conversion and the most spe…
Enable test cases (pmd#7146, pmd#7149)
[java] UnnecessaryBoxing: update the expected reports after the fix of …