Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnusedUnaryOperator: fix false positive with var assignment and if expression #5106

Merged
merged 1 commit into from Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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()
}
}