Skip to content

Use ground target types when handling lambdas and method refs passed to generic methods#1575

Merged
msridhar merged 8 commits into
masterfrom
issue-1522
May 25, 2026
Merged

Use ground target types when handling lambdas and method refs passed to generic methods#1575
msridhar merged 8 commits into
masterfrom
issue-1522

Conversation

@msridhar
Copy link
Copy Markdown
Collaborator

@msridhar msridhar commented May 13, 2026

Fixes #1522

When handling lambdas and method references passed to a generic method, if the generic method's formal parameter type is a class type with wildcards at the top level, we need to compute the ground target type for checking. In the ground target type, wildcards are replaced with their lower bound if explicit, and otherwise replaced with their upper bound.

So, for the test from #1522:

@NullMarked
class Test {
  static class Foo<T> {
    public final <V> Foo<V> mapNotNull(Function<? super T, ? extends @Nullable V> mapper) {
      throw new RuntimeException();
    }
  }
  static <T> Foo<T> after(Foo<Optional<T>> foo) {
    return foo.mapNotNull(x -> x.orElse(null));
  }
}

We have a lambda passed to mapNotNull, whose parameter type is Function<? super T, ? extends @Nullable V>. The ground target type for this parameter is Function<T, @Nullable V>, which should be used to infer types at the call site and check the lambda. In this case, inference succeeds, and the return of x.orElse(null) from the lambda is fine since the return type is @Nullable V.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved generic nullability inference for lambda expressions and method references by correctly grounding wildcard and parameterized types before applying nullability constraints.
    • Enhanced handling of complex nested wildcard type parameters in generic inference scenarios.
  • Tests

    • Expanded test coverage for wildcard nullness behavior across lambdas, method references, and nested-wildcard type parameter scenarios.

Review Change Stack

@codecov
Copy link
Copy Markdown

codecov Bot commented May 13, 2026

Codecov Report

❌ Patch coverage is 91.66667% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.20%. Comparing base (c315bd5) to head (38a6a9e).

Files with missing lines Patch % Lines
...java/com/uber/nullaway/generics/GenericsUtils.java 87.50% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1575      +/-   ##
============================================
- Coverage     88.30%   88.20%   -0.11%     
- Complexity     2926     2934       +8     
============================================
  Files           104      104              
  Lines          9776     9807      +31     
  Branches       1967     1974       +7     
============================================
+ Hits           8633     8650      +17     
- Misses          543      557      +14     
  Partials        600      600              

☔ View full report in Codecov by Sentry.
📢 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.

Copy link
Copy Markdown
Collaborator

@lazaroclapp lazaroclapp left a comment

Choose a reason for hiding this comment

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

Some questions just out of curiosity, but LGTM!

}
static void testNestedWildcard() {
invokeNested(box -> {
// BUG: Diagnostic contains: dereferenced expression box.get() is @Nullable
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.

What does the true negative case look like here? Changing Function<Box<? super String>, R> mapper with Function<Box<? extends String>, R> mapper?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, that's correct. I've enhanced the test to show this.

* rules for functional interface target types in JLS <a
* href="https://docs.oracle.com/javase/specs/jls/se21/html/jls-9.html#jls-9.9">9.9</a>.
*/
private static Type groundTypeArgument(Type typeArgument, VisitorState state) {
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 works the same regardless of whether we are looking at the types used for the arguments of the function vs the return argument of the function? This looks correct to me from 9.9, but feels a bit counter-intuitive...

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, that's correct. It was counterintuitive to me too. It's basically strictly on the bounds of the wildcard type, independently of where it is used.

@msridhar msridhar enabled auto-merge (squash) May 25, 2026 18:04
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 25, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: dd21ba8f-873d-4202-8a28-c2913aecfa24

📥 Commits

Reviewing files that changed from the base of the PR and between c315bd5 and 38a6a9e.

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

Walkthrough

This PR implements target-type grounding for wildcard generics in NullAway's poly-expression (lambda and method-reference) nullability inference. A new groundTargetType utility in GenericsUtils replaces immediate wildcard type arguments with their bounds. The maybeStorePolyExpressionTypeFromTarget method is refactored to accept VisitorState and ground the target before restoring explicit nullability. Call sites throughout generic method inference and call-site checking apply grounding before storing inferred or explicit nullability for lambda and method-reference arguments. Four new tests replace a previously ignored test, validating nullness diagnostics for generic inference with null-returning expressions and nested wildcard preservation.

Possibly related PRs

  • uber/NullAway#1553: Updates compareGenericTypeParameterNullabilityForCall to store method-reference poly expression types via maybeStorePolyExpressionTypeFromTarget, directly aligned with this PR's poly-expression caching in the same pipeline.
  • uber/NullAway#1438: Changes GenericsChecks handling of method-reference generic nullability inference by extending inference to process method references instead of skipping them.
  • uber/NullAway#1256: Instance-based GenericsChecks refactor that makes call sites use VisitorState directly, providing the foundation for this PR's state-aware maybeStorePolyExpressionTypeFromTarget.

Suggested labels

jspecify

Suggested reviewers

  • lazaroclapp
  • yuxincs
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: using ground target types for lambdas and method references in generic methods.
Linked Issues check ✅ Passed The PR implementation matches the objective from #1522: it fixes lambda/method reference handling for generic parameters with wildcards by introducing ground target types.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing issue #1522: implementing wildcard grounding in GenericsChecks, adding groundTargetType utility in GenericsUtils, and adding comprehensive test coverage.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 issue-1522

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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 and usage tips.

@msridhar msridhar merged commit 9e7cfb2 into master May 25, 2026
11 of 22 checks passed
@msridhar msridhar deleted the issue-1522 branch May 25, 2026 18:18
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.

Lambda argument to Flux#mapNotNull with null return value flagged as invalid

2 participants