Skip to content

Commit fd49eb9

Browse files
committed
SONARKT-400 Migrate UnusedPrivateMethodCheck to kotlin-analysis-api
1 parent 76827a9 commit fd49eb9

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

sonar-kotlin-checks/src/main/java/org/sonarsource/kotlin/checks/UnusedPrivateMethodCheck.kt

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ import org.jetbrains.kotlin.psi.KtOperationReferenceExpression
2424
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
2525
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
2626
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
27-
import org.jetbrains.kotlin.resolve.BindingContext
2827
import org.sonar.check.Rule
2928
import org.sonarsource.kotlin.api.checks.AbstractCheck
3029
import org.sonarsource.kotlin.api.checks.isInfix
3130
import org.sonarsource.kotlin.api.frontend.KotlinFileContext
31+
import org.sonarsource.kotlin.api.visiting.withKaSession
3232

3333
// Serializable method should not raise any issue in Kotlin.
3434
private val IGNORED_METHODS: Set<String> = setOf(
@@ -46,13 +46,12 @@ private val COMMON_ANNOTATIONS = listOf(
4646
"kotlin.jvm.Throws",
4747
)
4848

49-
@org.sonarsource.kotlin.api.frontend.K1only
5049
@Rule(key = "S1144")
5150
class UnusedPrivateMethodCheck : AbstractCheck() {
5251

5352
override fun visitClass(klass: KtClass, context: KotlinFileContext) {
5453
if (!klass.isTopLevel()) return
55-
klass.collectDescendantsOfType<KtNamedFunction> { it.shouldCheckForUsage(context.bindingContext) }
54+
klass.collectDescendantsOfType<KtNamedFunction> { it.shouldCheckForUsage() }
5655
.forEach {
5756
val functionName = it.name!!
5857
if (!IGNORED_METHODS.contains(functionName) && !it.isReferencedIn(klass, functionName)) {
@@ -71,15 +70,15 @@ class UnusedPrivateMethodCheck : AbstractCheck() {
7170
private fun KtClass.hasInfixReferences(name: String) =
7271
anyDescendantOfType<KtOperationReferenceExpression> { it.getReferencedName() == name }
7372

74-
private fun KtNamedFunction.shouldCheckForUsage(bindingContext: BindingContext) =
73+
private fun KtNamedFunction.shouldCheckForUsage() =
7574
isPrivate()
7675
&& !hasModifier(KtTokens.OPERATOR_KEYWORD)
77-
&& (annotationEntries.isEmpty() || annotatedWithCommonAnnotations(bindingContext))
76+
&& (annotationEntries.isEmpty() || annotatedWithCommonAnnotations())
7877

79-
private fun KtNamedFunction.annotatedWithCommonAnnotations(bindingContext: BindingContext) =
80-
bindingContext[BindingContext.FUNCTION, this]
81-
?.annotations
82-
?.all { it.fqName?.asString() in COMMON_ANNOTATIONS }
83-
?: false
78+
private fun KtNamedFunction.annotatedWithCommonAnnotations() = withKaSession {
79+
symbol.annotations.all {
80+
it.classId?.asFqNameString() in COMMON_ANNOTATIONS
81+
}
82+
}
8483

8584
}

0 commit comments

Comments
 (0)