Skip to content

Model the implicit close() of try-with-resources - #358

Open
CatarinaGamboa wants to merge 1 commit into
fix/compliance-levelfrom
fix/334-twr-close
Open

CatarinaGamboa wants to merge 1 commit into
fix/compliance-levelfrom
fix/334-twr-close

Conversation

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator

Fixes #334. Stacked on #352 (compliance level 17, needed to parse try (r)); retarget to main once #352 merges.

Problem

The close() Java inserts at the end of a try-with-resources block was never checked, so a double close or a use after the block passed verification.

Change

RefinementTypeChecker#visitCtTryWithResource scans resources → body → a synthesized r.close() per resource (reverse declaration order, as Java does) → catchers → finally. The close goes through the normal invocation check, so it works for both @StateRefinement classes and external refinements.

Errors are reported at the resource declaration (Res r = new Res()). For a Java 9 resource reference they're reported at the try (r) header.

Spoon workaround: Spoon 10.4.2 models try (r) as an implicit copy of r's declaration, initializer included. It is also repeated once per earlier local named r in the file, so try (r) can yield [r, r, r]. Scanning those would re-run new Res() and reset the state, so implicit resources are not scanned and are closed once per name.

Tests

mvn test: 369/369 pass.

🤖 Generated with Claude Code

Check `r.close()` for each resource when the try body ends, in reverse
declaration order and before catch/finally, so typestate errors from the
implicit close (double close, use after the block) are reported.

Java 9 resource references (`try (r)`) are modelled by Spoon 10.4.2 as an
implicit copy of r's declaration (initializer included), repeated once per
earlier local with the same name; these are not scanned and closed once.

Fixes #334

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

1 participant