Skip to content

Commit ed305d2

Browse files
authored
Merge pull request github#11032 from tamasvajk/kotlin-unused-for-loop-var
Kotlin: exclude loop variables on ranges from 'unused locals' check
2 parents 5766ff2 + e48dfcc commit ed305d2

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

java/ql/src/Violations of Best Practice/Dead Code/UnreadLocal.ql

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,10 @@ where
2626
not exists(getARead(v)) and
2727
// Discarded exceptions are covered by another query.
2828
not exists(CatchClause cc | cc.getVariable().getVariable() = v) and
29+
// Exclude common Kotlin pattern to do something n times: `for(i in 1..n) { doSomething() }
30+
not exists(EnhancedForStmt f |
31+
f.getVariable().getVariable() = v and
32+
f.getExpr().getType().(RefType).hasQualifiedName("kotlin.ranges", ["IntRange", "LongRange"])
33+
) and
2934
not readImplicitly(v)
3035
select v, "Variable '" + v + "' is never read."
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
| test.kt:8:10:8:10 | int e | Variable 'int e' is never read. |
2+
| test.kt:14:11:14:13 | int idx | Variable 'int idx' is never read. |
3+
| test.kt:14:16:14:16 | int e | Variable 'int e' is never read. |
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Violations of Best Practice/Dead Code/UnreadLocal.ql
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
fun fn0(size: Int) {
2+
for (idx in 1..size) {
3+
println()
4+
}
5+
}
6+
7+
fun fn1(a: Array<Int>) {
8+
for (e in a) {
9+
println()
10+
}
11+
}
12+
13+
fun fn2(a: Array<Int>) {
14+
for ((idx, e) in a.withIndex()) {
15+
println()
16+
}
17+
}
18+
19+
fun fn3() {
20+
for (i in 1 until 10) {
21+
println()
22+
}
23+
}
24+
25+
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.rangeTo in java.lang.Integer%

0 commit comments

Comments
 (0)