Skip to content

InstanceOfPatternMatch does not always handle generics correctly #482

Description

@cortlepp

What version of OpenRewrite are you using?

I am using

  • Maven plugin v6.3.2
  • rewrite-migrate-java v3.4.0

How are you running OpenRewrite?

I am using the Maven plugin, and my project is a single module project.

<plugin>
    <groupId>org.openrewrite.maven</groupId>
    <artifactId>rewrite-maven-plugin</artifactId>
    <version>6.3.2</version>
    <configuration>
        <exportDatatables>true</exportDatatables>
        <activeRecipes>
            <recipe>org.openrewrite.staticanalysis.InstanceOfPatternMatch</recipe>
        </activeRecipes>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.openrewrite.recipe</groupId>
            <artifactId>rewrite-migrate-java</artifactId>
            <version>3.4.0</version>
        </dependency>
    </dependencies>
</plugin>

What is the smallest, simplest way to reproduce the problem?

package org.example;

public class Main {
    public class Bar<T> {}
    public static void main(String[] args) {
        Object o = new Object();
        if (o instanceof Bar) {
            @SuppressWarnings("unsafe")
            Bar<String> barString = (Bar) o;
            System.out.println(barString);
        }
    }
}

What did you expect to see?

package org.example;

public class Main {
    public class Bar<T> {}
    public static void main(String[] args) {
        Object o = new Object();
        if (o instanceof Bar barString) {
            System.out.println(barString);
        }
    }
}

Note: casting to Bar<?> would not be correct in all cases, even if it would work in this one.

What did you see instead?

package org.example;

public class Main {
    public class Bar<T> {}
    public static void main(String[] args) {
        Object o = new Object();
        if (o instanceof Bar<String> barString) {
            System.out.println(barString);
        }
    }
}

What is the full stack trace of any errors you encountered?

The migration succeeds, but if you try to compile the changes afterwards javac fails with

java.lang.Object cannot be safely cast to org.example.Main.Bar<java.lang.String>

Are you interested in contributing a fix to OpenRewrite?

If I manage to do so with reasonable effort, yes.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Fields

No fields configured for issues without a type.

Projects

Status
Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions