From a6046336a597320e6f844cec3506fe69895ce4f1 Mon Sep 17 00:00:00 2001 From: Error Prone Team Date: Wed, 4 Jan 2023 07:34:16 -0800 Subject: [PATCH] Short-circuit StatementSwitchToExpressionSwitch analysis when presented with expression switch; add non-empty expression switch test case PiperOrigin-RevId: 499480786 --- .../StatementSwitchToExpressionSwitch.java | 7 ++++++- ...StatementSwitchToExpressionSwitchTest.java | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) 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 411bd34f4bc..fd490cbc95e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitch.java @@ -124,7 +124,12 @@ private static AnalysisResult analyzeSwitchTree(SwitchTree switchTree) { List statements = caseTree.getStatements(); CaseFallThru caseFallThru = CaseFallThru.MAYBE_FALLS_THRU; - if (statements == null || statements.isEmpty()) { + if (statements == null) { + // This case must be of kind CaseTree.CaseKind.RULE, and thus this is already an expression + // switch; no need to continue analysis. + return AnalysisResult.of( + /* canConvertDirectlyToExpressionSwitch= */ false, ImmutableList.of()); + } else if (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 623ee82f4b7..9bc9ecfce43 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java @@ -1017,7 +1017,7 @@ public void singleCaseConvertible_error() { } @Test - public void emptySwitchCases_noMatch() { + public void emptyExpressionSwitchCases_noMatch() { assumeTrue(RuntimeVersion.isAtLeast14()); helper .addSourceLines( @@ -1033,6 +1033,23 @@ public void emptySwitchCases_noMatch() { .doTest(); } + @Test + public void nonEmptyExpressionSwitchCases_noMatch() { + assumeTrue(RuntimeVersion.isAtLeast14()); + helper + .addSourceLines( + "Test.java", + "class Test {", + " void foo(int value) { ", + " switch (value) {", + " case 0 -> System.out.println(\"zero\");", + " default -> {System.out.println(\"non-zero\");}", + " }", + " }", + "}") + .doTest(); + } + @Test public void dynamicWithThrowableDuringInitializationFromMethod_noMatch() { assumeTrue(RuntimeVersion.isAtLeast14());