[WasmJs] Add support for external class reflection

Fix #KT-64890
This commit is contained in:
Igor Yakovlev
2024-01-26 21:16:29 +01:00
parent e302420197
commit 6930fc8fed
24 changed files with 330 additions and 81 deletions
@@ -0,0 +1,31 @@
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.wasm.internal
import kotlin.reflect.*
@Suppress("UNUSED_PARAMETER")
private fun getJsClassName(jsKlass: JsAny): String? =
js("jsKlass.name")
@Suppress("UNUSED_PARAMETER")
private fun instanceOf(ref: JsAny, jsKlass: JsAny): Boolean =
js("ref instanceof jsKlass")
internal class KExternalClassImpl<T : Any> @WasmPrimitiveConstructor constructor(private val jsConstructor: JsAny) : KClass<T> {
override val simpleName: String? get() = getJsClassName(jsConstructor)
override val qualifiedName: String? get() = null
override fun isInstance(value: Any?): Boolean =
value is JsExternalBox && instanceOf(value.ref, jsConstructor)
override fun equals(other: Any?): Boolean =
other is KExternalClassImpl<*> && jsConstructor == other.jsConstructor
override fun hashCode(): Int = simpleName.hashCode()
override fun toString(): String = "class $simpleName"
}
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package kotlin.wasm.internal
import kotlin.reflect.*
@Suppress("UNUSED_PARAMETER")
private fun getConstructor(obj: JsAny): JsAny? =
js("obj.constructor")
@Suppress("UNCHECKED_CAST")
internal actual fun <T : Any> getKClassForObject(obj: Any): KClass<T> {
if (obj !is JsExternalBox) return KClassImpl(getTypeInfoTypeDataByPtr(obj.typeInfo))
val jsConstructor = getConstructor(obj.ref) ?: error("JavaScript constructor is not defined")
return KExternalClassImpl(jsConstructor)
}