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

Fix not checking for spacing around binary operators inside unary expression #2653

Merged
merged 1 commit into from
May 12, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint
import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint.Status.STABLE
import com.pinterest.ktlint.rule.engine.core.api.isPartOf
import com.pinterest.ktlint.rule.engine.core.api.nextLeaf
import com.pinterest.ktlint.rule.engine.core.api.parent
import com.pinterest.ktlint.rule.engine.core.api.prevLeaf
import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe
import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe
Expand All @@ -39,6 +40,7 @@ import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtOperationExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression

@SinceKtlint("0.1", STABLE)
Expand Down Expand Up @@ -107,7 +109,7 @@ public class SpacingAroundOperatorsRule : StandardRule("op-spacing") {
}
}

private fun ASTNode.isUnaryOperator() = isPartOf(KtPrefixExpression::class)
private fun ASTNode.isUnaryOperator() = parent { it.psi is KtOperationExpression }?.psi is KtPrefixExpression

private fun ASTNode.isSpreadOperator() =
// fn(*array)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,4 +314,28 @@ class SpacingAroundOperatorsRuleTest {
LintViolation(4, 41, "Missing spacing after \"andThen\""),
).isFormattedAs(formattedCode)
}

@Test
fun `Given a binary operator inside a unary expression`() {
val code =
"""
val foo1 = !(null?:true)
val foo2 = !(null?: true)
val foo3 = !(null ?:true)
val foo4 = !(null ?: true)
""".trimIndent()
val formattedCode =
"""
val foo1 = !(null ?: true)
val foo2 = !(null ?: true)
val foo3 = !(null ?: true)
val foo4 = !(null ?: true)
""".trimIndent()
spacingAroundOperatorsRuleAssertThat(code)
.hasLintViolations(
LintViolation(1, 18, "Missing spacing around \"?:\""),
LintViolation(2, 18, "Missing spacing before \"?:\""),
LintViolation(3, 21, "Missing spacing after \"?:\""),
).isFormattedAs(formattedCode)
}
}