Skip to content

Honor @Contract when a @Nullable method is used as a method reference - #1679

Merged
msridhar merged 2 commits into
uber:masterfrom
Eljees:fix/1502-contract-method-reference
Aug 7, 2026
Merged

msridhar merged 2 commits into
uber:masterfrom
Eljees:fix/1502-contract-method-reference

Conversation

@Eljees

@Eljees Eljees commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1502.

The problem

A method annotated @Contract("null -> null; !null -> !null") returns non-null whenever it is given a non-null argument. When such a method is passed as a method reference to a functional interface whose parameter is @NonNull, the reference is a valid implementation of that interface — but NullAway reports:

referenced method returns @Nullable, but functional interface method
java.util.function.Function.apply(T) returns @NonNull

The @Contract handler is not consulted on this path at all: NullAway#checkOverriding only asks for the declared return nullness of the referenced method.

The fix

NullAway#matchMemberReference already calls handler.onMatchMethodReference(...) immediately before checkOverriding, and checkOverriding skips the error when the member reference has been given a computed nullness of NONNULL:

&& (memberReferenceTree == null
    || getComputedNullness(memberReferenceTree).equals(Nullness.NULLABLE))

StreamNullabilityPropagator#onMatchMethodReference already uses exactly this mechanism to mark a reference non-null. This PR implements onMatchMethodReference in ContractHandler the same way: if some contract clause has the consequent !null and every antecedent is either _ or !null at a position where the functional interface method is guaranteed to pass a non-null value, the reference is marked NONNULL.

The per-parameter nullness of the functional interface method is computed the same way NullAway#checkParamOverriding computes it: Nullness.paramHasNullableAnnotation, plus GenericsChecks#getGenericMethodParameterNullness against the inferred functional interface type in JSpecify mode, so that a @Nullable type argument is respected.

Conservative by construction:

  • only clauses whose antecedent count matches the referenced method's parameter count are used;
  • varargs on either side, and references whose parameter count differs from the interface's (i.e. unbound references, where the first interface parameter becomes the receiver), are skipped;
  • any antecedent that is not _ or !null (e.g. null, true, false) disqualifies the clause.

Tests

ContractsTests#contractImpliesNonNullForMethodReference and its JSpecify counterpart. Both fail on master and pass with the fix. Between them they cover five newly-accepted cases and five that must keep reporting:

case before after
@Contract("null -> null; !null -> !null") → String apply(String) error accepted
@Contract("_ -> !null") error accepted
@Contract("!null, _ -> !null") → two-parameter interface error accepted
JSpecify: Function<String, String> (the reported case) error accepted
JSpecify: own Fn<P extends @Nullable Object, ...> with Fn<String, String> error accepted
@Contract("null -> null") only error error
no @Contract at all error error
interface parameter declared @Nullable error error
JSpecify: Function<@Nullable String, String> error error
JSpecify: own Fn<@Nullable String, String> error error

The full :nullaway:test suite passes, and Google Java Format leaves the change unmodified.


Before pressing the "Create Pull Request" button, please provide the following:

  • A description about what and why you are contributing, even if it's trivial.

  • The issue number(s) or PR number(s) in the description if you are contributing in response to those.

  • If applicable, unit tests.

Note on AI usage

I am a first-time contributor here, so per CONTRIBUTING.md: I used Claude to help explore the checkOverriding / onMatchMethodReference code path and to draft the handler implementation and the tests. I reviewed every line of the change myself, ran the two new tests against unpatched master first to confirm they fail without the fix, then ran them and the full :nullaway:test suite with the fix applied. I have read and understood all of the changes in this PR.

A method annotated @contract("null -> null; !null -> !null") returns
non-null for a non-null argument, but NullAway rejected passing such a
method as a method reference to a functional interface with a @nonnull
parameter: checkOverriding only consulted the declared return nullness,
and the contract handler was never asked on that path.

Implement onMatchMethodReference in ContractHandler. When a contract
clause has the consequent !null and every antecedent is _ or !null at a
position where the functional interface method is guaranteed to pass a
non-null value, mark the reference NONNULL via setComputedNullness - the
same mechanism StreamNullabilityPropagator already uses.

Fixes uber#1502
@CLAassistant

CLAassistant commented Aug 6, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

ContractHandler now analyzes Java method references that target methods with @Contract annotations. It infers a non-null result when the contract and functional-interface parameter nullness are compatible. The analysis excludes varargs, mismatched arity, unsupported clauses, nullable parameters, and nullable JSpecify generic instantiations. ContractsTests adds standard-mode and JSpecify-mode coverage.

Possibly related PRs

  • uber/NullAway#1295: Related through ContractHandler and ContractsTests, with focus on contract validation.
  • uber/NullAway#1438: Related through method-reference nullness handling and JSpecify generic inference.
  • uber/NullAway#1597: Extends ContractHandler analysis for another contract-based stream behavior.

Suggested reviewers: msridhar, yuxincs, lazaroclapp

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation and tests address issue #1502 by recognizing non-null results from contracted method references with non-null inputs.
Out of Scope Changes check ✅ Passed The changes are limited to ContractHandler logic and related tests for method-reference nullness handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: honoring @Contract annotations for nullable methods used as method references.
✨ 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.

This is a beautiful fix and a great explanation. Thank you!!

@msridhar
msridhar enabled auto-merge (squash) August 7, 2026 22:54
@msridhar
msridhar disabled auto-merge August 7, 2026 22:54
@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.77%. Comparing base (2092eb0) to head (ca47007).

Files with missing lines Patch % Lines
...er/nullaway/handlers/contract/ContractHandler.java 75.00% 3 Missing and 8 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1679      +/-   ##
============================================
- Coverage     87.82%   87.77%   -0.06%     
- Complexity     3131     3142      +11     
============================================
  Files           109      109              
  Lines         10562    10606      +44     
  Branches       2135     2150      +15     
============================================
+ Hits           9276     9309      +33     
- Misses          608      611       +3     
- Partials        678      686       +8     

☔ 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 enabled auto-merge (squash) August 7, 2026 23:07
@msridhar
msridhar merged commit 9904903 into uber:master Aug 7, 2026
12 of 14 checks passed
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.

False positive for using nullable method with strict Contract("null -> null; !null -> !null") as a function !null -> !null

3 participants