Repository navigation
Correctly get parameter types for a lambda whose type was inferred - #1348
Conversation
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
|
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 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. 📒 Files selected for processing (1)
WalkthroughAdds 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
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (3)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.javanullaway/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.javanullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.javanullaway/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.javanullaway/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.javanullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaArgTests.javanullaway/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. BothgetNullabilityUtil.getFunctionalInterfaceMethod()andTypeSubstitutionUtils.memberType()return non-nullable types with no@Nullableannotations, 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 oflambdaWithRawType()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. BothtypeOfParameterWithInferredLambdaandwildcardAndArrayTypesappear exactly once in the file. The AI-generated summary's claim about duplication was incorrect.Likely an incorrect or invalid review comment.
| 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); | ||
| } |
There was a problem hiding this comment.
🧹 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.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)
715-721: Consider defensive null check forASTHelpers.getType.The
castToNonNullat line 716 assumesASTHelpers.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
updateTypeWithInferredNullabilityensures lambda types properly incorporate inferred nullability from the generic method call context.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (2)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.javanullaway/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.javanullaway/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.javanullaway/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.javanullaway/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.Typesto support the newgetInferredLambdaParameterTypehelper 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:
- Identifying lambda parameters (not in the containing method's formal parameters)
- Finding the enclosing lambda and its inferred type
- Computing the functional interface method type as a member of the inferred type
- 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
updateTypeWithInferredNullabilitywhich 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:
updateMethodTypeWithInferredNullabilityapplies 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
NULLABLEfor comparison insubstituteInferredNullabilityForTypeVariablesVisitorStatefor accessing javac types and synthetic annotation typesElementfor the type variable nullability map keysAlso 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:
- Substitute inferred nullability for type variables
- Restore explicit annotations from the original type (taking precedence over inference)
- Apply to the target type at the use site
The early return for null
typeVarNullabilityis a good defensive check.
209-247: LGTM!Well-implemented helper that:
- Only processes
NULLABLEinferred types (non-null is the default, requiring no annotation)- Uses
TypeVarWithSymbolCollectorto find all occurrences of each type variable (handling cases where the same type variable appears multiple times)- Performs a batch substitution for efficiency
The approach correctly handles edge cases like type variables with modified bounds from previous substitutions.
| @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; | ||
| } |
There was a problem hiding this comment.
🧹 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.
There was a problem hiding this comment.
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
typesToUpdateandorigTypeshave the same length. IforigTypesis shorter, accessingl1.headafterl1becomes empty would returnnull, potentially causing issues downstream inupdateTypeWithInferredNullability.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
📒 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
TypeVarinstances 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 multipleTypeVarmatches may occur.
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 -->
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
Tests
✏️ Tip: You can customize this high-level summary in your review settings.