[stdlib] Merge js-ir specific sources into common js sources

This commit is contained in:
Ilya Gorbunov
2023-10-06 22:20:58 +02:00
committed by Space Team
parent f00d4022c4
commit 911fa3bbbb
55 changed files with 54 additions and 65 deletions
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2023 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.coroutines
// Do not remove this file.
// During klib deserialization the compiler uses this file as a place for declaring function type interfaces.
// See FunctionTypeInterfacePackages.kt
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2023 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
// Do not remove this file.
// During klib deserialization the compiler uses this file as a place for declaring function type interfaces.
// See FunctionTypeInterfacePackages.kt
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2023 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.reflect
// Do not remove this file.
// During klib deserialization the compiler uses this file as a place for declaring function type interfaces.
// See FunctionTypeInterfacePackages.kt
@@ -0,0 +1,104 @@
/*
* Copyright 2010-2018 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.coroutines
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
@SinceKotlin("1.3")
@JsName("CoroutineImpl")
internal abstract class CoroutineImpl(private val resultContinuation: Continuation<Any?>?) : Continuation<Any?> {
protected var state = 0
protected var exceptionState = 0
protected var result: dynamic = null
protected var exception: dynamic = null
protected var finallyPath: Array<Int>? = null
private val _context: CoroutineContext? = resultContinuation?.context
public override val context: CoroutineContext get() = _context!!
private var intercepted_: Continuation<Any?>? = null
public fun intercepted(): Continuation<Any?> =
intercepted_
?: (context[ContinuationInterceptor]?.interceptContinuation(this) ?: this)
.also { intercepted_ = it }
override fun resumeWith(result: Result<Any?>) {
var current = this
var currentResult: Any? = result.getOrNull()
var currentException: Throwable? = result.exceptionOrNull()
// This loop unrolls recursion in current.resumeWith(param) to make saner and shorter stack traces on resume
while (true) {
with(current) {
// Set result and exception fields in the current continuation
if (currentException == null) {
this.result = currentResult
} else {
state = exceptionState
exception = currentException
}
try {
val outcome = doResume()
if (outcome === COROUTINE_SUSPENDED) return
currentResult = outcome
currentException = null
} catch (exception: dynamic) { // Catch all exceptions
currentResult = null
currentException = exception.unsafeCast<Throwable>()
}
releaseIntercepted() // this state machine instance is terminating
val completion = resultContinuation!!
if (completion is CoroutineImpl) {
// unrolling recursion via loop
current = completion
} else {
// top-level completion reached -- invoke and return
if (currentException != null) {
completion.resumeWithException(currentException!!)
} else {
completion.resume(currentResult)
}
return
}
}
}
}
private fun releaseIntercepted() {
val intercepted = intercepted_
if (intercepted != null && intercepted !== this) {
context[ContinuationInterceptor]!!.releaseInterceptedContinuation(intercepted)
}
this.intercepted_ = CompletedContinuation // just in case
}
protected abstract fun doResume(): Any?
public open fun create(completion: Continuation<*>): Continuation<Unit> {
throw UnsupportedOperationException("create(Continuation) has not been overridden")
}
public open fun create(value: Any?, completion: Continuation<*>): Continuation<Unit> {
throw UnsupportedOperationException("create(Any?;Continuation) has not been overridden")
}
}
internal object CompletedContinuation : Continuation<Any?> {
override val context: CoroutineContext
get() = error("This continuation is already complete")
override fun resumeWith(result: Result<Any?>) {
error("This continuation is already complete")
}
override fun toString(): String = "This continuation is already complete"
}
@@ -0,0 +1,185 @@
/*
* Copyright 2010-2018 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.
*/
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "UNCHECKED_CAST")
package kotlin.coroutines.intrinsics
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.CoroutineImpl
import kotlin.internal.InlineOnly
/**
* Invoke 'invoke' method of suspend super type
* Because callable references translated with local classes,
* necessary to call it in special way, not in synamic way
*/
@Suppress("UNUSED_PARAMETER", "unused")
@PublishedApi
internal fun <T> (suspend () -> T).invokeSuspendSuperType(
completion: Continuation<T>
): Any? {
throw NotImplementedError("It is intrinsic method")
}
/**
* Invoke 'invoke' method of suspend super type with receiver
* Because callable references translated with local classes,
* necessary to call it in special way, not in synamic way
*/
@Suppress("UNUSED_PARAMETER", "unused")
@PublishedApi
internal fun <R, T> (suspend R.() -> T).invokeSuspendSuperTypeWithReceiver(
receiver: R,
completion: Continuation<T>
): Any? {
throw NotImplementedError("It is intrinsic method")
}
/**
* Invoke 'invoke' method of suspend super type with receiver and param
* Because callable references translated with local classes,
* necessary to call it in special way, not in synamic way
*/
@Suppress("UNUSED_PARAMETER", "unused")
@PublishedApi
internal fun <R, P, T> (suspend R.(P) -> T).invokeSuspendSuperTypeWithReceiverAndParam(
receiver: R,
param: P,
completion: Continuation<T>
): Any? {
throw NotImplementedError("It is intrinsic method")
}
/**
* Starts unintercepted coroutine without receiver and with result type [T] and executes it until its first suspension.
* Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE_SUSPENDED] if it suspends.
* In the latter case, the [completion] continuation is invoked when coroutine completes with result or exception.
*
* The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor] that might
* be present in the completion's [CoroutineContext]. It is the invoker's responsibility to ensure that a proper invocation
* context is established.
*
* This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn] to resume the execution of a suspended
* coroutine using a reference to the suspending function.
*/
@SinceKotlin("1.3")
@InlineOnly
public actual inline fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn(
completion: Continuation<T>
): Any? {
val a = this.asDynamic()
return if (jsTypeOf(a) == "function") a(completion)
else this.invokeSuspendSuperType(completion)
}
/**
* Starts unintercepted coroutine with receiver type [R] and result type [T] and executes it until its first suspension.
* Returns the result of the coroutine or throws its exception if it does not suspend or [COROUTINE_SUSPENDED] if it suspends.
* In the latter case, the [completion] continuation is invoked when coroutine completes with result or exception.
*
* The coroutine is started directly in the invoker's thread without going through the [ContinuationInterceptor] that might
* be present in the completion's [CoroutineContext]. It is the invoker's responsibility to ensure that a proper invocation
* context is established.
*
* This function is designed to be used from inside of [suspendCoroutineUninterceptedOrReturn] to resume the execution of a suspended
* coroutine using a reference to the suspending function.
*/
@SinceKotlin("1.3")
@InlineOnly
public actual inline fun <R, T> (suspend R.() -> T).startCoroutineUninterceptedOrReturn(
receiver: R,
completion: Continuation<T>
): Any? {
val a = this.asDynamic()
return if (jsTypeOf(a) == "function") a(receiver, completion)
else this.invokeSuspendSuperTypeWithReceiver(receiver, completion)
}
@InlineOnly
internal actual inline fun <R, P, T> (suspend R.(P) -> T).startCoroutineUninterceptedOrReturn(
receiver: R,
param: P,
completion: Continuation<T>
): Any? {
val a = this.asDynamic()
return if (jsTypeOf(a) == "function") a(receiver, param, completion)
else this.invokeSuspendSuperTypeWithReceiverAndParam(receiver, param, completion)
}
/**
* Creates unintercepted coroutine without receiver and with result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*
* This function returns unintercepted continuation.
* Invocation of `resume(Unit)` starts coroutine directly in the invoker's thread without going through the
* [ContinuationInterceptor] that might be present in the completion's [CoroutineContext].
* It is the invoker's responsibility to ensure that a proper invocation context is established.
* [Continuation.intercepted] can be used to acquire the intercepted continuation.
*
* Repeated invocation of any resume function on the resulting continuation corrupts the
* state machine of the coroutine and may result in arbitrary behaviour or exception.
*/
@SinceKotlin("1.3")
public actual fun <T> (suspend () -> T).createCoroutineUnintercepted(
completion: Continuation<T>
): Continuation<Unit> =
createCoroutineFromSuspendFunction(completion) {
val a = this.asDynamic()
if (jsTypeOf(a) == "function") a(completion)
else this.invokeSuspendSuperType(completion)
}
/**
* Creates unintercepted coroutine with receiver type [R] and result type [T].
* This function creates a new, fresh instance of suspendable computation every time it is invoked.
*
* To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance.
* The [completion] continuation is invoked when coroutine completes with result or exception.
*
* This function returns unintercepted continuation.
* Invocation of `resume(Unit)` starts coroutine directly in the invoker's thread without going through the
* [ContinuationInterceptor] that might be present in the completion's [CoroutineContext].
* It is the invoker's responsibility to ensure that a proper invocation context is established.
* [Continuation.intercepted] can be used to acquire the intercepted continuation.
*
* Repeated invocation of any resume function on the resulting continuation corrupts the
* state machine of the coroutine and may result in arbitrary behaviour or exception.
*/
@SinceKotlin("1.3")
public actual fun <R, T> (suspend R.() -> T).createCoroutineUnintercepted(
receiver: R,
completion: Continuation<T>
): Continuation<Unit> =
createCoroutineFromSuspendFunction(completion) {
val a = this.asDynamic()
if (jsTypeOf(a) == "function") a(receiver, completion)
else this.invokeSuspendSuperTypeWithReceiver(receiver, completion)
}
/**
* Intercepts this continuation with [ContinuationInterceptor].
*/
@SinceKotlin("1.3")
public actual fun <T> Continuation<T>.intercepted(): Continuation<T> =
(this as? CoroutineImpl)?.intercepted() ?: this
private inline fun <T> createCoroutineFromSuspendFunction(
completion: Continuation<T>,
crossinline block: () -> Any?
): Continuation<Unit> {
return object : CoroutineImpl(completion as Continuation<Any?>) {
override fun doResume(): Any? {
if (exception != null) throw exception
return block()
}
}
}
@@ -0,0 +1,110 @@
/*
* Copyright 2010-2019 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
public actual open class Error : Throwable {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class Exception : Throwable {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class RuntimeException : Exception {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class IllegalArgumentException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class IllegalStateException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class IndexOutOfBoundsException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
}
public actual open class ConcurrentModificationException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class UnsupportedOperationException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class NumberFormatException : IllegalArgumentException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
}
public actual open class NullPointerException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
}
public actual open class ClassCastException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
}
public actual open class AssertionError : Error {
public actual constructor() : super()
public constructor(message: String?) : super(message)
public actual constructor(message: Any?) : super(message?.toString(), message as? Throwable)
@SinceKotlin("1.4")
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
}
public actual open class NoSuchElementException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
}
@SinceKotlin("1.3")
public actual open class ArithmeticException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
}
public actual open class NoWhenBranchMatchedException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
public actual open class UninitializedPropertyAccessException : RuntimeException {
public actual constructor() : super()
public actual constructor(message: String?) : super(message)
public actual constructor(message: String?, cause: Throwable?) : super(message, cause)
public actual constructor(cause: Throwable?) : super(cause)
}
@@ -0,0 +1,17 @@
/*
* Copyright 2010-2020 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.math
/**
* Returns this value with the sign bit same as of the [sign] value.
*
* If [sign] is `NaN` the sign of the result is undefined.
*/
@SinceKotlin("1.2")
public actual fun Double.withSign(sign: Double): Double {
val thisSignBit = doubleSignBit(this)
val newSignBit = doubleSignBit(sign)
return if (thisSignBit == newSignBit) this else -this
}
@@ -0,0 +1,62 @@
/*
* Copyright 2010-2020 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
/**
* Returns a bit representation of the specified floating-point value as [Long]
* according to the IEEE 754 floating-point "double format" bit layout.
*/
@SinceKotlin("1.2")
public actual fun Double.toBits(): Long =
doubleToRawBits(if (this.isNaN()) Double.NaN else this)
/**
* Returns a bit representation of the specified floating-point value as [Long]
* according to the IEEE 754 floating-point "double format" bit layout,
* preserving `NaN` values exact layout.
*/
@SinceKotlin("1.2")
public actual fun Double.toRawBits(): Long =
doubleToRawBits(this)
/**
* Returns the [Double] value corresponding to a given bit representation.
*/
@SinceKotlin("1.2")
@kotlin.internal.InlineOnly
public actual inline fun Double.Companion.fromBits(bits: Long): Double =
doubleFromBits(bits)
/**
* Returns a bit representation of the specified floating-point value as [Int]
* according to the IEEE 754 floating-point "single format" bit layout.
*
* Note that in Kotlin/JS [Float] range is wider than "single format" bit layout can represent,
* so some [Float] values may overflow, underflow or loose their accuracy after conversion to bits and back.
*/
@SinceKotlin("1.2")
public actual fun Float.toBits(): Int =
floatToRawBits(if (this.isNaN()) Float.NaN else this)
/**
* Returns a bit representation of the specified floating-point value as [Int]
* according to the IEEE 754 floating-point "single format" bit layout,
* preserving `NaN` values exact layout.
*
* Note that in Kotlin/JS [Float] range is wider than "single format" bit layout can represent,
* so some [Float] values may overflow, underflow or loose their accuracy after conversion to bits and back.
*/
@SinceKotlin("1.2")
public actual fun Float.toRawBits(): Int =
floatToRawBits(this)
/**
* Returns the [Float] value corresponding to a given bit representation.
*/
@SinceKotlin("1.2")
@kotlin.internal.InlineOnly
public actual inline fun Float.Companion.fromBits(bits: Int): Float =
floatFromBits(bits)
@@ -0,0 +1,28 @@
/*
* Copyright 2010-2023 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.reflect
/**
* Creates a new instance of the class, calling a constructor which either has no parameters or all parameters of which have
* a default value. If there are no or many such constructors, an exception is thrown.
*/
@OptIn(JsIntrinsic::class)
@SinceKotlin("1.9")
@ExperimentalJsReflectionCreateInstance
public fun <T : Any> KClass<T>.createInstance(): T {
val jsClass = js.asDynamic()
if (jsClass === js("Object")) return js("{}")
val noArgsConstructor = jsClass.`$metadata$`.unsafeCast<Metadata?>()?.defaultConstructor
?: throw IllegalArgumentException("Class \"$simpleName\" should have a single no-arg constructor")
return if (jsIsEs6() && noArgsConstructor !== jsClass) {
js("noArgsConstructor.call(jsClass)")
} else {
js("new noArgsConstructor()")
}
}
@@ -0,0 +1,11 @@
/*
* Copyright 2010-2020 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.js
// DON'T USE! Use `K::class.js` instead.
// The declaration kept only for backward compatibility with older compilers
// TODO remove, but when?
internal external fun <T : Any> jsClass(): JsClass<T>
@@ -0,0 +1,19 @@
/*
* Copyright 2010-2020 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.
*/
import kotlin.reflect.*
import kotlin.reflect.js.internal.*
@PublishedApi
internal fun <T : Annotation> KClass<*>.findAssociatedObject(annotationClass: KClass<T>): Any? {
return if (this is KClassImpl<*> && annotationClass is KClassImpl<T>) {
val key = annotationClass.jClass.asDynamic().`$metadata$`?.associatedObjectKey?.unsafeCast<Int>() ?: return null
val map = jClass.asDynamic().`$metadata$`?.associatedObjects ?: return null
val factory = map[key] ?: return null
return factory()
} else {
null
}
}
@@ -0,0 +1,15 @@
/*
* Copyright 2010-2019 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.text
/**
* Returns a string representation of this [Long] value in the specified [radix].
*
* @throws IllegalArgumentException when [radix] is not a valid radix for number to string conversion.
*/
@SinceKotlin("1.2")
public actual fun Long.toString(radix: Int): String =
this.toStringImpl(checkRadix(radix))