Skip to content

Commit

Permalink
Do not insert a trailing comma in a multiline when-entry containing a…
Browse files Browse the repository at this point in the history
… guard (#2825)

Closes #2817
  • Loading branch information
paul-dingemans authored Oct 4, 2024
1 parent d829568 commit 524ecb3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import com.pinterest.ktlint.rule.engine.core.util.cast
import com.pinterest.ktlint.ruleset.standard.StandardRule
import org.ec4j.core.model.PropertyType
import org.ec4j.core.model.PropertyType.PropertyValueParser
import org.jetbrains.kotlin.KtNodeTypes.WHEN_ENTRY_GUARD
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
Expand Down Expand Up @@ -257,7 +258,13 @@ public class TrailingCommaOnDeclarationSiteRule :
val trailingCommaNode = prevLeaf?.findPreviousTrailingCommaNodeOrNull()
val trailingCommaState =
when {
hasWhenGuard() -> {
// The compiler won't allow any comma in the when-entry in case it contains a guard clause
TrailingCommaState.NOT_EXISTS
}

isMultiline(psi) -> if (trailingCommaNode != null) TrailingCommaState.EXISTS else TrailingCommaState.MISSING

else -> if (trailingCommaNode != null) TrailingCommaState.REDUNDANT else TrailingCommaState.NOT_EXISTS
}
when (trailingCommaState) {
Expand Down Expand Up @@ -425,6 +432,8 @@ public class TrailingCommaOnDeclarationSiteRule :
return codeLeaf?.takeIf { it.elementType == COMMA }
}

private fun ASTNode.hasWhenGuard() = elementType == WHEN_ENTRY && children().any { it.elementType == WHEN_ENTRY_GUARD }

private fun containsLineBreakInLeavesRange(
from: PsiElement,
to: PsiElement,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1066,4 +1066,28 @@ class TrailingCommaOnDeclarationSiteRuleTest {
.hasLintViolation(3, 13, "Missing trailing comma and newline before \"->\"")
.isFormattedAs(formattedCode)
}

@Test
fun `Issue 2817 - Given when condition with guard clause`() {
val code =
"""
val x1 =
when (true) {
true if foo("a") -> true
else -> false
}
val x2 =
when (true) {
true if foo(
"a",
)
-> true
else -> false
}
""".trimIndent()
trailingCommaOnDeclarationSiteRuleAssertThat(code)
.withEditorConfigOverride(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY to true)
.hasNoLintViolations()
}
}

0 comments on commit 524ecb3

Please sign in to comment.