Skip to content

Conversation

@mdhamed238
Copy link
Contributor

Describe the PR

This PR fixes a false positive in the UnusedLocalVariable rule where pattern variables declared via instanceof are incorrectly reported as unused when they appear inside an if statement that is the direct child of a for-each loop without braces.

The Root Cause

In SymbolTableResolver, the ASTForeachStatement was previously handled by the outer MyVisitor class. When a for-each loop omits braces, its body (e.g., an ASTIfStatement) is visited using the outer visitor's context. However, the logic for extracting and pushing pattern variable bindings (flow-sensitive scoping) is implemented only within the inner StatementVisitor.

Consequently, the pattern variable s in if (o instanceof String s) was never registered in the symbol table when nested directly under a foreach because the IfStatement was visited by MyVisitor, which lacks the pattern-matching awareness of StatementVisitor.

The Fix

I moved the visit(ASTForeachStatement) logic from MyVisitor to StatementVisitor. This ensures that the loop body is always visited with a visitor capable of handling pattern bindings, aligning the behavior with how while and standard for loops are already implemented in PMD 7.

Related issues

Ready?

  • Added unit tests for fixed bug/feature
  • Passing all unit tests
  • Complete build ./mvnw clean verify passes (checked automatically by github actions)
  • Added (in-code) documentation (if needed)

@adangel adangel changed the title Fix issue 6328 [java] Fix #6328: UnusedLocalVariable Dec 21, 2025
@pmd-actions-helper
Copy link
Contributor

Documentation Preview

Compared to main:
This changeset changes 0 violations,
introduces 0 new violations, 0 new errors and 0 new configuration errors,
removes 0 violations, 0 errors and 0 configuration errors.

Regression Tester Report

(comment created at 2025-12-21 18:57:14+00:00 for 5cd9580)

@adangel adangel changed the title [java] Fix #6328: UnusedLocalVariable [java] Fix #6328: UnusedLocalVariable should consider pattern variable in for-each without curly braces Dec 24, 2025
@adangel adangel added this to the 7.20.0 milestone Dec 24, 2025
Copy link
Member

@adangel adangel left a comment

Choose a reason for hiding this comment

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

Thanks!

@adangel adangel merged commit cf7871e into pmd:main Dec 24, 2025
12 checks passed
@oowekyala oowekyala self-assigned this Dec 24, 2025
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.

[java] UnusedLocalVariable: False positive for pattern variable in for-each without braces

3 participants