Repository navigation
Improve wildcard mismatch diagnostics for identical-looking types - #1627
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1627 +/- ##
============================================
- Coverage 88.17% 88.06% -0.12%
- Complexity 3064 3070 +6
============================================
Files 105 105
Lines 10304 10342 +38
Branches 2079 2091 +12
============================================
+ Hits 9086 9108 +22
- Misses 576 581 +5
- Partials 642 653 +11 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
7e0c16b to
7772e62
Compare
415384d to
d8b11fb
Compare
eb7ae34 to
d3dbe81
Compare
d8b11fb to
cece51d
Compare
e513d4d to
d36c18c
Compare
WalkthroughThe PR adds wildcard upper-bound details to pseudo-assignment incompatible-type diagnostics when rendered left- and right-hand types appear identical. It introduces recursive handling for wildcard, parameterized, superclass, and array types, adds regression tests for regular and array conversions, and documents a Javadoc requirement for non-trivial methods. Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
d36c18c to
773a1e7
Compare
773a1e7 to
ab7e9c9
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)
420-448: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winWildcard-bound fragment and "is a subtype of" fragment can both be appended, producing a redundant message.
When
prettyRhsType.equals(prettyLhsType)(the new branch) and the pre-existing subtype-detail branch below both fire — which happens whenever the two declared types pretty-print identically but are notisSameType(e.g. a plainWildcardTypevs. aCapturedTypewrapping a wildcard, as in the newweirdErrorMessageReducedFromSpringtest) — the message ends up with both fragments concatenated, e.g."... (target wildcard upper bound is Object; source wildcard upper bound is@nullableObject) (Flux<?> is a subtype of Flux<?>)". The trailing subtype clause is redundant/confusing here since both sides pretty-print identically. The test'sDiagnostic containsassertion won't catch this since it's a substring match.Consider making these mutually exclusive (e.g.
else if) or skipping the subtype fragment when the wildcard-bound fragment was already added.💬 Suggested fix
if (prettyRhsType.equals(prettyLhsType)) { String wildcardBoundMismatch = firstDifferingWildcardBound(lhsType, rhsType, state); if (wildcardBoundMismatch != null) { result += " (" + wildcardBoundMismatch + ")"; + return result; } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around lines 420 - 448, Make the detail-fragment logic in errorMessageForIncompatibleTypesAtPseudoAssignment mutually exclusive: when identical pretty types produce a non-null wildcardBoundMismatch, do not append the later “is a subtype of” clause. Preserve the subtype detail for cases where no wildcard-bound fragment was added.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 420-448: Make the detail-fragment logic in
errorMessageForIncompatibleTypesAtPseudoAssignment mutually exclusive: when
identical pretty types produce a non-null wildcardBoundMismatch, do not append
the later “is a subtype of” clause. Preserve the subtype detail for cases where
no wildcard-bound fragment was added.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 065d1bca-1c5e-4e6a-ae4b-67eda2d43cd6
📒 Files selected for processing (3)
AGENTS.mdnullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java
ab7e9c9 to
4056aa0
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)
420-448: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winWildcard-mismatch and "is a subtype of" fragments can both be appended, producing a confusing double-parenthesized message.
When
prettyRhsType.equals(prettyLhsType)(so a wildcard-bound fragment is added) butASTHelpers.isSameTypestill returnsfalsefor the pair (e.g. structurally-related but distinct declared types whose simple names happen to print identically), the second block below can also append" (%s is a subtype of %s)", yielding two parenthetical fragments in one message. Make the two additions mutually exclusive.🐛 Proposed fix
+ boolean appendedWildcardMismatch = false; if (prettyRhsType.equals(prettyLhsType)) { String wildcardBoundMismatch = firstDifferingWildcardBound(lhsType, rhsType, state); if (wildcardBoundMismatch != null) { result += " (" + wildcardBoundMismatch + ")"; + appendedWildcardMismatch = true; } } if (!ASTHelpers.isSameType(lhsType, rhsType, state) + && !appendedWildcardMismatch && lhsType.getKind() == TypeKind.DECLARED && rhsType.getKind() == TypeKind.DECLARED) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around lines 420 - 448, Make the wildcard-bound and subtype-detail additions in errorMessageForIncompatibleTypesAtPseudoAssignment mutually exclusive. Track whether firstDifferingWildcardBound added a fragment, and only evaluate or append the asSuper subtype fragment when no wildcard-bound mismatch was added; preserve the existing conditions and message text otherwise.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 466-469: Replace the direct cast of lhsType.tsym in the
TypeSubstitutionUtils.asSuper call with the same safe Symbol.ClassSymbol
instanceof pattern used near the earlier equivalent lookup; only perform the
supertype lookup when lhsType.tsym is a ClassSymbol, and preserve the existing
behavior otherwise.
In `@nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java`:
- Around line 936-985: Update weirdErrorMessageReducedFromSpring and
identicalLookingWildcardNestedInArrayErrorMessage to use
makeHelperWithInferenceFailureWarning() instead of makeHelper(), preserving
their existing sources and assertions while ensuring generic type-inference
failures emit the explicit GENERIC_INFERENCE_FAILURE diagnostic.
- Around line 961-985: The regression coverage only compares identical declared
wildcard types and does not exercise the superclass substitution path in
firstDifferingWildcardBound. Add a test alongside
identicalLookingWildcardNestedInArrayErrorMessage using distinct related
declared types, such as a subtype and its superclass, with a nested wildcard
bound mismatch, and assert the diagnostic reports that mismatch through the
asSuper path.
---
Outside diff comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 420-448: Make the wildcard-bound and subtype-detail additions in
errorMessageForIncompatibleTypesAtPseudoAssignment mutually exclusive. Track
whether firstDifferingWildcardBound added a fragment, and only evaluate or
append the asSuper subtype fragment when no wildcard-bound mismatch was added;
preserve the existing conditions and message text otherwise.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 13638f9f-6c97-412c-b0b4-ecaa3c90f4bf
📒 Files selected for processing (3)
AGENTS.mdnullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java
| if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) { | ||
| Type rhsTypeAsSuper = | ||
| TypeSubstitutionUtils.asSuper( | ||
| state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Unchecked cast to Symbol.ClassSymbol, unlike the safe pattern used a few lines above.
(Symbol.ClassSymbol) lhsType.tsym is an unchecked cast. A few lines earlier in this same file (Line 436-437), the equivalent lookup uses the safe instanceof Symbol.ClassSymbol classSymbol pattern instead of casting directly. Type.ClassType subtypes (e.g. error/recovery types) are not guaranteed to have a ClassSymbol as tsym, so this path risks a ClassCastException crashing the check for that compilation unit.
🛡️ Proposed fix
if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) {
+ if (!(lhsType.tsym instanceof Symbol.ClassSymbol lhsClassSymbol)) {
+ return null;
+ }
Type rhsTypeAsSuper =
TypeSubstitutionUtils.asSuper(
- state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config);
+ state.getTypes(), rhsType, lhsClassSymbol, config);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) { | |
| Type rhsTypeAsSuper = | |
| TypeSubstitutionUtils.asSuper( | |
| state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config); | |
| if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) { | |
| if (!(lhsType.tsym instanceof Symbol.ClassSymbol lhsClassSymbol)) { | |
| return null; | |
| } | |
| Type rhsTypeAsSuper = | |
| TypeSubstitutionUtils.asSuper( | |
| state.getTypes(), rhsType, lhsClassSymbol, config); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 466 - 469, Replace the direct cast of lhsType.tsym in the
TypeSubstitutionUtils.asSuper call with the same safe Symbol.ClassSymbol
instanceof pattern used near the earlier equivalent lookup; only perform the
supertype lookup when lhsType.tsym is a ClassSymbol, and preserve the existing
behavior otherwise.
| @Test | ||
| public void weirdErrorMessageReducedFromSpring() { | ||
| makeHelper() | ||
| .addSourceLines( | ||
| "Test.java", | ||
| """ | ||
| import org.jspecify.annotations.NullMarked; | ||
| import org.jspecify.annotations.NullUnmarked; | ||
| @NullMarked | ||
| final class Test { | ||
| static final class Flux<T> {} | ||
| @NullUnmarked | ||
| static final class Flow<T> {} | ||
| static <T> Flux<T> asFlux(Flow<? extends T> flow) { | ||
| throw new RuntimeException(); | ||
| } | ||
| static Flux<?> convert(Object source) { | ||
| // BUG: Diagnostic contains: incompatible types: Flux<?> cannot be converted to Flux<?> (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object) | ||
| return asFlux((Flow<?>) source); | ||
| } | ||
| } | ||
| """) | ||
| .doTest(); | ||
| } | ||
|
|
||
| @Test | ||
| public void identicalLookingWildcardNestedInArrayErrorMessage() { | ||
| makeHelper() | ||
| .addSourceLines( | ||
| "Test.java", | ||
| """ | ||
| import org.jspecify.annotations.NullMarked; | ||
| import org.jspecify.annotations.NullUnmarked; | ||
| @NullMarked | ||
| final class Test { | ||
| static final class Flux<T> {} | ||
| @NullUnmarked | ||
| static final class Flow<T> {} | ||
| static <T> Flux<T>[] asFluxArray(Flow<? extends T> flow) { | ||
| throw new RuntimeException(); | ||
| } | ||
| static Flux<?>[] convert(Object source) { | ||
| // BUG: Diagnostic contains: incompatible types: Flux<?> [] cannot be converted to Flux<?> [] (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object) | ||
| return asFluxArray((Flow<?>) source); | ||
| } | ||
| } | ||
| """) | ||
| .doTest(); | ||
| } | ||
|
|
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Consider makeHelperWithInferenceFailureWarning() for consistency with other generic-inference tests.
Both weirdErrorMessageReducedFromSpring and identicalLookingWildcardNestedInArrayErrorMessage invoke generic methods (asFlux/asFluxArray) that go through NullAway's type-variable nullability inference, exactly like the other tests in this file that consistently use makeHelperWithInferenceFailureWarning() (e.g. wildcardSuperBoundsAndInference, groundTargetTypePreservesNestedWildcards, issue1500). Using plain makeHelper() here means a future inference regression for these calls would silently fall back rather than surfacing an explicit GENERIC_INFERENCE_FAILURE diagnostic.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java` around
lines 936 - 985, Update weirdErrorMessageReducedFromSpring and
identicalLookingWildcardNestedInArrayErrorMessage to use
makeHelperWithInferenceFailureWarning() instead of makeHelper(), preserving
their existing sources and assertions while ensuring generic type-inference
failures emit the explicit GENERIC_INFERENCE_FAILURE diagnostic.
| @Test | ||
| public void identicalLookingWildcardNestedInArrayErrorMessage() { | ||
| makeHelper() | ||
| .addSourceLines( | ||
| "Test.java", | ||
| """ | ||
| import org.jspecify.annotations.NullMarked; | ||
| import org.jspecify.annotations.NullUnmarked; | ||
| @NullMarked | ||
| final class Test { | ||
| static final class Flux<T> {} | ||
| @NullUnmarked | ||
| static final class Flow<T> {} | ||
| static <T> Flux<T>[] asFluxArray(Flow<? extends T> flow) { | ||
| throw new RuntimeException(); | ||
| } | ||
| static Flux<?>[] convert(Object source) { | ||
| // BUG: Diagnostic contains: incompatible types: Flux<?> [] cannot be converted to Flux<?> [] (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object) | ||
| return asFluxArray((Flow<?>) source); | ||
| } | ||
| } | ||
| """) | ||
| .doTest(); | ||
| } | ||
|
|
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Missing regression test for the cross-class (superclass) wildcard-mismatch path.
Both new tests compare Flux<?> against Flux<?> (the same declared class on both sides), so the asSuper-based substitution branch of firstDifferingWildcardBound (for two genuinely different but related declared types, e.g. a subtype passed where a supertype is expected) isn't exercised by any test added in this diff. Consider adding a test where lhs/rhs use different, related declared types with a nested wildcard mismatch to cover that recursion path.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java` around
lines 961 - 985, The regression coverage only compares identical declared
wildcard types and does not exercise the superclass substitution path in
firstDifferingWildcardBound. Add a test alongside
identicalLookingWildcardNestedInArrayErrorMessage using distinct related
declared types, such as a subtype and its superclass, with a nested wildcard
bound mismatch, and assert the diagnostic reports that mismatch through the
asSuper path.
… suggest a wildcard bound ## Why In JSpecify mode, passing a `List<?>` to `Collection.addAll` in `@NullMarked` code is reported as `incompatible types: List<?> cannot be converted to Collection<? extends Object> (List<?> is a subtype of Collection<?>)`. The report is correct: an unbounded wildcard takes the upper bound of the type variable it instantiates, and `E` of `List` has a `@Nullable Object` bound in the JSpecify JDK model, while `? extends Object` requires a non-null element. Nothing in the message says so, and the parenthetical reads as a contradiction (uber#1822). A message about types nested a few levels deep is worse still: both types are printed in full and nothing points at the argument the check failed on. ## What Three changes to the `incompatible types` message, which the assignment, return, and parameter reporters share. **The wildcard-bound explanation reaches implicit bounds.** The explanation added in uber#1627 was emitted only where the two types print identically or a captured wildcard is involved. A wildcard whose upper bound is implicit (`?`, `? super X`) hides the difference just as a capture does, so the explanation is now emitted for those too, naming the type variable whose bound the wildcard inherits. **Where writing that bound out repairs the assignment, the message suggests it.** A suggestion is offered only when two conditions hold, and neither is inferred from the mismatches the message describes. The check has to accept it: every wildcard an explicit bound repairs is rewritten, and the result is passed to `subtypeParameterNullability`, the predicate that rejected the assignment in the first place. This covers an incompatibility no wildcard mismatch describes, such as a nullness difference on a concrete type argument. And the reader has to be able to write it: a candidate the check accepts may still print `capture of ?` or `A & B`, which no declaration may contain, so `isDenotable` mirrors `GenericTypePrettyPrintingVisitor` and rejects the four node kinds it renders as non-source text. Deciding this by classifying the collected mismatches was tried first and abandoned: the collector reports wildcard bound differences only, so no rule over its output can be sufficient. **Where no bound repairs it, a caret marks the argument at fault on both types.** The message prints the source type and the target type on their own lines with a caret run under one argument of each, and a note beside it saying what the source may hold and what the target requires. The argument is the first wildcard whose bounds the target does not accept; where the target accepts every wildcard difference, it is the concrete type argument it rejects, and that position is named only when exactly one qualifies. A caret needs a unique position to point at, so where the marked type occurs more than once in either printed type the message describes the difference in prose instead. The type variable is located by the wildcard's position in the type the user wrote. javac's `WildcardType.bound` is overwritten by each substitution during `asSuper`, so after viewing `List<?>` as a `Collection` it names `E` of an intermediate supertype such as `SequencedCollection` instead of `E` of `List`. Captured wildcards keep using `bound`, which still points at the type the capture came from. A target `? extends X` bound is now also compared against a non-wildcard source argument, so a mismatch nested in `List<List<?>>` is explained as well. ## Examples The issue's own case, where an explicit bound repairs the assignment: ```text incompatible types: List<?> cannot be converted to Collection<? extends Object> (List<?> is a subtype of Collection<?>; target wildcard upper bound is Object; source wildcard upper bound is @nullable Object; source wildcard ? has no explicit upper bound, so it takes the upper bound of type variable E of List; did you mean List<? extends Object>?) ``` The same explanation for a wildcard nested inside another type argument, where the suggestion repeats the whole source type: ```text incompatible types: Map<String, Cache<Integer, ?>> cannot be converted to Map<String, Cache<Integer, ? extends Object>> (target wildcard upper bound is Object; source wildcard upper bound is @nullable Object; source wildcard ? has no explicit upper bound, so it takes the upper bound of type variable V of Cache; did you mean Map<String, Cache<Integer, ? extends Object>>?) ``` No bound repairs this one, so the caret says which of the two nested arguments failed: ```text incompatible types: Map<? extends Object, List<? extends Collection<@nullable String>>> cannot be converted to Map<? extends Object, List<? extends Collection<String>>> Map<? extends Object, List<? extends Collection<@nullable String>>> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ upper bound is Collection<@nullable String> Map<? extends Object, List<? extends Collection<String>>> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ requires Collection<String> ``` ## Verification Seventeen new tests in `WildcardTests` cover both directions of the suggestion decision and both of the caret decision, and four existing expectations in `WildcardTests` and `GenericMethodTests` gained a caret block. Every test that asserts a suggestion also compiles the suggested text in the same source and asserts it draws no diagnostic, so a suggestion that would not in fact repair the assignment fails on that control rather than on the expectation. The tests that assert no suggestion pin one reason each: an unrewritable `? super` source, an explicit-bound mismatch, bounds differing below the top level, a concrete type argument, and a candidate holding a capture. Each new test was checked to fail against a deliberately broken implementation. `:nullaway:test` and `:nullaway:buildWithNullAway` pass. ## Scope The `incompatible types` message is shared by the assignment, return, and parameter reporters, and all three carry the new clauses. The ternary, method-reference, and override reporters build their own messages and are unchanged, so a `List<?>` in one of those positions still gets the bare parenthetical; that is existing behavior, not a regression, and is left for a follow-up. Two guards in `suggestedSourceType` have no test because no input was found that reaches them: the class-type requirement on the bound to write out, and three of the four node kinds `isDenotable` rejects. Both are recorded in the code rather than claimed as covered. Fixes uber#1822 Assisted-by: Claude Code (claude-fable-5-1) Assisted-by: Claude Code (claude-opus-5)
Before, sometimes we would sometimes emit confusing errors involving wilcard types like:
In cases where the error is due to incompatible upper bounds (the case we have observed in practice), this PR extends the error messages to describe the relevant bounds. We could definitely still do better here, but at least this helps a bit.
Summary by CodeRabbit
Bug Fixes
Tests
Documentation