Skip to content

Improve wildcard mismatch diagnostics for identical-looking types - #1627

Merged
msridhar merged 6 commits into
masterfrom
weird-wildcard-message
Jul 24, 2026
Merged

msridhar merged 6 commits into
masterfrom
weird-wildcard-message

Conversation

@msridhar

@msridhar msridhar commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Before, sometimes we would sometimes emit confusing errors involving wilcard types like:

incompatible types: Flux<?> cannot be converted to Flux<?>

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

    • Improved incompatible-type diagnostics for nested wildcard and generic array scenarios.
    • When LHS and RHS appear similar, the message now more clearly highlights mismatched target vs. source wildcard upper bounds.
  • Tests

    • Added new JUnit cases covering reduced incompatible-type diagnostic text for nested wildcards and array forms.
  • Documentation

    • Added a coding-style guideline requiring Javadoc for non-trivial methods.

@msridhar

msridhar commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@codecov

codecov Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 56.41026% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.06%. Comparing base (a7f21cc) to head (9798bd8).

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 56.41% 6 Missing and 11 partials ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@msridhar
msridhar force-pushed the jspecify-conditional-expr-wildcard branch from 7e0c16b to 7772e62 Compare July 16, 2026 02:58
@msridhar
msridhar force-pushed the weird-wildcard-message branch from 415384d to d8b11fb Compare July 16, 2026 02:58
@msridhar
msridhar force-pushed the jspecify-conditional-expr-wildcard branch from eb7ae34 to d3dbe81 Compare July 17, 2026 18:18
@msridhar
msridhar force-pushed the weird-wildcard-message branch from d8b11fb to cece51d Compare July 17, 2026 18:18
Base automatically changed from jspecify-conditional-expr-wildcard to master July 18, 2026 19:44
@msridhar
msridhar force-pushed the weird-wildcard-message branch 4 times, most recently from e513d4d to d36c18c Compare July 20, 2026 23:38
@msridhar
msridhar marked this pull request as ready for review July 21, 2026 00:00
@msridhar
msridhar requested a review from lazaroclapp July 21, 2026 00:03
@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The 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: lazaroclapp, yuxincs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change to wildcard mismatch diagnostics for identical-looking types.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch weird-wildcard-message

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@msridhar
msridhar force-pushed the weird-wildcard-message branch from d36c18c to 773a1e7 Compare July 24, 2026 00:16
@msridhar
msridhar requested review from yuxincs and removed request for lazaroclapp July 24, 2026 01:37
@msridhar
msridhar force-pushed the weird-wildcard-message branch from 773a1e7 to ab7e9c9 Compare July 24, 2026 01:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Wildcard-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 not isSameType (e.g. a plain WildcardType vs. a CapturedType wrapping a wildcard, as in the new weirdErrorMessageReducedFromSpring test) — the message ends up with both fragments concatenated, e.g. "... (target wildcard upper bound is Object; source wildcard upper bound is @nullable Object) (Flux<?> is a subtype of Flux<?>)". The trailing subtype clause is redundant/confusing here since both sides pretty-print identically. The test's Diagnostic contains assertion 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

📥 Commits

Reviewing files that changed from the base of the PR and between 773a1e7 and ab7e9c9.

📒 Files selected for processing (3)
  • AGENTS.md
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java

@msridhar
msridhar force-pushed the weird-wildcard-message branch from ab7e9c9 to 4056aa0 Compare July 24, 2026 17:08
@msridhar
msridhar enabled auto-merge (squash) July 24, 2026 17:08

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Wildcard-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) but ASTHelpers.isSameType still returns false for 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

📥 Commits

Reviewing files that changed from the base of the PR and between ab7e9c9 and 4056aa0.

📒 Files selected for processing (3)
  • AGENTS.md
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java

Comment on lines +466 to +469
if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) {
Type rhsTypeAsSuper =
TypeSubstitutionUtils.asSuper(
state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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.

Comment on lines +936 to +985
@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();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

Comment on lines +961 to +985
@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();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

@msridhar
msridhar merged commit 4876805 into master Jul 24, 2026
12 of 14 checks passed
@msridhar
msridhar deleted the weird-wildcard-message branch July 24, 2026 17:38
vlsi added a commit to vlsi/NullAway that referenced this pull request Sep 9, 2026
… 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)
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.

2 participants