rewrite-migrate-java
rewrite-migrate-java copied to clipboard
UseVarForGenericMethodInvocations 'mvn rewrite:run' crash
What version of OpenRewrite are you using?
Latest 3.4.0
What is the smallest, simplest way to reproduce the problem?
@Test
public void useVarBug() {
rewriteRun(
spec -> spec.recipe(new UseVarForGenericMethodInvocations()),
version(
//language=java
java(
"""
import java.util.Optional;
class A {
<T extends Number> void test(T element) {
Optional<T> o = Optional.of(element);
}
}
""",
"""
import java.util.Optional;
class A {
<T extends Number> void test(T element) {
var o = Optional.of(element);
}
}
"""), 17));
}
What did you expect to see?
Replace variable with var
What did you see instead?
It crashes.
What is the full stack trace of any errors you encountered?
org.openrewrite.internal.RecipeRunException: java.lang.IllegalArgumentException: Expected a template that would generate exactly one statement to replace one statement, but generated 2. Template:
var o = __P__.<java.util.Optional<T extends java.lang.Number>>/*__p1__*/p()
Substitutions:
Substitutions(code=var #{} = #{any()}, parameters=[o, Optional.of(element)], propertyPlaceholderHelper=org.openrewrite.internal.PropertyPlaceholderHelper@3ee0b4f7)
Statement:
Optional<T> o = Optional.of(element)
Are you interested in contributing a fix to OpenRewrite
I think there are 2 issues here.
In the JavaTemplate implementation:
var o = __P__.<java.util.Optional<T extends java.lang.Number>>/*__p1__*/p()
should be
var o = __P__.<java.util.Optional<T>>/*__p1__*/p()
and this would work by making the template in UseVarForGenericMethodInvocations context sensitive.
But maybe, for this recipe, it would be best to do the "transformation" by hand, instead of using JavaTemplate?
Ideally the template could remain context-free. Possibly we could add generics support by detecting that the type of the second template parameter (the variable initializer) uses generics and then instead of generating a class like:
class Template {
// ...
}
we would generate:
class Template<T extends java.lang.Number> {
// ...
}
So maybe there are cases for context-free templates when generics can be supported transparently?