IfElseIfConstructToSwitch drops leading comments inside single-statement blocks and creates 2-case switches (SonarQube S1301)
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
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
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
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de openrewrite/rewrite-migrate-java
-
bug
Dificultad 3/5 1-2 días Aptitud para principiantes 72/100
openrewrite/rewrite-migrate-java#1319 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 3/5 1-2 días Aptitud para principiantes 55/100
openrewrite/rewrite-migrate-java#1314 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 3/5 1-2 días Aptitud para principiantes 55/100
openrewrite/rewrite-migrate-java#1310 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 4/5 3-5 días Aptitud para principiantes 55/100
openrewrite/rewrite-migrate-java#1307 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 55/100
openrewrite/rewrite-migrate-java#1304 ·
Los mantenedores suelen responder en 1 día
Todos los issues de openrewrite/rewrite-migrate-java
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
2026 Error Report
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
triplea-game/triplea#15096 ·
Los mantenedores suelen responder en 1 día
-
[Bug][API] Switching workflow versions leaves schedules onlinePosiblemente ocupada @zhuangchong la tomó hoy. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
apache/dolphinscheduler#18731 ·
Los mantenedores suelen responder en 1 día
-
Implement JDBC Domain Enums (`SqlCategory`, `SqlExecutionStatus`, `SqlExecutionType`) in Core ModuleAbiertocore-module enhancement good first issue
Dificultad 1/5 1-3 horas Aptitud para principiantes 87/100
sdlc-pro/spring-lens#531 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
apache/rocketmq-dashboard#7340 ·
Los mantenedores suelen responder en 3 días