How can I find most common super type for two type...
# compiler
p
How can I find most common super type for two types (IrType) in IR compiler backend? May be there is already utility function for it?
Copy code
fun findMostCommonSuperTypeFor(type1: IrType, type2: IrType) : IrType {
  TODO("?")
}
d
You can call this method passing proper
IrTypeContext
🙏 1
p
@dmitriy.novozhilov could you point how to find right IrTypeContext implementation? I'm trying to use IrTypeSystemContextImpl(IrBuiltIns) but got exception upon calling commonSuperType(List<KotlinTypeMarker>)
Copy code
java.lang.IllegalStateException: Should not be called
	at org.jetbrains.kotlin.ir.types.IrTypeSystemContext$DefaultImpls.isError(IrTypeSystemContext.kt:388)
	at org.jetbrains.kotlin.ir.types.IrTypeSystemContextImpl.isError(IrTypeSystemContext.kt:627)
	at org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator.findErrorTypeInSupertypes(NewCommonSuperTypeCalculator.kt:262)
	at org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator.commonSuperTypeForNotNullTypes(NewCommonSuperTypeCalculator.kt:234)
	at org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator.commonSuperTypeForSimpleTypes(NewCommonSuperTypeCalculator.kt:103)
	at org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator.commonSuperType(NewCommonSuperTypeCalculator.kt:62)
	at org.jetbrains.kotlin.resolve.calls.NewCommonSuperTypeCalculator.commonSuperType(NewCommonSuperTypeCalculator.kt:27)
d
That's interesting It seems that no one tried to calculate CST in IR before You can create your own implementation of
IrTypeSystemContext
(with delegation to
IrTypeSystemContextImpl
) and override
isError
(so it will always return
false
)
p
Yes. For temporary workaround I made like this:
Copy code
private val typeSystem = object : IrTypeSystemContext { // TODO temporary workaround
        override val irBuiltIns: IrBuiltIns
            get() = pluginContext.irBuiltIns

        // if not overriden then throws 'Should not be called'
        override fun TypeConstructorMarker.isError(): Boolean {
            return false
        }

        // if not overriden with returning null then call to commonSuperType(List<KotlinTypeMarker>) return Int type for any input
        override fun findCommonIntegerLiteralTypesSuperType(explicitSupertypes: List<SimpleTypeMarker>): SimpleTypeMarker? {
            return null
        }
    }
d
You need smth like this:
Copy code
val baseContext = IrTypeSystemContextImpl(irBuiltIns)
val context = object : IrTypeSystemContext by baseContext {
    override fun TypeConstructorMarker.isError(): Boolean {
        return false
    }
}
Ah, I missed that all implementations are actually in the interface So your option is fine too
p
There is one more function I need to override (see previous message) If not override then for any list of types I got Int as common type
👍 1