-
-
Notifications
You must be signed in to change notification settings - Fork 755
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
Potential new rule: DoubleNegativeLambda #5937
Merged
Merged
Changes from 13 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
f09fecb
Add rule to detekt double negatives from function name expressed in n…
drawers 9063e75
Fix issue id
drawers dde9fac
Fix test snippets not compiling
drawers ea570a5
Fix test snippets not compiling
drawers df6a662
Add config for negative function name parts
drawers 38a187a
Add value with reason config for negative function names
drawers 4748ba8
Rename forbiddenFunction to negativeFunction
drawers 6f7ab16
Rename lambdaExpression to lambdaArgument
drawers e7b22f1
Make compliant/noncompliant example clearer
drawers 6483b16
Add test against logical not on prefixing brackets
drawers 12b0006
Add extra test
drawers bacd753
Clean up FQN use in tests
drawers 2ded6a4
Make recommendation full-text, not just the simple name of the counte…
drawers 525956e
Add `none` as a default
drawers dbfebfd
Adjust tests to account for none as a default
drawers File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
130 changes: 130 additions & 0 deletions
130
...les-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/DoubleNegativeLambda.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
package io.gitlab.arturbosch.detekt.rules.style | ||
|
||
import io.gitlab.arturbosch.detekt.api.CodeSmell | ||
import io.gitlab.arturbosch.detekt.api.Config | ||
import io.gitlab.arturbosch.detekt.api.Debt | ||
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 io.gitlab.arturbosch.detekt.api.config | ||
import io.gitlab.arturbosch.detekt.api.internal.Configuration | ||
import io.gitlab.arturbosch.detekt.api.valuesWithReason | ||
import org.jetbrains.kotlin.lexer.KtTokens | ||
import org.jetbrains.kotlin.psi.KtCallExpression | ||
import org.jetbrains.kotlin.psi.KtExpression | ||
import org.jetbrains.kotlin.psi.KtOperationReferenceExpression | ||
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType | ||
|
||
/** | ||
* Detects negation in lambda blocks where the function name is also in the negative (like `takeUnless`). | ||
* A double negative is harder to read than a positive. In particular, if there are multiple conditions with `&&` etc. inside | ||
* the lambda, then the reader may need to unpack these using DeMorgan's laws. Consider rewriting the lambda to use a positive version | ||
* of the function (like `takeIf`). | ||
* | ||
* <noncompliant> | ||
* fun Int.evenOrNull() = takeUnless { it % 2 != 0 } | ||
* </noncompliant> | ||
* <compliant> | ||
* fun Int.evenOrNull() = takeIf { it % 2 == 0 } | ||
* </compliant> | ||
*/ | ||
class DoubleNegativeLambda(config: Config = Config.empty) : Rule(config) { | ||
|
||
override val issue = Issue( | ||
"DoubleNegativeLambda", | ||
Severity.Style, | ||
"Double negative from a function name expressed in the negative (like `takeUnless`) with a lambda block " + | ||
"that also contains negation. This is more readable when rewritten using a positive form of the function " + | ||
"(like `takeIf`).", | ||
Debt.FIVE_MINS, | ||
) | ||
|
||
private val splitCamelCaseRegex = "(?<=[a-z])(?=[A-Z])".toRegex() | ||
|
||
private val negationTokens = listOf( | ||
KtTokens.EXCL, | ||
KtTokens.EXCLEQ, | ||
KtTokens.EXCLEQEQEQ, | ||
KtTokens.NOT_IN, | ||
KtTokens.NOT_IS, | ||
) | ||
|
||
@Configuration( | ||
"Function names expressed in the negative that can form double negatives with their lambda blocks. " + | ||
"These are grouped together with a recommendation to use a positive counterpart, or `null` if this is " + | ||
"unknown." | ||
) | ||
private val negativeFunctions: List<NegativeFunction> by config( | ||
valuesWithReason( | ||
"takeUnless" to "Use `takeIf` instead.", | ||
) | ||
) { list -> | ||
list.map { NegativeFunction(simpleName = it.value, recommendation = it.reason) } | ||
} | ||
|
||
@Configuration( | ||
"Function name parts to look for in the lambda block when deciding " + | ||
"if the lambda contains a negative." | ||
) | ||
private val negativeFunctionNameParts: Set<String> by config(listOf("not", "non")) { it.toSet() } | ||
|
||
override fun visitCallExpression(expression: KtCallExpression) { | ||
super.visitCallExpression(expression) | ||
val calleeExpression = expression.calleeExpression?.text ?: return | ||
val negativeFunction = negativeFunctions.firstOrNull { it.simpleName == calleeExpression } ?: return | ||
val lambdaArgument = expression.lambdaArguments.firstOrNull() ?: return | ||
|
||
val forbiddenChildren = lambdaArgument.collectDescendantsOfType<KtExpression> { | ||
it.isForbiddenNegation() | ||
} | ||
|
||
if (forbiddenChildren.isNotEmpty()) { | ||
report( | ||
CodeSmell( | ||
issue, | ||
Entity.from(expression), | ||
formatMessage(forbiddenChildren, negativeFunction) | ||
) | ||
) | ||
} | ||
} | ||
|
||
private fun KtExpression.isForbiddenNegation(): Boolean { | ||
return when (this) { | ||
is KtOperationReferenceExpression -> operationSignTokenType in negationTokens | ||
is KtCallExpression -> text == "not()" || text.split(splitCamelCaseRegex).map { it.lowercase() } | ||
.any { it in negativeFunctionNameParts } | ||
|
||
else -> false | ||
} | ||
} | ||
|
||
private fun formatMessage( | ||
forbiddenChildren: List<KtExpression>, | ||
negativeFunction: NegativeFunction, | ||
) = buildString { | ||
append("Double negative through using ${forbiddenChildren.joinInBackTicks()} inside a ") | ||
append("`${negativeFunction.simpleName}` lambda. ") | ||
if (negativeFunction.recommendation != null) { | ||
append(negativeFunction.recommendation) | ||
} else { | ||
append("Rewrite in the positive.") | ||
} | ||
} | ||
|
||
private fun List<KtExpression>.joinInBackTicks() = joinToString { "`${it.text}`" } | ||
|
||
/** | ||
* A function that can form a double negative with its lambda. | ||
*/ | ||
private data class NegativeFunction( | ||
val simpleName: String, | ||
val recommendation: String?, | ||
) | ||
|
||
companion object { | ||
const val NEGATIVE_FUNCTIONS = "negativeFunctions" | ||
const val NEGATIVE_FUNCTION_NAME_PARTS = "negativeFunctionNameParts" | ||
} | ||
} | ||
Check warning on line 130 in detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/DoubleNegativeLambda.kt Codecov / codecov/patchdetekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/DoubleNegativeLambda.kt#L130
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
238 changes: 238 additions & 0 deletions
238
...style/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/DoubleNegativeLambdaSpec.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,238 @@ | ||
package io.gitlab.arturbosch.detekt.rules.style | ||
|
||
import io.gitlab.arturbosch.detekt.api.Config | ||
import io.gitlab.arturbosch.detekt.api.ValueWithReason | ||
import io.gitlab.arturbosch.detekt.test.TestConfig | ||
import io.gitlab.arturbosch.detekt.test.assertThat | ||
import io.gitlab.arturbosch.detekt.test.compileAndLint | ||
import io.gitlab.arturbosch.detekt.test.toConfig | ||
import org.junit.jupiter.api.Test | ||
|
||
class DoubleNegativeLambdaSpec { | ||
|
||
private val subject = DoubleNegativeLambda(Config.empty) | ||
|
||
@Test | ||
fun `reports simple logical not`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isEven() = this % 2 == 0 | ||
val rand = Random.Default.nextInt().takeUnless { !it.isEven() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports logical not in binary expression`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isEven() = this % 2 == 0 | ||
val rand = Random.Default.nextInt().takeUnless { it > 0 && !it.isEven() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports logical not prefixing brackets`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isEven() = this % 2 == 0 | ||
val rand = Random.Default.nextInt().takeUnless { !(it == 0 || it.isEven()) } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports negation inside nested lambda`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isEven() = this % 2 == 0 | ||
val rand = Random.Default.nextInt().takeUnless { it.isEven().takeIf { i -> !i } ?: false } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports double nested negation`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isEven() = this % 2 == 0 | ||
val rand = Random.Default.nextInt().takeUnless { it.isEven().takeUnless { i -> !i } ?: false } | ||
""".trimIndent() | ||
|
||
val findings = subject.compileAndLint(code) | ||
assertThat(findings).hasSize(2) | ||
assertThat(findings[0]).hasSourceLocation(3, 62) // second takeUnless | ||
assertThat(findings[1]).hasSourceLocation(3, 37) // first takeUnless | ||
} | ||
|
||
@Test | ||
fun `reports function with 'not' in the name`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isNotZero() = this != 0 | ||
val rand = Random.Default.nextInt().takeUnless { it.isNotZero() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports zero-param function with 'non' in the name`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isNonNegative() = 0 < this | ||
val rand = Random.Default.nextInt().takeUnless { it.isNonNegative() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports single-param function with 'non' in the name`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isNotGreaterThan(other: Int) = other < this | ||
val rand = Random.Default.nextInt().takeUnless { it.isNotGreaterThan(0) } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports not equal`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
val rand = Random.Default.nextInt().takeUnless { it != 0 } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports not equal by reference`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
val rand = Random.Default.nextInt().takeUnless { it !== 0 } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports !in`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
val rand = Random.Default.nextInt().takeUnless { it !in 1..3 } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports !is`() { | ||
val code = """ | ||
val list = listOf(3, "a", true) | ||
val maybeBoolean = list.firstOrNull().takeUnless { it !is Boolean } | ||
""".trimIndent() | ||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports use of operator fun not`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
val rand = Random.Default.nextInt().takeUnless { (it > 0).not() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `does not report function with 'not' in part of the name`() { | ||
val code = """ | ||
fun String.hasAnnotations() = this.contains("annotations") | ||
val nonAnnotated = "".takeUnless { it.hasAnnotations() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `does not report non-null assert in takeUnless`() { | ||
val code = """ | ||
val x = "".takeUnless { it!!.isEmpty() } | ||
""".trimIndent() | ||
|
||
assertThat(subject.compileAndLint(code)).isEmpty() | ||
} | ||
|
||
@Test | ||
fun `reports negative function name from config`() { | ||
val config = | ||
TestConfig( | ||
DoubleNegativeLambda.NEGATIVE_FUNCTIONS to listOf( | ||
ValueWithReason(value = "none", reason = "any").toConfig(), | ||
ValueWithReason(value = "filterNot", reason = "filter").toConfig(), | ||
) | ||
) | ||
val code = """ | ||
fun Int.isEven() = this % 2 == 0 | ||
val isValid = listOf(1, 2, 3).filterNot { !it.isEven() }.none { it != 0 } | ||
""".trimIndent() | ||
|
||
assertThat(DoubleNegativeLambda(config).compileAndLint(code)).hasSize(2) | ||
} | ||
|
||
@Test | ||
fun `reports negative function name parts from config`() { | ||
val config = TestConfig(DoubleNegativeLambda.NEGATIVE_FUNCTION_NAME_PARTS to listOf("isnt")) | ||
val code = """ | ||
import kotlin.random.Random | ||
fun Int.isntOdd() = this % 2 == 0 | ||
val rand = Random.Default.nextInt().takeUnless { it.isntOdd() } | ||
""".trimIndent() | ||
|
||
assertThat(DoubleNegativeLambda(config).compileAndLint(code)).hasSize(1) | ||
} | ||
|
||
@Test | ||
fun `reports multiple negations in message`() { | ||
val code = """ | ||
import kotlin.random.Random | ||
val list: List<Int> = listOf(1, 2, 3) | ||
val rand = Random.Default.nextInt().takeUnless { it !in list && it != 0 } | ||
""".trimIndent() | ||
|
||
val findings = subject.compileAndLint(code) | ||
assertThat(findings).hasSize(1) | ||
assertThat(findings).hasStartSourceLocation(3, 37) | ||
assertThat(findings).hasEndSourceLocation(3, 74) | ||
assertThat(findings[0]).hasMessage( | ||
"Double negative through using `!in`, `!=` inside a `takeUnless` lambda. Use `takeIf` instead." | ||
) | ||
} | ||
|
||
@Test | ||
fun `report for negative function with no positive counterpart`() { | ||
val config = | ||
TestConfig( | ||
DoubleNegativeLambda.NEGATIVE_FUNCTIONS to listOf( | ||
ValueWithReason(value = "none", reason = null).toConfig(), | ||
) | ||
) | ||
val code = """ | ||
val list = listOf(1, 2, 3) | ||
val result = list.none { it != 0 } | ||
""".trimIndent() | ||
|
||
val findings = DoubleNegativeLambda(config).compileAndLint(code) | ||
assertThat(findings[0]).hasMessage( | ||
"Double negative through using `!=` inside a `none` lambda. Rewrite in the positive." | ||
) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what's the reason why you haven't included
none
andfilterNot
in the default here?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you for the review.
I think there is a good case to add
none
as a default. I searched a few big Kotlin codebases, including Detekt and KotlinPoet. I couldn't find any examples ofnone
with a negation in its lambda. So it seems it would be something we would catch in a code review. Addingnone
would help explain the rule to consumers too.I did not include
filterNot
because it seems there are a few cases where it seems more readable leaving it in the negative. I found this example in KotlinPoet:Rewriting this, we'd end up with:
What do you think about adding
none
as a default and leaving outfilterNot
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yup makes sense, thanks for clarifying 👍
none
feels also like the most natural use case for this rule