Repository navigation
Strip reference casts when computing access paths - #1997
Conversation
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)
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughAccess-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: Priority: ⬇️ Low Change: Bug fix Merge Risk: ⚪ Minimal · up to
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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 -->
… 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 -->
…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 -->
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):
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
Tests