Skip to content

Commit

Permalink
Handle case null in switch statements (#1100)
Browse files Browse the repository at this point in the history
In Java 21+, when a `switch` statement contains `case null`, the
expression being switched on is allowed to be `null`.

Fixes #930
  • Loading branch information
msridhar authored Dec 18, 2024
1 parent 18c9723 commit 41c7c55
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -244,4 +244,27 @@ public void testSwitchExprNullCaseDataflow() {
"}")
.doTest();
}

@Test
public void switchStatementCaseNull() {
defaultCompilationHelper
.addSourceLines(
"Test.java",
"package com.uber;",
"import org.jspecify.annotations.Nullable;",
"public class Test {",
" public enum NullableEnum {",
" VALUE1, VALUE2;",
" }",
" static Object handleNullableEnumCaseNullDefaultStatement(@Nullable NullableEnum nullableEnum) {",
" Object result;",
" switch (nullableEnum) {",
" case null -> result = new Object();",
" default -> result = nullableEnum.toString();",
" }",
" return result;",
" }",
"}")
.doTest();
}
}
2 changes: 1 addition & 1 deletion nullaway/src/main/java/com/uber/nullaway/NullAway.java
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ public Description matchSwitch(SwitchTree tree, VisitorState state) {
switchSelectorExpression = ((ParenthesizedTree) switchSelectorExpression).getExpression();
}

if (mayBeNullExpr(state, switchSelectorExpression)) {
if (!TreeUtils.hasNullCaseLabel(tree) && mayBeNullExpr(state, switchSelectorExpression)) {
String message =
"switch expression " + state.getSourceForNode(switchSelectorExpression) + " is @Nullable";
ErrorMessage errorMessage =
Expand Down
2 changes: 1 addition & 1 deletion nullaway/src/test/java/com/uber/nullaway/CoreTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ public void cfNullableArrayField() {
}

@Test
public void supportSwitchExpression() {
public void switchOnNullable() {
defaultCompilationHelper
.addSourceLines(
"TestPositive.java",
Expand Down

0 comments on commit 41c7c55

Please sign in to comment.