[Suggestion] add IntelliJ's SuspiciousCollectionsMethodCallsInspection
- Dominant language
- Java
- Stars
- 7.2k
- Forks
- 820
- Avg merge
- 5h 9m
- Merged PRs (30d)
- 50
Description
### Description of the problem / feature request:
CollectionIncompatibleType does not catch Set[InterfaceA].contains(interfaceB) and similar interface-related cases. It is technically correct that collection of InterfaceA can contain InterfaceB objects, but IntelliJ says "Suspicious call to 'Set.contains'" and it can be very helpful.
### Feature requests: what underlying problem are you trying to solve with this feature?
Be able to trigger errors when collection type mismatches argument types (where some of them are interfaces).
It can be a very common pattern where you only expect to use collection type argument aspect of objects you put in/get out, also full program analysis could be able to find out that indeed there's no common subtype of A and B anywhere in your code or that you never actually put B into collection of A.
Extra note that (hashed) collections use Object.hashCode/equals, but what most of simple use-cases really need is for collection to store As or Bs and don't treat them as potentially compatible via subtyping elsewhere.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```java
interface A {}
interface B { A getA(); }
class Test { {
// should trigger a warning, note: user actually wanted to type b.getA()
new java.util.HashSet().contains((B)null);
} }
```
Or as a part of CollectionIncompatibleTypeTest
```java
@Test
public void interfaceVsClassTests() {
compilationHelper
.addSourceLines(
"Test.java",
"import java.util.HashSet;",
"interface IA {}",
"interface IB {}",
"class CA {}",
"class CB {}",
"final class CF {}", // final class makes interface-class comparisons strict
"public interface Test {",
" static void test(IA ia, IB ib, CA ca, CB cb, CF cf) {", // all of lines should be getting at least a warning
" new HashSet().contains(ib);",
" new HashSet().contains(ia);",
" new HashSet().contains(cb);",
" new HashSet().contains(ca);",
" new HashSet().contains(ca);",
" new HashSet().contains(ia);",
" new HashSet().contains(cf);",
" new HashSet().contains(ia);",
" }",
"}"
).doTest();
}
```
### What version of Error Prone are you using?
master@6541e8e406e329468e8376bc1e4972e18a6268a9
### Have you found anything relevant by searching the web?
IntelliJ inspection https://github.com/JetBrains/intellij-community/blob/6ae9af85cbf4c46a71e6b6090db1b4826dd8aa3e/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/SuspiciousCollectionsMethodCallsInspection.java
SpotBugs doesn't seem to have such inspection.
Contributor guide
Assessment
This issue has not been assessed yet.