Hacktoberfest 2026: le issue che i maintainer hanno segnato per ottobre, aperte e adatte ai principianti. Sfoglia le issue Hacktoberfest

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

Aperta Adatta ai principianti
#1,305 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
68/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
java
Ambito
backend

Direzione di ricerca

Leggi IfElseIfConstructToSwitch.java, in particolare getStatement, e la riproduzione in IfElseIfConstructToSwitchTest.java. Inizia verificando come i commenti iniziali vengono associati all’unica istruzione di un blocco e come la conversione gestisce i due controlli di pattern segnalati più il fallback. Aggiungi test di regressione per entrambi i comportamenti; il lavoro è concluso quando i commenti vengono preservati e lo switch risultante evita il problema segnalato della soglia di due case.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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()) {
Lingua principale
Java
Stelle
160
Fork
133
Merge medio
7h 49m
PR unite (30g)
60

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di openrewrite/rewrite-migrate-java

Tutte le issue di openrewrite/rewrite-migrate-java

Issue simili

Altre issue su Java

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.