Skip to content

Commit 76b44c7

Browse files
markhbradyError Prone Team
authored and
Error Prone Team
committed
[StatementSwitchToExpressionSwitch] Bugfix to not group case null with a normal case following it
PiperOrigin-RevId: 758210665
1 parent b8acf10 commit 76b44c7

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,14 @@ private static AnalysisResult analyzeSwitchTree(SwitchTree switchTree, VisitorSt
298298
return DEFAULT_ANALYSIS_RESULT;
299299
}
300300

301+
// Null case can never be grouped with a following case (except possibly default)
302+
if (caseIndex > 0
303+
&& groupedWithNextCase.get(caseIndex - 1)
304+
&& isNullCase.get(caseIndex - 1)
305+
&& !isDefaultCase) {
306+
return DEFAULT_ANALYSIS_RESULT;
307+
}
308+
301309
// Grouping null with default requires Java 21+
302310
if (caseIndex > 0
303311
&& isNullCase.get(caseIndex - 1)

core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,6 +1377,36 @@ public int foo(Suit suit) {
13771377
.doTest();
13781378
}
13791379

1380+
@Test
1381+
public void switchByEnum_firstNullCase_noError() {
1382+
// The null case cannot be grouped with a following regular case per Java syntax
1383+
assume().that(Runtime.version().feature()).isAtLeast(21);
1384+
helper
1385+
.addSourceLines(
1386+
"Test.java",
1387+
"""
1388+
class Test {
1389+
public int foo(Suit suit) {
1390+
switch (suit) {
1391+
case null:
1392+
case DIAMOND:
1393+
return 123;
1394+
case SPADE:
1395+
throw new RuntimeException("Spade");
1396+
case HEART:
1397+
throw new RuntimeException("Heart");
1398+
case CLUB:
1399+
throw new NullPointerException("Club");
1400+
}
1401+
}
1402+
}
1403+
""")
1404+
.setArgs(
1405+
"-XepOpt:StatementSwitchToExpressionSwitch:EnableReturnSwitchConversion",
1406+
"-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion=false")
1407+
.doTest();
1408+
}
1409+
13801410
@Test
13811411
public void switchByEnum_nullGroupedWithDefault_error() {
13821412
assume().that(Runtime.version().feature()).isAtLeast(21);

0 commit comments

Comments
 (0)