[java] Fix #6328: UnusedLocalVariable should consider pattern variable in for-each without curly braces #6344
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Describe the PR
This PR fixes a false positive in the
UnusedLocalVariablerule where pattern variables declared viainstanceofare incorrectly reported as unused when they appear inside anifstatement that is the direct child of afor-eachloop without braces.The Root Cause
In
SymbolTableResolver, theASTForeachStatementwas previously handled by the outerMyVisitorclass. When afor-eachloop omits braces, its body (e.g., anASTIfStatement) 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 innerStatementVisitor.Consequently, the pattern variable
sinif (o instanceof String s)was never registered in the symbol table when nested directly under aforeachbecause theIfStatementwas visited byMyVisitor, which lacks the pattern-matching awareness ofStatementVisitor.The Fix
I moved the
visit(ASTForeachStatement)logic fromMyVisitortoStatementVisitor. This ensures that the loop body is always visited with a visitor capable of handling pattern bindings, aligning the behavior with howwhileand standardforloops are already implemented in PMD 7.Related issues
Ready?
./mvnw clean verifypasses (checked automatically by github actions)