Hi, any hints on creating suspend lambdas in IR? I...
# compiler
n
Hi, any hints on creating suspend lambdas in IR? I’ve been using this function (see thread) which works well for non-suspending lambdas. Now I tried to adapt it to be suspending, but I get:
Compilation failed: Expected ‘BaseContinuationImpl.invokeSuspend’ but was ‘org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl@7521bfb7’
The compiler throws this error here if it helps.
Copy code
fun irLambda(
    context: IrGeneratorContext,
    parent: IrDeclarationParent,
    valueParameters: List<IrType>,
    returnType: IrType,
    suspend: Boolean = false,
    content: IrBlockBodyBuilder.(IrSimpleFunction) -> Unit
): IrFunctionExpression {
    val lambda = context.irFactory.buildFun {
        startOffset = SYNTHETIC_OFFSET
        endOffset = SYNTHETIC_OFFSET
        origin = IrDeclarationOrigin.LOCAL_FUNCTION_FOR_LAMBDA
        name = Name.special("<anonymous>")
        visibility = DescriptorVisibilities.LOCAL
        isSuspend = suspend
        this.returnType = returnType
    }.apply {
        this.parent = parent
        valueParameters.forEachIndexed { index, type ->
            addValueParameter("arg$index", type)
        }
        body = DeclarationIrBuilder(context, this.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET).irBlockBody {
            content(this@apply)
        }
    }
    return IrFunctionExpressionImpl(
        startOffset = SYNTHETIC_OFFSET,
        endOffset = SYNTHETIC_OFFSET,
        type = run {
            when (suspend) {
                true -> context.irBuiltIns.functionN(valueParameters.size)
                else -> context.irBuiltIns.suspendFunctionN(valueParameters.size)
            }.typeWith(*valueParameters.toTypedArray(), returnType)
        },
        origin = IrStatementOrigin.LAMBDA,
        function = lambda
    )
}
s
Might be the case of different
IrStatementOrigin
or something like this I suggest writing the desired code in Kotlin and then dumping IR, and then comparing with the dump of your custom lambda
n
Turns out I had a stupid typo in the snipped above,
true
instead of
false
. Thanks for your help Andrei 🙏