rewrite icon indicating copy to clipboard operation
rewrite copied to clipboard

InstanceOfPatternMatch removes try-with-resource variable

Open delanym opened this issue 9 months ago • 6 comments

Given the code

   if (object instanceof JarArtifact) {
      try (JarArtifact a = (JarArtifact) object) {

a rewrite using InstanceOfPatternMatch results in

    if (object instanceof JarArtifact a) {
      try () {

A fix could be to simply remove the parenthesis

    if (object instanceof JarArtifact a) {
      try {

but that may leave the object unclosed, so it should probably be left alone.

delanym avatar May 07 '24 12:05 delanym

Thanks for the report! That would be a bug indeed; we should not make that change when the assignment is in a try-with-resources-try-block. Is this something you'd want to help fix? Even a draft PR with just a unit test added would already help.

timtebeek avatar May 07 '24 13:05 timtebeek

I forget in which Java version this was, but possibly 9, the syntax allows for an expression in try-with-resources and doesn't mandate declaring a new variable. So with an appropriate language version we can leverage that.

knutwannheden avatar May 07 '24 15:05 knutwannheden

Yes 9 https://bugs.openjdk.org/browse/JDK-7196163

delanym avatar May 08 '24 12:05 delanym

@timtebeek I'll have a go at it. How to detect Java source version?

delanym avatar May 08 '24 12:05 delanym

Awesome, thanks for the offer to help! We determine the Java version when we parse the project, and store that in a marker called JavaVersion. A common pattern is to define a Precondition through UsesJavaVersion, to limit when a recipe should apply. https://github.com/openrewrite/rewrite/blob/03c458404073082275a752063887c188d213afbe/rewrite-java/src/main/java/org/openrewrite/java/search/UsesJavaVersion.java#L30

In rare cases we one can also read the marker directly, but use that only when preconditions aren't an option.

timtebeek avatar May 08 '24 12:05 timtebeek

In this particular case we probably don't need anything in addition, as instanceof pattern variables were added in Java 11. So that precondition is already a given.

knutwannheden avatar May 08 '24 12:05 knutwannheden