Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle case null in switch statements #1100

Merged
merged 1 commit into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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() {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rename to clarify what is being tested; this test was written before Java added switch expressions

defaultCompilationHelper
.addSourceLines(
"TestPositive.java",
Expand Down
Loading