Skip to content

Improve handling and error messages when using this inside an anonymous class - #1305

Merged
msridhar merged 5 commits into
masterfrom
issue-1202
Oct 4, 2025
Merged

msridhar merged 5 commits into
masterfrom
issue-1202

Conversation

@msridhar

@msridhar msridhar commented Oct 3, 2025 •

Copy link
Copy Markdown
Collaborator

Fixes #1202

We add correct handling for the case where the (generic) anonymous class has explicit type arguments, and a clearer error message for cases where the diamond operator is used (which we still don't handle fully). We had to pass in the VisitorState to the getTreeType function, necessitating a bunch of small changes.

Summary by CodeRabbit

  • Bug Fixes

    • Correctly handles anonymous-class types in type formatting.
    • Preserves type-use annotations during generic type resolution, reducing false positives.
    • Improved handling of “this” inside anonymous classes.
    • More reliable nullability inference across assignments, method calls, and conditional expressions.
  • Tests

    • Added tests covering anonymous-class usage with explicit type parameters.
    • Added tests for anonymous classes using the diamond operator.

@coderabbitai

coderabbitai Bot commented Oct 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds an anonymous-class early-return in generic-type pretty printing and threads VisitorState through GenericsChecks’ type-extraction and inference code, including special handling for IdentifierTree "this" in anonymous classes. Adds two jspecify tests for anonymous-class this usage and diamond operator inference.

Changes

Cohort / File(s) Summary
Pretty-printing for anonymous types
nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java
Adds an early-return branch in visitClassType that returns t.toString() when t.isAnonymous() to bypass further pretty-printing.
State-aware type extraction and inference
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
Refactors getTreeType to accept VisitorState and propagates state through many inference/constraint methods (assignment, parameter, call inference). Adds special-case handling for IdentifierTree named "this" inside anonymous classes to derive the enclosing anonymous class type; updates numerous call sites to pass state.
Tests for anonymous classes and diamonds
nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java
Adds two tests: thisUsageInAnonymousClass() and thisUsageInAnonymousClassWithDiamonds() to exercise anonymous-class this type resolution and diamond-operator inference with nullability checks.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant GC as GenericsChecks
  participant GT as getTreeType(tree, state)
  participant Sym as Symbol/ASTHelpers
  participant PP as GenericTypePrettyPrintingVisitor

  GC->>GT: resolve type for a tree (passes VisitorState)
  alt tree is Identifier "this" inside anonymous class
    GT->>Sym: derive enclosing anonymous class type via symbol.owner/enclosing
    Sym-->>GT: annotated anonymous-class Type
  else other tree kinds
    GT->>Sym: fallback to ASTHelpers.getType(tree) or symbol.type
    Sym-->>GT: Type (may include annotations)
  end
  GT-->>GC: return resolved Type (state-aware)
  GC->>GC: generate constraints / infer generics (state threaded)
  GC->>PP: request pretty-print of type for diagnostics
  alt type.isAnonymous()
    PP-->>GC: return t.toString() (early return)
  else
    PP-->>GC: return pretty-printed type
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60–90 minutes

Possibly related PRs

Suggested reviewers

  • yuxincs
  • lazaroclapp

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.57% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly captures the main change of improving how this inside an anonymous class is handled and reported, matching the PR’s focus on handling and error messages for that scenario.
Linked Issues Check ✅ Passed The changes implement the required handling for this in anonymous inner classes by deriving the correct anonymous class type with state-aware getTreeType, adjust pretty-printing via the visitor early-return, and add tests for explicit and diamond generic cases, thus fully addressing the coding requirements of issue #1202.
Out of Scope Changes Check ✅ Passed All modifications, including state propagation in getTreeType, the pretty-print visitor adjustment, and corresponding tests, directly support the issue’s goal of correct type reporting and error messages for this in anonymous classes and do not introduce unrelated changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch issue-1202

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7d5bc3 and 64cbc33.

📒 Files selected for processing (1)
  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (17 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-28T04:54:20.953Z
Learnt from: msridhar
PR: uber/NullAway#1248
File: nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java:847-857
Timestamp: 2025-08-28T04:54:20.953Z
Learning: In NullAway's GenericsChecks.java, NewClassTree support for explicit type argument substitution requires more extensive changes beyond just modifying the conditional in compareGenericTypeParameterNullabilityForCall. The maintainers prefer to handle NewClassTree support in a separate follow-up rather than expanding the scope of PRs focused on specific issues like super constructor calls.

Applied to files:

  • nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build caffeine with snapshot
  • GitHub Check: Build and test on macos-latest
  • GitHub Check: Build and test on ubuntu-latest
  • GitHub Check: Build spring-framework with snapshot
  • GitHub Check: Build and test on windows-latest
🔇 Additional comments (5)
nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java (5)

410-410: LGTM! Method signature enhanced to support state-aware type resolution.

Adding the VisitorState parameter enables preservation of type-use annotations in more scenarios, which is essential for fixing the issue with error messages for anonymous classes.


431-447: Correctly resolves this in anonymous classes.

This logic properly handles the case where this is used inside an anonymous class by walking up the symbol hierarchy (symbol → owner → enclosing class → type). This directly addresses issue #1202 where error messages were showing incorrect type names.

The null-safety checks and fallback to symbol.type ensure defensive handling of edge cases.


484-484: LGTM! Comprehensive threading of state parameter through call sites.

All call sites to getTreeType have been consistently updated to pass the VisitorState parameter. This ensures state-aware type resolution throughout the codebase, enabling proper preservation of type-use annotations in various contexts including:

  • Assignment checking
  • Parameter validation
  • Return type checking
  • Conditional expressions
  • Method invocations
  • Override checking

Also applies to: 506-506, 610-610, 683-683, 700-700, 705-705, 716-717, 719-719, 793-793, 893-894, 923-923, 925-925, 962-962, 1061-1061, 1259-1259, 1327-1327, 1330-1330, 1430-1430, 1437-1437, 1523-1523


682-683: LGTM! Constraint generation methods updated to accept state.

The addition of VisitorState state as the first parameter to generateConstraintsForCall and generateConstraintsForParam enables proper threading of state through the constraint generation logic for type inference.

Also applies to: 704-705


1326-1327: LGTM! Assignment inference updated to use state-aware type resolution.

The addition of the VisitorState parameter enables proper type resolution with preserved annotations in assignment contexts, consistent with the overall threading of state through the codebase.

Also applies to: 1330-1330


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 and usage tips.

@msridhar

msridhar commented Oct 3, 2025

Copy link
Copy Markdown
Collaborator Author

@coderabbitai configuration

@coderabbitai

coderabbitai Bot commented Oct 3, 2025

Copy link
Copy Markdown
Contributor
CodeRabbit configuration
language: en-US
tone_instructions: ''
early_access: false
enable_free_tier: true
reviews:
  profile: chill
  request_changes_workflow: false
  high_level_summary: true
  high_level_summary_placeholder: '@coderabbitai summary'
  high_level_summary_in_walkthrough: false
  auto_title_placeholder: '@coderabbitai'
  auto_title_instructions: ''
  review_status: true
  commit_status: true
  fail_commit_status: false
  collapse_walkthrough: false
  changed_files_summary: true
  sequence_diagrams: true
  estimate_code_review_effort: true
  assess_linked_issues: true
  related_issues: true
  related_prs: true
  suggested_labels: true
  auto_apply_labels: false
  suggested_reviewers: true
  auto_assign_reviewers: false
  in_progress_fortune: true
  poem: false
  labeling_instructions: []
  path_filters: []
  path_instructions: []
  abort_on_close: true
  disable_cache: false
  auto_review:
    enabled: true
    auto_incremental_review: true
    ignore_title_keywords: []
    labels: []
    drafts: false
    base_branches: []
    ignore_usernames: []
  finishing_touches:
    docstrings:
      enabled: true
    unit_tests:
      enabled: true
  pre_merge_checks:
    docstrings:
      mode: warning
      threshold: 80
    title:
      mode: warning
      requirements: ''
    description:
      mode: warning
    issue_assessment:
      mode: warning
    custom_checks: []
  tools:
    ast-grep:
      rule_dirs: []
      util_dirs: []
      essential_rules: true
      packages: []
    shellcheck:
      enabled: true
    ruff:
      enabled: true
    markdownlint:
      enabled: true
    github-checks:
      enabled: true
      timeout_ms: 90000
    languagetool:
      enabled: true
      enabled_rules: []
      disabled_rules: []
      enabled_categories: []
      disabled_categories: []
      enabled_only: false
      level: default
    biome:
      enabled: true
    hadolint:
      enabled: true
    swiftlint:
      enabled: true
    phpstan:
      enabled: true
      level: default
    phpmd:
      enabled: true
    phpcs:
      enabled: true
    golangci-lint:
      enabled: true
    yamllint:
      enabled: true
    gitleaks:
      enabled: true
    checkov:
      enabled: true
    detekt:
      enabled: true
    eslint:
      enabled: true
    flake8:
      enabled: true
    rubocop:
      enabled: true
    buf:
      enabled: true
    regal:
      enabled: true
    actionlint:
      enabled: true
    pmd:
      enabled: true
    cppcheck:
      enabled: true
    semgrep:
      enabled: true
    circleci:
      enabled: true
    clippy:
      enabled: true
    sqlfluff:
      enabled: true
    prismaLint:
      enabled: true
    pylint:
      enabled: true
    oxc:
      enabled: true
    shopifyThemeCheck:
      enabled: true
    luacheck:
      enabled: true
    brakeman:
      enabled: true
    dotenvLint:
      enabled: true
    htmlhint:
      enabled: true
    checkmake:
      enabled: true
    osvScanner:
      enabled: true
chat:
  art: true
  auto_reply: true
  integrations:
    jira:
      usage: auto
    linear:
      usage: auto
knowledge_base:
  opt_out: false
  web_search:
    enabled: true
  code_guidelines:
    enabled: true
    filePatterns: []
  learnings:
    scope: auto
  issues:
    scope: auto
  jira:
    usage: auto
    project_keys: []
  linear:
    usage: auto
    team_keys: []
  pull_requests:
    scope: auto
  mcp:
    usage: auto
    disabled_servers: []
code_generation:
  docstrings:
    language: en-US
    path_instructions: []
  unit_tests:
    path_instructions: []

@codecov

codecov Bot commented Oct 3, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.75000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 88.49%. Comparing base (d3726ea) to head (64cbc33).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...ava/com/uber/nullaway/generics/GenericsChecks.java 93.33% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1305      +/-   ##
============================================
- Coverage     88.49%   88.49%   -0.01%     
- Complexity     2476     2479       +3     
============================================
  Files            93       93              
  Lines          8214     8228      +14     
  Branches       1617     1623       +6     
============================================
+ Hits           7269     7281      +12     
  Misses          474      474              
- Partials        471      473       +2     

☔ View full report in Codecov by Sentry.
📢 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.

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

LGTM! :)

@msridhar
msridhar merged commit 24f3675 into master Oct 4, 2025
@msridhar
msridhar deleted the issue-1202 branch October 4, 2025 21:50
subhramit pushed a commit to subhramit/NullAway that referenced this pull request Oct 24, 2026
…argument (uber#2037)

Issue uber#1155 reported two false positives in JSpecify mode. A call on a
`new` expression dropped the `@Nullable` type argument of the class, so
`Inner<@nullable Object> mThing = new Inner<@nullable
Object>().identity();` was reported as an assignment from
`Inner<Object>`. Inside `new Callback<@nullable Integer>() { ... }`,
`Callback<@nullable Integer> self = this;` was reported the same way.
Both now pass: uber#1571 (0.13.6) fixed the call on a `new` expression, and
uber#1305 (0.12.11) fixed `this` in an anonymous class. The test for the
first case, `GenericsTests.callWithConstructorReceiver`, was still
`@Ignore`d.

The `@Ignore` is removed, and the test now also assigns the same call to
`Inner<Object>`, which must be reported, so it fails whether the type
argument is dropped or the call is no longer checked.
`GenericsTests.thisUsageInAnonymousClass` passed `this` only as an
argument; it now also assigns `this` to a local, in the anonymous class
with a `@Nullable` type argument (no error) and in the one without it
(error).

Each case was seen failing with its fix disabled, under `:nullaway:test`
on JDK 21: skipping the receiver substitution for a call on a `new`
expression brings back the reported warning on `mThing`, and skipping
the `this` branch of `getTreeType` brings it back on `self = this`.

Fixes uber#1155

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 generic nullability checks, including
constructor receiver calls and assignments within anonymous-class
callbacks.
* Added checks for both accepted and incompatible assignments involving
nullable callback types.

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

Wrong class name used in error message when "this" is used in an anonymous inner class

2 participants