Skip to content

Better support for conditional expressions in JSpecify mode - #1608

Merged
msridhar merged 26 commits into
masterfrom
jspecify-conditional-expr-wildcard
Jul 18, 2026
Merged

msridhar merged 26 commits into
masterfrom
jspecify-conditional-expr-wildcard

Conversation

@msridhar

@msridhar msridhar commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

We improve support for conditional expressions in JSpecify mode, by properly inferring types of conditional expressions where appropriate. We also propagate types from the assignment context through (nested) conditional expressions to correctly infer types of generic method calls nested within such expressions. See the new ConditionalExprTests for examples.

We extract out some common code for finding a type from the assignment context given a TreePath into a new method getTargetTypeFromParentContext, and now use it consistently to handle getting assignment contexts for conditional expressions, generic method calls, and diamond constructor calls. As part of this extraction, we make more consistent our handling of var-declared locals (ensuring we don't use their javac-inferred type during our own inference), and we add tests for this.

Apologies for the size of this PR; it would have been a bit awkward to make it smaller.

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved nullability and generic type inference for conditional (?:) expressions, including nested conditionals and scenarios influenced by dataflow/loops.
    • More accurate type inference when conditional results feed into assignments, method calls, and diamond constructor usage.
    • Enhanced handling of var cases where conditional expressions don’t supply enough target type information for generic/diamond inference.
  • Tests

    • Added expanded JUnit coverage for conditional-expression inference/nullability, diamond and generic inference edge cases, and dataflow/loop interactions.

@msridhar

msridhar commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

@msridhar
msridhar marked this pull request as draft June 15, 2026 05:20
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

GenericsChecks now treats conditional expressions as context-sensitive poly expressions with cached inferred types and dedicated handling for assignments, returns, calls, diamond construction, constraints, and nullability checks. New tests cover conditional generic inference, nested expressions, dataflow, loops, and var-related inference cases.

Possibly related PRs

  • uber/NullAway#1309: Introduces dataflow-aware generic inference plumbing extended by this conditional-expression handling.
  • uber/NullAway#1430: Adds poly-expression type caching extended here to conditional expressions.
  • uber/NullAway#1464: Updates context-sensitive diamond inference used by conditional-expression parent handling.

Suggested reviewers: yuxincs, lazaroclapp

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.82% 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 matches the main change: improved conditional-expression handling in JSpecify mode.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jspecify-conditional-expr-wildcard

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.

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 2088-2097: The `inferConditionalExpressionType` method returns a
nullable Type, but the result assigned to `actualParameterType` is used without
a null check. Add a null check immediately after the assignment from
`inferConditionalExpressionType` (within the conditional block for
ConditionalExpressionTree) to ensure `actualParameterType` is not null before it
is used at line 2098 in the `subtypeParameterNullability` call. If the result is
null, handle it appropriately by continuing to the next iteration or setting a
default value, similar to how other branches handle edge cases.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b9f9ce7e-22a5-4370-9033-dd6605649ea9

📥 Commits

Reviewing files that changed from the base of the PR and between 0b3145b and 6b53e13.

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

@codecov

codecov Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.45455% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.20%. Comparing base (b2e8461) to head (966ea20).

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 85.45% 7 Missing and 17 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1608      +/-   ##
============================================
+ Coverage     88.10%   88.20%   +0.09%     
- Complexity     3050     3075      +25     
============================================
  Files           105      105              
  Lines         10192    10293     +101     
  Branches       2066     2087      +21     
============================================
+ Hits           8980     9079      +99     
- Misses          572      573       +1     
- Partials        640      641       +1     

☔ 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 force-pushed the jspecify-conditional-expr-wildcard branch 2 times, most recently from 77cd8fd to 464e44a Compare June 16, 2026 23:11
@msridhar
msridhar force-pushed the jspecify-conditional-expr-wildcard branch 3 times, most recently from 7e7240a to 516ec37 Compare June 26, 2026 17:01
@msridhar
msridhar force-pushed the jspecify-conditional-expr-wildcard branch from 516ec37 to 14ba0f3 Compare July 3, 2026 21:12
@msridhar msridhar changed the title [draft] Better support for conditional expressions in JSpecify mode Better support for conditional expressions in JSpecify mode Jul 4, 2026
@msridhar
msridhar marked this pull request as ready for review July 4, 2026 01:32
@msridhar
msridhar requested a review from lazaroclapp July 4, 2026 01:34

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 1872-1888: In getConditionalExpressionType, the cached
assignment-context type can still be raw and should not be returned or stored
as-is. Update the logic around inferredPolyExpressionTypes and
getTargetTypeForConditionalExpression so that any typeFromAssignmentContext is
passed through typeOrNullIfRaw(...) before caching and before returning,
ensuring inferConditionalExpressionType never sees a raw conditional target.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c5df7e9e-5c51-46eb-9730-a74f0e63eb9b

📥 Commits

Reviewing files that changed from the base of the PR and between 6b53e13 and 7e0c16b.

📒 Files selected for processing (4)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/ConditionalExprTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java

@lazaroclapp lazaroclapp 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.

Hey, sorry this one took me a while, but it is was indeed a fairly involved PR, so no chance to get to it during the week...

As it is, I still don't really have the entire algorithm / design swapped in memory (nor do I think I can in a feasible amount of time 😅 ), so a lot of my comments are local to what I see each individual method do and to the tests, but hopefully still useful!

Looks like we can handle a ton of complex inference cases now, though! Cool! 🎉

}
void test() {
// BUG: Diagnostic contains: passing @Nullable parameter
var inferredFromInitializer = new Box<>(null);

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.

Why does this return an error? Shouldn't it just infer Box<@Nullable Object>? (I think the test is explicitly asserting that it does not, but I am not sure I recall why those would be the semantics. Maybe worth a comment or JSpecify link?)

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.

You're right, there should be no warning there. I opened a new issue for this, #1633. I thought this was testing something useful before despite the limitation; looking more closely, I'm now not so sure. But I want to leave this test in for now, to be sure it stays around. So I'm just going to add a comment linking that new issue.

Comment on lines +268 to +269
// BUG: Diagnostic contains: passing @Nullable parameter
var inferredFromInitializer = flag ? new Box<>(null) : new Box<>("fallback");

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.

I mention it above, but again mildly surprised that var inferredFromInitializer isn't just inferred to be Box<@Nullable String> here. I suspect there is a reason for it in the JSpecify semantics, just think it might be worth a short comment (see GenericDiamondTests.java's comment)

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.

I've added a comment for this one as well

@msridhar
msridhar force-pushed the jspecify-conditional-expr-wildcard branch from 7e0c16b to 7772e62 Compare July 16, 2026 02:58

@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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 1979-1989: Update getTargetTypeFromParentContext() handling of
ReturnTree to support an enclosing LambdaExpressionTree in addition to
MethodTree. For lambdas, including expression-bodied lambdas, derive and return
the functional interface’s return type while preserving the existing
method-return and null fallback behavior.
- Around line 1991-2006: Update the MethodInvocationTree handling in
getTreeType() to apply the library-modeled generic nullability override to the
formal parameter returned by getFormalParameterTypeForArgument before
constructing and caching TargetTypeAndAssignmentKind. Ensure
inferConditionalExpressionType() observes the handler-adjusted target instead of
the raw javac formal type, while preserving the existing generic-inference and
null-method-type branches.

In `@nullaway/src/test/java/com/uber/nullaway/jspecify/ConditionalExprTests.java`:
- Around line 113-137: Add return-context coverage to conditional expression
tests near conditionalAsMethodArgument: define methods returning nullable and
non-null String values, and exercise conditionals whose branches include
nullable and non-null results. Assert the nullable return case is accepted and
the non-null return case reports the expected nullable-value diagnostic,
covering propagation of the return target type.
- Around line 174-186: Update the var declaration test around
inferredFromInitializer to assert the inferred nullable element type by
dereferencing get() in a way that would produce a diagnostic if inferred as
non-null, following the pattern used in VarDeclaredLocalTests. Preserve the
existing explicit nullable and non-null target checks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: dd5f30cb-34ee-4fcc-b04a-873093d89635

📥 Commits

Reviewing files that changed from the base of the PR and between 7e0c16b and 7772e62.

📒 Files selected for processing (4)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/ConditionalExprTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java

Comment on lines +1991 to +2006
if (parent instanceof MethodInvocationTree parentInvocation) {
if (isGenericCallNeedingInference(parentInvocation)) {
// The parent invocation's formal parameter type is still part of the inference problem, not
// a solved target type. Generic method inference will handle this expression from the
// parent
// call side.
return new TargetTypeAndAssignmentKind(null, false);
}
Type methodType = ASTHelpers.getType(parentInvocation.getMethodSelect());
if (methodType == null) {
return new TargetTypeAndAssignmentKind(null, false);
}
return new TargetTypeAndAssignmentKind(
getFormalParameterTypeForArgument(
parentInvocation, methodType.asMethodType(), expressionTree),
false);

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Apply library-model overrides before caching the argument target.

getTreeType() reaches this path before the later conditional-specific inference and caches the formal type from javac. Consequently, inferConditionalExpressionType() returns that cached type instead of the handler-adjusted formal parameter, ignoring library-modeled generic nullability.

Proposed fix
       Type methodType = ASTHelpers.getType(parentInvocation.getMethodSelect());
-      if (methodType == null) {
+      Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(parentInvocation);
+      if (methodType == null || methodSymbol == null) {
         return new TargetTypeAndAssignmentKind(null, false);
       }
+      Type.MethodType modeledMethodType =
+          handler.onOverrideMethodType(
+              methodSymbol, methodType.asMethodType(), parentState, parentInvocation);
       return new TargetTypeAndAssignmentKind(
           getFormalParameterTypeForArgument(
-              parentInvocation, methodType.asMethodType(), expressionTree),
+              parentInvocation, modeledMethodType, expressionTree),
           false);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 1991 - 2006, Update the MethodInvocationTree handling in getTreeType() to
apply the library-modeled generic nullability override to the formal parameter
returned by getFormalParameterTypeForArgument before constructing and caching
TargetTypeAndAssignmentKind. Ensure inferConditionalExpressionType() observes
the handler-adjusted target instead of the raw javac formal type, while
preserving the existing generic-inference and null-method-type branches.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (2)

1878-1886: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Skip raw conditional targets before caching.

getTargetTypeForConditionalExpression can return a raw typeFromAssignmentContext, which is then cached directly in inferredPolyExpressionTypes and returned without checking .isRaw(). This allows raw types to bypass inference checks or cause NullPointerExceptions later.

Wrap typeFromAssignmentContext with typeOrNullIfRaw(...) before caching and returning.

🐛 Proposed fix
     TargetTypeAndAssignmentKind targetTypeAndAssignmentKind =
         getTargetTypeForConditionalExpression(tree, state, calledFromDataflow);
-    Type typeFromAssignmentContext = targetTypeAndAssignmentKind.typeFromAssignmentContext();
+    Type typeFromAssignmentContext = typeOrNullIfRaw(targetTypeAndAssignmentKind.typeFromAssignmentContext());
     if (typeFromAssignmentContext != null) {
       if (!calledFromDataflow) {
         inferredPolyExpressionTypes.put(tree, typeFromAssignmentContext);
       }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 1878 - 1886, Update the conditional-expression handling around
getTargetTypeForConditionalExpression so typeFromAssignmentContext is passed
through typeOrNullIfRaw(...) before caching or returning. Use the normalized
result for inferredPolyExpressionTypes and return it, preserving the existing
calledFromDataflow behavior.

1980-1990: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Handle lambda parents here too. getTargetTypeFromParentContext() drops the target type for lambdas: block-bodied lambdas fall through because ReturnTree only accepts MethodTree, and expression-bodied lambdas have no LambdaExpressionTree branch. Returning the lambda’s functional-interface return type would keep conditional expressions inside lambdas inferable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 1980 - 1990, The getTargetTypeFromParentContext() ReturnTree handling must
support lambda parents as well as methods. When
findEnclosingMethodOrLambdaOrInitializer() resolves a LambdaExpressionTree,
derive and return its functional-interface return type; ensure expression-bodied
lambdas are handled through an explicit LambdaExpressionTree branch, while
preserving the existing method return-type behavior.
♻️ Duplicate comments (1)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)

2000-2007: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Apply library-model overrides before caching the argument target.

getTreeType() reaches this path before the later conditional-specific inference and caches the formal type from javac. Consequently, inferConditionalExpressionType() will return that cached type instead of the handler-adjusted formal parameter, ignoring library-modeled generic nullability.

🐛 Proposed fix
-      Type methodType = ASTHelpers.getType(parentInvocation.getMethodSelect());
-      if (methodType != null) {
+      Type methodType = ASTHelpers.getType(parentInvocation.getMethodSelect());
+      Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(parentInvocation);
+      if (methodType != null && methodSymbol != null) {
+        Type.MethodType modeledMethodType =
+            handler.onOverrideMethodType(
+                methodSymbol, methodType.asMethodType(), parentState, parentInvocation);
         return new TargetTypeAndAssignmentKind(
             getFormalParameterTypeForArgument(
-                parentInvocation, methodType.asMethodType(), expressionTree),
+                parentInvocation, modeledMethodType, expressionTree),
             false);
       }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 2000 - 2007, Update the target-type caching path in getTreeType() so
library-model overrides are applied before caching or returning the formal
argument type. Ensure inferConditionalExpressionType() observes the
handler-adjusted formal parameter rather than a javac-derived cached type, while
preserving the existing behavior for non-library-modeled calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 1878-1886: Update the conditional-expression handling around
getTargetTypeForConditionalExpression so typeFromAssignmentContext is passed
through typeOrNullIfRaw(...) before caching or returning. Use the normalized
result for inferredPolyExpressionTypes and return it, preserving the existing
calledFromDataflow behavior.
- Around line 1980-1990: The getTargetTypeFromParentContext() ReturnTree
handling must support lambda parents as well as methods. When
findEnclosingMethodOrLambdaOrInitializer() resolves a LambdaExpressionTree,
derive and return its functional-interface return type; ensure expression-bodied
lambdas are handled through an explicit LambdaExpressionTree branch, while
preserving the existing method return-type behavior.

---

Duplicate comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 2000-2007: Update the target-type caching path in getTreeType() so
library-model overrides are applied before caching or returning the formal
argument type. Ensure inferConditionalExpressionType() observes the
handler-adjusted formal parameter rather than a javac-derived cached type, while
preserving the existing behavior for non-library-modeled calls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 45e3ab57-3e47-455d-ae2f-44e59155aa1b

📥 Commits

Reviewing files that changed from the base of the PR and between 7772e62 and c4a9da2.

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (3)

1880-1886: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Skip raw conditional targets before caching.

typeFromAssignmentContext can be a raw type. Caching it here without a check allows raw types to bypass the explicit raw check in inferConditionalExpressionType, as subsequent calls will read the cached raw type directly. Wrap the extracted type with typeOrNullIfRaw(...) to prevent caching and returning raw conditional targets.

🐛 Proposed fix
-    Type typeFromAssignmentContext = targetTypeAndAssignmentKind.typeFromAssignmentContext();
+    Type typeFromAssignmentContext =
+        typeOrNullIfRaw(targetTypeAndAssignmentKind.typeFromAssignmentContext());
     if (typeFromAssignmentContext != null) {
       if (!calledFromDataflow) {
         inferredPolyExpressionTypes.put(tree, typeFromAssignmentContext);
       }
       return typeFromAssignmentContext;
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 1880 - 1886, Update the typeFromAssignmentContext handling in
inferConditionalExpressionType to pass the extracted type through
typeOrNullIfRaw before caching or returning it. Preserve the existing
calledFromDataflow behavior, and ensure raw conditional targets are treated as
null so they cannot bypass the explicit raw-type check on later calls.

1983-1993: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Propagate lambda return types into conditional expressions.
getTargetTypeFromParentContext() only resolves ReturnTree to a MethodTree, so conditionals inside lambdas still lose target typing here. Handle the enclosing LambdaExpressionTree for block-bodied lambdas and the direct lambda parent for expression-bodied lambdas, and add tests for both cases.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 1983 - 1993, Update getTargetTypeFromParentContext() to resolve return
target types from enclosing LambdaExpressionTree nodes as well as MethodTree
nodes: use the lambda’s functional-interface return type for block-bodied
lambdas and handle a directly parented expression-bodied lambda. Preserve
existing method return handling, and add coverage for both lambda body forms
inside conditional expressions.

2003-2024: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Apply library-model overrides before extracting the argument target type.

The target type extraction for conditional arguments caches the raw formal parameter from javac without applying library-modeled generic nullability. Apply handler.onOverrideMethodType(...) to override the formal parameter before calling getFormalParameterTypeForArgument for both generic method invocations and constructor calls.

🐛 Proposed fix
       Type methodType = ASTHelpers.getType(parentInvocation.getMethodSelect());
-      if (methodType != null) {
+      Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(parentInvocation);
+      if (methodType != null && methodSymbol != null) {
+        Type.MethodType modeledMethodType =
+            handler.onOverrideMethodType(
+                methodSymbol, methodType.asMethodType(), parentState, parentInvocation);
         return new TargetTypeAndAssignmentKind(
             getFormalParameterTypeForArgument(
-                parentInvocation, methodType.asMethodType(), expressionTree),
+                parentInvocation, modeledMethodType, expressionTree),
             false);
       }
     }
     // (Also 2c, but for constructors)
     if (parent instanceof NewClassTree parentConstructorCall) {
       Type parentClassType = getTreeType(parentConstructorCall, parentState, calledFromDataflow);
       if (parentClassType != null) {
         Symbol parentCtorSymbol = ASTHelpers.getSymbol(parentConstructorCall);
         Type parentCtorType =
             TypeSubstitutionUtils.memberType(
                 state.getTypes(), parentClassType, parentCtorSymbol, config);
+        Type.MethodType modeledCtorType =
+            handler.onOverrideMethodType(
+                (Symbol.MethodSymbol) parentCtorSymbol,
+                parentCtorType.asMethodType(),
+                parentState,
+                null);
         return new TargetTypeAndAssignmentKind(
             getFormalParameterTypeForArgument(
-                parentConstructorCall, parentCtorType.asMethodType(), expressionTree),
+                parentConstructorCall, modeledCtorType, expressionTree),
             false);
       }
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java` around
lines 2003 - 2024, Update the generic method-invocation and constructor branches
in the target-type extraction logic to pass the resolved method type through
handler.onOverrideMethodType(...) before calling
getFormalParameterTypeForArgument. Apply the override to both methodType and
parentCtorType, preserving the existing lookup and return behavior while
ensuring modeled generic nullability is used.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java`:
- Around line 1880-1886: Update the typeFromAssignmentContext handling in
inferConditionalExpressionType to pass the extracted type through
typeOrNullIfRaw before caching or returning it. Preserve the existing
calledFromDataflow behavior, and ensure raw conditional targets are treated as
null so they cannot bypass the explicit raw-type check on later calls.
- Around line 1983-1993: Update getTargetTypeFromParentContext() to resolve
return target types from enclosing LambdaExpressionTree nodes as well as
MethodTree nodes: use the lambda’s functional-interface return type for
block-bodied lambdas and handle a directly parented expression-bodied lambda.
Preserve existing method return handling, and add coverage for both lambda body
forms inside conditional expressions.
- Around line 2003-2024: Update the generic method-invocation and constructor
branches in the target-type extraction logic to pass the resolved method type
through handler.onOverrideMethodType(...) before calling
getFormalParameterTypeForArgument. Apply the override to both methodType and
parentCtorType, preserving the existing lookup and return behavior while
ensuring modeled generic nullability is used.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f2b6a306-992c-4f33-99b8-10ea9646c2fd

📥 Commits

Reviewing files that changed from the base of the PR and between c4a9da2 and 4d89561.

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

@msridhar
msridhar force-pushed the jspecify-conditional-expr-wildcard branch from eb7ae34 to d3dbe81 Compare July 17, 2026 18:18
@msridhar
msridhar requested a review from lazaroclapp July 17, 2026 19:37
@msridhar

Copy link
Copy Markdown
Collaborator Author

Thanks for the detailed review @lazaroclapp ! I believe I've addressed all the feedback now, so this is ready for another look

@msridhar
msridhar merged commit 43a78f3 into master Jul 18, 2026
10 of 14 checks passed
@msridhar
msridhar deleted the jspecify-conditional-expr-wildcard branch July 18, 2026 19:44
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