Skip to content

Skip parentheses around a lambda or method reference passed to unmarked code - #1999

Merged
msridhar merged 3 commits into
uber:masterfrom
vlsi:fix-1993-generics-parens
Oct 21, 2026
Merged

msridhar merged 3 commits into
uber:masterfrom
vlsi:fix-1993-generics-parens

Conversation

@vlsi

@vlsi vlsi commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

In JSpecify mode, a lambda or method reference passed to unmarked code may return @Nullable when its functional interface method returns a type variable. GenericsChecks.passingLambdaOrMethodRefWithGenericReturnToUnmarkedCode grants that exemption, but it read the direct parent of the lambda and expected a MethodInvocationTree. With parentheses around the argument the parent is a ParenthesizedTree, so the unmarked call was not recognized, and NullAway reported code it accepts without the parentheses. With the JSpecify JDK models off, so that Stream and Map are unmarked:

l.stream().map((Test::toNull))
  referenced method returns @Nullable, but functional interface method java.util.function.Function.apply(String) returns @NonNull
m.computeIfAbsent(key, (k -> null))
  returning @Nullable expression from method with @NonNull return type

The check now skips any number of enclosing parentheses before it looks for the call. A parenthesized lambda or method reference passed to a marked method is still reported.

Two other places in GenericsChecks test an unstripped argument for LambdaExpressionTree or MemberReferenceTree: checkTypeParameterNullnessForAssignability and runInferenceForCall, which store the poly-expression type of an assigned lambda and of a lambda argument to an inferred generic call. They are unchanged: paren and no-paren pairs (a lambda that dereferences a parameter inferred @Nullable, a method ref with a @NonNull parameter, a Supplier returning null, assignments to Consumer<@Nullable String>) were reported identically. The other parent and argument reads in GenericsChecks already skip parentheses. The unmarked-callee exemption still covers only a method call: a lambda passed to an unmarked constructor, behind a cast, or inside a conditional gets none, with or without parentheses.

The new tests in GenericsTests cover single and nested parentheses, expression and block lambdas, and method refs, for an unmarked and a marked callee, plus both reproducers from the issue; they fail on the base commit.

Part of #1993

🤖 Generated with Claude Code

Assisted-by: Claude Code (claude-opus-5-5)

Summary by CodeRabbit

  • Bug Fixes

    • Improved nullability analysis for parenthesized lambda expressions and method references passed as arguments.
    • Prevented incorrect diagnostics when these callbacks are passed to unannotated or unmarked APIs.
    • Preserved appropriate nullable-return diagnostics when callbacks are passed to APIs with nullability annotations.
  • Tests

    • Added coverage for parenthesized callbacks in regular and JSpecify-enabled analysis scenarios, including common JDK collection and stream APIs.

vlsi added 2 commits October 20, 2026 19:11
Part of uber#1993

Assisted-by: Claude Code (claude-opus-5-5)
@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: uber/NullAway/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: d92e622a-edab-4669-8af5-61f8c0dd8bd4
📥 Commits

Reviewing files that changed from the base of the PR and between 49350c4 and d02a0b3.

📒 Files selected for processing: 2
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
  • nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.

Walkthrough

The parent lookup now skips enclosing parentheses before checking whether a lambda or method reference is an argument to a method invocation. Tests cover parenthesized callbacks passed to marked and unmarked callees, including unmarked JDK Map and Stream APIs when JSpecify JDK models are disabled.

Suggested reviewers: msridhar

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to d02a0

The parenthesized-callback change has no identified issue that needs resolution before merge.

Pre-merge checks: Passed 4 · Failed 1

Failed 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: skipping parentheses around lambdas or method references passed to unmarked code.
Description check Passed The description directly explains the bug, implementation, scope, and test coverage for the changeset.
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 a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1999      +/-   ##
============================================
+ Coverage     88.15%   88.16%   +0.01%     
  Complexity       38       38              
============================================
  Files           117      117              
  Lines         11946    11949       +3     
  Branches       2448     2449       +1     
============================================
+ Hits          10531    10535       +4     
  Misses          641      641              
+ Partials        774      773       -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 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.

So annoying to analyze ASTs and have to deal with parentheses everywhere 🙂

Somewhat relatedly, when I first wrote it I thought GenericsChecks.passingLambdaOrMethodRefWithGenericReturnToUnmarkedCode was a temporary hack. Maybe we should have a follow-up issue on the "right" way to do that check, though it might require deeper unspecified nullness support

@msridhar
msridhar enabled auto-merge (squash) October 21, 2026 01:44
@msridhar
msridhar merged commit bb30450 into uber:master Oct 21, 2026
18 checks passed
msridhar pushed a commit that referenced this pull request Oct 21, 2026
…literals (#2002)

Parentheses around a lambda, a method reference, a stream receiver, or a boolean literal produced false positives, because several handlers matched those trees with `instanceof` on the tree as written, and a `ParenthesizedTree` matched none of their cases. For example, `s.filter((b -> b.get() != null)).map(b -> b.get().length())` reported `dereferenced expression 'b.get()' is @Nullable`, and an `@EnsuresNonNullIf("item")` method that ends in `return (false);` after `if (item != null) { return (true); }` reported `Method is annotated with @EnsuresNonNullIf but does not ensure fields [item]`. The same code without the parentheses compiles cleanly.

The handlers now strip parentheses before they match, at these sites:

- `StreamNullabilityPropagator`: the argument of `filter` and `map` (lambda, method reference, or anonymous class); the receiver that links a stream call to the call before it, as in `(s.filter(...)).map(...)`; the argument of `collect` and the lambdas passed to the collector factory; the boolean literal a filter returns; and, in JSpecify mode, the method reference that marks a filter as null-rejecting, as in `filter((Objects::nonNull))`.
- `EnsuresNonNullIfHandler`: the boolean literal a return statement returns.
- `SynchronousCallbackHandler`: a parenthesized lambda passed to a method whose callbacks run synchronously, such as `Iterable.forEach`, gets the access paths of the enclosing method, as an unparenthesized one does.

The other `instanceof` checks in the handlers either receive expressions through `NullAway.mayBeNullExpr`, which already strips parentheses and casts, or test dataflow nodes, which carry no parentheses.

Caller sees:
- `java.lang.IllegalStateException: null filterNullStore for tree` when a stream filter can only return `(false)`, as plain `return false;` already does on master; #1996 removes that exception for both forms.
- No `dereferenced expression ... is @Nullable`, `incompatible types`, or `Method is annotated with @EnsuresNonNullIf but does not ensure fields` warning for the parenthesized forms above.

Each new test fails on master with the false positive and passes with this change; each fixed site has its own test, and controls with the same parentheses but no null check still report.

Part of #1993 (groups B and C). Casts (group A) are #1997 and the parenthesized arguments to unmarked code in `GenericsChecks` (group D) are #1999. #1996 also edits `StreamNullabilityPropagator`, in `onDataflowInitialStore` and `onMatchMethodReference`, which this change does not touch.

Assisted-by: Claude Code (claude-opus-5-5)


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

## Summary by CodeRabbit

* **Bug Fixes**
  * Improved nullability analysis for expressions enclosed in parentheses.
  * Stream, reactive, callback, and `forEach` expressions now correctly preserve nullness information when parenthesized.
  * Parenthesized boolean literals are now validated correctly in nullability contracts.
  * Collector handling, chained calls, method references, and lambda expressions now recognize equivalent parenthesized forms.

* **Tests**
  * Added coverage for parenthesized Stream, RxJava, callback, lambda, collector, and contract expressions.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
msridhar pushed a commit that referenced this pull request Oct 22, 2026
…e in generics checks (#2012)

In JSpecify mode, NullAway reported different warnings for a lambda or method reference wrapped in parentheses than for the same expression without them. This is a variation of #1993, which #1999 fixed for lambdas and method references passed to unmarked code.

Assigning a parenthesized lambda to a field of a parameterized receiver reported a false `incompatible types` warning and missed the dereference inside the body:

    box.field = (t -> { t.length(); return ""; });  // Box<String>, field is @nullable Function<@nullable T, T>
    incompatible types: @nullable Function<String, String> cannot be converted to @nullable Function<@nullable T, T>

The unparenthesized form reports only `dereferenced expression 't' is @Nullable`. A parenthesized method reference in the same position missed `parameter s of referenced method is @NonNull`.

Passing a parenthesized lambda or method reference to a generic method reported a false positive where the unparenthesized form reported nothing, for example after a null-rejecting filter with the JSpecify JDK models turned off:

    xs.stream().filter(Objects::nonNull).map((x -> x.length()))
    dereferenced expression 'x' is @nullable
    xs.stream().filter(Objects::nonNull).map((Test::len))
    parameter s of referenced method is @nonnull, but parameter in functional interface method java.util.function.Function.apply(@nullable String) is @nullable

Both checks recorded the target-derived type of a poly expression only when the right-hand side or the argument was itself a lambda or method reference, while every reader of that type looks it up under the tree with parentheses stripped. Assignment checking and the storing of inferred argument types after generic method inference now strip parentheses before the check and store the type under the unwrapped tree. The remaining `LambdaExpressionTree` and `MemberReferenceTree` checks in `GenericsChecks` and `GenericsUtils` already receive a stripped tree or test the enclosing path rather than an argument.

Assisted-by: Claude Code (claude-opus-5-5)


🤖 Generated with [Claude Code](https://claude.com/claude-code)


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

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **Bug Fixes**
  - Improved nullability analysis for parenthesized lambda expressions and method references.
  - Generic assignments and calls now correctly preserve inferred nullness information when expressions are wrapped in parentheses.
  - Stream operations following null-filtering now correctly recognize elements as non-null.

- **Tests**
  - Added coverage for nullable generic function fields, stream filtering, lambdas, and method references.

<!-- 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants