min
10/04/2026, 8:53 AMclass MyCompilerPluginRegistrar: CompilerPluginRegistrar() {
override val pluginId = BuildConfig.KOTLIN_PLUGIN_ID
override val supportsK2 = true
override fun ExtensionStorage.registerExtensions(
configuration: CompilerConfiguration,
) {
FirExtensionRegistrarAdapter.registerExtension(MyFirExtensionRegistrar())
IrGenerationExtension.registerExtension(MyIrGenerationExtension())
}
}
I’m working on my first plugin. I’ve implemented the FIR layer to generate a companion method in every annotated class. I’ve been told to give it a body in the IR layer.min
10/04/2026, 8:54 AMclass MyIrGenerationExtension: IrGenerationExtension {
override fun generate(
moduleFragment: IrModuleFragment,
pluginContext: IrPluginContext,
) {
moduleFragment.transformChildrenVoid(
MyIrElementTransformerVoid(pluginContext)
)
}
}
private class MyIrElementTransformerVoid(
private val pluginContext: IrPluginContext,
): IrElementTransformerVoid() {
override fun visitSimpleFunction(
declaration: IrSimpleFunction,
): IrStatement {
val annotatedConstructor = declaration.takeIf(IrSimpleFunction::isGeneratedCompanionMethod)
?.parentAsClass // `companion object`
?.parentAsClass // `class`
?.primaryConstructor
?: return declaration
declaration.body = DeclarationIrBuilder(pluginContext, declaration.symbol)
return declaration
}
}
private fun IrSimpleFunction.isGeneratedCompanionMethod(): Boolean {
return this.origin == KEY.origin
&& this.name == COMPANION_METHOD_TO_GENERATE
}
The declaration, if it’s a generated companion method, should have the same signature as the annotatedConstructor. I want it to relay every argument to and the return value from the constructor.
val annotatedConstructor = declaration.takeIf(IrSimpleFunction::isGeneratedCompanionMethod)
.coalesce { return declaration } // `?: return declaration`
.parentAsClass // `companion object`
.parentAsClass // `class`
.primaryConstructor!!
Can I assert the above in the IR, since my FIR would have reported an error diagnostic if it was missing? Also can somebody please point me to a worked example of constructing the declaration.body?Youssef Shoaib [MOD]
10/04/2026, 8:58 AMmin
10/04/2026, 9:01 AMYoussef Shoaib [MOD]
10/04/2026, 9:06 AMmin
10/04/2026, 9:34 AMYoussef Shoaib [MOD]
10/04/2026, 9:35 AMerror(someIr.dump()) (dump is an extension function I believe, so your IDE should offer to import it once you type that in)min
10/04/2026, 10:21 AM