Read annotations of method called from kotlin in plugin

Hi,

I am working on plugin that shows gutter icon on usages of method with special annotation. I need to support all cases:

  • java usage of java method
  • java usage of kotlin method
  • kotlin usage of kotlin method
  • kotlin usage of java method

I am able to make it work for first 2 cases and for the third one, but in some weird way, that i don't like. I am not able to do it for fourth case.

Here is my simplified code


private fun lineMarkerInfoForKotlin(element: PsiElement): LineMarkerInfo<PsiElement>? {
if (element !is KtCallExpression) return null

val resolved = element.calleeExpression?.mainReference?.resolve()
if (resolved is KtNamedFunction) {
val hasAnnotation = resolved.annotationEntries
.any { it.typeReference?.text == MyAnnotation::class.java.simpleName }

if (hasAnnotation) {
return lineMarkerInfo(element)
}
}
return null
}

private fun lineMarkerInfoForJava(element: PsiElement): LineMarkerInfo<PsiElement>? {
if (element !is PsiReferenceExpression) return null
val method = (element.resolve() as? PsiMethod) ?: return null

if (!AnnotationDetectorUtils.hasAnnotation(method, MyAnnotation::class.java.name)) return null

return lineMarkerInfo(element)
}

private fun lineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement> {
return LineMarkerInfo(
element,
element.getTextRange(),
ICON,
Pass.UPDATE_ALL,
TOOLTIP_PROVIDER,
null,
GutterIconRenderer.Alignment.LEFT
)
}

internal object AnnotationDetectorUtils {

fun hasAnnotation(element: PsiElement, annotationName: String): Boolean {
return findAnnotation(element, annotationName) != null
}

fun findAnnotation(element: PsiElement, annotationName: String): PsiAnnotation? {
return (element as? PsiModifierListOwner)
?.modifierList
?.annotations
?.firstOrNull { annotationName == it.qualifiedName }
}
}

Can you please point me to the doc or any example of how can I achieve my task?

Thanks.

0

Please sign in to leave a comment.