Skip to content

Correctly get parameter types for a lambda whose type was inferred - #1348

Merged
msridhar merged 22 commits into
masterfrom
map-lambda-bug
Dec 31, 2025
Merged

msridhar merged 22 commits into
masterfrom
map-lambda-bug

Conversation

@msridhar

@msridhar msridhar commented Nov 23, 2025 •

Copy link
Copy Markdown
Collaborator

Previously we would just use the type from javac, which wouldn't properly account for cases where we had inferred the type of the lambda since it was passed to a generic method.

Also, store the proper inferred types for lambdas in the inferredLambdaTypes, with inferred nullability applied to the type of the lambda at the call site. This was exposed in #1416, and addressing that initial issue alone led again to the issue addressed here with getting the wrong parameter types for lambdas.

Perform related refactorings to consolidate and move type-substitution-related code to TypeSubstitutionUtils. (Sorry for the size of this PR.)

Fixes #1416

Summary by CodeRabbit

  • New Features

    • Improved lambda-parameter type inference for generic method calls, applying inferred nullability at call sites while preserving explicit annotations and propagating nullability through method argument and return types for more accurate types.
  • Tests

    • Added tests covering inferred-lambda-parameter, wildcard/array, raw-type-lambda and related inference cases.
    • Several test methods were duplicated in this update and should be de-duplicated.

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

@codecov

codecov Bot commented Nov 23, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.18072% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.33%. Comparing base (8dd292f) to head (86973df).
⚠️ Report is 20 commits behind head on master.

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 91.17% 0 Missing and 3 partials ⚠️
.../uber/nullaway/generics/TypeSubstitutionUtils.java 97.95% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1348      +/-   ##
============================================
- Coverage     88.36%   88.33%   -0.03%     
- Complexity     2659     2672      +13     
============================================
  Files            98       98              
  Lines          8835     8884      +49     
  Branches       1767     1778      +11     
============================================
+ Hits           7807     7848      +41     
- Misses          508      514       +6     
- Partials        520      522       +2     

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

@coderabbitai

coderabbitai Bot commented Nov 23, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@msridhar has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 18 minutes and 33 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c83f289 and 86973df.

📒 Files selected for processing (1)
  • nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java

Walkthrough

Adds handling for inferred lambda parameter types to GenericsChecks via a new private helper and consults it from getTreeType for IdentifierTree nodes. Replaces the removed getTypeWithInferredNullability usage with TypeSubstitutionUtils.updateTypeWithInferredNullability / updateMethodTypeWithInferredNullability when applying inferred nullability to method types, return types, and lambda argument types during generic-method inference. Updates runInferenceForCall and substituteTypeArgsInGenericMethodType to store and use these updated types. Adds an import for com.sun.tools.javac.code.Types and several new unit tests (some duplicated).

Possibly related PRs

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 40.91% 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
Title check ✅ Passed The title directly and specifically describes the main change: fixing how parameter types are obtained for lambdas with inferred types in generic method contexts.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 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 001713b and 111de8c.

📒 Files selected for processing (3)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java
🧰 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.
📚 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/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.java
  • 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/GenericMethodTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.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/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.java
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
⏰ 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 caffeine with snapshot
  • GitHub Check: Build and test on ubuntu-latest
  • GitHub Check: Build and test on macos-latest
  • GitHub Check: Build spring-framework with snapshot
  • GitHub Check: Build and test on windows-latest
🔇 Additional comments (4)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (2)

458-465: LGTM! Clean handling of lambda parameter type inference.

The logic correctly identifies lambda parameters and retrieves their inferred types when available, falling through to the existing logic otherwise.


517-559: The implementation is correct. Both getNullabilityUtil.getFunctionalInterfaceMethod() and TypeSubstitutionUtils.memberType() return non-nullable types with no @Nullable annotations, as confirmed by their signatures and widespread usage throughout the codebase without defensive null checks. The code already guards against uninitialized lambda types at line 534, which is the appropriate control flow check. No additional null-safety handling is required.

nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.java (1)

242-263: No duplication found. The search confirms only a single definition of lambdaWithRawType() exists at line 243. The AI-generated summary was incorrect.

nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java (1)

1322-1363: No duplication issue exists. Both typeOfParameterWithInferredLambda and wildcardAndArrayTypes appear exactly once in the file. The AI-generated summary's claim about duplication was incorrect.

Likely an incorrect or invalid review comment.

Comment on lines 746 to 752
if (argument instanceof LambdaExpressionTree lambdaExpressionTree) {
Type inferredType =
getTypeWithInferredNullability(state, formalParamType, typeVarNullability);
inferredLambdaTypes.put(lambdaExpressionTree, inferredType);
Type lambdaTreeType = castToNonNull(ASTHelpers.getType(lambdaExpressionTree));
Type restored =
updateWithInferredNullability(
lambdaTreeType, formalParamType, typeVarNullability, state);
inferredLambdaTypes.put(lambdaExpressionTree, restored);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Verify null-safety of ASTHelpers.getType for lambda expressions.

Line 747 uses castToNonNull(ASTHelpers.getType(lambdaExpressionTree)), which assumes getType never returns null for lambda expressions. While this is likely true in practice, it's worth verifying this assumption holds for all cases, including error scenarios or incomplete code.

Consider adding a null check and skipping storage if the type is unavailable:

🔎 Suggested defensive coding
                 if (argument instanceof LambdaExpressionTree lambdaExpressionTree) {
-                  Type lambdaTreeType = castToNonNull(ASTHelpers.getType(lambdaExpressionTree));
-                  Type restored =
-                      updateWithInferredNullability(
-                          lambdaTreeType, formalParamType, typeVarNullability, state);
-                  inferredLambdaTypes.put(lambdaExpressionTree, restored);
+                  Type lambdaTreeType = ASTHelpers.getType(lambdaExpressionTree);
+                  if (lambdaTreeType != null) {
+                    Type restored =
+                        updateWithInferredNullability(
+                            lambdaTreeType, formalParamType, typeVarNullability, state);
+                    inferredLambdaTypes.put(lambdaExpressionTree, restored);
+                  }
                 }
🤖 Prompt for AI Agents
In nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java around
lines 746 to 752, the code assumes ASTHelpers.getType(lambdaExpressionTree) is
non-null by calling castToNonNull directly; add a defensive null check: call
ASTHelpers.getType(lambdaExpressionTree) into a local variable, if it is null
skip the update/storage (or continue) to avoid NPEs in error/incomplete-code
cases, otherwise proceed to cast/updateWithInferredNullability and put the
restored type into inferredLambdaTypes; optionally log or comment that missing
types are intentionally skipped.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)

715-721: Consider defensive null check for ASTHelpers.getType.

The castToNonNull at line 716 assumes ASTHelpers.getType(lambdaExpressionTree) never returns null for lambda expressions. While this is likely true in practice, a defensive check could improve robustness for edge cases like incomplete code during IDE analysis.

The logic change itself is correct - using updateTypeWithInferredNullability ensures lambda types properly incorporate inferred nullability from the generic method call context.

📜 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 6a2e741 and 28a6d68.

📒 Files selected for processing (2)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.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.
📚 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/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.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/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.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.java
  • nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
📚 Learning: 2025-08-29T18:41:43.584Z
Learnt from: msridhar
Repo: uber/NullAway PR: 1259
File: jdk-recent-unit-tests/src/test/java/com/uber/nullaway/jdk17/SwitchTests.java:318-321
Timestamp: 2025-08-29T18:41:43.584Z
Learning: Classes annotated with NullMarked are analyzed by NullAway even if they are not in packages specified by the AnnotatedPackages configuration. The NullMarked annotation guarantees NullAway analysis.

Applied to files:

  • nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
🪛 GitHub Actions: Continuous integration
nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java

[error] 160-160: Gradle build failed: compilation failed due to -Werror. 'TypeSubstitutionUtils.java:160' contains a documented issue: [EmptyBlockTag] A block tag (@PARAM, @return, @throws, @deprecated) has an empty description. (See log for details.)

🔇 Additional comments (8)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (5)

36-36: LGTM!

Import added for com.sun.tools.javac.code.Types to support the new getInferredLambdaParameterType helper method.


456-463: LGTM!

Good addition to handle lambda parameters with inferred types. The early return when an inferred type is found ensures the correct nullability annotations are propagated for lambda parameters passed to generic methods.


515-557: LGTM with minor note.

The implementation correctly resolves lambda parameter types by:

  1. Identifying lambda parameters (not in the containing method's formal parameters)
  2. Finding the enclosing lambda and its inferred type
  3. Computing the functional interface method type as a member of the inferred type
  4. Returning the parameter type at the matching index

The logic is sound and integrates well with the existing inference framework.


663-666: LGTM!

Good refactoring to use updateTypeWithInferredNullability which properly handles the three-step process: substitute inferred nullability, restore explicit annotations, and apply to the call site type. This correctly addresses the issue with inferred lambda types.


1567-1575: LGTM!

Good handling of both inference success and failure cases:

  • On success: updateMethodTypeWithInferredNullability applies the inferred type variable nullability
  • On failure: returns the method type at call site without substitutions, avoiding potential errors from incomplete inference

This ensures robust behavior regardless of inference outcome.

nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java (3)

4-4: LGTM!

Necessary imports added for the new functionality:

  • Static import of NULLABLE for comparison in substituteInferredNullabilityForTypeVariables
  • VisitorState for accessing javac types and synthetic annotation types
  • Element for the type variable nullability map keys

Also applies to: 8-8, 21-21


101-146: LGTM!

Well-documented implementation of the three-step nullability update process. The Javadoc clearly explains each step with examples:

  1. Substitute inferred nullability for type variables
  2. Restore explicit annotations from the original type (taking precedence over inference)
  3. Apply to the target type at the use site

The early return for null typeVarNullability is a good defensive check.


209-247: LGTM!

Well-implemented helper that:

  1. Only processes NULLABLE inferred types (non-null is the default, requiring no annotation)
  2. Uses TypeVarWithSymbolCollector to find all occurrences of each type variable (handling cases where the same type variable appears multiple times)
  3. Performs a batch substitution for efficiency

The approach correctly handles edge cases like type variables with modified bounds from previous substitutions.

Comment on lines +187 to +207
@SuppressWarnings("ReferenceEquality")
private static List<Type> updateTypeListNullability(
List<Type> typesToUpdate,
List<Type> origTypes,
@Nullable Map<Element, ConstraintSolver.InferredNullability> typeVarNullability,
VisitorState state,
Config config) {
ListBuffer<Type> buf = new ListBuffer<>();
boolean changed = false;
for (List<Type> l = typesToUpdate, l1 = origTypes; l.nonEmpty(); l = l.tail, l1 = l1.tail) {
Type toUpdate = l.head;
Type orig = l1.head;
Type t2 =
updateTypeWithInferredNullability(toUpdate, orig, typeVarNullability, state, config);
buf.append(t2);
if (t2 != toUpdate) {
changed = true;
}
}
return changed ? buf.toList() : typesToUpdate;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Verify list length invariant.

The parallel iteration at line 196 assumes typesToUpdate and origTypes have the same length. If they differ, this could cause issues when one list is exhausted before the other.

This should be safe given the current callers (same method type's argtypes/thrown), but consider adding a precondition check for defensive coding.

🔎 Optional defensive check
  private static List<Type> updateTypeListNullability(
      List<Type> typesToUpdate,
      List<Type> origTypes,
      @Nullable Map<Element, ConstraintSolver.InferredNullability> typeVarNullability,
      VisitorState state,
      Config config) {
+   Verify.verify(
+       typesToUpdate.size() == origTypes.size(),
+       "type lists must have same length");
    ListBuffer<Type> buf = new ListBuffer<>();
🤖 Prompt for AI Agents
In nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
around lines 187 to 207, the loop assumes typesToUpdate and origTypes have
identical lengths; add a defensive precondition that verifies their lengths
match before iterating (e.g., check list sizes or walk both lists to confirm
same length and throw an IllegalArgumentException or use
Preconditions.checkArgument/assert with a clear message if they differ), then
proceed with the existing parallel iteration unchanged.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java (1)

187-207: Consider adding defensive precondition check for list length invariant.

The parallel iteration assumes typesToUpdate and origTypes have the same length. If origTypes is shorter, accessing l1.head after l1 becomes empty would return null, potentially causing issues downstream in updateTypeWithInferredNullability.

While this should be safe given current callers (method type's argtypes/thrown always have matching lengths), a defensive check would make this more robust.

🔎 Optional defensive check
  private static List<Type> updateTypeListNullability(
      List<Type> typesToUpdate,
      List<Type> origTypes,
      @Nullable Map<Element, ConstraintSolver.InferredNullability> typeVarNullability,
      VisitorState state,
      Config config) {
+   Verify.verify(
+       typesToUpdate.size() == origTypes.size(),
+       "type lists must have same length");
    ListBuffer<Type> buf = new ListBuffer<>();
📜 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 28a6d68 and c83f289.

📒 Files selected for processing (1)
  • nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.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.
📚 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/TypeSubstitutionUtils.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/TypeSubstitutionUtils.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/TypeSubstitutionUtils.java
📚 Learning: 2025-08-29T18:41:43.584Z
Learnt from: msridhar
Repo: uber/NullAway PR: 1259
File: jdk-recent-unit-tests/src/test/java/com/uber/nullaway/jdk17/SwitchTests.java:318-321
Timestamp: 2025-08-29T18:41:43.584Z
Learning: Classes annotated with NullMarked are analyzed by NullAway even if they are not in packages specified by the AnnotatedPackages configuration. The NullMarked annotation guarantees NullAway analysis.

Applied to files:

  • nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
🧬 Code graph analysis (1)
nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)
  • GenericsChecks (72-2096)
⏰ 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 and test on windows-latest
  • GitHub Check: Build and test on ubuntu-latest
  • GitHub Check: Build spring-framework with snapshot
  • GitHub Check: Build and test on macos-latest
  • GitHub Check: Build caffeine with snapshot
🔇 Additional comments (3)
nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java (3)

4-4: LGTM!

The new imports are correctly added and all are used by the new methods introduced in this file.

Also applies to: 8-8, 21-21


148-185: LGTM!

The method correctly applies inferred nullability to all components of the method type (arguments, return type, thrown types). The reference equality optimization to avoid creating new objects when nothing changed is appropriate, and the @SuppressWarnings("ReferenceEquality") annotation is correctly applied.


209-247: LGTM!

The method correctly handles the complexity of finding all TypeVar instances with matching symbols (which may differ due to prior substitutions) and substitutes inferred nullability appropriately. The early return when no substitutions are needed is a good optimization, and the comment at lines 228-230 helpfully explains why multiple TypeVar matches may occur.

@msridhar
msridhar requested a review from yuxincs December 31, 2025 00:34
@msridhar
msridhar merged commit 8d65bf5 into master Dec 31, 2025
7 checks passed
@msridhar
msridhar deleted the map-lambda-bug branch December 31, 2025 01:59
@msridhar msridhar added the jspecify Related to support for jspecify standard (see jspecify.dev) label Jan 21, 2026
msridhar added a commit that referenced this pull request Mar 25, 2026
Fixes #1455 

For reference here is the test case:
```java
@NullMarked
class Foo<OuterT> {

  interface Supplier<T extends @nullable Object> {
    T get();
  }

  Supplier<@nullable OuterT> sup;

  <T extends Supplier<?>> T acceptSup(T supplier) {
    return supplier;
  }

  void test() {
    acceptSup(sup);
  }
}
```
What goes wrong here is at the call `acceptSup(sup)`, `javac` infers the
type argument to be `Supplier<OuterT>`, dropping the `@Nullable`
annotation on `OuterT` seen in the declaration of `sup`. I cannot figure
out exactly when annotations get dropped; e.g., it does not seem to
happen if `sup` is a formal parameter rather than a field. For the case
above, our inference correctly infers that `T` itself should be
`@NonNull`, but then we still report an error since `Supplier<@nullable
OuterT>` (the type of `sup`) is incompatible with `Supplier<OuterT>`
(what we think is the formal parameter type).

This started happening in 0.13.0 due to
#1348, because we started computing
the proper method types at call sites to report better error messages.
Unfortunately, this is leading to unforeseen interactions with `javac`'s
type inference like the issue above; but I'd like to see if we can work
around the corner cases since it's important to have good error
messages.

For this case, we add a method
`restoreMissingNullabilityFromSingleTopLevelTypeVarArguments` that
repairs the method type by re-introducing explicit nullability
annotations nested in actual parameter types onto the formal parameter
types. We try to tailor the fix narrowly for this case and to not
introduce unsoundness by re-introducing annotations across parameter
positions inconsistently.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Improved null-safety for generic method calls by restoring nested
nullability on inferred type arguments, ensuring consistent
substitutions and safely falling back when restoration isn’t possible.

* **Tests**
* Added a unit test covering generic method type inference and warning
behavior for JSPECIFY-style nullability scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jspecify Related to support for jspecify standard (see jspecify.dev)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ClassCastException in JSpecify mode when generics and arrays are involved

2 participants