Skip to content

AnnotateNullableMethods might crash with JavaTemplate parsing failure #6520

@greg-at-moderne

Description

@greg-at-moderne

What version of OpenRewrite are you using?

  • OR current main = 6c7992a
  • rewrite-static-analysis current main = f51717c344476a514e5844841a07e597952bc1fb

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

Add:

    @Test
    void anonymousClass() {
        rewriteRun(
          spec -> spec.recipe(toRecipe(() -> new JavaIsoVisitor<>() {
              @Override
              public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration md, ExecutionContext executionContext) {
                  return JavaTemplate.builder("@SuppressWarnings(\"ALL\")")
                    .build()
                    .apply(getCursor(), md.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
              }
          })),
          java(
            """
            import org.jspecify.annotations.NullMarked;

            @NullMarked
            public class A {
                static A a = new A(new Object() {
                    @Override
                    public String toString() {
                        return null;
                    }
                }, "Elvar Fridriksson");
                public A(Object o, String s) {}
            }
            """
          )
        );
    }

to one of the JavaTemplateTest tests.

It fails with:

Caused by: org.openrewrite.internal.RecipeRunException: java.lang.IllegalArgumentException: Could not parse as Java:
import org.jspecify.annotations.NullMarked;
public class A{new A(new Object() {
        @Override
        public String toString() {
            return null;
        }
    }, "Elvar Fridriksson"){new Object(){/*__TEMPLATE_cfcc2025-6662__*/@SuppressWarnings("ALL")
 void $method() {}};};}
@interface $Placeholder {}
	at org.openrewrite.TreeVisitor.visit(TreeVisitor.java:278)
	at org.openrewrite.TreeVisitor.visit(TreeVisitor.java:154)
	at org.openrewrite.java.JavaTemplate.apply(JavaTemplate.java:121)
	at org.openrewrite.java.JavaTemplateTest6Test$13.visitMethodDeclaration(JavaTemplateTest6Test.java:514)

I've also noticed that the test works if there's no second String argument hanging in the subsequent line.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtest providedAlready replicated with a unit test, using JUnit pioneer's ExpectedToFail

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions