Skip to content

Strip reference casts when computing access paths - #1997

Merged
msridhar merged 2 commits into
uber:masterfrom
vlsi:fix-1993-casts-dataflow
Oct 21, 2026
Merged

msridhar merged 2 commits into
uber:masterfrom
vlsi:fix-1993-casts-dataflow

Conversation

@vlsi

@vlsi vlsi commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

A cast at the root of an expression that NullAway checks hid the expression from dataflow, so a null check, a contract, an assertion, or a map lookup on the cast did not refine its operand. Each of these reported a false positive, while the same code without the cast compiled cleanly (group A of #1993):

if ((Object) o != null) { return o.toString(); }    // dereferenced expression 'o' is @Nullable
if (isNotNull((Object) o)) { return o.toString(); } // isNotNull has @Contract("null -> false")
Preconditions.checkNotNull((Integer) i); return i;  // unboxing of a @Nullable expression 'i'
if (m.get((String) k) != null) { return m.get(k).toString(); }
return (boolean) (item != null);                    // in an @EnsuresNonNullIf("item") method

AccessPath.getAccessPathForNode returned null for a TypeCastNode, and AccessPathNullnessPropagation.visitTypeCast kept only the regular store, which dropped the then and else facts of a boolean operand.

getAccessPathForNode now strips casts to reference types first. Such a cast yields the reference it was given or throws, so the cast is null exactly when its operand is. The strip applies to every caller, so dereferences, instanceof, assert, switch operands, and the assertion and library-model handlers also refine the operand of a reference cast. A cast to a primitive type is kept and has no access path, because it can change the value: for a long l, m.get((int) l) looks up an Integer key and m.get(l) a Long key. visitTypeCast passes the then and else stores through, since a cast keeps the truth value of a boolean operand.

New tests cover each of the five shapes and, beside each, a case that still warns: the branch where the operand is null, an unchecked variable, and a map key under a primitive cast.

Part of #1993

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

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved nullness analysis for reference-type casts, preserving refinements across casts and downcasts.
    • Preserved branch-based nullness facts when boolean conditions are cast.
    • Improved handling of contracts and non-null guarantees involving cast expressions.
    • Kept primitive casts distinct during access-path and map-key analysis.
  • Tests

    • Added regression coverage for cast-based nullness refinement, contracts, returned conditions, and map-key matching.

A cast at the root of an expression that NullAway checks hid the expression from dataflow, so a null check, a contract, an assertion, or a map lookup on the cast did not refine its operand. Each of these reported a false positive, while the same code without the cast compiled cleanly (group A of uber#1993):

    if ((Object) o != null) { return o.toString(); }    // dereferenced expression 'o' is @nullable
    if (isNotNull((Object) o)) { return o.toString(); } // isNotNull has @contract("null -> false")
    Preconditions.checkNotNull((Integer) i); return i;  // unboxing of a @nullable expression 'i'
    if (m.get((String) k) != null) { return m.get(k).toString(); }
    return (boolean) (item != null);                    // in an @EnsuresNonNullIf("item") method

AccessPath.getAccessPathForNode returned null for a TypeCastNode, and AccessPathNullnessPropagation.visitTypeCast kept only the regular store, which dropped the then and else facts of a boolean operand.

getAccessPathForNode now strips casts to reference types first. Such a cast yields the reference it was given or throws, so the cast is null exactly when its operand is. The strip applies to every caller, so dereferences, instanceof, assert, switch operands, and the assertion and library-model handlers also refine the operand of a reference cast. A cast to a primitive type is kept and has no access path, because it can change the value: for a long l, m.get((int) l) looks up an Integer key and m.get(l) a Long key. visitTypeCast passes the then and else stores through, since a cast keeps the truth value of a boolean operand.

New tests cover each of the five shapes and, beside each, a case that still warns: the branch where the operand is null, an unchecked variable, and a map key under a primitive cast.

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: 704f3b7b-fdd8-4e17-9fcc-a1ce20fab747
📥 Commits

Reviewing files that changed from the base of the PR and between 4000c90 and 81b96c7.

📒 Files selected for processing: 5
  • nullaway/src/main/java/com/uber/nullaway/dataflow/AccessPath.java
  • nullaway/src/main/java/com/uber/nullaway/dataflow/AccessPathNullnessPropagation.java
  • nullaway/src/test/java/com/uber/nullaway/AccessPathsTests.java
  • nullaway/src/test/java/com/uber/nullaway/ContractsTests.java
  • nullaway/src/test/java/com/uber/nullaway/EnsuresNonNullIfTests.java

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

Walkthrough

Access-path lookup now removes reference casts while preserving primitive casts. Type-cast analysis preserves existing then and else nullness stores when both are available. Regression tests cover casted access paths, map keys, contract arguments, and casted boolean conditions.

Suggested reviewers: msridhar

Priority: ⬇️ Low

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 81b96

No actionable merge-blocking issue is established. Complete the normal test checks before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 5 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 primary change: stripping reference casts during access-path computation.
Description check Passed The description directly explains the access-path and type-cast changes, affected dataflow cases, and regression tests.
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.11%. Comparing base (f7b81c4) to head (81b96c7).

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #1997   +/-   ##
=========================================
  Coverage     88.10%   88.11%           
  Complexity       38       38           
=========================================
  Files           117      117           
  Lines         11940    11944    +4     
  Branches       2444     2447    +3     
=========================================
+ Hits          10520    10524    +4     
  Misses          644      644           
  Partials        776      776           

☔ 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 enabled auto-merge (squash) October 21, 2026 01:14
@msridhar
msridhar disabled auto-merge October 21, 2026 01:17
@msridhar
msridhar enabled auto-merge (squash) October 21, 2026 01:17
@msridhar
msridhar merged commit 486dff9 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
… to its own type (#2014)

A map key, a constant method argument, or an array index wrapped in a cast to its own static type lost its access path, so a null check on the plain expression did not refine the cast one. Each of these reported a false positive, while the same code without the cast compiled cleanly:

    if (m.get("k") != null) { m.get((String) ("k")).toString(); } // dereferenced expression 'm.get((String) ("k"))' is @nullable
    if (m.get(42) != null) { m.get((int) (42)).toString(); }
    if (m.get(key) != null) { m.get((int) (key)).toString(); }    // int key
    if (get(0) != null) { get((int) (0)).toString(); }            // @nullable Object get(int)
    if (apply("hello") != null) { apply((String) ("hello")).toString(); }
    if (fizz[i] != null) { fizz[(int) (i)].toString(); }          // @nullable String[] fizz

AccessPath.argumentToMapKeySpecifier and the constant-argument branch of buildAccessPathRecursive both decide by the argument's tree kind, and a cast is a TYPE_CAST tree, so a literal, a constant field, or an Integer.valueOf call under a cast matched none of their cases. The array branch read the index node without stripping casts. stripCasts also kept every cast to a primitive type, including one to the operand's own type, so `(int) (42)` and `(int) key` stayed opaque even where casts were stripped.

stripCasts now also removes a cast to a primitive type when the operand already has that type. The map-key, constant-argument, and array-index paths strip casts before they look at the argument. The constant-argument branch also unwraps a widening conversion and recognizes the boxing call on the dataflow node instead of the tree, so `getLong((int) (0))` for a long parameter and `getBoxed((int) (0))` for an Integer parameter reach the literal. A cast to any other primitive type still has no access path: for a long l, `(int) l` and `l` box to different map keys, and `m.get((long) (42))` is a different key from `m.get(42)`.

This is a variation of #1993: #1997 stripped reference casts in getAccessPathForNode, and these sites matched on the tree or read the index before reaching it.

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 nullness analysis for expressions containing redundant casts, widening conversions, and boxing.
  - Equivalent string, integer, boxed-integer, constant-field, method-argument, and array-index expressions now correctly retain established nullness information.
  - Value-changing casts, such as converting a `long` index to `int`, continue to be treated as distinct expressions and produce appropriate diagnostics.
- **Tests**
  - Added coverage for cast handling across access paths, method arguments, constants, and array indices.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
subhramit pushed a commit to subhramit/NullAway that referenced this pull request Oct 24, 2026
…guments (uber#2046)

Three behaviors fixed by earlier changes had no test, so a regression in
any of them would pass the suite.

- uber#444: a null check on a cast around `Map.get`, as in `(String)
m.get("k") == null ? "" : (String) m.get("k")`, did not refine
`m.get("k")`, and the result was reported as `@Nullable`. uber#1997 fixed it
by stripping reference casts when it computes access paths, but its
tests cast a local or a map key, not the `get` result. The new
`AccessPathsTests` case fails on f7b81c4, the parent of uber#1997, with
`returning @nullable expression from method with @nonnull return type`.
- uber#1290, method reference: `invoke(Test::returnsNull)` for `<R> void
invoke(Supplier<@nullable R>)` and a `static @nullable Object
returnsNull()` was reported with `Failed to infer type argument
nullability` and `referenced method returns @nullable, but functional
interface method Test.Supplier.get() returns @NonNull`. uber#1430 fixed it;
its test passes an unbound receiver reference to a `Function`. The new
case beside `supplierLambdaInference` fails with both diagnostics on
0b4156b, the parent of uber#1430.
- uber#1290, dereference: inside `invoke`, dereferencing `supplier.get()`
for a `java.util.function.Supplier<@nullable R>` is reported only with
the JSpecify JDK models (`JSpecifyJDKModels=true`, or
`JSpecifyExperimental=true`). Without them `Supplier` is unmarked and
`get()` is not treated as `@Nullable`. The new `JSpecifyJDKModelsTest`
case fails when its helper leaves out the models flag.

The lambda case of uber#1290, `invoke(() -> null)`, is already covered by
`supplierLambdaInference` (uber#1337).

Fixes uber#444
Fixes uber#1290

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

* **Tests**
* Expanded coverage for nullability analysis involving casted map
lookups, including checks that distinguish between matching and
different keys.
* Added JSpecify coverage for nullable values returned from suppliers
and for nullability inferred through method references.
* Added checks for the expected diagnostics when nullable values are
dereferenced, alongside cases where no diagnostic is expected.

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