Skip to content

Use inference for generic call passed as receiver to instance method - #1293

Merged
msridhar merged 6 commits into
masterfrom
another-generic-inference-receiver-issue
Sep 16, 2025
Merged

msridhar merged 6 commits into
masterfrom
another-generic-inference-receiver-issue

Conversation

@msridhar

@msridhar msridhar commented Sep 16, 2025 •

Copy link
Copy Markdown
Contributor

See the new test; we missed this case before.

Summary by CodeRabbit

  • New Features

    • Improved nullability analysis for chained calls where a generic method invocation is used as the receiver; the analyzer now infers receiver types when explicit type arguments are absent, yielding more accurate diagnostics.
  • Bug Fixes

    • Reduced incorrect or missing diagnostics for generic method receivers and nullable types; better detection of potential null dereferences.
  • Tests

    • Added test coverage validating inference and error reporting for nullable receivers in generic method call chains.

@coderabbitai

coderabbitai Bot commented Sep 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a receiver-based generic-method inference path in GenericsChecks: when a MemberSelect receiver is a generic MethodInvocation without explicit type arguments, the code attempts to infer the receiver’s method-call type and uses it as the enclosing type for subsequent nullability checks. A unit test exercising this inference is added.

Changes

Cohort / File(s) Summary
Generics inference on receiver in call resolution
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
For receiver paths under a MemberSelectTree, build a local receiver and, if isGenericCallNeedingInference(receiver) is true, call inferGenericMethodCallType(state, (MethodInvocationTree) receiver, null, false) and use that result as the enclosing type; otherwise fall back to getTreeType(receiver). Also mark typeFromAssignmentContext parameter as @Nullable on inferGenericMethodCallType.
Tests for receiver-based inference diagnostics
nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java
Adds inferenceFromReceiverPassing() test that constructs a generic make method returning Foo<U> with U extends @Nullable Object, invokes make(null).get().toString(), and asserts a diagnostic showing inference-based nullability on the receiver chain.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Checker
  participant GenericsChecks
  participant AST as AST Node
  participant Inference as Inference Engine

  Checker->>GenericsChecks: getEnclosingTypeForCallExpression(call)
  GenericsChecks->>AST: inspect receiver of MemberSelectTree
  alt receiver is MethodInvocation && isGenericCallNeedingInference
    GenericsChecks->>Inference: inferGenericMethodCallType(receiver, ..., typeFromAssignmentContext=null)
    Inference-->>GenericsChecks: inferred MethodInvocation type
    GenericsChecks-->>Checker: enclosingType = inferred type
  else
    GenericsChecks->>AST: getTreeType(receiver)
    GenericsChecks-->>Checker: enclosingType = tree type
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • lazaroclapp
  • yuxincs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately and concisely summarizes the primary change—adding generic type inference for generic calls used as receivers of instance methods—and directly matches the code and test updates in the PR. It is specific, clear, and appropriate for a teammate scanning the commit history.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch another-generic-inference-receiver-issue

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 36e680d and b8cb51f.

📒 Files selected for processing (2)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (2 hunks)
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java

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: 0

🧹 Nitpick comments (2)
nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java (1)

1219-1242: Add a parenthesized receiver variant to avoid regressions

We also hit this shape in real code: ((make(null))).get().toString(). Add it to lock behavior.

Apply this diff inside the test body:

       // BUG: Diagnostic contains: dereferenced expression
       make(null).get().toString();
+      // Also with a parenthesized receiver
+      // BUG: Diagnostic contains: dereferenced expression
+      ((make(null))).get().toString();
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1)

1403-1409: Handle parenthesized receivers and preserve raw‑type bail‑out

  • Strip parentheses on the receiver before checking for a generic call; otherwise (make(...)).get() won’t trigger inference.
  • If the inferred receiver type ends up raw, return null to keep existing “bail out on raw types” semantics consistent with getTreeType.

Apply this diff:

-        ExpressionTree receiver = ((MemberSelectTree) methodSelect).getExpression();
-        if (isGenericCallNeedingInference(receiver)) {
-          enclosingType =
-              inferGenericMethodCallType(state, (MethodInvocationTree) receiver, null, false);
-        } else {
-          enclosingType = getTreeType(receiver);
-        }
+        ExpressionTree receiver =
+            ASTHelpers.stripParentheses(((MemberSelectTree) methodSelect).getExpression());
+        Type candidate;
+        if (isGenericCallNeedingInference(receiver)) {
+          candidate =
+              inferGenericMethodCallType(state, (MethodInvocationTree) receiver, null, false);
+        } else {
+          candidate = getTreeType(receiver);
+        }
+        if (candidate != null && candidate.isRaw()) {
+          enclosingType = null;
+        } else {
+          enclosingType = candidate;
+        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 085fd42 and 5c77f3e.

📒 Files selected for processing (2)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (1 hunks)
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: msridhar
PR: uber/NullAway#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
PR: uber/NullAway#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
📚 Learning: 2025-08-14T18:50:06.159Z
Learnt from: msridhar
PR: uber/NullAway#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
⏰ 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). (4)
  • GitHub Check: Build and test on macos-latest
  • GitHub Check: Build and test on windows-latest
  • GitHub Check: Build spring-framework with snapshot
  • GitHub Check: Build caffeine with snapshot
🔇 Additional comments (1)
nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java (1)

1219-1242: Good coverage for receiver‑inference case

Test clearly exercises the missed path (generic call as receiver) and asserts the right diagnostic.

@msridhar
msridhar enabled auto-merge (squash) September 16, 2025 23:21
@codecov

codecov Bot commented Sep 16, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.38%. Comparing base (085fd42) to head (b8cb51f).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #1293   +/-   ##
=========================================
  Coverage     88.37%   88.38%           
- Complexity     2467     2468    +1     
=========================================
  Files            93       93           
  Lines          8188     8193    +5     
  Branches       1614     1615    +1     
=========================================
+ Hits           7236     7241    +5     
  Misses          479      479           
  Partials        473      473           

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

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