Skip to content

Commit

Permalink
Catch java.lang.NoSuchFieldError when looking for WHEN_ENTRY_GUARD in…
Browse files Browse the repository at this point in the history
… kotlin version 2.0.1 (#2857)

As this exception was not caught in the rule, and also not in the RuleExecutionContext it terminated linting/formatting of files containing a WHEN_ENTRY with an exception. In the Ktlint CLI this exception was swallowed. In ktlint-intellij-plugin the exception was recorded and became visible to users.

Closes #2856
  • Loading branch information
paul-dingemans authored Nov 5, 2024
1 parent 1c6083e commit dc4e2fb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ internal class RuleExecutionContext private constructor(
} else {
executeRuleWithoutAutocorrectApproveHandlerOnNodeRecursively(node, rule, autocorrectHandler, emitAndApprove)
}
} catch (e: Exception) {
} catch (e: Throwable) {
if (autocorrectHandler is NoneAutocorrectHandler) {
val (line, col) = positionInTextLocator(node.startOffset)
throw RuleExecutionException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ public class TrailingCommaOnDeclarationSiteRule :
val trailingCommaNode = prevLeaf?.findPreviousTrailingCommaNodeOrNull()
val trailingCommaState =
when {
hasWhenGuard() -> {
hasWhenEntryGuard() -> {
// The compiler won't allow any comma in the when-entry in case it contains a guard clause
TrailingCommaState.NOT_EXISTS
}
Expand Down Expand Up @@ -444,7 +444,16 @@ 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 ASTNode.hasWhenEntryGuard() = elementType == WHEN_ENTRY && hasWhenEntryGuardKotlin21()

private fun ASTNode.hasWhenEntryGuardKotlin21(): Boolean =
// TODO: Remove try-catch wrapping once kotlin version is upgraded to 2.1 or above
try {
children().any { it.elementType == WHEN_ENTRY_GUARD }
} catch (e: NoSuchFieldError) {
// Prior to Kotlin 2.1 the WHEN_ENTRY_GUARD can not be retrieved successfully.
false
}

private fun containsLineBreakInLeavesRange(
from: PsiElement,
Expand Down

0 comments on commit dc4e2fb

Please sign in to comment.