How can I get the declaration of a `KtElement` usi...
# compiler
f
How can I get the declaration of a
KtElement
using the kotlin compiler api? When I try to access `getReference()`/`getReferences()` all I get is null / empty list. I'm assuming there's some extra configuration I need to do, because calls to resolve references go through this call:
Copy code
ServiceManager.getService(KotlinReferenceProvidersService::class.java) ?: NO_REFERENCES_SERVICE
And the left hand side is always null.
s
Do you want to find the element reference is connected to?
f
Given a method call
Copy code
fun main() {
  val x = Foo()
  x.bar() <----
}
I want to see where
bar
is defined and what class owns it.
s
this reference is usually connected to
call
or
resolvedCall
, which can point you to descriptor of the function and class, so you can use them iirc, compiler has
getResolvedCall()
extension for expressions
note that they are available only when analysis is completed 🙂
f
@shikasd How can I get an instance of
BindingContext
for
call
and
resolvedCall
?
I managed to get an instance of
TopDownAnalysisContext
, is there some way to go from there to a
BindingContext
?
s
depends on the extension you are in 🙂 if you have binding trace, you should be good to go
f
I'm not writing a compiler plugin, I'm using the compiler API to do a transformation on kotlin source, and I've followed this example for the basic setup https://github.com/vektory79/kotlin-script-parser-test/blob/master/src/main/java/hello/CompileTest.kt and I've also made some changes to make it compile since it seems the api changed slightly https://hastebin.com/sakowujopo.java
s
You can use componentProvider to get
BindingTrace
type It contains
BindingContext
and also allows you to modify it 🙂
Note that you still need to run analyzer before accessing
BindingContext
, as otherwise it will be empty
f
Aha! This is what I need! Thank you very much!
s
yep, it is similar you have property descriptor and
KotlinType
you can use KotlinType to get class descriptor out of it
f
how do I get a
KotlinType
from a
KtTypeReference
and a property descriptor from `KtProperty`(I think that's the right type for properties)?
Or whatever the correct
KtElement
is, i'm not sure which it is
ok I found
getAbbreviatedTypeOrType
Hmm... it seems i'm getting
UnresolvedType
errors when using types defined in the classpath... Solving that probably won't be fun
s
It is available from binding context as well, I don't remember exact properties you should also include types from the classpath, I guess, not sure how you are compiling those atm 🙂
f
I am including types from the classpath like so
Copy code
configuration.addJvmClasspathRoots(classPath.map { it.toFile() })
The full code is here https://hasteb.in/eqahijib.kotlin, is there anything I'm missing for including types?
classpath
includes a jar which defines the types
s