openrewrite / rewrite

Automated mass refactoring of source code.
https://docs.openrewrite.org
Apache License 2.0
2.19k stars 329 forks source link

Parser error for Java 21 switch expression #4153

Open Bananeweizen opened 6 months ago

Bananeweizen commented 6 months ago

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

    @Test
    void switchCase() {
        rewriteRun(
          java(
            """
              public class A {
                Object reproduce() {
                    Object object = new Object();
                    return switch (object) {
                        case Integer i -> "1";
                        default -> null;
                    };
                }
              }
               """
          )
        );
    }

What did you expect to see?

No changes.

What did you see instead?

The Java formatter wrongly adds "default" to the case statement label.

JavaParserTest > switchCase() FAILED
    org.opentest4j.AssertionFailedError: [When parsing and printing the source code back to text without modifications, the printed source didn't match the original source code. This means there is a bug in the parser implementation itself. Please open an issue to report this, providing a sample of the code that generated this error for "A.java":
    diff --git a/A.java b/A.java
    index 7a1a443..2ab6912 100644
    --- a/A.java
    +++ b/A.java
    @@ -2,7 +2,7 @@
       Object reproduce() {
           Object object = new Object();
           return switch (object) {
    -          case Integer i -> "1";
    +          defaultcase Integer i -> "1";
               default -> null;
           };
       }
    ]
    expected: "public class A {
      Object reproduce() {
          Object object = new Object();
          return switch (object) {
              case Integer i -> "1";
              default -> null;
          };
      }
    }"
     but was: "public class A {
      Object reproduce() {
          Object object = new Object();
          return switch (object) {
              defaultcase Integer i -> "1";
              default -> null;
          };
      }
    }"

Are you interested in contributing a fix to OpenRewrite?

Maybe. Right now I have trouble getting IDEA to compile rewrite, so I can't really debug...

timtebeek commented 6 months ago

Thanks for pointing this out! Indeed our Java 21 parser does not yet support all feature of Java 21, regrettably. Definitely something to improve as Java 21 becomes more mainstream. The test is already helpful, and thanks for the offer to help explore what changes are needed.

Not sure if you'd already seen that we have some detailed set up instructions specifically for openrewrite/rewrite, which might help you here to limit to just the modules you're interested in. Beyond that Slack is perhaps the best source of info for questions around expanding the parser, such that we can loop in folks with more knowledge in a more synchronous fashion.