Skip to content

Commit 30fc6ac

Browse files
authored
Merge pull request github#10961 from tamasvajk/kotlin-abstract-collection-cast
Kotlin: Improve `java/abstract-to-concrete-cast` to handle `when` branches
2 parents 7e2c06d + a0490f4 commit 30fc6ac

File tree

4 files changed

+16
-3
lines changed

4 files changed

+16
-3
lines changed

java/ql/src/Violations of Best Practice/Implementation Hiding/AbstractToConcreteCollection.ql

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,11 @@ import java
1616
import semmle.code.java.Collections
1717

1818
predicate guardedByInstanceOf(VarAccess e, RefType t) {
19-
exists(IfStmt s, InstanceOfExpr instanceCheck, RefType checkType |
20-
s.getCondition() = instanceCheck and
19+
exists(Stmt s, InstanceOfExpr instanceCheck, RefType checkType |
20+
(
21+
s.(IfStmt).getCondition() = instanceCheck or
22+
s.(WhenBranch).getCondition() = instanceCheck
23+
) and
2124
instanceCheck.getCheckedType() = checkType and
2225
// The same variable appears as the subject of the `instanceof`.
2326
instanceCheck.getExpr() = e.getVariable().getAnAccess() and
@@ -27,7 +30,11 @@ predicate guardedByInstanceOf(VarAccess e, RefType t) {
2730
(checkType = t or checkType = t.getSourceDeclaration().(GenericType).getRawType()) and
2831
// The expression appears in one of the branches.
2932
// (We do not verify here whether the guard is correctly implemented.)
30-
exists(Stmt branch | branch = s.getThen() or branch = s.getElse() |
33+
exists(Stmt branch |
34+
branch = s.(IfStmt).getThen() or
35+
branch = s.(IfStmt).getElse() or
36+
branch = s.(WhenBranch).getRhs()
37+
|
3138
branch = e.getEnclosingStmt().getEnclosingStmt+()
3239
)
3340
)

java/ql/test/kotlin/query-tests/AbstractToConcreteCollection/AbstractToConcreteCollection.expected

Whitespace-only changes.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Violations of Best Practice/Implementation Hiding/AbstractToConcreteCollection.ql
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
fun fn(m: MutableList<Int>) {
2+
if (m is ArrayList) {
3+
m.ensureCapacity(5)
4+
}
5+
}

0 commit comments

Comments
 (0)