From 23547ac2ef8ca0f3274fc7cbd82d656c62028486 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Thu, 4 Apr 2024 17:38:26 -0700 Subject: [PATCH] Allow `CONST_CASE != null` in YodaCondition Follow-up to https://github.com/google/error-prone/commit/9b2c2a9fc8dcea7c40ec6574c6325dc82f534abd PiperOrigin-RevId: 622020333 --- .../errorprone/bugpatterns/YodaCondition.java | 3 +++ .../bugpatterns/YodaConditionTest.java | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/YodaCondition.java b/core/src/main/java/com/google/errorprone/bugpatterns/YodaCondition.java index 7a2055d6932..e37a4f74364 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/YodaCondition.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/YodaCondition.java @@ -120,6 +120,9 @@ private static boolean seemsConstant(Tree tree) { if (constValue(tree) != null) { return true; } + if (tree.getKind().equals(Tree.Kind.NULL_LITERAL)) { + return true; + } var symbol = getSymbol(tree); if (!(symbol instanceof VarSymbol)) { return false; diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java index eaf08537c49..6185c7d6660 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java @@ -18,6 +18,7 @@ import com.google.errorprone.BugCheckerRefactoringTestHelper; import com.google.errorprone.BugCheckerRefactoringTestHelper.FixChoosers; +import com.google.errorprone.CompilationTestHelper; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -27,6 +28,9 @@ public final class YodaConditionTest { private final BugCheckerRefactoringTestHelper refactoring = BugCheckerRefactoringTestHelper.newInstance(YodaCondition.class, getClass()); + private final CompilationTestHelper testHelper = + CompilationTestHelper.newInstance(YodaCondition.class, getClass()); + @Test public void primitive() { refactoring @@ -205,4 +209,18 @@ public void provablyNonNull_nullIntolerantFix() { "}") .doTest(); } + + @Test + public void nullableConstant() { + testHelper + .addSourceLines( + "Test.java", + "class Test {", + " private static final String CONST = null;", + " public static boolean f() {", + " return CONST != null;", + " }", + "}") + .doTest(); + } }