From b6b1b4e20b4a40cca2e433a9f65f67d70ec03934 Mon Sep 17 00:00:00 2001 From: ghm Date: Tue, 3 Jan 2023 03:27:49 -0800 Subject: [PATCH] Obey @Keep in PreferredInterfaceType. PiperOrigin-RevId: 499172455 --- .../bugpatterns/PreferredInterfaceType.java | 5 +++++ .../bugpatterns/PreferredInterfaceTypeTest.java | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java b/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java index b4cd1223c63..cda7ae736ac 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/PreferredInterfaceType.java @@ -39,6 +39,7 @@ import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.methodCanBeOverridden; +import static com.google.errorprone.util.ASTHelpers.shouldKeep; import com.google.auto.value.AutoValue; import com.google.common.collect.ArrayListMultimap; @@ -200,6 +201,10 @@ private boolean variableIsFixable(VariableTree tree, VarSymbol symbol) { if (symbol.getKind() == ElementKind.PARAMETER) { return false; } + if (shouldKeep(tree)) { + return false; + } + // TODO(ghm): Open source @Keep on the elements in SHOULD_IGNORE, and remove this. if (SHOULD_IGNORE.matches(tree, state)) { return false; } diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java index 04395c71a41..58552ed1734 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java @@ -897,4 +897,18 @@ public void charSequences() { "}") .doTest(); } + + @Test + public void obeysKeep() { + refactoringHelper + .addInputLines( + "Test.java", + "import com.google.errorprone.annotations.Keep;", + "import java.util.ArrayList;", + "class Test {", + " @Keep private static final Iterable FOO = new ArrayList<>();", + "}") + .expectUnchanged() + .doTest(); + } }