Skip to content

[java] Fix #6742: CloseResource false positive for a wrapped resource assigned without an initializer - #6918

Merged
UncleOwen merged 5 commits into
pmd:mainfrom
Eljees:fix/closeresource-wrapped-without-initializer-6742
Aug 7, 2026
Merged

UncleOwen merged 5 commits into
pmd:mainfrom
Eljees:fix/closeresource-wrapped-without-initializer-6742

Conversation

@Eljees

@Eljees Eljees commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Fixes #6742

CloseResource recognizes that a resource wrapped by another resource does not need to be closed on
its own — but only when the wrapper is created in the variable's initializer. The runtime-equivalent
split form is flagged:

ObjectOutputStream oout = new ObjectOutputStream(pout);   // no violation
oout.close();

ObjectOutputStream oout;                                  // violation
oout = new ObjectOutputStream(pout);
oout.close();

The whole wrapping decision hangs on var.getInitializer():

private TypeNode getWrappedResourceType(ASTVariableId var) {
    ASTExpression initExpr = initializerExpressionOf(var);   // null for a split declaration
    if (initExpr != null) {
        ASTConstructorCall resAlloc = getLastResourceAllocation(initExpr);
        ...

With an initializer, getWrappedResourceType finds the new ObjectOutputStream(...) call, picks up
pout through getFirstArgumentVariableIfResource, and checkForResources uses that as the effective
type — so shouldVarOfTypeBeClosedInMethod returns false. Without one, the wrapping is simply invisible
and the declared type is used instead.

Per JLS §14.4.2 a local declaration with an initializer is equivalent to a declaration followed by a
separate assignment, so both shapes should reach the same verdict. This adds
initializerOrFirstAssignedValueOf(), which falls back to the value of the variable's first assignment,
and uses it in getWrappedResourceType().

I deliberately left initializerExpressionOf() itself alone: it is also used by
getFirstReassigningStatementBeforeBeingClosed(), which distinguishes initialized from uninitialized
variables on purpose (isNotNullInitialized), and widening it there would change the
"reassigned before being closed" behaviour too. If you would rather have the fallback applied
consistently in both places, say so and I will do that instead.

Before / after

Two cases added to CloseResource.xml — the reporter's snippet in both shapes, with rule defaults:

before:  Tests run: 103, Failures: 1
           [java] CloseResource: plain close, split declaration and assignment (#6742)
           -> Expected 0 problem(s), 1 problem(s) found.
after:   Tests run: 103, Failures: 0, Errors: 0, Skipped: 0
         BUILD SUCCESS

Run with mvn -pl pmd-java test -Dtest=CloseResourceTest on temurin-25. The control case
(declaration with initializer) passes before and after, so the change only affects the split form.

AI-assisted (LLM used for drafting); the change and both runs above are mine.

…rce assigned without an initializer

getWrappedResourceType only looked at the variable initializer, so the split declaration/assignment form did not recognize the wrapping resource and was reported. Per JLS 14.4.2 both shapes are equivalent.

Signed-off-by: Eljees <[email protected]>
@pmd-actions-helper

pmd-actions-helper Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
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, 16 errors and 9 configuration errors.
There are 0 changed duplications, 0 new duplications and 0 removed duplications.
There are 0 changed CPD errors, 0 new CPD errors and 0 removed CPD errors.

Regression Tester Report

(comment created at 2026-08-07 08:36:47+00:00 for 21203b7)

@UncleOwen UncleOwen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please see the notes I left on your tests.

The change itself looks good. Have you thought about the other call to initializerExpressionOf (in getFirstReassigningStatementBeforeBeingClosed)? Does that need to be changed as well? I don't think it does, but would appreciate if you could confirm this.

Both were raised in review. The direct-return case duplicates the existing 'pmd#1011 CloseResource Rule ignores Constructors' test a few hundred lines up, and the nested-block one is not about pmd#2840 at all - neither belongs in a change scoped to pmd#6742. CloseResourceTest: 101 tests, 0 failures.

Signed-off-by: Eljees <[email protected]>
@Eljees

Eljees commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — both notes were right, and your question turned out to have a more interesting answer than "no".

Tests. Dropped both #2840 cases in d404adc: the direct-return one does duplicate #1011 CloseResource Rule ignores Constructors a few hundred lines up (same shape, same expectation), and the nested-block one is, as you say, not about #2840. Neither belongs in a change scoped to #6742. CloseResourceTest is now 101 tests, 0 failures.

The other initializerExpressionOf call. You are right that it does not need to change — and I think it must not. I tried it: substituting initializerOrFirstAssignedValueOf in getFirstReassigningStatementBeforeBeingClosed makes #1011 CloseResource Rule ignores Constructors - closed in finally fail (expected 0 problems, got 1).

The two call sites want different things:

boolean isInitialized = isNotNullInitialized(variable);                    // true when there is no initializer at all
ASTExpression initializingExpression = initializerExpressionOf(variable);  // null in that case
...
if (initializingExpression != null && !inSameIfBlock(...) && ...) return statement;

For a variable declared without an initializer, isNotNullInitialized is already true (there is no null literal to find), so the null coming out of initializerExpressionOf is the only thing keeping that branch quiet. Feed it the first assigned value instead and the branch starts firing on split declarations — it widens REASSIGN_BEFORE_CLOSED rather than narrowing a false positive, which is the opposite direction from this PR.

Put differently: getWrappedResourceType asks "what value does this variable hold", which is where the JLS 14.4.2 equivalence applies, while getFirstReassigningStatementBeforeBeingClosed deliberately treats "declared without an initializer" as "there is no initializer to reassign over". I left it alone.

Runs for the record — same command each time, only the rule file swapped, rule classes forced to recompile:

variant result
this PR 103 tests, 0 failures (101 / 0 after dropping the two tests)
pre-PR rule + this PR's tests 1 failure: the new #6742 split-declaration case (red-first)
this PR + second call site substituted 1 failure: #1011 ... closed in finally

AI-assisted (LLM used for drafting and for running the checks above); the analysis and the runs are mine.

@UncleOwen UncleOwen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks!

@UncleOwen UncleOwen added this to the 7.27.0 milestone Aug 6, 2026
@UncleOwen

Copy link
Copy Markdown
Member

Something seems to be wrong with github actions... https://www.githubstatus.com/

@UncleOwen
UncleOwen merged commit ffc2425 into pmd:main Aug 7, 2026
9 checks passed
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] CloseResource: False positive when a correctly-closed resource is declared without initializer

2 participants