Merge pull request #11032 from tamasvajk/kotlin-unused-for-loop-var

Kotlin: exclude loop variables on ranges from 'unused locals' check
This commit is contained in:
Tamás Vajk
2022-11-07 15:44:10 +01:00
committed by GitHub
4 changed files with 34 additions and 0 deletions

View File

@@ -26,5 +26,10 @@ where
not exists(getARead(v)) and
// Discarded exceptions are covered by another query.
not exists(CatchClause cc | cc.getVariable().getVariable() = v) and
// Exclude common Kotlin pattern to do something n times: `for(i in 1..n) { doSomething() }
not exists(EnhancedForStmt f |
f.getVariable().getVariable() = v and
f.getExpr().getType().(RefType).hasQualifiedName("kotlin.ranges", ["IntRange", "LongRange"])
) and
not readImplicitly(v)
select v, "Variable '" + v + "' is never read."

View File

@@ -0,0 +1,3 @@
| test.kt:8:10:8:10 | int e | Variable 'int e' is never read. |
| test.kt:14:11:14:13 | int idx | Variable 'int idx' is never read. |
| test.kt:14:16:14:16 | int e | Variable 'int e' is never read. |

View File

@@ -0,0 +1 @@
Violations of Best Practice/Dead Code/UnreadLocal.ql

View File

@@ -0,0 +1,25 @@
fun fn0(size: Int) {
for (idx in 1..size) {
println()
}
}
fun fn1(a: Array<Int>) {
for (e in a) {
println()
}
}
fun fn2(a: Array<Int>) {
for ((idx, e) in a.withIndex()) {
println()
}
}
fun fn3() {
for (i in 1 until 10) {
println()
}
}
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.rangeTo in java.lang.Integer%