From 6bd568d418694043bfec7961dff0ba5559bb856a Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Tue, 16 Jul 2024 10:52:31 -0700 Subject: [PATCH] Don't complain about unused variables named `_` See https://openjdk.org/jeps/456 Fixes https://github.com/google/error-prone/issues/4451 PiperOrigin-RevId: 652904059 --- .../google/errorprone/util/RuntimeVersion.java | 5 +++++ .../errorprone/bugpatterns/UnusedVariable.java | 1 + .../bugpatterns/UnusedVariableTest.java | 15 +++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java b/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java index 14ae3dd37fc..0785489c645 100644 --- a/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java +++ b/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.java @@ -79,6 +79,11 @@ public static boolean isAtLeast21() { return FEATURE >= 21; } + /** Returns true if the current runtime is JDK 22 or newer. */ + public static boolean isAtLeast22() { + return FEATURE >= 22; + } + /** * Returns the latest {@code --release} version. * diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java index 71e12a7f237..0e8f41a500e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/UnusedVariable.java @@ -198,6 +198,7 @@ public final class UnusedVariable extends BugChecker implements CompilationUnitT this.exemptNames = ImmutableSet.builder() .add("ignored") + .add("") // `var _ = ...` is handled as an empty variable name .addAll(flags.getListOrEmpty("Unused:exemptNames")) .build(); diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java index 92107250de7..4db2f04b54f 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java @@ -1679,4 +1679,19 @@ public void parameterUsedInOverride() { .expectUnchanged() .doTest(); } + + @Test + public void underscoreVariable() { + assumeTrue(RuntimeVersion.isAtLeast22()); + refactoringHelper + .addInputLines( + "Test.java", + "class Test {", + " public static void main(String[] args) {", + " var _ = new Object();", + " }", + "}") + .expectUnchanged() + .doTest(); + } }