-
-
Notifications
You must be signed in to change notification settings - Fork 757
/
VarCouldBeVal.kt
239 lines (215 loc) · 10 KB
/
VarCouldBeVal.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package io.gitlab.arturbosch.detekt.rules.style
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.DetektVisitor
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.config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.isLateinit
import io.gitlab.arturbosch.detekt.rules.isOverride
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtObjectLiteralExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtUnaryExpression
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.util.containingNonLocalDeclaration
/**
* Reports var declarations (both local variables and private class properties) that could be val,
* as they are not re-assigned. Val declarations are assign-once (read-only), which makes understanding
* the current state easier.
*
* <noncompliant>
* fun example() {
* var i = 1 // violation: this variable is never re-assigned
* val j = i + 1
* }
* </noncompliant>
*
* <compliant>
* fun example() {
* val i = 1
* val j = i + 1
* }
* </compliant>
*/
@ActiveByDefault(since = "1.16.0")
@RequiresTypeResolution
class VarCouldBeVal(config: Config = Config.empty) : Rule(config) {
override val defaultRuleIdAliases: Set<String> = setOf("CanBeVal")
override val issue: Issue = Issue(
"VarCouldBeVal",
Severity.Maintainability,
"Var declaration could be val.",
Debt.FIVE_MINS
)
@Configuration("Whether to ignore uninitialized lateinit vars")
private val ignoreLateinitVar: Boolean by config(defaultValue = false)
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
if (bindingContext == BindingContext.EMPTY) return
val assignmentVisitor = AssignmentVisitor(bindingContext, ignoreLateinitVar)
file.accept(assignmentVisitor)
assignmentVisitor.getNonReAssignedDeclarations().forEach {
report(CodeSmell(issue, Entity.from(it), "Variable '${it.nameAsSafeName.identifier}' could be val."))
}
}
@Suppress("TooManyFunctions")
private class AssignmentVisitor(
private val bindingContext: BindingContext,
private val ignoreLateinitVar: Boolean
) : DetektVisitor() {
private val declarationCandidates = mutableSetOf<KtNamedDeclaration>()
private val assignments = mutableMapOf<String, MutableSet<KtExpression>>()
private val escapeCandidates = mutableMapOf<DeclarationDescriptor, List<KtProperty>>()
fun getNonReAssignedDeclarations(): List<KtNamedDeclaration> {
return declarationCandidates.filterNot { it.hasAssignments() }
}
private fun KtNamedDeclaration.hasAssignments(): Boolean {
val declarationName = nameAsSafeName.toString()
val assignments = assignments[declarationName]
if (assignments.isNullOrEmpty()) return false
val declarationDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this]
return assignments.any {
it.getResolvedCall(bindingContext)?.resultingDescriptor?.original == declarationDescriptor
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
// The super() call should be first in the function so that any properties
// declared in potential object literals can be evaluated.
super.visitNamedFunction(function)
evaluateReturnExpression(function.initializer)
}
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
if (property.isDeclarationCandidate()) {
declarationCandidates.add(property)
}
// Check for whether the initializer contains an object literal.
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, property]
val initializer = property.initializer
if (descriptor != null && initializer != null) {
evaluateAssignmentExpression(descriptor, initializer)
}
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
super.visitUnaryExpression(expression)
if (expression.operationToken in unaryAssignmentOperators) {
expression.baseExpression?.let(::visitAssignment)
}
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
super.visitBinaryExpression(expression)
if (expression.operationToken in KtTokens.ALL_ASSIGNMENTS) {
expression.left?.let(::visitAssignment)
// Check for whether the assignment contains an object literal.
val descriptor = (expression.left as? KtNameReferenceExpression)?.let {
it.getResolvedCall(bindingContext)?.resultingDescriptor
}
val expressionRight = expression.right
if (descriptor != null && expressionRight != null) {
evaluateAssignmentExpression(descriptor, expressionRight)
}
}
}
override fun visitReturnExpression(expression: KtReturnExpression) {
super.visitReturnExpression(expression)
evaluateReturnExpression(expression.returnedExpression)
}
private fun evaluateAssignmentExpression(
descriptor: DeclarationDescriptor,
rightExpression: KtExpression,
) {
when (rightExpression) {
is KtObjectLiteralExpression -> {
escapeCandidates[descriptor] = rightExpression.collectDescendantsOfType {
it.isEscapeCandidate()
}
}
is KtIfExpression -> {
rightExpression.then?.let { evaluateAssignmentExpression(descriptor, it) }
rightExpression.`else`?.let { evaluateAssignmentExpression(descriptor, it) }
}
is KtBlockExpression -> {
rightExpression.lastBlockStatementOrThis()
.takeIf { it != rightExpression }
?.let { evaluateAssignmentExpression(descriptor, it) }
}
}
}
private fun evaluateReturnExpression(returnedExpression: KtExpression?) {
when (returnedExpression) {
is KtObjectLiteralExpression -> {
returnedExpression.collectDescendantsOfType<KtProperty> {
it.isEscapeCandidate()
}.forEach(declarationCandidates::remove)
}
is KtNameReferenceExpression -> {
returnedExpression.getResolvedCall(bindingContext)?.resultingDescriptor?.let { descriptor ->
escapeCandidates[descriptor]?.forEach(declarationCandidates::remove)
}
}
is KtIfExpression -> {
evaluateReturnExpression(returnedExpression.then)
evaluateReturnExpression(returnedExpression.`else`)
}
is KtBlockExpression -> {
returnedExpression.lastBlockStatementOrThis()
.takeIf { it != returnedExpression }
?.let { evaluateReturnExpression(it) }
}
}
}
private fun KtProperty.isDeclarationCandidate(): Boolean {
return when {
!isVar || isOverride() || (ignoreLateinitVar && isLateinit()) -> false
isLocal || isPrivate() -> true
else -> {
// Check for whether property belongs to an anonymous object
// defined in a function.
containingClassOrObject
?.takeIf { it.isObjectLiteral() }
?.containingNonLocalDeclaration() != null
}
}
}
private fun KtProperty.isEscapeCandidate(): Boolean {
return !isPrivate() &&
(containingClassOrObject as? KtObjectDeclaration)?.isObjectLiteral() == true
}
private fun visitAssignment(assignedExpression: KtExpression) {
val name = if (assignedExpression is KtQualifiedExpression) {
assignedExpression.selectorExpression
} else {
assignedExpression
}?.text ?: return
assignments.getOrPut(name) { mutableSetOf() }.add(assignedExpression)
}
}
private companion object {
private val unaryAssignmentOperators = setOf(KtTokens.MINUSMINUS, KtTokens.PLUSPLUS)
}
}