Repository navigation
Properly check generic method overriding in explicitly-typed anonymous classes - #808
Conversation
lazaroclapp
left a comment
There was a problem hiding this comment.
Sorry it took so long. One initial pass here. Overall, it looks good.
| " public @Nullable String apply(String s) { return null; }", | ||
| " };", | ||
| " FnClass<String, @Nullable String> fn4 = new FnClass<String, @Nullable String>() {", | ||
| " public @Nullable String apply(String s) { return null; }", |
There was a problem hiding this comment.
Why are both true positive cases on the parameter and both true negatives on the return value? Seems like it might test more combinations to do one each?
| if (newClassTree == null) { | ||
| throw new RuntimeException( | ||
| "method should be inside a NewClassTree " + state.getSourceForNode(path.getLeaf())); | ||
| } |
There was a problem hiding this comment.
Do we want a check that the NewClassTree is for the same type as symbol['s supertype]? Or can that be safely assumed to never break?
There was a problem hiding this comment.
Can we add a test case for when the class name is given as something other than a simple name? new Foo.Builder<@Nullable String>() { ... } or even new Foo<@Nullable String>.Builder() {...}?
There was a problem hiding this comment.
Do we want a check that the
NewClassTreeis for the same type assymbol['s supertype]? Or can that be safely assumed to never break?
I added a check in af6ca1f; can't hurt :-)
Can we add a test case for when the class name is given as something other than a simple name?
new Foo.Builder<@Nullable String>() { ... }or evennew Foo<@Nullable String>.Builder() {...}?
I added some tests in 16eb9c2 but one of them is failing (see overrideAnonymousNestedClass()) 😐 I propose I fix that issue in a follow-up; does that sound ok?
…m/msridhar/NullAway into override-anonymous-class-checking
Codecov ReportAttention:
Additional details and impacted files@@ Coverage Diff @@
## master #808 +/- ##
============================================
- Coverage 86.79% 86.75% -0.05%
- Complexity 1870 1876 +6
============================================
Files 74 74
Lines 6178 6197 +19
Branches 1202 1206 +4
============================================
+ Hits 5362 5376 +14
- Misses 405 408 +3
- Partials 411 413 +2
☔ View full report in Codecov by Sentry. |
|
@lazaroclapp I finally got around to addressing your feedback here; sorry for the long delay. |
lazaroclapp
left a comment
There was a problem hiding this comment.
See minor comment above, but otherwise SGTM!
There was a problem hiding this comment.
Let's create and link an issue!
…1699) ## Summary Un-ignores `overrideAnonymousNestedClass`, which exercises an anonymous class instantiated via a qualified `new` expression with two levels of generics: ```java class Test { class Wrapper<P extends @nullable Object> { abstract class Fn<R extends @nullable Object> { abstract R apply(P p); } } void anonymousNestedClasses() { Wrapper<@nullable String>.Fn<String> fn1 = (this.new Wrapper<@nullable String>()).new Fn<String>() { public String apply(String s) { return s; } }; } } ``` `Fn.apply(P p)` references the *outer* class `Wrapper`'s type variable `P`. The `@Nullable` annotation for `P` lives in the qualifier sub-expression (`this.new Wrapper<@nullable String>()`), not in the `Fn<String>` part naming the class actually being instantiated. ## Diagnosis Running the ignored test (rather than assuming the issue title described the actual behavior) showed this is a hard, uncaught crash, not a silently-missed diagnostic: ``` com.google.common.base.VerifyException: <anonymous com.uber.Test.Wrapper<java.lang.String>.Fn<java.lang.String>> is not assignable to com.uber.Test.Wrapper<P>.Fn<java.lang.String> at com.google.common.base.Verify.verify(Verify.java:411) at com.uber.nullaway.generics.GenericsChecks.getTypeForSymbol(GenericsChecks.java:2472) at com.uber.nullaway.generics.GenericsChecks.getGenericMethodReturnTypeNullness(GenericsChecks.java:2447) at com.uber.nullaway.NullAway.overriddenMethodReturnsNonNull(NullAway.java:1339) ``` `GenericsChecks.getTreeType`'s `NewClassTree` handling only ever consulted `newClassTree.getIdentifier()` (`Fn<String>`) via `PreservedAnnotationTreeVisitor`, never `newClassTree.getEnclosingExpression()` (the qualifier `this.new Wrapper<@nullable String>()`). `PreservedAnnotationTreeVisitor.visitParameterizedType` built the enclosing type from `baseType.getEnclosingType()` — `Fn`'s *statically-declared* enclosing type, `Wrapper<P>`, with the raw, unsubstituted type variable `P` still present, completely unconnected to what the qualifier expression actually evaluates to. This is a materially different (and worse) bug than "annotations get dropped" — the enclosing type was never resolved to any real instantiation at all. `getTypeForSymbol`'s own sanity-check `verify()` correctly caught the resulting type mismatch and threw. This gap was left open deliberately by #837 ("JSpecify: initial handling of generic enclosing types for inner classes"), whose commit message states it fixed the enclosing-type case for ordinary declared types but explicitly did not yet handle `NewClassTree`s. ## Fix Adds `GenericsChecks.withEnclosingTypeFromQualifier`, called from `getTreeType`'s `NewClassTree` branch. It reads `newClassTree.getEnclosingExpression()`; if present, it recursively calls the existing `getTreeType` on that qualifier to get its own correctly-substituted, annotated type (this recursion is bounded by the qualifier-chain depth in the source, so arbitrarily deep nesting is handled for free with no new logic), then splices that in as the enclosing type via `TypeMetadataBuilder.createClassType`, replacing the broken `baseType.getEnclosingType()` result. If there's no qualifying expression (the ordinary, unqualified anonymous-class case #808 already handles correctly), the type is returned unchanged. This is separate from, and does not touch, the diamond-operator anonymous-class gap tracked in #1475 (a distinct, early-bailout branch in the same method). Fixes #836 ## Testing - Ran `overrideAnonymousNestedClass` with `@Ignore` removed *before* writing any fix, to confirm the actual failure mode (the crash above) rather than assume it from the issue text. - With the fix in place, ran `overrideAnonymousNestedClass` again: passes, no crash, expected diagnostic reported. - Added `overrideAnonymousDeeplyNestedClass`, a 3-level-deep qualified-nesting case (`Wrapper.Middle.Fn`), to confirm the recursive approach generalizes beyond the 2-level case in the original test. - Negative control: temporarily disabled the new logic two different ways (short-circuiting the call site, and forcing `getEnclosingExpression()` to `null` inside the helper) and reran both tests — both failed (reproducing the original crash) without the fix, confirming they're load-bearing rather than passing vacuously. Reverted both before finalizing. - `./gradlew :nullaway:test` (full module suite): 914 tests, 0 failures, 0 errors. - `./gradlew :nullaway:spotlessJavaCheck`. ## AI usage disclosure > I used Claude Code for this PR. I asked it to scope the issue, which involved parallel research into how NullAway resolves types for anonymous classes and what the prior partial fix (#837) had and hadn't addressed; I reviewed those findings before agreeing to proceed. Before writing any fix, Claude ran the ignored test to confirm the actual failure mode rather than relying on the issue title, which surfaced that this is an uncaught crash rather than a silently-missed diagnostic. Claude then implemented the fix and wrote the additional test coverage, including a negative-control check (temporarily disabling the fix to confirm the new tests actually fail without it). I reviewed the resulting diff and asked follow-up questions to confirm my own understanding of the change, including what `TYPE_METADATA_BUILDER.createClassType` returns and whether the recursive call in `withEnclosingTypeFromQualifier` risks a stack overflow on deeply nested qualifiers (it doesn't: the recursion is bounded by the qualifier-chain depth in the source, which is small in any realistic code). I have read and understood all the changes in this PR. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved nullability analysis for qualified inner-class constructor expressions, preserving inferred type annotations in generic contexts. * Correctly handles nullability compatibility for anonymous classes nested within generic and deeply nested types. * **Tests** * Enabled coverage for anonymous nested-class overrides. * Added test coverage for deeply nested generic anonymous classes and nullable versus non-null parameters. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This completes a task lingering from #755, which did not handle overriding in anonymous classes. This case is slightly tricky as javac does not preserve annotations on type arguments in the types it computes for anonymous classes. To fix, we pass a
Symbolwhere we were passing aTypein a couple places, as then we can callSymbol.isAnonymous()to check for an anonymous type. In such a case, we try to get the type from the enclosingNewClassTreeof the overriding method. Note that this PR still does not handle anonymous classes that use the diamond operator; we add a test to show the gaps.