Skip to content

Add positive test cases for annotations on generic method return types - #1704

Merged
msridhar merged 2 commits into
uber:masterfrom
dbwiddis:jspecify-return-type-arg-positive-test
Aug 14, 2026
Merged

msridhar merged 2 commits into
uber:masterfrom
dbwiddis:jspecify-return-type-arg-positive-test

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

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:

@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
    Handle annotations on type variables in return and field types #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.

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.

nonNullInReturnTypeArg asserted only the negative direction: that a
@nonnull type argument restored onto a method's return type is accepted
where a non-null type argument is expected. The error-reporting direction
was untested for method returns, although nonNullInFieldTypeArg covers it
for field reads.

Adds an asNullable() counterpart and asserts that passing or assigning its
result where a non-null type argument is expected is reported. This is the
case reported in uber#1201, which was already fixed by uber#1371: the repro from
the issue reports no error at 6dd3976 and is correctly flagged at
938a897, and guarding out the restoreExplicitNullabilityAnnotations call
that uber#1371 added makes both new assertions fail on current master.

Resolves uber#1201
@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 702c3faf-d2eb-4155-8334-111d8415207e

📥 Commits

Reviewing files that changed from the base of the PR and between 89359bd and fdfa4ac.

📒 Files selected for processing (1)
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java

Walkthrough

Added MaybeNull.asNullable() to convert MaybeNull<T> to MaybeNull<@nullable T>. Expanded GenericsTests.java to test nullable and non-null MaybeNull inputs. The tests verify valid nullable assignments and reject conversions to MaybeNull<String>.

Possibly related PRs

  • uber/NullAway#1266: Covers related generic type-annotation and as-supertype handling.
  • uber/NullAway#1371: Introduces the related MaybeNull generic-return test extended by this change.

Suggested labels: jspecify

Suggested reviewers: msridhar, yuxincs

Merge Risk: ⚪ Minimal · up to fdfa4

This change only expands test coverage for existing annotation behavior and does not alter production code; no actionable merge-blocking risk remains after normal checks and review.

🚥 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 clearly describes the added positive test coverage for annotations on generic method return types.
Linked Issues check ✅ Passed The tests cover nullable generic return types and verify errors when assigned or passed as non-null generic types, addressing issue #1201.
Out of Scope Changes check ✅ Passed The changes are limited to relevant test coverage and contain no unrelated production or scope-expanding changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks!

@msridhar
msridhar enabled auto-merge (squash) August 14, 2026 20:45
@codecov

codecov Bot commented Aug 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 87.83%. Comparing base (811383b) to head (b856023).

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #1704   +/-   ##
=========================================
  Coverage     87.83%   87.83%           
  Complexity     3184     3184           
=========================================
  Files           109      109           
  Lines         10815    10815           
  Branches       2186     2186           
=========================================
  Hits           9499     9499           
  Misses          622      622           
  Partials        694      694           

☔ 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 merged commit daa5828 into uber:master Aug 14, 2026
14 checks passed
@dbwiddis
dbwiddis deleted the jspecify-return-type-arg-positive-test branch August 14, 2026 21:15
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.

No error reported if receiver type argument is NonNull while method return type parameter is Nullable

2 participants