forked from detekt/detekt
/
CanBeNonNullable.kt
584 lines (540 loc) · 24 KB
/
CanBeNonNullable.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
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.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.isAbstract
import io.gitlab.arturbosch.detekt.rules.isNonNullCheck
import io.gitlab.arturbosch.detekt.rules.isNullCheck
import io.gitlab.arturbosch.detekt.rules.isOpen
import io.gitlab.arturbosch.detekt.rules.isOverride
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtIsExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtPostfixExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtPropertyDelegate
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtSafeQualifiedExpression
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtWhenCondition
import org.jetbrains.kotlin.psi.KtWhenConditionIsPattern
import org.jetbrains.kotlin.psi.KtWhenConditionWithExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.isFirstStatement
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.smartcasts.getKotlinTypeForComparison
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isNullable
/**
* This rule inspects variables marked as nullable and reports which could be
* declared as non-nullable instead.
*
* It's preferred to not have functions that do "nothing".
* A function that does nothing when the value is null hides the logic,
* so it should not allow null values in the first place.
* It is better to move the null checks up around the calls,
* instead of having it inside the function.
*
* This could lead to less nullability overall in the codebase.
*
* <noncompliant>
* class A {
* var a: Int? = 5
*
* fun foo() {
* a = 6
* }
* }
*
* class A {
* val a: Int?
* get() = 5
* }
*
* fun foo(a: Int?) {
* val b = a!! + 2
* }
*
* fun foo(a: Int?) {
* if (a != null) {
* println(a)
* }
* }
*
* fun foo(a: Int?) {
* if (a == null) return
* println(a)
* }
* </noncompliant>
*
* <compliant>
* class A {
* var a: Int = 5
*
* fun foo() {
* a = 6
* }
* }
*
* class A {
* val a: Int
* get() = 5
* }
*
* fun foo(a: Int) {
* val b = a + 2
* }
*
* fun foo(a: Int) {
* println(a)
* }
* </compliant>
*/
@RequiresTypeResolution
class CanBeNonNullable(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(
javaClass.simpleName,
Severity.Style,
"Variable can be changed to non-nullable, as it is never set to null.",
Debt.TEN_MINS
)
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
PropertyCheckVisitor().visitKtFile(file)
ParameterCheckVisitor().visitKtFile(file)
}
@Suppress("TooManyFunctions")
private inner class ParameterCheckVisitor : DetektVisitor() {
private val nullableParams = mutableMapOf<DeclarationDescriptor, NullableParam>()
override fun visitNamedFunction(function: KtNamedFunction) {
if (function.isOverride()) {
return
}
val candidateDescriptors = mutableSetOf<DeclarationDescriptor>()
function.valueParameters.asSequence()
.filter {
it.typeReference?.typeElement is KtNullableType
}
.mapNotNull { parameter ->
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parameter]?.let {
it to parameter
}
}
.forEach { (descriptor, param) ->
candidateDescriptors.add(descriptor)
nullableParams[descriptor] = NullableParam(param)
}
val validSingleChildExpression = if (function.initializer == null) {
val children = function.bodyBlockExpression
?.allChildren
?.filterIsInstance<KtExpression>()
?.toList()
.orEmpty()
if (children.size == 1) {
children.first().determineSingleExpression(candidateDescriptors)
} else {
INELIGIBLE_SINGLE_EXPRESSION
}
} else {
INELIGIBLE_SINGLE_EXPRESSION
}
// Evaluate the function, then analyze afterwards whether the candidate properties
// could be made non-nullable.
super.visitNamedFunction(function)
candidateDescriptors.asSequence()
.mapNotNull(nullableParams::remove)
// The heuristic for whether a nullable param can be made non-nullable is:
// * It has been forced into a non-null type, either by `!!` or by
// `checkNonNull()`/`requireNonNull()`, or
// * The containing function only consists of a single non-null check on
// the param, either via an if/when check or with a safe-qualified expression.
.filter {
val onlyNonNullCheck = validSingleChildExpression && it.isNonNullChecked && !it.isNullChecked
it.isNonNullForced || it.isNullCheckReturnsUnit || onlyNonNullCheck
}
.forEach { nullableParam ->
report(
CodeSmell(
issue,
Entity.from(nullableParam.param),
"The nullable parameter '${nullableParam.param.name}' can be made non-nullable."
)
)
}
}
override fun visitCallExpression(expression: KtCallExpression) {
val calleeName = expression.calleeExpression
.getResolvedCall(bindingContext)
?.resultingDescriptor
?.name
?.toString()
// Check for whether a call to `checkNonNull()` or `requireNonNull()` has
// been made.
if (calleeName == REQUIRE_NOT_NULL_NAME || calleeName == CHECK_NOT_NULL_NAME) {
expression.valueArguments.forEach { valueArgument ->
valueArgument.getArgumentExpression()?.let { argumentExpression ->
updateNullableParam(argumentExpression) { it.isNonNullForced = true }
}
}
}
super.visitCallExpression(expression)
}
override fun visitPostfixExpression(expression: KtPostfixExpression) {
if (expression.operationToken == KtTokens.EXCLEXCL) {
expression.baseExpression?.let { baseExpression ->
updateNullableParam(baseExpression) { it.isNonNullForced = true }
}
}
super.visitPostfixExpression(expression)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
val subjectDescriptor = expression.subjectExpression
?.let { it as? KtNameReferenceExpression }
?.getResolvedCall(bindingContext)
?.resultingDescriptor
val whenConditions = expression.entries.flatMap { it.conditions.asList() }
if (subjectDescriptor != null) {
whenConditions.evaluateSubjectWhenExpression(expression, subjectDescriptor)
} else {
whenConditions.forEach { whenCondition ->
if (whenCondition is KtWhenConditionWithExpression) {
whenCondition.expression.evaluateCheckStatement(expression.elseExpression)
}
}
}
super.visitWhenExpression(expression)
}
override fun visitIfExpression(expression: KtIfExpression) {
expression.condition.evaluateCheckStatement(expression.`else`)
if (expression.isFirstStatement()) {
evaluateNullCheckReturnsUnit(expression.condition, expression.then)
}
super.visitIfExpression(expression)
}
private fun evaluateNullCheckReturnsUnit(condition: KtExpression?, then: KtExpression?) {
val thenExpression = if (then is KtBlockExpression) then.firstStatement else then
if (thenExpression !is KtReturnExpression) return
if (thenExpression.returnedExpression != null) return
if (condition is KtBinaryExpression && condition.isNullCheck()) {
getDescriptor(condition.left, condition.right)
?.let { nullableParams[it] }
?.let { it.isNullCheckReturnsUnit = true }
}
}
override fun visitSafeQualifiedExpression(expression: KtSafeQualifiedExpression) {
updateNullableParam(expression.receiverExpression) { it.isNonNullChecked = true }
super.visitSafeQualifiedExpression(expression)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
val isExtensionForNullable = expression.getResolvedCall(bindingContext)
?.resultingDescriptor
?.extensionReceiverParameter
?.type
?.isMarkedNullable
if (isExtensionForNullable == true) {
expression.receiverExpression
.getRootExpression()
?.let { rootExpression ->
updateNullableParam(rootExpression) { it.isNullChecked = true }
}
}
super.visitDotQualifiedExpression(expression)
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (expression.operationToken == KtTokens.ELVIS) {
expression.left
.getRootExpression()
?.let { rootExpression ->
updateNullableParam(rootExpression) { it.isNullChecked = true }
}
}
super.visitBinaryExpression(expression)
}
private fun KtExpression?.getRootExpression(): KtExpression? {
// Look for the expression that was the root of a potential call chain.
var receiverExpression = this
while (receiverExpression is KtQualifiedExpression) {
receiverExpression = receiverExpression.receiverExpression
}
return receiverExpression
}
private fun KtExpression?.determineSingleExpression(candidateDescriptors: Set<DeclarationDescriptor>): Boolean {
return when (this) {
is KtReturnExpression -> INELIGIBLE_SINGLE_EXPRESSION
is KtIfExpression -> ELIGIBLE_SINGLE_EXPRESSION
is KtDotQualifiedExpression -> {
this.getRootExpression()
.getResolvedCall(bindingContext)
?.resultingDescriptor
?.let(candidateDescriptors::contains) == true
}
is KtCallExpression -> INELIGIBLE_SINGLE_EXPRESSION
else -> ELIGIBLE_SINGLE_EXPRESSION
}
}
private fun KtExpression?.getNonNullChecks(): List<CallableDescriptor>? {
return when (this) {
is KtBinaryExpression -> evaluateBinaryExpression()
is KtIsExpression -> evaluateIsExpression()
else -> null
}
}
private fun KtExpression?.evaluateCheckStatement(elseExpression: KtExpression?) {
this.getNonNullChecks()?.let { nonNullChecks ->
val nullableParamCallback = if (elseExpression.isValidElseExpression()) {
{ nullableParam: NullableParam ->
nullableParam.isNonNullChecked = true
nullableParam.isNullChecked = true
}
} else {
{ nullableParam -> nullableParam.isNonNullChecked = true }
}
nonNullChecks.forEach { nullableParams[it]?.let(nullableParamCallback) }
}
}
// Helper function for if- and when-statements that will recursively check for whether
// any function params have been checked for being a non-nullable type.
private fun KtBinaryExpression.evaluateBinaryExpression(): List<CallableDescriptor> {
val leftExpression = left
val rightExpression = right
val nonNullChecks = mutableListOf<CallableDescriptor>()
if (isNullCheck()) {
getDescriptor(leftExpression, rightExpression)
?.let { nullableParams[it] }
?.let { it.isNullChecked = true }
} else if (isNonNullCheck()) {
getDescriptor(leftExpression, rightExpression)?.let(nonNullChecks::add)
}
// Recursively iterate into the if-check if possible
leftExpression.getNonNullChecks()?.let(nonNullChecks::addAll)
rightExpression.getNonNullChecks()?.let(nonNullChecks::addAll)
return nonNullChecks
}
private fun getDescriptor(leftExpression: KtExpression?, rightExpression: KtExpression?): CallableDescriptor? {
return when {
leftExpression is KtNameReferenceExpression -> leftExpression
rightExpression is KtNameReferenceExpression -> rightExpression
else -> null
}?.getResolvedCall(bindingContext)
?.resultingDescriptor
}
private fun KtIsExpression.evaluateIsExpression(): List<CallableDescriptor> {
val descriptor = this.leftHandSide.getResolvedCall(bindingContext)?.resultingDescriptor
?: return emptyList()
return if (isNullableCheck(typeReference, isNegated)) {
nullableParams[descriptor]?.let { it.isNullChecked = true }
emptyList()
} else {
listOf(descriptor)
}
}
private fun List<KtWhenCondition>.evaluateSubjectWhenExpression(
expression: KtWhenExpression,
subjectDescriptor: CallableDescriptor
) {
var isNonNullChecked = false
var isNullChecked = false
forEach { whenCondition ->
when (whenCondition) {
is KtWhenConditionWithExpression -> {
if (whenCondition.expression?.text == "null") {
isNullChecked = true
}
}
is KtWhenConditionIsPattern -> {
if (isNullableCheck(whenCondition.typeReference, whenCondition.isNegated)) {
isNullChecked = true
} else {
isNonNullChecked = true
}
}
}
}
if (expression.elseExpression.isValidElseExpression()) {
if (isNullChecked) {
isNonNullChecked = true
} else if (isNonNullChecked) {
isNullChecked = true
}
}
nullableParams[subjectDescriptor]?.let {
if (isNullChecked) it.isNullChecked = true
if (isNonNullChecked) it.isNonNullChecked = true
}
}
private fun isNullableCheck(typeReference: KtTypeReference?, isNegated: Boolean): Boolean {
val isNullable = typeReference.isNullable(bindingContext)
return (isNullable && !isNegated) || (!isNullable && isNegated)
}
private fun KtExpression?.isValidElseExpression(): Boolean {
return this != null && this !is KtIfExpression && this !is KtWhenExpression
}
private fun KtTypeReference?.isNullable(bindingContext: BindingContext): Boolean {
return this?.let { bindingContext[BindingContext.TYPE, it] }?.isMarkedNullable == true
}
private fun updateNullableParam(expression: KtExpression, updateCallback: (NullableParam) -> Unit) {
expression.getResolvedCall(bindingContext)
?.resultingDescriptor
?.let { nullableParams[it] }
?.let(updateCallback)
}
}
private class NullableParam(val param: KtParameter) {
var isNullChecked = false
var isNonNullChecked = false
var isNonNullForced = false
var isNullCheckReturnsUnit = false
}
private inner class PropertyCheckVisitor : DetektVisitor() {
// A list of properties that are marked as nullable during their
// declaration but do not explicitly receive a nullable value in
// the declaration, so they could potentially be marked as non-nullable
// if the file does not encounter these properties being assigned
// a nullable value.
private val candidateProps = mutableMapOf<FqName, KtProperty>()
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
// Any candidate properties that were not removed during the inspection
// of the Kotlin file were never assigned nullable values in the code,
// thus they can be converted to non-nullable.
candidateProps.forEach { (_, property) ->
report(
CodeSmell(
issue,
Entity.from(property),
"The nullable variable '${property.name}' can be made non-nullable."
)
)
}
}
override fun visitClass(klass: KtClass) {
if (!klass.isInterface()) {
super.visitClass(klass)
}
}
override fun visitProperty(property: KtProperty) {
val type = property.getKotlinTypeForComparison(bindingContext)
if (type?.isNullableAndCanBeNonNullable() == true) {
val fqName = property.fqName
if (property.isCandidate() && fqName != null) {
candidateProps[fqName] = property
}
}
super.visitProperty(property)
}
override fun visitBinaryExpression(expression: KtBinaryExpression) {
if (expression.operationToken == KtTokens.EQ) {
val fqName = expression.left
?.getResolvedCall(bindingContext)
?.resultingDescriptor
?.fqNameOrNull()
if (
fqName != null &&
candidateProps.containsKey(fqName) &&
expression.right?.isNullableType() == true
) {
// A candidate property has been assigned a nullable value
// in the file's code, so it can be removed from the map of
// candidates for flagging.
candidateProps.remove(fqName)
}
}
super.visitBinaryExpression(expression)
}
/**
* Determines whether a type is nullable and can be made non-nullable; for most properties
* this is simply whether they are nullable, but for type parameters they can only be made
* non-nullable when explicitly marked nullable.
*
* Note that [KotlinType.isNullable] for type parameter types is true unless it inherits
* from a non-nullable type, e.g.:
* - nullable: <T> or <T : Any?>
* - non-nullable: <T : Any>
* But even if T is nullable, a property `val t: T` cannot be made into a non-nullable type.
*/
private fun KotlinType.isNullableAndCanBeNonNullable(): Boolean {
return if (TypeUtils.isTypeParameter(this)) isMarkedNullable else isNullable()
}
private fun KtProperty.isCandidate(): Boolean {
if (isOpen() || isAbstract()) return false
val isSetToNonNullable = initializer?.isNullableType() != true &&
getter?.isNullableType() != true &&
delegate?.returnsNullable() != true
val cannotSetViaNonPrivateMeans = !isVar || (isPrivate() || (setter?.isPrivate() == true))
return isSetToNonNullable && cannotSetViaNonPrivateMeans
}
private fun KtPropertyDelegate?.returnsNullable(): Boolean {
val property = this?.parent as? KtProperty ?: return false
val propertyDescriptor =
bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? PropertyDescriptor
return propertyDescriptor?.getter?.let {
bindingContext[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, it]
?.resultingDescriptor
?.returnType
?.isNullable() == true
} ?: false
}
private fun KtExpression?.isNullableType(): Boolean {
return when (this) {
is KtConstantExpression -> {
this.text == "null"
}
is KtIfExpression -> {
this.then.isNullableType() || this.`else`.isNullableType()
}
is KtPropertyAccessor -> {
(initializer?.getType(bindingContext)?.isNullable() == true) ||
(
bodyExpression
?.collectDescendantsOfType<KtReturnExpression>()
?.any { it.returnedExpression.isNullableType() } == true
)
}
else -> {
// only consider types which can be made non-nullable as nullable to warn on
// cases where a field has declared type `T?` but is only assigned as `T`; here
// `T` should not be considered nullable to enforce that the field could be
// declared as just `T`
this?.getType(bindingContext)?.isNullableAndCanBeNonNullable() == true
}
}
}
}
private companion object {
private const val REQUIRE_NOT_NULL_NAME = "requireNotNull"
private const val CHECK_NOT_NULL_NAME = "checkNotNull"
private const val INELIGIBLE_SINGLE_EXPRESSION = false
private const val ELIGIBLE_SINGLE_EXPRESSION = true
}
}