From 773f647afa57ab791d13cecf5ce5af6bde98ffde Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 31 Dec 2022 14:53:59 +0100 Subject: [PATCH] StatementSwitchToExpressionSwitch: handle empty statement blocks Fixes #3638. --- .../StatementSwitchToExpressionSwitch.java | 2 +- .../StatementSwitchToExpressionSwitchTest.java | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java b/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java index b885de8b298..8d53a085ae7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java @@ -122,7 +122,7 @@ private static AnalysisResult analyzeSwitchTree(SwitchTree switchTree) { List statements = caseTree.getStatements(); CaseFallThru caseFallThru = CaseFallThru.MAYBE_FALLS_THRU; - if (statements.isEmpty()) { + if (statements == null || statements.isEmpty()) { // If the code for this case is just an empty block, then it must fall thru caseFallThru = CaseFallThru.DEFINITELY_DOES_FALL_THRU; // Can group with the next case (unless this is the last case) diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java index 535fa765ee9..623ee82f4b7 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java @@ -1016,6 +1016,23 @@ public void singleCaseConvertible_error() { .doTest(); } + @Test + public void emptySwitchCases_noMatch() { + assumeTrue(RuntimeVersion.isAtLeast14()); + helper + .addSourceLines( + "Test.java", + "class Test {", + " void foo(int value) { ", + " switch (value) {", + " case 0 -> {}", + " default -> {}", + " }", + " }", + "}") + .doTest(); + } + @Test public void dynamicWithThrowableDuringInitializationFromMethod_noMatch() { assumeTrue(RuntimeVersion.isAtLeast14());