I now work on plugin and I have to work with KtCla...
# compiler
s
I now work on plugin and I have to work with KtClass(and similar classes). I really don't like it. Is there any way to convert KtClass to PsiClass (like in intellij plugins)?
d
No, there isn't. What exactly you don't like in
KtClass
?
s
@dmitriy.novozhilov I method with have annotation. I can get pure text off annotation, but I cannot do resolve and get all annotation's fields. is there any way to do it?
d
You can get function descriptor from binding context (
bindingContext[BindingContext.FUNCTION, psiFunction]
) and then extract annotations from it (
functionDescriptor.annotations
)
s
@dmitriy.novozhilov I see that I need to do @OptIn(ObsoleteDescriptorBasedAPI::class) to use BindingContext. Is there something better I could use?
d
Which extension point do you use? Is it
IrGenerationExtension
?
s
yes
d
In this case you need to work with IR itself, there is no need to touch PSI at all Something like
IrFunction.annotations
will suite for you
s
@dmitriy.novozhilov the issue is that it doesn't work for me.
Copy code
val klas = file.declarations[0] as org.jetbrains.kotlin.ir.declarations.impl.IrClassImpl
(((klas.declarations[1].annotations[0] as org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl).type as IrTypeBase).kotlinType!! as SimpleType).arguments

is empty

((klas.declarations[1].annotations[0] as org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl).type as IrTypeBase).kotlinType!!.constructor.parameters
is empty
I'd like to get output as Pair("value","annValue"). I'd also like to support custom annotations here as well. my example code is
Copy code
class Example5Annotation {

    @ExampleAnnotation("annValue")
    fun bla(): String =
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam non ligula in tellus scelerisque tempor. Pellentesque at blandit purus."

}
annotation class ExampleAnnotation(val value: String = "")
getting "value" is my issue
I think im missing something like .resolve() in PSI
d
arguments
of some type is generic type arguments of some specific type. E.g. for type
List<String>
arguments
will be
[String]
You really want to access arguments of annotation call:
Copy code
val irClass = irFile.declarations.first() as IrClass
val irFunction = irClass.declarations[1] as IrFunction
val irAnnotationCall = irFunction.annotations.first()
val irAnnotationParameters = irAnnotationCall.symbol.owner.valueParameters
val parameterToArgument = (0..irAnnotationCall.constructorTypeArgumentsCount).map { irAnnotationParameters[it] to irAnnotationCall.getValueArgument(it) }
s
@dmitriy.novozhilov thanks, it works 🙂
d
IR tree is already resolved and contains all necessary information, so there is no need in
resolve
method Each resolvable entity (like function call or annotation call) has
symbol
property which is reference to called declaration (and IR of it can be accessed via
symbol.owner
)
s
it makes sense, thx