/
MapGetWithNotNullAssertionOperator.kt
72 lines (67 loc) · 2.54 KB
/
MapGetWithNotNullAssertionOperator.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtPostfixExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
/**
* Reports calls of the map access methods `map[]` or `map.get()` with a not-null assertion operator `!!`.
* This may result in a NullPointerException.
* Preferred access methods are `map[]` without `!!`, `map.getValue()`, `map.getOrDefault()` or `map.getOrElse()`.
*
* Based on an IntelliJ IDEA inspection MapGetWithNotNullAssertionOperatorInspection.
*
* <noncompliant>
* val map = emptyMap<String, String>()
* map["key"]!!
*
* val map = emptyMap<String, String>()
* map.get("key")!!
* </noncompliant>
*
* <compliant>
* val map = emptyMap<String, String>()
* map["key"]
*
* val map = emptyMap<String, String>()
* map.getValue("key")
*
* val map = emptyMap<String, String>()
* map.getOrDefault("key", "")
*
* val map = emptyMap<String, String>()
* map.getOrElse("key", { "" })
* </compliant>
*/
@ActiveByDefault(since = "1.21.0")
class MapGetWithNotNullAssertionOperator(config: Config) : Rule(config) {
override val issue: Issue =
Issue(
"MapGetWithNotNullAssertionOperator",
Severity.CodeSmell,
"map.get() with not-null assertion operator (!!) can result in a NullPointerException. " +
"Consider usage of map.getValue(), map.getOrDefault() or map.getOrElse() instead.",
Debt.FIVE_MINS
)
override fun visitPostfixExpression(expression: KtPostfixExpression) {
if (expression.operationToken == KtTokens.EXCLEXCL && expression.isMapGet()) {
report(CodeSmell(issue, Entity.from(expression), "map.get() with not-null assertion operator (!!)"))
}
super.visitPostfixExpression(expression)
}
private fun KtPostfixExpression.isMapGet(): Boolean {
return this
.baseExpression
.getResolvedCall(bindingContext)
?.resultingDescriptor
?.fqNameSafe == FqName("kotlin.collections.Map.get")
}
}