/
CognitiveComplexity.kt
198 lines (165 loc) · 7.2 KB
/
CognitiveComplexity.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package io.github.detekt.metrics
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.rules.isElseIf
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
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.KtBreakExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtContinueExpression
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpressionWithLabel
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getCallNameExpression
/**
* Kotlin implementation of the cognitive complexity metric.
*
* Please see the "Cognitive Complexity: A new way of measuring understandability" white paper
* by G. Ann Campbell of SonarSource for further detail.
*
* https://www.sonarsource.com/docs/CognitiveComplexity.pdf
*/
class CognitiveComplexity private constructor() : DetektVisitor() {
private var complexity: Int = 0
override fun visitNamedFunction(function: KtNamedFunction) {
val visitor = FunctionComplexity(function)
visitor.visitNamedFunction(function)
complexity += visitor.complexity
}
data class BinExprHolder(val expr: KtBinaryExpression, val op: IElementType, val isEnclosed: Boolean)
@Suppress("detekt.TooManyFunctions") // visitor pattern
class FunctionComplexity(private val givenFunction: KtNamedFunction) : DetektVisitor() {
internal var complexity: Int = 0
private var nesting: Int = 0
private var topMostBinExpr: KtBinaryExpression? = null
private fun addComplexity() {
complexity += 1 + nesting
}
private inline fun nestAround(block: () -> Unit) {
nesting++
block()
nesting--
}
private fun testJumpWithLabel(expression: KtExpressionWithLabel) {
if (expression.labelQualifier != null) {
complexity++
}
}
private fun KtCallExpression.isRecursion(): Boolean {
val args = lambdaArguments.size + valueArguments.size
val isInsideSameScope = parent !is KtQualifiedExpression ||
(parent as? KtQualifiedExpression)?.receiverExpression is KtThisExpression
return isInsideSameScope &&
getCallNameExpression()?.getReferencedName() == givenFunction.name &&
args == givenFunction.valueParameters.size
}
override fun visitWhenExpression(expression: KtWhenExpression) {
addComplexity()
nestAround { super.visitWhenExpression(expression) }
}
override fun visitForExpression(expression: KtForExpression) {
addComplexity()
nestAround { super.visitForExpression(expression) }
}
override fun visitIfExpression(expression: KtIfExpression) {
val isElseIf = expression.isElseIf()
if (isElseIf) nesting--
addComplexity()
val elseBranch = expression.`else`
if (elseBranch != null && elseBranch !is KtIfExpression) {
addComplexity()
}
nestAround { super.visitIfExpression(expression) }
if (isElseIf) nesting++
}
override fun visitBreakExpression(expression: KtBreakExpression) {
testJumpWithLabel(expression)
super.visitBreakExpression(expression)
}
override fun visitContinueExpression(expression: KtContinueExpression) {
testJumpWithLabel(expression)
super.visitContinueExpression(expression)
}
override fun visitReturnExpression(expression: KtReturnExpression) {
testJumpWithLabel(expression)
super.visitReturnExpression(expression)
}
override fun visitNamedFunction(function: KtNamedFunction) {
if (function != givenFunction) {
nestAround { super.visitNamedFunction(function) }
} else {
super.visitNamedFunction(function)
}
}
override fun visitCatchSection(catchClause: KtCatchClause) {
addComplexity()
nestAround { super.visitCatchSection(catchClause) }
}
override fun visitWhileExpression(expression: KtWhileExpression) {
addComplexity()
nestAround { super.visitWhileExpression(expression) }
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
addComplexity()
nestAround { super.visitDoWhileExpression(expression) }
}
override fun visitCallExpression(expression: KtCallExpression) {
if (expression.isRecursion()) {
complexity++
}
super.visitCallExpression(expression)
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
nestAround { super.visitLambdaExpression(lambdaExpression) }
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (topMostBinExpr == null) {
topMostBinExpr = expression
}
super.visitBinaryExpression(expression)
if (topMostBinExpr == expression) {
val nestedBinExprs = expression.collectDescendantsOfType<KtBinaryExpression>()
.asSequence()
.map { BinExprHolder(it, it.operationToken, it.parent is KtParenthesizedExpression) }
.filter { it.op in logicalOps }
.sortedBy { it.expr.operationReference.textRange.startOffset }
.toList()
calculateBinaryExprComplexity(nestedBinExprs)
topMostBinExpr = null
}
}
private fun calculateBinaryExprComplexity(usedExpr: List<BinExprHolder>) {
var lastOp: IElementType? = null
for (binExpr in usedExpr) {
if (lastOp == null) {
complexity++
} else if (lastOp != binExpr.op || binExpr.isEnclosed) {
complexity++
}
lastOp = binExpr.op
}
}
}
companion object {
val KEY = Key<Int>("detekt.metrics.cognitive_complexity")
private val logicalOps = setOf(KtTokens.ANDAND, KtTokens.OROR)
fun calculate(element: KtElement): Int {
val visitor = CognitiveComplexity()
element.accept(visitor)
return visitor.complexity
}
}
}