Skip to content

Commit

Permalink
Yoda conditions: consider static fields which are in SHOUTY_CASE to…
Browse files Browse the repository at this point in the history
… be constant.

Motivated by `Boolean.TRUE`, but that seemed a bit special-casey.

PiperOrigin-RevId: 619497318
  • Loading branch information
graememorgan authored and Error Prone Team committed Mar 27, 2024
1 parent 29d9335 commit 9b2c2a9
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import static com.google.errorprone.util.ASTHelpers.getNullnessValue;
import static com.google.errorprone.util.ASTHelpers.getReceiver;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import static java.lang.String.format;

import com.google.errorprone.BugPattern;
Expand All @@ -41,6 +42,7 @@
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.util.Objects;
import java.util.regex.Pattern;

/** See the summary. */
@BugPattern(
Expand Down Expand Up @@ -119,6 +121,12 @@ private static boolean seemsConstant(Tree tree) {
return true;
}
var symbol = getSymbol(tree);
return symbol instanceof VarSymbol && symbol.isEnum();
if (!(symbol instanceof VarSymbol)) {
return false;
}
return symbol.isEnum()
|| (isStatic(symbol) && CONSTANT_CASE.matcher(symbol.getSimpleName().toString()).matches());
}

private static final Pattern CONSTANT_CASE = Pattern.compile("[A-Z0-9_]+");
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,50 @@ public void primitive() {
.doTest();
}

@Test
public void boxedBoolean() {
refactoring
.addInputLines(
"Test.java",
"class Test {",
" boolean yoda(Boolean a) {",
" return Boolean.TRUE.equals(a);",
" }",
"}")
.addOutputLines(
"Test.java",
"import java.util.Objects;",
"class Test {",
" boolean yoda(Boolean a) {",
" return Objects.equals(a, Boolean.TRUE);",
" }",
"}")
.doTest();
}

@Test
public void boxedVsUnboxedBoolean() {
refactoring
.addInputLines(
"Test.java",
"class Test {",
" boolean yoda(boolean a) {",
" return Boolean.TRUE.equals(a);",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" boolean yoda(boolean a) {",
// NOTE: this is a broken fix! We could detect this if it turns out to be an issue in
// practice.
" return a.equals(Boolean.TRUE);",
" }",
"}")
.allowBreakingChanges()
.doTest();
}

@Test
public void enums() {
refactoring
Expand Down

0 comments on commit 9b2c2a9

Please sign in to comment.