Skip to content

Commit

Permalink
Disallow comments in try-catch-finally at unexpected locations (#2432)
Browse files Browse the repository at this point in the history
Closes #2427
  • Loading branch information
paul-dingemans authored Dec 11, 2023
1 parent 2d480c6 commit b55c689
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe
import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceBeforeMe
import com.pinterest.ktlint.ruleset.standard.StandardRule
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet

/**
* Checks spacing and wrapping of try-catch-finally.
Expand Down Expand Up @@ -55,6 +56,10 @@ public class TryCatchFinallySpacingRule :
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
) {
if (node.isPartOfComment() && node.treeParent.elementType in TRY_CATCH_FINALLY_TOKEN_SET) {
emit(node.startOffset, "No comment expected at this location", false)
return
}
when (node.elementType) {
BLOCK -> {
visitBlock(node, emit, autoCorrect)
Expand All @@ -70,7 +75,7 @@ public class TryCatchFinallySpacingRule :
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit,
autoCorrect: Boolean,
) {
if (node.treeParent.elementType !in TRY_CATCH_FINALLY_ELEMENT_TYPES) {
if (node.treeParent.elementType !in TRY_CATCH_FINALLY_TOKEN_SET) {
return
}

Expand Down Expand Up @@ -116,7 +121,7 @@ public class TryCatchFinallySpacingRule :
private fun ASTNode.elementTypeName() = elementType.toString().lowercase()

private companion object {
val TRY_CATCH_FINALLY_ELEMENT_TYPES = listOf(TRY, CATCH, FINALLY)
val TRY_CATCH_FINALLY_TOKEN_SET = TokenSet.create(TRY, CATCH, FINALLY)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,29 @@ class TryCatchFinallySpacingRuleTest {
).isFormattedAs(formattedCode)
}
}

@Test
fun `Issue 2427 - Given a try-catch with a comment at an unexpected location`() {
val code =
"""
fun foo() {
try {
trySomething()
} // Unexpected comment
catch (e: IOException) {
catchSomething()
} // Unexpected comment
finally {
finallySomething()
}
}
""".trimIndent()
tryCatchRuleAssertThat(code)
.hasLintViolations(
LintViolation(4, 7, "No comment expected at this location", false),
LintViolation(5, 5, "A single space is required before 'catch'"),
LintViolation(7, 7, "No comment expected at this location", false),
LintViolation(8, 5, "A single space is required before 'finally'"),
)
}
}

0 comments on commit b55c689

Please sign in to comment.