Skip to content

Commit

Permalink
Fixed #255 - unnecessary semi-colon false positive
Browse files Browse the repository at this point in the history
  • Loading branch information
shyiko committed Jul 21, 2018
1 parent 7220c77 commit d028b95
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.github.shyiko.ktlint.ruleset.standard

import com.github.shyiko.ktlint.core.Rule
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
Expand All @@ -18,15 +19,16 @@ class NoSemicolonsRule : Rule("no-semi") {
if (node is LeafPsiElement && node.textMatches(";") && !node.isPartOfString() &&
!node.isPartOf(KtEnumEntry::class)) {
val nextLeaf = PsiTreeUtil.nextLeaf(node, true)
if (nextLeaf == null /* eof */ ||
(nextLeaf is PsiWhiteSpace && (nextLeaf.text.contains("\n") ||
PsiTreeUtil.nextLeaf(nextLeaf, true) == null /* \s+ and then eof */))
) {
if (doesNotRequirePreSemi(nextLeaf)) {
emit(node.startOffset, "Unnecessary semicolon", true)
if (autoCorrect) {
node.treeParent.removeChild(node)
}
} else if (nextLeaf !is PsiWhiteSpace) {
val prevLeaf = PsiTreeUtil.prevLeaf(node, true)
if (prevLeaf is PsiWhiteSpace && prevLeaf.textContains('\n')) { // \n;{
return
}
// todo: move to a separate rule
emit(node.startOffset + 1, "Missing spacing after \";\"", true)
if (autoCorrect) {
Expand All @@ -35,4 +37,15 @@ class NoSemicolonsRule : Rule("no-semi") {
}
}
}

private fun doesNotRequirePreSemi(nextLeaf: PsiElement?): Boolean {
if (nextLeaf is PsiWhiteSpace) {
val nextNextLeaf = PsiTreeUtil.nextLeaf(nextLeaf, true)
return (
nextNextLeaf == null || // \s+ and then eof
nextLeaf.textContains('\n') && !nextNextLeaf.textMatches("{")
)
}
return nextLeaf == null /* eof */
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ class NoSemicolonsRuleTest {
fun name() { a(); return b }
println(";")
println();
Any();
{
}.print()
Any()
;{ /*...*/ }.print()
}
""".trimIndent()
)).isEqualTo(listOf(
Expand Down

0 comments on commit d028b95

Please sign in to comment.