Repository navigation
[java] Fix #5159: UnusedAssignment: an assert statement may not run - #7104
Merged
Merged
Conversation
Assertions are disabled by default, so the dataflow pass must not treat an assert as always evaluated. Visit its condition and detail message in a forked state and join it with the state before the statement. Fixes pmd#5159
Contributor
|
Compared to main: (comment created at 2026-09-25 20:44:52+00:00 for b082d30) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
UnusedAssignmentassumed that anassertstatement always runs, so an assignment made inside one was treated as always overwriting the variable. Assertions are disabled by default at runtime, and #5159 shows the idiom that depends on it:Here the rule reported
falseas never used, although it is exactly the value read when assertions are off.DataflowPasshad no case forASTAssertStatement, so the default child-by-child visit applied. This adds one: the condition and the detail message are visited in a forked state, which is then joined with the state before the statement, the same way anifwithoutelseis handled. Reads inside the assert are still recorded as usages, so nothing that was used before becomes unused.Tests
Three cases in
UnusedAssignment.xml:assert n > 0 : reason = "negative";), which only runs when the assertion is enabled and fails: no violation for the initializer;assert: still reported, so the assert does not hide real dead stores.Without the change the first two fail (
Expected 0 problem(s), 1 problem(s) found). With it,UnusedAssignmentTest,UnusedLocalVariableTest,ImmutableFieldTestandSingularFieldTest(the rules built onDataflowPass) pass: 353 tests, 0 failures.Related issues
Ready?
./mvnw clean verifypasses (checked automatically by github actions)