Hi, is there a method to parse a File into a IrFil...
# compiler
f
Hi, is there a method to parse a File into a IrFile ? (I know that i can get IrFiles with IrGenerationExtension, but that compile phase is too late for my usecase)
s
Hi, depends on what you are trying to achieve. If you want to compile a file into IrFile separately, you can emulate compilation chain yourself. In case you want to have a compiler plugin and add files to existing compilation, I think IR is not quite a right place to do so. I would look into AnalysisHandlerExtension and use KtFiles for that instead.
z
@shikasd any pointers on that API? Unfortunately it's undocumented
s
@Zac Sweers which one are you looking for? One for creating IrFiles or KtFiles?
z
I guess IrFiles? I'm looking to familiarize myself and was eyeing reimplementing auto-service and auto-factory
s
Hm, it feels like Ir is too low level for this, it is usually used for (bytecode) generation rather than understanding the contents If you want to reimplement auto service as a compiler plugin, I would suggest looking into DeclarationChecker API and check annotations from there. I could give some code pointers when I am near the laptop :)
So, not sure why exactly you want to create either Kt or Ir files from source code, but here's the ways Compose does it for tests:
KtFile
is pretty straight-forward, there's a factory in compiler that exposes a method to parse
VirtualFile
(thin abstraction on top of disk/memory files) into `KtFile`: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]/compose/compiler/plugins/kotlin/AbstractCodegenTest.kt;l=251
IrFile
is a bit more annoying, there are a lot of weird things to setup, and you also need to assemble half of compiler here, but you can do it as well: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/[…]pose/compiler/plugins/kotlin/AbstractIrTransformTest.kt;l=341 Otherwise, if you want to create a compiler plugin which hooks into existing compilation and analyses classes from there, you need to use extension API. For your goals, I suggest using
DeclarationChecker
, e.g. https://github.com/ShikaSD/compiler-plugin-talk-example/blob/master/compiler-plugin/src/main/kotlin/SerializationDeclarationChecker.kt. You can check the annotations, emit resources into the build folder and then merge them into final jar. But, if you fancy something more powerful (e.g. running a separate gradle task for all of this),
AnalysisHandlerExtension
is the thing you need. It is allows to fully analyse the module and then abandon codegen/return an error/retry with more files. Afaik, KSP uses it under the hood.
z
thanks so much! i'll take a look. I was starting with
AnalysisHandlerExtension
is what I'd been looking at currently