From 150c60d1e7a9be9e1fb1035f1b19d872a09bf8fd Mon Sep 17 00:00:00 2001 From: cpovirk Date: Mon, 7 Oct 2024 07:31:28 -0700 Subject: [PATCH] Flag calls to `Sequenced*` insertion APIs on `Sorted*` instances. PiperOrigin-RevId: 683177531 --- .../bugpatterns/DoNotCallChecker.java | 10 ++++++++ .../bugpatterns/DoNotCallCheckerTest.java | 24 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java index 552806e15bf0..b3512da95e5e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java @@ -143,6 +143,16 @@ public class DoNotCallChecker extends BugChecker .put( instanceMethod().onExactClass("java.sql.Time").named("toInstant"), "sqlTime.toInstant() is not supported. Did you mean to call toLocalTime() instead?") + .put( + instanceMethod() + .onDescendantOf("java.util.SortedMap") + .namedAnyOf("putFirst", "putLast"), + "Sorted collections do not support insertions with explicit positioning") + .put( + instanceMethod() + .onDescendantOf("java.util.SortedSet") + .namedAnyOf("addFirst", "addLast"), + "Sorted collections do not support insertions with explicit positioning") .put( instanceMethod() .onExactClass("java.util.concurrent.ThreadLocalRandom") diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java index 2e9181bdd6dd..6eb6fe3a743d 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java @@ -516,6 +516,30 @@ public void badApis() { .doTest(); } + @Test + public void sortedCollectionSequencedCollectionMethods() { + testHelper + .addSourceLines( + "Test.java", + """ + import java.util.TreeMap; + import java.util.TreeSet; + public class Test { + public void foo(TreeMap map, TreeSet set) { + // BUG: Diagnostic contains: DoNotCall + map.putFirst("foo", "bar"); + // BUG: Diagnostic contains: DoNotCall + map.putLast("foo", "bar"); + // BUG: Diagnostic contains: DoNotCall + set.addFirst("foo"); + // BUG: Diagnostic contains: DoNotCall + set.addLast("foo"); + } + } + """) + .doTest(); + } + @Test public void readLock_newCondition() { assertThrows(