Skip to content

Properly check generic method overriding in explicitly-typed anonymous classes - #808

Merged
msridhar merged 94 commits into
apache:masterfrom
msridhar:override-anonymous-class-checking
Sep 29, 2023
Merged

msridhar merged 94 commits into
apache:masterfrom
msridhar:override-anonymous-class-checking

Conversation

@msridhar

Copy link
Copy Markdown
Contributor

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 Symbol where we were passing a Type in a couple places, as then we can call Symbol.isAnonymous() to check for an anonymous type. In such a case, we try to get the type from the enclosing NewClassTree of 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.

@msridhar msridhar added the jspecify Related to support for jspecify standard (see jspecify.dev) label Aug 18, 2023
@msridhar
msridhar requested a review from lazaroclapp August 18, 2023 14:32

@lazaroclapp lazaroclapp 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.

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; }",

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (newClassTree == null) {
throw new RuntimeException(
"method should be inside a NewClassTree " + state.getSourceForNode(path.getLeaf()));
}

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.

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?

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.

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() {...}?

@msridhar msridhar Sep 29, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

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 even new 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?

@codecov

codecov Bot commented Sep 1, 2023 •

Copy link
Copy Markdown

Codecov Report

Attention: 3 lines in your changes are missing coverage. Please review.

Comparison is base (7d8cd4a) 86.79% compared to head (26085c4) 86.75%.

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     
Files Coverage Δ
...away/src/main/java/com/uber/nullaway/NullAway.java 89.68% <100.00%> (ø)
...rc/main/java/com/uber/nullaway/GenericsChecks.java 89.65% <86.36%> (-0.32%) ⬇️

... and 2 files with indirect coverage changes

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@msridhar

Copy link
Copy Markdown
Contributor Author

@lazaroclapp I finally got around to addressing your feedback here; sorry for the long delay.

@lazaroclapp lazaroclapp 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.

See minor comment above, but otherwise SGTM!

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.

Let's create and link an issue!

@msridhar
msridhar enabled auto-merge (squash) September 29, 2023 04:47
@msridhar
msridhar merged commit b64d1c1 into apache:master Sep 29, 2023
@msridhar
msridhar deleted the override-anonymous-class-checking branch September 29, 2023 04:56
msridhar pushed a commit that referenced this pull request Aug 13, 2026
…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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jspecify Related to support for jspecify standard (see jspecify.dev)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants