Skip to content

Commit

Permalink
Fixing ClassCastException with NoLineBreakBeforeAssignmentRule when t…
Browse files Browse the repository at this point in the history
…here is no space after assignment

Fixes pinterest#693
  • Loading branch information
shashachu committed Jun 1, 2020
1 parent 5ad1671 commit 894e697
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.pinterest.ktlint.ruleset.standard

import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.EQ
import com.pinterest.ktlint.core.ast.ElementType.REGULAR_STRING_PART
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
Expand All @@ -14,7 +15,14 @@ class NoLineBreakBeforeAssignmentRule : Rule("no-line-break-before-assignment")
if (prevElement is PsiWhiteSpace && prevElement.text.contains("\n")) {
emit(node.startOffset, "Line break before assignment is not allowed", true)
if (autoCorrect) {
(node.treeNext?.psi as LeafPsiElement).rawReplaceWithText(prevElement.text)
val leaf = node.treeNext?.psi as? LeafPsiElement
if (leaf != null) {
leaf.rawReplaceWithText(prevElement.text)
} else {
(node.psi as LeafPsiElement).rawInsertAfterMe(
LeafPsiElement(REGULAR_STRING_PART, prevElement.text)
)
}
(prevElement as LeafPsiElement).rawReplaceWithText(" ")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,21 @@ class NoLineBreakBeforeAssignmentRuleTest {
""".trimIndent()
)
}

@Test
fun `test assignment with no following space issue #693`() {
assertThat(
NoLineBreakBeforeAssignmentRule().format(
"""
fun a()
=f()
""".trimIndent()
)
).isEqualTo(
"""
fun a() =
f()
""".trimIndent()
)
}
}

0 comments on commit 894e697

Please sign in to comment.