Hacktoberfest 2026: los issues que los mantenedores marcaron para octubre, abiertos y aptos para principiantes. Explorar issues de Hacktoberfest

IfElseIfConstructToSwitch drops leading comments inside single-statement blocks and creates 2-case switches (SonarQube S1301)

Abierto Apto para principiantes
#1,305 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
68/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
java
Área
backend

Línea de trabajo

Lee IfElseIfConstructToSwitch.java, especialmente getStatement, y la reproducción en IfElseIfConstructToSwitchTest.java. Empieza por comprobar cómo se adjuntan los comentarios iniciales a la única sentencia de un bloque y cómo la conversión gestiona las dos comprobaciones de patrones más el fallback indicados. Añade cobertura de regresión para ambos comportamientos; se considerará terminado cuando se conserven los comentarios y el switch resultante evite el problema indicado con el umbral de dos case.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug

I checked out all relevant OpenRewrite repo's, fed the AI with existing recipe name and a very careful description. Antigravity with Vertex / Gemini was then tasked to check and test. .Also to create a ticket for it, using your default template. The result is shown beneath.

What version of OpenRewrite are you using?

  • OpenRewrite v8.30.0
  • rewrite-maven-plugin:6.50.0
  • Java 25

How are you running OpenRewrite?

I am using the Maven plugin on a multi-module Java 21+ project:

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

When an if-else-if-else construct contains inline comments preceding single statements inside { ... } blocks:

class Test {
    void draw(Object cell) {
        if (cell instanceof FirstType first) {
            // First type cell description.
            render(first);
        } else if (cell instanceof SecondType second) {
            // Second type cell description.
            render(second);
        } else {
            throw new IllegalStateException("Unknown: " + cell.getClass().getName());
        }
    }
    void render(Object o) {}
}

Or as an OpenRewrite unit test in IfElseIfConstructToSwitchTest.java:

@Test
void preserveSingleStatementBranchLeadingComment() {
    rewriteRun(
      //language=java
      java(
        """
          class Test {
              void draw(Object cell) {
                  if (cell instanceof FirstType first) {
                      // First type cell description.
                      render(first);
                  } else if (cell instanceof SecondType second) {
                      // Second type cell description.
                      render(second);
                  } else {
                      throw new IllegalStateException("Unknown: " + cell.getClass().getName());
                  }
              }
              void render(Object o) {}
          }
          """,
        """
          class Test {
              void draw(Object cell) {
                  switch (cell) {
                      case FirstType first -> {
                          // First type cell description.
                          render(first);
                      }
                      case SecondType second -> {
                          // Second type cell description.
                          render(second);
                      }
                      case null, default -> throw new IllegalStateException("Unknown: " + cell.getClass().getName());
                  }
              }
              void render(Object o) {}
          }
          """
      )
    );
}

What did you expect to see?

Comments placed above statements inside { ... } should be preserved (by keeping the block { ... } if unwrapping would lose comments):

class Test {
    void draw(Object cell) {
        switch (cell) {
            case FirstType first -> {
                // First type cell description.
                render(first);
            }
            case SecondType second -> {
                // Second type cell description.
                render(second);
            }
            case null, default -> throw new IllegalStateException("Unknown: " + cell.getClass().getName());
        }
    }
    void render(Object o) {}
}

(Additionally: hasLastElseBlock should not count toward the minimum 3 cases threshold, as converting 2 pattern checks + fallback else results in a 2-case switch triggering SonarQube/Checkstyle java:S1301).

What did you see instead?

The single-statement block { ... } is unwrapped and all inline comments are permanently deleted:

class Test {
    void draw(Object cell) {
        switch (cell) {
            case FirstType first -> render(first);
            case SecondType second -> render(second);
            case null, default -> throw new IllegalStateException("Unknown: " + cell.getClass().getName());
        }
    }
    void render(Object o) {}
}
Root Cause

In IfElseIfConstructToSwitch.java:

private Statement getStatement(Statement statement) {
    if (statement instanceof J.Block && ((J.Block) statement).getStatements().size() == 1) {
        Statement firstStatement = ((J.Block) statement).getStatements().get(0);
        if ((firstStatement instanceof Expression || firstStatement instanceof J.Throw) &&
                firstStatement.getComments().isEmpty() &&
                statement.getComments().isEmpty() &&
                ((J.Block) statement).getEnd().getComments().isEmpty()) {
            return firstStatement;
        }
    }
    return statement;
}

Leading comments inside the block are attached to firstStatement.getPrefix().getComments(). Because firstStatement.getPrefix().getComments().isEmpty() is not checked, getStatement() unwraps the block and discards the comments.

What is the full stack trace of any errors you encountered?

N/A (No runtime exception thrown — this is silent comment loss during AST transformation).

Are you interested in contributing a fix to OpenRewrite?

Yes, I have already reproduced the issue, added a unit test, and verified the fix locally:

diff --git a/src/main/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitch.java b/src/main/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitch.java
--- a/src/main/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitch.java
+++ b/src/main/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitch.java
@@ -347,6 +347,7 @@ public class IfElseIfConstructToSwitch extends Recipe {
             if (statement instanceof J.Block && ((J.Block) statement).getStatements().size() == 1) {
                 Statement firstStatement = ((J.Block) statement).getStatements().get(0);
                 if ((firstStatement instanceof Expression || firstStatement instanceof J.Throw) &&
+                        firstStatement.getPrefix().getComments().isEmpty() &&
                         firstStatement.getComments().isEmpty() &&
                         statement.getComments().isEmpty() &&
                         ((J.Block) statement).getEnd().getComments().isEmpty()) {
Lenguaje dominante
Java
Estrellas
160
Forks
133
Merge medio
7 h 49 min
PR fusionados (30 d)
60

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openrewrite/rewrite-migrate-java

Todos los issues de openrewrite/rewrite-migrate-java

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.