/
UnnecessaryPartOfBinaryExpression.kt
77 lines (68 loc) · 2.62 KB
/
UnnecessaryPartOfBinaryExpression.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
73
74
75
76
77
package io.gitlab.arturbosch.detekt.rules.performance
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 org.jetbrains.kotlin.com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.utils.addIfNotNull
/**
* Unnecessary binary expression add complexity to the code and accomplish nothing. They should be removed.
* The rule works with all binary expression included if and when condition. The rule also works with all predicates.
* The rule verify binary expression only in case when the expression use only one type of the following
* operators || or &&.
*
* <noncompliant>
* val foo = true
* val bar = true
*
* if (foo || bar || foo) {
* }
* </noncompliant>
*
* <compliant>
* val foo = true
* if (foo) {
* }
* </compliant>
*
*/
class UnnecessaryPartOfBinaryExpression(config: Config = Config.empty) : Rule(config) {
override val issue: Issue = Issue(
"UnnecessaryPartOfBinaryExpression",
Severity.Performance,
"Detects duplicate condition into binary expression and recommends to remove unnecessary checks",
Debt.FIVE_MINS
)
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
if (expression.parent is KtBinaryExpression) return
val operator = expression.operationToken
if (operator != KtTokens.OROR && operator != KtTokens.ANDAND) return
val expressions = expression.expressions(operator).map { it.text.replace(whiteSpace, "") }
if (expressions.size != expressions.distinct().size) {
report(CodeSmell(issue, Entity.from(expression), issue.description))
}
}
private fun KtBinaryExpression.expressions(operator: IElementType): List<KtExpression> {
val expressions = mutableListOf<KtExpression>()
fun collect(expression: KtExpression?) {
if (expression !is KtBinaryExpression || expression.operationToken != operator) {
expressions.addIfNotNull(expression)
return
}
collect(expression.left)
collect(expression.right)
}
collect(this)
return expressions
}
companion object {
private val whiteSpace = "\\s".toRegex()
}
}