Merge pull request #10961 from tamasvajk/kotlin-abstract-collection-cast

Kotlin: Improve `java/abstract-to-concrete-cast` to handle `when` branches
This commit is contained in:
Tamás Vajk
2022-10-25 13:27:19 +02:00
committed by GitHub
4 changed files with 16 additions and 3 deletions

View File

@@ -16,8 +16,11 @@ import java
import semmle.code.java.Collections
predicate guardedByInstanceOf(VarAccess e, RefType t) {
exists(IfStmt s, InstanceOfExpr instanceCheck, RefType checkType |
s.getCondition() = instanceCheck and
exists(Stmt s, InstanceOfExpr instanceCheck, RefType checkType |
(
s.(IfStmt).getCondition() = instanceCheck or
s.(WhenBranch).getCondition() = instanceCheck
) and
instanceCheck.getCheckedType() = checkType and
// The same variable appears as the subject of the `instanceof`.
instanceCheck.getExpr() = e.getVariable().getAnAccess() and
@@ -27,7 +30,11 @@ predicate guardedByInstanceOf(VarAccess e, RefType t) {
(checkType = t or checkType = t.getSourceDeclaration().(GenericType).getRawType()) and
// The expression appears in one of the branches.
// (We do not verify here whether the guard is correctly implemented.)
exists(Stmt branch | branch = s.getThen() or branch = s.getElse() |
exists(Stmt branch |
branch = s.(IfStmt).getThen() or
branch = s.(IfStmt).getElse() or
branch = s.(WhenBranch).getRhs()
|
branch = e.getEnclosingStmt().getEnclosingStmt+()
)
)

View File

@@ -0,0 +1 @@
Violations of Best Practice/Implementation Hiding/AbstractToConcreteCollection.ql

View File

@@ -0,0 +1,5 @@
fun fn(m: MutableList<Int>) {
if (m is ArrayList) {
m.ensureCapacity(5)
}
}