Skip to content

Commit

Permalink
Fix check for spacing around operator for binary operators inside una…
Browse files Browse the repository at this point in the history
…ry expression (#2653)

For example an expression wrapped in `!(<some-binary-expression>)` should check/fix spacing around the operator in the inner binary expression.

Fixes #2652
  • Loading branch information
cflee authored May 12, 2024
1 parent 605b5e7 commit 238f9f3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
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)
}
}

0 comments on commit 238f9f3

Please sign in to comment.