Skip to content

Commit

Permalink
MaxChainedCallsOnSameLine: don't count class references as chained calls
Browse files Browse the repository at this point in the history
  • Loading branch information
t-kameyama committed Jun 16, 2023
1 parent 3ddaa00 commit 75d708a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.config
import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
Expand Down Expand Up @@ -73,18 +74,19 @@ class MaxChainedCallsOnSameLine(config: Config = Config.empty) : Rule(config) {
private fun KtExpression.countChainedCalls(): Int {
return when (this) {
is KtQualifiedExpression -> when {
receiverExpression.isReferenceToPackage() || callOnNewLine() -> 0
receiverExpression.isReferenceToPackageOrClass() || callOnNewLine() -> 0
else -> receiverExpression.countChainedCalls() + 1
}
is KtUnaryExpression -> baseExpression?.countChainedCalls() ?: 0
else -> 0
}
}

private fun KtExpression.isReferenceToPackage(): Boolean {
private fun KtExpression.isReferenceToPackageOrClass(): Boolean {
val selectorOrThis = (this as? KtQualifiedExpression)?.selectorExpression ?: this
if (selectorOrThis !is KtReferenceExpression) return false
return bindingContext[BindingContext.REFERENCE_TARGET, selectorOrThis] is PackageViewDescriptor
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, selectorOrThis]
return descriptor is PackageViewDescriptor || descriptor is ClassDescriptor
}

private fun KtQualifiedExpression.callOnNewLine(): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,25 @@ class MaxChainedCallsOnSameLineSpec(private val env: KotlinCoreEnvironment) {
assertThat(rule.compileAndLintWithContext(env, code)).isEmpty()
}

@Test
fun `does not count class references as chained calls`() {
val code = """
sealed class Nav {
object List : Nav {
sealed interface Params {
object Groups : Params {
enum class Source {
Profiles
}
}
}
}
}
val x = Nav.List.Params.Groups.Source.Profiles
""".trimIndent()
assertThat(rule.compileAndLintWithContext(env, code)).isEmpty()
}

@Test
fun `does not count package references as chained calls`() {
val code = """
Expand Down

0 comments on commit 75d708a

Please sign in to comment.