Skip to content

Commit

Permalink
UnusedUnaryOperator: fix false positive with var assignment and if ex…
Browse files Browse the repository at this point in the history
…pression (detekt#5106)
  • Loading branch information
t-kameyama authored and VitalyVPinchuk committed Jul 25, 2022
1 parent 2dde603 commit d1effe7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
Expand Up @@ -17,8 +17,8 @@ import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.psiUtil.getTopmostParentOfType
import org.jetbrains.kotlin.psi.psiUtil.leaves
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
Expand Down Expand Up @@ -62,7 +62,7 @@ class UnusedUnaryOperator(config: Config = Config.empty) : Rule(config) {
.none { it is PsiWhiteSpace && it.textContains('\n') }
) return

val parentOrSelf = (expression.getTopmostParentOfType<KtBinaryExpression>() ?: expression) as KtExpression
val parentOrSelf = expression.parentBinaryExpressionOrThis()
if (parentOrSelf.isUsedAsExpression(bindingContext)) return

val operatorDescriptor = expression.operationReference.getResolvedCall(bindingContext)
Expand All @@ -72,4 +72,8 @@ class UnusedUnaryOperator(config: Config = Config.empty) : Rule(config) {
val message = "This '${parentOrSelf.text}' is not used"
report(CodeSmell(issue, Entity.from(expression), message))
}

private fun KtExpression.parentBinaryExpressionOrThis(): KtExpression {
return parents.takeWhile { it is KtBinaryExpression }.lastOrNull() as? KtBinaryExpression ?: this
}
}
Expand Up @@ -122,4 +122,20 @@ class UnusedUnaryOperatorSpec(private val env: KotlinCoreEnvironment) {
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}

@Test
fun `var assignment by if expression`() {
val code = """
fun test(b: Boolean) {
var x = 0
x = if (b) {
-1
} else {
1
}
}
"""
val findings = subject.compileAndLintWithContext(env, code)
assertThat(findings).isEmpty()
}
}

0 comments on commit d1effe7

Please sign in to comment.