From b84b80c2624219894ea67ee6beee97d1ec01860b Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Tue, 19 Jan 2021 10:39:04 -0800 Subject: [PATCH] Don't crash on 'arrow' switches in `FallThrough` arrow switches don't fall through, so this check doesn't apply to them, just exiting gracefully is all we need to do here. Fixes https://github.com/google/error-prone/issues/2118 PiperOrigin-RevId: 352602004 --- .../errorprone/bugpatterns/FallThrough.java | 6 +++-- .../bugpatterns/FallThroughTest.java | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/FallThrough.java b/core/src/main/java/com/google/errorprone/bugpatterns/FallThrough.java index 2f519bb026c..0a5284ccae7 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/FallThrough.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/FallThrough.java @@ -35,6 +35,7 @@ import com.sun.source.tree.SwitchTree; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Position; +import java.util.List; import java.util.regex.Pattern; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @@ -57,13 +58,14 @@ public Description matchSwitch(SwitchTree tree, VisitorState state) { break; } CaseTree next = it.peek(); - if (caseTree.getStatements().isEmpty()) { + List statements = caseTree.getStatements(); + if (statements == null || statements.isEmpty()) { continue; } // We only care whether the last statement completes; javac would have already // reported an error if that statement wasn't reachable, and the answer is // independent of any preceding statements. - boolean completes = Reachability.canCompleteNormally(getLast(caseTree.getStatements())); + boolean completes = Reachability.canCompleteNormally(getLast(statements)); int endPos = caseEndPosition(state, caseTree); if (endPos == Position.NOPOS) { break; diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/FallThroughTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/FallThroughTest.java index 95ff8396fb0..203f5c40e1c 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/FallThroughTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/FallThroughTest.java @@ -16,7 +16,10 @@ package com.google.errorprone.bugpatterns; +import static org.junit.Assume.assumeTrue; + import com.google.errorprone.CompilationTestHelper; +import com.google.errorprone.util.RuntimeVersion; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -95,4 +98,23 @@ public void emptyBlock() { "}") .doTest(); } + + @Test + public void arrowSwitch() { + assumeTrue(RuntimeVersion.isAtLeast14()); + testHelper + .addSourceLines( + "Test.java", + "class Test {", + " enum Case { ONE, TWO }", + " void m(Case c) {", + " switch (c) {", + " case ONE -> {}", + " case TWO -> {}", + " default -> {}", + " }", + " }", + "}") + .doTest(); + } }