Repository navigation
Handle annotations on type variables in return and field types - #1371
Conversation
WalkthroughAdds restoration of explicit type-use nullability annotations in GenericsChecks.getTreeType when ASTHelpers.getType(tree) returns non-null: for MethodInvocationTree results it restores annotations from the invoked method's declared return type, and for MemberSelectTree that refers to a field it restores annotations from the field's declared type. The restoration is applied after computing the base result and before raw-type checks. Two tests were added covering non-null annotations in generic return positions and in generic field type arguments. Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro 📒 Files selected for processing (2)
🧰 Additional context used🧠 Learnings (4)📓 Common learnings📚 Learning: 2025-08-28T04:54:20.953ZApplied to files:
📚 Learning: 2025-10-29T23:56:18.236ZApplied to files:
📚 Learning: 2025-08-14T18:50:06.159ZApplied to files:
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
🔇 Additional comments (3)
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 |
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (2)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java(1 hunks)nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java(1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: msridhar
Repo: uber/NullAway PR: 1248
File: nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java:847-857
Timestamp: 2025-08-28T04:54:20.953Z
Learning: In NullAway's GenericsChecks.java, NewClassTree support for explicit type argument substitution requires more extensive changes beyond just modifying the conditional in compareGenericTypeParameterNullabilityForCall. The maintainers prefer to handle NewClassTree support in a separate follow-up rather than expanding the scope of PRs focused on specific issues like super constructor calls.
Learnt from: msridhar
Repo: uber/NullAway PR: 1316
File: jdk-javac-plugin/src/main/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializer.java:261-293
Timestamp: 2025-10-29T23:56:18.236Z
Learning: In NullAway's jdk-javac-plugin NullnessAnnotationSerializer, type variable bounds with annotations (e.g., `T extends Nullable Object`) are checked at their declaration sites by the typeParamHasAnnotation method for both class-level and method-level type parameters. The hasJSpecifyAnnotationDeep method is designed to check type uses (return types, parameters, etc.) and does not need a TYPEVAR case because type variable declaration bounds are already handled separately.
📚 Learning: 2025-08-28T04:54:20.953Z
Learnt from: msridhar
Repo: uber/NullAway PR: 1248
File: nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java:847-857
Timestamp: 2025-08-28T04:54:20.953Z
Learning: In NullAway's GenericsChecks.java, NewClassTree support for explicit type argument substitution requires more extensive changes beyond just modifying the conditional in compareGenericTypeParameterNullabilityForCall. The maintainers prefer to handle NewClassTree support in a separate follow-up rather than expanding the scope of PRs focused on specific issues like super constructor calls.
Applied to files:
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java
📚 Learning: 2025-10-29T23:56:18.236Z
Learnt from: msridhar
Repo: uber/NullAway PR: 1316
File: jdk-javac-plugin/src/main/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializer.java:261-293
Timestamp: 2025-10-29T23:56:18.236Z
Learning: In NullAway's jdk-javac-plugin NullnessAnnotationSerializer, type variable bounds with annotations (e.g., `T extends Nullable Object`) are checked at their declaration sites by the typeParamHasAnnotation method for both class-level and method-level type parameters. The hasJSpecifyAnnotationDeep method is designed to check type uses (return types, parameters, etc.) and does not need a TYPEVAR case because type variable declaration bounds are already handled separately.
Applied to files:
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java
📚 Learning: 2025-08-14T18:50:06.159Z
Learnt from: msridhar
Repo: uber/NullAway PR: 1245
File: guava-recent-unit-tests/src/test/java/com/uber/nullaway/guava/NullAwayGuavaParametricNullnessTests.java:101-102
Timestamp: 2025-08-14T18:50:06.159Z
Learning: In NullAway JSpecify tests, when JDK version requirements exist due to bytecode annotation reading capabilities, prefer failing tests over skipping them on unsupported versions to ensure CI catches regressions and enforces proper JDK version usage for developers.
Applied to files:
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java
🧬 Code graph analysis (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)
nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java (1)
TypeSubstitutionUtils(23-312)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Build spring-framework with snapshot
- GitHub Check: Build and test on ubuntu-latest
- GitHub Check: Build and test on macos-latest
- GitHub Check: Build caffeine with snapshot
- GitHub Check: Build and test on windows-latest
🔇 Additional comments (1)
nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java (1)
2706-2728: LGTM! Test effectively validates the fix for issue #1354.The test correctly verifies that
@NonNullannotations on type variables in generic return types (likeMaybeNull<@NonNull T>) are properly propagated through method invocation chains. The test structure is clean and follows the existing patterns in the test suite.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #1371 +/- ##
============================================
- Coverage 88.48% 88.47% -0.01%
- Complexity 2614 2616 +2
============================================
Files 98 98
Lines 8751 8766 +15
Branches 1745 1749 +4
============================================
+ Hits 7743 7756 +13
Misses 504 504
- Partials 504 506 +2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
This leads to new errors on Spring, but fixing them causes errors with the current release. So, we'll have to deal with Spring integration test builds failing for a bit. |
#1704) ## Summary #1201 reports that no error is issued when a method's return type carries a nullability annotation on a type variable that is instantiated from the receiver's type argument: ```java @NullMarked class Test { private static class Inner<T extends @nullable Object> { Inner<@nullable T> identity() { return this; } } Inner<Object> mThing = new Inner<Object>(); void foo() { mThing = mThing.identity(); // should warn } } ``` Rather than assume the issue described current behavior, I ran the example verbatim as a test first. On current `master` NullAway **does** report the expected error: ``` warning: [NullAway] incompatible types: Inner<@nullable Object> cannot be converted to Inner<Object> mThing = mThing.identity(); ``` This was fixed by `938a8972` (#1371, "Handle annotations on type variables in return and field types"), which was filed against #1354 and resolved this issue as a side effect. Confirmed by building both sides: the repro reports nothing at `6dd3976f`, the commit immediately preceding it, and is correctly flagged at `938a8972`. That matches the mechanism. #1371 added `restoreExplicitNullabilityAnnotations` to the `MethodInvocationTree` and `MemberSelectTree` branches of `GenericsChecks.getTreeType`. That call has since moved into the `getMethodTypeForInvocation` path but is still what makes this case work: the receiver's type is used to compute the method's type as a member of it via `TypeSubstitutionUtils.memberType`, substituting `T := Object` into the declared return type `Inner<@nullable T>` to yield `Inner<@nullable Object>`, and the explicit annotation is then restored onto the result. The assignment check then sees the mismatch against the declared `Inner<Object>`. So no production change is needed here. While confirming that, though, I found a gap in the test coverage, which is what this PR closes. `nonNullInReturnTypeArg` — the test #1371 added for method return types — asserts only the **negative** direction, that a restored `@NonNull` type argument is *accepted* where a non-null type argument is expected. The error-reporting direction is untested for method returns, although `nonNullInFieldTypeArg` covers it for field reads. That missing direction is exactly what #1201 reports, so it seems worth pinning down. This PR adds an `asNullable()` counterpart to the existing `asNonNull()` and asserts both directions. `MaybeNull<String> m2 = nonNull.asNullable();` is structurally the case from the issue: the receiver substitutes `T := String` into the declared return type `MaybeNull<@nullable T>`, and the assignment is flagged. No production code changes. ## Testing - Extended `nonNullInReturnTypeArg` in `GenericsTests.java` with two positive cases (argument passing and assignment), keeping an unannotated negative case alongside them so the test pins down both directions and doesn't just assert that we over-report. - Negative control on current `master`: guarding out the `restoreExplicitNullabilityAnnotations` call that #1371 added makes both new assertions fail. It also flips the pre-existing negative case `accept(nullable.asNonNull())` into a false positive, since without the restore the receiver's type argument is echoed back in place of the declared annotation. - Confirmed the issue's own repro reports nothing at `6dd3976f` and passes at `938a8972`. - `./gradlew :nullaway:test` — 918 tests, 0 failures. Resolves #1201 ## AI usage disclosure > I used Claude Code for this PR. I asked it to help me find a good next contribution among the open > `jspecify` issues; it ran the repro from #1201 and found the issue had already been fixed on `master`. > When I asked it to check my assumption that the behavior was already well tested, it found that > `nonNullInReturnTypeArg` covers only the negative direction. I decided to close that gap with a test > rather than simply comment on the issue, and directed it to identify the exact commit that fixed the > issue and to demonstrate that the new assertions fail without that fix. It located #1371 via > `git log -S`, installed a JDK 25 so the pre-fix commit would build, and ran the repro at both > `6dd3976f` and `938a8972`; it also guarded out the `restoreExplicitNullabilityAnnotations` call on > current `master` to confirm the new cases fail without it. I have read and understood all the changes > in this PR. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for converting `MaybeNull` values to a nullable generic form. * Nullable and non-null values can now be handled together while preserving type-safety. * **Tests** * Expanded coverage for valid nullable conversions. * Added verification that invalid conversions to non-null generic values are rejected. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Fixes #1354
If a method return type or a field type has nullability annotations on field types, those annotations need to be restored when getting the type of a corresponding method invocation or field read.
Summary by CodeRabbit
Bug Fixes
Tests
✏️ Tip: You can customize this high-level summary in your review settings.