Skip to content

UseVarForGenericMethodInvocations 'mvn rewrite:run' crash #698

@fmodesto

Description

@fmodesto

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions