All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.gitlab.arturbosch.detekt.rules.GuardClauses.kt Maven / Gradle / Ivy

package io.gitlab.arturbosch.detekt.rules

import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis

inline fun  KtNamedFunction.yieldStatementsSkippingGuardClauses(): Sequence =
    sequence {
        var firstNonGuardFound = false
        [email protected]?.statements?.forEach {
            if (firstNonGuardFound) {
                yield(it)
            } else if (!it.isGuardClause() && !it.isSuperCall()) {
                firstNonGuardFound = true
                yield(it)
            }
        }
    }

fun KtExpression.isSuperCall(): Boolean {
    return (this as? KtDotQualifiedExpression)?.receiverExpression is KtSuperExpression
}

inline fun  KtExpression.isGuardClause(): Boolean {
    val descendantExpr = this.findDescendantOfType() ?: return false
    return this.isIfConditionGuardClause(descendantExpr) || this.isElvisOperatorGuardClause(descendantExpr)
}

fun  KtExpression.isIfConditionGuardClause(descendantExpr: T): Boolean {
    val ifExpr = this as? KtIfExpression ?: return false
    return ifExpr.`else` == null &&
        descendantExpr === ifExpr.then?.lastBlockStatementOrThis()
}

fun  KtExpression.isElvisOperatorGuardClause(descendantExpr: T): Boolean =
    this.anyDescendantOfType { it.operationToken == KtTokens.ELVIS && it.right == descendantExpr }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy