Skip to content

JSpecify: Apply annotations on type variables to lambdas in more cases - #1428

Merged
msridhar merged 7 commits into
masterfrom
lambda-poly-expression
Jan 7, 2026
Merged

msridhar merged 7 commits into
masterfrom
lambda-poly-expression

Conversation

@msridhar

@msridhar msridhar commented Jan 6, 2026 •

Copy link
Copy Markdown
Collaborator

Consider this example:

import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
import java.util.function.Function;
@NullMarked
class Test {
  static class Foo<T> {
    T doSomething(Function<@Nullable T, T> f) {
      return f.apply(null);
    }
  }
  void test(Foo<String> foo) {
    String s =
        foo.doSomething(
            t -> {
              return "length: " + t.length();
            });
  }
}

NullAway should produce an error at t.length() since t may be null. Before this PR, NullAway would not give an error, since for a Foo<String> foo, it treated the type of the formal parameter as Function<String, String>, without considering the @Nullable annotation in Function<@Nullable T, T>. This PR closes that gap, both for passing lambdas as parameters and for assigning them to fields.

Summary by CodeRabbit

  • Improvements
    • Enhanced nullability analysis for lambda expressions in generic type contexts.
    • Improved detection of null-dereference issues when lambdas use generic type variables.
    • Better nullability tracking for lambdas assigned to fields or used as method arguments and return values.

✏️ Tip: You can customize this high-level summary in your review settings.

@codecov

codecov Bot commented Jan 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.44%. Comparing base (cdb7675) to head (cd9a4e3).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 83.33% 1 Missing and 3 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1428      +/-   ##
============================================
- Coverage     88.45%   88.44%   -0.02%     
- Complexity     2664     2672       +8     
============================================
  Files            97       97              
  Lines          8830     8852      +22     
  Branches       1767     1772       +5     
============================================
+ Hits           7811     7829      +18     
- Misses          506      507       +1     
- Partials        513      516       +3     

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

@msridhar
msridhar marked this pull request as ready for review January 7, 2026 00:01
@msridhar msridhar changed the title Apply annotations on type variables to lambdas in more cases JSpecify: Apply annotations on type variables to lambdas in more cases Jan 7, 2026
@coderabbitai

coderabbitai Bot commented Jan 7, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

This PR enhances NullAway's lambda nullability inference in generic contexts by introducing caching of lambda target types and standardizing assignment-target checks. The main changes include adding inferredLambdaTypes caching to store and retrieve previously inferred lambda types, introducing helper methods (isAssignmentToLocalVariable, isAssignmentToField, isAssignmentToKind) to unify assignment-target detection, and adding maybeStoreLambdaTypeFromTarget to cache lambda types with restored nullability annotations. The getTreeType method is enhanced to consult cached lambda types for LambdaExpressionTree nodes. A new test class GenericLambdaTests is added with three tests verifying correct nullability propagation for lambdas using annotated type variables in generic contexts.

Possibly related PRs

  • PR #1348: Directly modifies GenericsChecks.java to detect, store, and consult inferred lambda target and parameter types for generic/lambda nullability inference
  • PR #1375: Modifies GenericsChecks to improve nullability and type inference for lambdas in generic contexts through lambda type handling
  • PR #1337: Modifies GenericsChecks.java to enhance lambda-type inference with constraint generation from lambda return expressions for generic-method inference

Suggested reviewers

  • yuxincs
  • lazaroclapp

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Apply annotations on type variables to lambdas in more cases' directly and clearly summarizes the main change: extending NullAway to properly handle type variable annotations in lambda inference.
✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fb90c3 and b6cb584.

📒 Files selected for processing (2)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java
🧰 Additional context used
🧠 Learnings (5)
📓 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.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.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.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java
📚 Learning: 2025-12-31T23:59:13.310Z
Learnt from: msridhar
Repo: uber/NullAway PR: 1421
File: nullaway/src/main/java/com/uber/nullaway/NullAway.java:339-340
Timestamp: 2025-12-31T23:59:13.310Z
Learning: In Error Prone's ASTHelpers class, the getSymbol(MethodInvocationTree) overload is guaranteed to return a non-null Symbol.MethodSymbol. This differs from other overloads of getSymbol() that may return null. Therefore, no null check is required after calling ASTHelpers.getSymbol() with a MethodInvocationTree parameter.

Applied to files:

  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.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/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java
🔇 Additional comments (6)
nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java (1)

1-106: LGTM! Comprehensive test coverage for lambda nullability with generic type variables.

The test class thoroughly covers the three key scenarios from the PR objectives:

  1. Lambdas passed as method arguments (lines 11-38)
  2. Lambdas assigned to fields or local variables (lines 40-73)
  3. Lambdas returned from methods (lines 75-99)

Each test correctly verifies that nullability annotations on type variables (e.g., @Nullable T) propagate to lambda parameters, ensuring that dereferences are properly flagged.

nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (5)

422-431: LGTM! Correct lambda type retrieval with caching.

The implementation properly consults the inferredLambdaTypes cache for lambda expressions, falls back to ASTHelpers.getType when not cached, and correctly handles raw types by returning null (consistent with the existing pattern in this method).


599-603: LGTM! Selective lambda type caching for field assignments.

The condition correctly identifies field assignments (excluding local variables) and caches the lambda's target type. This compensates for javac dropping nullability annotations on type variables in lambda target types for field assignments, as documented in maybeStoreLambdaTypeFromTarget.


618-636: LGTM! Well-factored helper methods for assignment-target detection.

The refactoring introduces a clean, reusable pattern for checking assignment targets. The isAssignmentToKind method properly handles both VariableTree and AssignmentTree cases, includes appropriate null-safety checks, and uses clear exception handling for unexpected tree types.


1319-1320: LGTM! Lambda type caching for method argument context.

The code correctly stores the lambda's target type when it's passed as a method argument, using the formal parameter type as the target. This complements the field assignment caching and ensures lambda parameter types reflect the annotated type variables from the method signature.


2063-2080: LGTM! Well-implemented lambda type restoration and caching.

The method is clearly documented and correctly implements the core fix:

  1. Guards against raw types and duplicate caching
  2. Retrieves the lambda's tree type
  3. Restores explicit nullability annotations from the target type using TypeSubstitutionUtils.restoreExplicitNullabilityAnnotations
  4. Caches the restored type for later use

This addresses the issue where javac drops nullability annotations on type variables in lambda target types, ensuring that subsequent checks (e.g., in lambda bodies) have access to the correctly annotated functional interface type.


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 requested a review from yuxincs January 7, 2026 00:07
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