Skip to content

[StatementSwitchToExpressionSwitch] Bugfix to not group case null with a normal case following it #5044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,14 @@ private static AnalysisResult analyzeSwitchTree(SwitchTree switchTree, VisitorSt
return DEFAULT_ANALYSIS_RESULT;
}

// Null case can never be grouped with a following case (except possibly default)
if (caseIndex > 0
&& groupedWithNextCase.get(caseIndex - 1)
&& isNullCase.get(caseIndex - 1)
&& !isDefaultCase) {
return DEFAULT_ANALYSIS_RESULT;
}

// Grouping null with default requires Java 21+
if (caseIndex > 0
&& isNullCase.get(caseIndex - 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1377,6 +1377,36 @@ public int foo(Suit suit) {
.doTest();
}

@Test
public void switchByEnum_firstNullCase_noError() {
// The null case cannot be grouped with a following regular case per Java syntax
assume().that(Runtime.version().feature()).isAtLeast(21);
helper
.addSourceLines(
"Test.java",
"""
class Test {
public int foo(Suit suit) {
switch (suit) {
case null:
case DIAMOND:
return 123;
case SPADE:
throw new RuntimeException("Spade");
case HEART:
throw new RuntimeException("Heart");
case CLUB:
throw new NullPointerException("Club");
}
}
}
""")
.setArgs(
"-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion",
"-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion=false")
.doTest();
}

@Test
public void switchByEnum_nullGroupedWithDefault_error() {
assume().that(Runtime.version().feature()).isAtLeast(21);
Expand Down
Loading