Skip to content

NullCheckAsSwitchCase adds null case to non-complete switch expression #786

@protocol7

Description

@protocol7

What version of OpenRewrite are you using?

  • org.openrewrite:rewrite-core:8.56.1
  • org.openrewrite.recipe:rewrite-migrate-java:3.12.0

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

When a switch expression does not cover all possible values, null check can not be added to it.

  @Test
  public void nullInSwitchNotAllPossibleInput() {
    rewriteRun(
        spec -> spec.recipe(new NullCheckAsSwitchCase()),
        java(
            """
            package com.helloworld;

            import java.time.DayOfWeek;

            public class Foo {
              public void foo() {}
            
              public void bar(DayOfWeek day) {
                if (day == null) {
                  throw new RuntimeException("");
                }
            
                switch (day) {
                  case MONDAY -> foo(); // do something
                }
              }
            }
            """));
  }
org.opentest4j.AssertionFailedError: [Expected recipe to complete in 0 cycles, but took at least one more cycle. Between the last two executed cycles there were changes to "com/helloworld/Foo.java"]
expected:
  "package com.helloworld;

  import java.time.DayOfWeek;

  public class Foo {
    public void foo() {}

    public void bar(DayOfWeek day) {
      if (day == null) {
        throw new RuntimeException("");
      }

      switch (day) {
        case MONDAY -> foo(); // do something
      }
    }
  }"
 but was:
  "package com.helloworld;

  import java.time.DayOfWeek;

  public class Foo {
    public void foo() {}

    public void bar(DayOfWeek day) {

      switch (day) {
            case null -> throw new RuntimeException("");
        case MONDAY -> foo(); // do something
      }
    }
  }"
	at org.openrewrite.test.LargeSourceSetCheckingExpectedCycles.afterCycle(LargeSourceSetCheckingExpectedCycles.java:97)
	at org.openrewrite.RecipeScheduler.runRecipeCycles(RecipeScheduler.java:95)
	at org.openrewrite.RecipeScheduler.scheduleRun(RecipeScheduler.java:41)
	at org.openrewrite.Recipe.run(Recipe.java:441)
	at org.openrewrite.test.RewriteTest.rewriteRun(RewriteTest.java:377)
	at org.openrewrite.test.RewriteTest.rewriteRun(RewriteTest.java:130)

With the recipe output, compilation will fail with error: the switch statement does not cover all possible input values.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions