Skip to content

Commit

Permalink
Don't crash for CaseKind.RULE in SwitchDefault
Browse files Browse the repository at this point in the history
Fixes #2705

PiperOrigin-RevId: 413868350
  • Loading branch information
sumitbhagwani authored and Error Prone Team committed Dec 3, 2021
1 parent aa8f00b commit b803e04
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
Expand Up @@ -28,6 +28,7 @@
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.Reachability;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import java.util.ArrayList;
import java.util.Iterator;
Expand All @@ -52,17 +53,20 @@ public Description matchSwitch(SwitchTree tree, VisitorState state) {
// Collect all case trees in the statement group containing the default
List<CaseTree> defaultStatementGroup = new ArrayList<>();
Iterator<? extends CaseTree> it = tree.getCases().iterator();
List<? extends StatementTree> caseTreeStatements = null;
while (it.hasNext()) {
CaseTree caseTree = it.next();
caseTreeStatements = caseTree.getStatements();
defaultStatementGroup.add(caseTree);
if (caseTree.getExpression() == null) {
while (it.hasNext() && caseTree.getStatements().isEmpty()) {
while (it.hasNext() && caseTreeStatements.isEmpty()) {
caseTree = it.next();
caseTreeStatements = caseTree.getStatements();
defaultStatementGroup.add(caseTree);
}
break;
}
if (!caseTree.getStatements().isEmpty()) {
if (caseTreeStatements != null && !caseTreeStatements.isEmpty()) {
defaultStatementGroup.clear();
}
}
Expand Down
Expand Up @@ -16,14 +16,22 @@

package com.google.errorprone.bugpatterns;

import static org.junit.Assume.assumeTrue;

import com.google.errorprone.BugCheckerRefactoringTestHelper;
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;

/** {@link SwitchDefault}Test */
@RunWith(JUnit4.class)
public class SwitchDefaultTest {

private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(SwitchDefault.class, getClass());

private final BugCheckerRefactoringTestHelper testHelper =
BugCheckerRefactoringTestHelper.newInstance(SwitchDefault.class, getClass());

Expand Down Expand Up @@ -224,4 +232,27 @@ public void refactoring_outOfOrder() {
"}")
.doTest();
}

@Test
public void newNotation_validDefault() {
assumeTrue(RuntimeVersion.isAtLeast14());
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" public static void nothing1() { }",
" public static void nothing2() { }",
" public static void nothing3() { }",
" public static void switchDefaultCrash(int i)",
" {",
" switch(i) {",
" case 0 -> nothing1();",
" case 1 -> nothing2();",
" default -> nothing3();",
" }",
" }",
" }",
"}")
.doTest();
}
}

0 comments on commit b803e04

Please sign in to comment.