Skip to content

Commit

Permalink
NullTernary shouldn't crash on JDK 14
Browse files Browse the repository at this point in the history
Fixes #1982

PiperOrigin-RevId: 346000494
  • Loading branch information
sumitbhagwani authored and Error Prone Team committed Dec 8, 2020
1 parent 156c7a5 commit 2835cbd
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1565,8 +1565,15 @@ public Type visitAnnotation(AnnotationTree tree, Void unused) {

@Override
public Type visitCase(CaseTree tree, Void unused) {
SwitchTree switchTree = (SwitchTree) parent.getParentPath().getLeaf();
return getType(switchTree.getExpression());
Tree t = parent.getParentPath().getLeaf();
// JDK 12+, t can be SwitchExpressionTree
if (t instanceof SwitchTree) {
SwitchTree switchTree = (SwitchTree) t;
return getType(switchTree.getExpression());
}
// TODO(bhagwani): When the ErrorProne project switches to JDK 12, we should check
// for SwitchExpressionTree.
return null;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ public static boolean isAtLeast13() {
return MAJOR >= 13;
}

/** Returns true if the current runtime is JDK 14 or newer. */
public static boolean isAtLeast14() {
return MAJOR >= 14;
}

/** Returns true if the current runtime is JDK 15 or newer. */
public static boolean isAtLeast15() {
return MAJOR >= 15;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -121,4 +124,25 @@ public void conditionalInCondition() {
"}")
.doTest();
}

@Test
public void expressionSwitch_doesNotCrash() {
assumeTrue(RuntimeVersion.isAtLeast14());
testHelper
.addSourceLines(
"Test.java",
"class Test {",
" static String doStuff(SomeEnum enumVar) {",
" return switch (enumVar) {",
" case A -> enumVar.name() != null ? \"AAA\" : null;",
" default -> null;",
" };",
" }",
" ",
" static enum SomeEnum {",
" A, B",
" }",
"}")
.doTest();
}
}

0 comments on commit 2835cbd

Please sign in to comment.