Skip to content

Commit

Permalink
Refactor RedundantElseInWhen to use compiler warning (#3214)
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kameyama authored and arturbosch committed Jan 16, 2021
1 parent 895fd7f commit 1edbe2e
Showing 1 changed file with 5 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,10 @@ 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.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.cfg.WhenChecker
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingContext.DECLARATION_TO_DESCRIPTOR
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.source.getPsi

/*
* Based on code from Kotlin compiler:
* https://github.com/JetBrains/kotlin/blob/v1.3.30/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt
*/
/**
* Turn on this rule to flag `when` expressions that contain a redundant `else` case. This occurs when it can be
* verified that all cases are already covered when checking cases on an enum or sealed class.
Expand Down Expand Up @@ -83,19 +72,10 @@ class RedundantElseInWhen(config: Config = Config.empty) : Rule(config) {
super.visitWhenExpression(whenExpression)

if (bindingContext == BindingContext.EMPTY) return
if (whenExpression.elseExpression == null) return
val subjectType = whenExpression.subjectExpression?.getType(bindingContext)

if (subjectType != null && WhenChecker.getMissingCases(whenExpression, bindingContext).isEmpty()) {
val subjectClass = subjectType.constructor.declarationDescriptor as? ClassDescriptor
val pseudocodeDescriptor =
bindingContext[DECLARATION_TO_DESCRIPTOR, subjectClass?.toSourceElement?.getPsi()]
if (subjectClass == null ||
KotlinBuiltIns.isBooleanOrNullableBoolean(subjectType) ||
subjectClass.module == pseudocodeDescriptor?.module
) {
report(CodeSmell(issue, Entity.from(whenExpression), "When expression contains redundant `else` case."))
}
val elseEntry = whenExpression.entries.lastOrNull { it.isElse } ?: return
val compilerReports = bindingContext.diagnostics.forElement(elseEntry)
if (compilerReports.any { it.factory == Errors.REDUNDANT_ELSE_IN_WHEN }) {
report(CodeSmell(issue, Entity.from(whenExpression), "When expression contains redundant `else` case."))
}
}
}

0 comments on commit 1edbe2e

Please sign in to comment.