Refact stdlib generator, add support for different backends

[JS IR BE] Runtime fixes
 * Do not generate external declarations for IR BE
 * Move `arrayToString` helper function out of shared JS stdlib
 * Fix arrays type check for IR BE
This commit is contained in:
Roman Artemev
2018-11-12 14:28:47 +03:00
committed by romanart
parent 05b1a99022
commit c5922bf74b
23 changed files with 1847 additions and 68 deletions
@@ -1,4 +1,3 @@
// IGNORE_BACKEND: JS_IR
// WITH_RUNTIME // WITH_RUNTIME
fun box(): String { fun box(): String {
-1
View File
@@ -1,4 +1,3 @@
// IGNORE_BACKEND: JS_IR
// WITH_RUNTIME // WITH_RUNTIME
fun box(): String { fun box(): String {
@@ -1,4 +1,3 @@
// IGNORE_BACKEND: JS_IR
// WITH_RUNTIME // WITH_RUNTIME
fun box(): String { fun box(): String {
@@ -1,4 +1,3 @@
// IGNORE_BACKEND: JS_IR
// WITH_RUNTIME // WITH_RUNTIME
fun getCopyToArray(): Array<Int> = listOf(2, 3, 9).toTypedArray() fun getCopyToArray(): Array<Int> = listOf(2, 3, 9).toTypedArray()
@@ -65,6 +65,10 @@ private val runtimeSources = listOfKtFilesFrom(
"libraries/stdlib/js/src/kotlin/currentBeMisc.kt", "libraries/stdlib/js/src/kotlin/currentBeMisc.kt",
// IR BE has its own generated sources
"libraries/stdlib/js/src/generated",
"libraries/stdlib/js/src/kotlin/collectionsExternal.kt",
// Full version is defined in stdlib // Full version is defined in stdlib
// This file is useful for smaller subset of runtime sources // This file is useful for smaller subset of runtime sources
"libraries/stdlib/js/irRuntime/rangeExtensions.kt", "libraries/stdlib/js/irRuntime/rangeExtensions.kt",
@@ -167,6 +167,7 @@ object NashornIrJsTestChecker : AbstractNashornJsTestChecker() {
listOf( listOf(
BasicBoxTest.TEST_DATA_DIR_PATH + "nashorn-polyfills.js", BasicBoxTest.TEST_DATA_DIR_PATH + "nashorn-polyfills.js",
"libraries/stdlib/js/src/js/polyfills.js",
"js/js.translator/testData/out/irBox/testRuntime.js" "js/js.translator/testData/out/irBox/testRuntime.js"
).forEach(engine::loadFile) ).forEach(engine::loadFile)
@@ -7558,6 +7558,11 @@ public class BoxJsTestGenerated extends AbstractBoxJsTest {
runTest("js/js.translator/testData/box/standardClasses/arraySize.kt"); runTest("js/js.translator/testData/box/standardClasses/arraySize.kt");
} }
@TestMetadata("arraySort.kt")
public void testArraySort() throws Exception {
runTest("js/js.translator/testData/box/standardClasses/arraySort.kt");
}
@TestMetadata("arraysIterator.kt") @TestMetadata("arraysIterator.kt")
public void testArraysIterator() throws Exception { public void testArraysIterator() throws Exception {
runTest("js/js.translator/testData/box/standardClasses/arraysIterator.kt"); runTest("js/js.translator/testData/box/standardClasses/arraysIterator.kt");
@@ -7558,6 +7558,11 @@ public class IrBoxJsTestGenerated extends AbstractIrBoxJsTest {
runTest("js/js.translator/testData/box/standardClasses/arraySize.kt"); runTest("js/js.translator/testData/box/standardClasses/arraySize.kt");
} }
@TestMetadata("arraySort.kt")
public void testArraySort() throws Exception {
runTest("js/js.translator/testData/box/standardClasses/arraySort.kt");
}
@TestMetadata("arraysIterator.kt") @TestMetadata("arraysIterator.kt")
public void testArraysIterator() throws Exception { public void testArraysIterator() throws Exception {
runTest("js/js.translator/testData/box/standardClasses/arraysIterator.kt"); runTest("js/js.translator/testData/box/standardClasses/arraysIterator.kt");
@@ -0,0 +1,20 @@
// EXPECTED_REACHABLE_NODES: 1284
package foo
fun test(actual: DoubleArray, expect: DoubleArray): String {
for (index in 0 until expect.size) {
val expectedElem: Any = expect[index]
val actualElem: Any = actual[index]
if (expectedElem != actualElem) {
return "Content at index $index does not match: $expectedElem != $actualElem"
}
}
return "OK"
}
fun box(): String {
val array = doubleArrayOf(Double.NaN, Double.POSITIVE_INFINITY, Double.NaN, 1.0, Double.NaN, +0.0, Double.NaN, -0.0, Double.NaN, -1.0, Double.NaN, Double.NEGATIVE_INFINITY)
array.sort()
return test(array, doubleArrayOf(Double.NEGATIVE_INFINITY, -1.0, -0.0, +0.0, 1.0, Double.POSITIVE_INFINITY, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN))
}
@@ -5,9 +5,60 @@
package kotlin.collections package kotlin.collections
import kotlin.js.*
// Copied from libraries/stdlib/js/src/kotlin/collections/utils.kt // Copied from libraries/stdlib/js/src/kotlin/collections/utils.kt
// Current inliner doesn't rename symbols inside `js` fun // Current inliner doesn't rename symbols inside `js` fun
@Suppress("UNUSED_PARAMETER") @Suppress("UNUSED_PARAMETER")
internal fun deleteProperty(obj: Any, property: Any) { internal fun deleteProperty(obj: Any, property: Any) {
js("delete obj[property]") js("delete obj[property]")
} }
internal fun arrayToString(array: Array<*>) = array.joinToString(", ", "[", "]") { toString(it) }
internal fun <T> Array<out T>.contentDeepHashCodeInternal(): Int {
var result = 1
for (element in this) {
val elementHash = when {
element == null -> 0
isArrayish(element) -> (element.unsafeCast<Array<*>>()).contentDeepHashCodeInternal()
element is UByteArray -> element.contentHashCode()
element is UShortArray -> element.contentHashCode()
element is UIntArray -> element.contentHashCode()
element is ULongArray -> element.contentHashCode()
else -> element.hashCode()
}
result = 31 * result + elementHash
}
return result
}
internal fun <T> T.contentEqualsInternal(other: T): Boolean {
val a = this.asDynamic()
val b = other.asDynamic()
if (a === b) return true
if (!isArrayish(b) || a.length != b.length) return false
for (i in 0 until a.length) {
if (a[i] != b[i]) {
return false
}
}
return true
}
internal fun <T> T.contentHashCodeInternal(): Int {
val a = this.asDynamic()
var result = 1
for (i in 0 until a.length) {
result = result * 31 + hashCode(a[i])
}
return result
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. 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.collections
//
// NOTE: THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import kotlin.js.*
/**
* Reverses elements in the list in-place.
*/
public actual fun <T> MutableList<T>.reverse(): Unit {
val midPoint = (size / 2) - 1
if (midPoint < 0) return
var reverseIndex = lastIndex
for (index in 0..midPoint) {
val tmp = this[index]
this[index] = this[reverseIndex]
this[reverseIndex] = tmp
reverseIndex--
}
}
@@ -0,0 +1,284 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. 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.comparisons
//
// NOTE: THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import kotlin.js.*
/**
* Returns the greater of two values.
* If values are equal, returns the first one.
*/
@SinceKotlin("1.1")
public actual fun <T : Comparable<T>> maxOf(a: T, b: T): T {
return if (a >= b) a else b
}
/**
* Returns the greater of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Byte, b: Byte): Byte {
return Math.max(a.toInt(), b.toInt()).unsafeCast<Byte>()
}
/**
* Returns the greater of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Short, b: Short): Short {
return Math.max(a.toInt(), b.toInt()).unsafeCast<Short>()
}
/**
* Returns the greater of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Int, b: Int): Int {
return Math.max(a, b)
}
/**
* Returns the greater of two values.
*/
@SinceKotlin("1.1")
@Suppress("DEPRECATION_ERROR", "NOTHING_TO_INLINE")
public actual inline fun maxOf(a: Long, b: Long): Long {
return if (a >= b) a else b
}
/**
* Returns the greater of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Float, b: Float): Float {
return Math.max(a, b)
}
/**
* Returns the greater of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Double, b: Double): Double {
return Math.max(a, b)
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
public actual fun <T : Comparable<T>> maxOf(a: T, b: T, c: T): T {
return maxOf(a, maxOf(b, c))
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Byte, b: Byte, c: Byte): Byte {
return Math.max(a.toInt(), b.toInt(), c.toInt()).unsafeCast<Byte>()
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Short, b: Short, c: Short): Short {
return Math.max(a.toInt(), b.toInt(), c.toInt()).unsafeCast<Short>()
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Int, b: Int, c: Int): Int {
return Math.max(a, b, c)
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public actual inline fun maxOf(a: Long, b: Long, c: Long): Long {
return maxOf(a, maxOf(b, c))
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Float, b: Float, c: Float): Float {
return Math.max(a, b, c)
}
/**
* Returns the greater of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun maxOf(a: Double, b: Double, c: Double): Double {
return Math.max(a, b, c)
}
/**
* Returns the smaller of two values.
* If values are equal, returns the first one.
*/
@SinceKotlin("1.1")
public actual fun <T : Comparable<T>> minOf(a: T, b: T): T {
return if (a <= b) a else b
}
/**
* Returns the smaller of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Byte, b: Byte): Byte {
return Math.min(a.toInt(), b.toInt()).unsafeCast<Byte>()
}
/**
* Returns the smaller of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Short, b: Short): Short {
return Math.min(a.toInt(), b.toInt()).unsafeCast<Short>()
}
/**
* Returns the smaller of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Int, b: Int): Int {
return Math.min(a, b)
}
/**
* Returns the smaller of two values.
*/
@SinceKotlin("1.1")
@Suppress("DEPRECATION_ERROR", "NOTHING_TO_INLINE")
public actual inline fun minOf(a: Long, b: Long): Long {
return if (a <= b) a else b
}
/**
* Returns the smaller of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Float, b: Float): Float {
return Math.min(a, b)
}
/**
* Returns the smaller of two values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Double, b: Double): Double {
return Math.min(a, b)
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
public actual fun <T : Comparable<T>> minOf(a: T, b: T, c: T): T {
return minOf(a, minOf(b, c))
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Byte, b: Byte, c: Byte): Byte {
return Math.min(a.toInt(), b.toInt(), c.toInt()).unsafeCast<Byte>()
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Short, b: Short, c: Short): Short {
return Math.min(a.toInt(), b.toInt(), c.toInt()).unsafeCast<Short>()
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Int, b: Int, c: Int): Int {
return Math.min(a, b, c)
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public actual inline fun minOf(a: Long, b: Long, c: Long): Long {
return minOf(a, minOf(b, c))
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Float, b: Float, c: Float): Float {
return Math.min(a, b, c)
}
/**
* Returns the smaller of three values.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
@Suppress("DEPRECATION_ERROR")
public actual inline fun minOf(a: Double, b: Double, c: Double): Double {
return Math.min(a, b, c)
}
@@ -103,14 +103,14 @@ public fun isChar(c: Any): Boolean {
} }
// TODO: Distinguish Boolean/Byte and Short/Char // TODO: Distinguish Boolean/Byte and Short/Char
public fun isBooleanArray(a: dynamic): Boolean = isArray(a) && a.asDynamic().`$type$` == "BooleanArray" public fun isBooleanArray(a: dynamic): Boolean = isArray(a) && a.`$type$` == "BooleanArray"
public fun isByteArray(a: dynamic): Boolean = js("a instanceof Int8Array").unsafeCast<Boolean>() public fun isByteArray(a: dynamic): Boolean = js("a instanceof Int8Array").unsafeCast<Boolean>()
public fun isShortArray(a: dynamic): Boolean = js("a instanceof Int16Array").unsafeCast<Boolean>() public fun isShortArray(a: dynamic): Boolean = js("a instanceof Int16Array").unsafeCast<Boolean>()
public fun isCharArray(a: dynamic): Boolean = isArray(a) && a.asDynamic().`$type$` == "CharArray" public fun isCharArray(a: dynamic): Boolean = isArray(a) && a.`$type$` == "CharArray"
public fun isIntArray(a: dynamic): Boolean = js("a instanceof Int32Array").unsafeCast<Boolean>() public fun isIntArray(a: dynamic): Boolean = js("a instanceof Int32Array").unsafeCast<Boolean>()
public fun isFloatArray(a: dynamic): Boolean = js("a instanceof Float32Array").unsafeCast<Boolean>() public fun isFloatArray(a: dynamic): Boolean = js("a instanceof Float32Array").unsafeCast<Boolean>()
public fun isDoubleArray(a: dynamic): Boolean = js("a instanceof Float64Array").unsafeCast<Boolean>() public fun isDoubleArray(a: dynamic): Boolean = js("a instanceof Float64Array").unsafeCast<Boolean>()
public fun isLongArray(a: dynamic): Boolean = isArray(a) && a.asDynamic().`$type$` == "LongArray" public fun isLongArray(a: dynamic): Boolean = isArray(a) && a.`$type$` == "LongArray"
internal fun jsIn(x: String, y: dynamic): Boolean = js("x in y") internal fun jsIn(x: String, y: dynamic): Boolean = js("x in y")
+16 -1
View File
@@ -288,12 +288,27 @@ if (typeof ArrayBuffer.isView === "undefined") {
} }
// Patch sort to work with TypedArrays if needed. // Patch sort to work with TypedArrays if needed.
// TODO: consider to remove following function and replace it with `Kotlin.doubleCompareTo` (see misc.js)
var totalOrderComparator = function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
if (a === b) {
if (a !== 0) return 0;
var ia = 1 / a;
return ia === 1 / b ? 0 : (ia < 0 ? -1 : 1);
}
return a !== a ? (b !== b ? 0 : 1) : -1
};
for (var i = 0; i < arrays.length; ++i) { for (var i = 0; i < arrays.length; ++i) {
var TypedArray = arrays[i]; var TypedArray = arrays[i];
if (typeof TypedArray.prototype.sort === "undefined") { if (typeof TypedArray.prototype.sort === "undefined") {
Object.defineProperty(TypedArray.prototype, 'sort', { Object.defineProperty(TypedArray.prototype, 'sort', {
value: function(compareFunction) { value: function(compareFunction) {
return Array.prototype.sort.call(this, compareFunction); return Array.prototype.sort.call(this, compareFunction || totalOrderComparator);
} }
}); });
} }
@@ -6,7 +6,6 @@
package kotlin.collections package kotlin.collections
import kotlin.comparisons.naturalOrder import kotlin.comparisons.naturalOrder
import kotlin.internal.InlineOnly
import kotlin.random.Random import kotlin.random.Random
/** Returns the array if it's not `null`, or an empty array otherwise. */ /** Returns the array if it's not `null`, or an empty array otherwise. */
@@ -50,10 +49,6 @@ internal actual fun <T> copyToArrayImpl(collection: Collection<*>, array: Array<
return array return array
} }
@library("arrayToString")
@Suppress("UNUSED_PARAMETER")
internal fun arrayToString(array: Array<*>): String = definedExternally
/** /**
* Returns an immutable list containing only the specified object [element]. * Returns an immutable list containing only the specified object [element].
*/ */
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2018 JetBrains s.r.o. 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.collections
@library("arrayToString")
@Suppress("UNUSED_PARAMETER")
internal fun arrayToString(array: Array<*>): String = definedExternally
@@ -46,14 +46,16 @@ fun main(args: Array<String>) {
val commonDir = baseDir.resolveExistingDir("libraries/stdlib/common/src/generated") val commonDir = baseDir.resolveExistingDir("libraries/stdlib/common/src/generated")
val jvmDir = baseDir.resolveExistingDir("libraries/stdlib/jvm/src/generated") val jvmDir = baseDir.resolveExistingDir("libraries/stdlib/jvm/src/generated")
val jsDir = baseDir.resolveExistingDir("libraries/stdlib/js/src/generated") val jsDir = baseDir.resolveExistingDir("libraries/stdlib/js/src/generated")
val jsIrDir = baseDir.resolveExistingDir("libraries/stdlib/js/irRuntime/generated")
templateGroups.groupByFileAndWrite { (platform, source) -> templateGroups.groupByFileAndWrite { (target, source) ->
// File("build/out/$platform/$source.kt") // File("build/out/$platform/$source.kt")
when (platform) { when (target) {
Platform.Common -> commonDir.resolve("_${source.name.capitalize()}.kt") KotlinTarget.Common -> commonDir.resolve("_${source.name.capitalize()}.kt")
Platform.JVM -> jvmDir.resolve("_${source.name.capitalize()}Jvm.kt") KotlinTarget.JVM -> jvmDir.resolve("_${source.name.capitalize()}Jvm.kt")
Platform.JS -> jsDir.resolve("_${source.name.capitalize()}Js.kt") KotlinTarget.JS -> jsDir.resolve("_${source.name.capitalize()}Js.kt")
Platform.Native -> error("Native is unsupported yet") KotlinTarget.JS_IR -> jsIrDir.resolve("_${source.name.capitalize()}Js.kt")
KotlinTarget.Native -> error("Native is unsupported yet")
} }
} }
} }
@@ -83,8 +83,14 @@ object ArrayOps : TemplateGroupBase() {
} }
on(Platform.JS) { on(Platform.JS) {
annotation("""@library("arrayEquals")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("arrayEquals")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentEqualsInternal(other)" }
}
} }
} }
@@ -116,8 +122,14 @@ object ArrayOps : TemplateGroupBase() {
} }
} }
on(Platform.JS) { on(Platform.JS) {
annotation("""@library("arrayDeepEquals")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("arrayDeepEquals")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentDeepEqualsImpl(other)" }
}
} }
} }
@@ -141,8 +153,13 @@ object ArrayOps : TemplateGroupBase() {
body { "return java.util.Arrays.toString(this)" } body { "return java.util.Arrays.toString(this)" }
} }
on(Platform.JS) { on(Platform.JS) {
annotation("""@library("arrayToString")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("arrayToString")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return arrayToString(this as Array<*>)" }
}
} }
} }
@@ -174,8 +191,13 @@ object ArrayOps : TemplateGroupBase() {
} }
} }
on(Platform.JS) { on(Platform.JS) {
annotation("""@library("arrayDeepToString")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("arrayDeepToString")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentDeepToStringImpl()" }
}
} }
} }
@@ -196,8 +218,13 @@ object ArrayOps : TemplateGroupBase() {
body { "return java.util.Arrays.hashCode(this)" } body { "return java.util.Arrays.hashCode(this)" }
} }
on(Platform.JS) { on(Platform.JS) {
annotation("""@library("arrayHashCode")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("arrayHashCode")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentHashCodeInternal()" }
}
} }
} }
@@ -227,8 +254,13 @@ object ArrayOps : TemplateGroupBase() {
} }
} }
on(Platform.JS) { on(Platform.JS) {
annotation("""@library("arrayDeepHashCode")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("arrayDeepHashCode")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentDeepHashCodeInternal()" }
}
} }
} }
@@ -756,8 +788,13 @@ object ArrayOps : TemplateGroupBase() {
} }
specialFor(ArraysOfPrimitives) { specialFor(ArraysOfPrimitives) {
if (primitive != PrimitiveType.Long) { if (primitive != PrimitiveType.Long) {
annotation("""@library("primitiveArraySort")""") on(Backend.Legacy) {
body { "definedExternally" } annotation("""@library("primitiveArraySort")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "this.asDynamic().sort()" }
}
} }
} }
} }
@@ -86,12 +86,26 @@ enum class Platform {
Common, Common,
JVM, JVM,
JS, JS,
Native; Native
}
enum class Backend {
Any,
Legacy,
IR
}
enum class KotlinTarget(val platform: Platform, val backend: Backend) {
Common(Platform.Common, Backend.Any),
JVM(Platform.JVM, Backend.Any),
JS(Platform.JS, Backend.Legacy),
JS_IR(Platform.JS, Backend.IR),
Native(Platform.Native, Backend.IR);
val fullName get() = "Kotlin/$name" val fullName get() = "Kotlin/$name"
companion object { companion object {
val values = values().toList() val values = KotlinTarget.values().toList()
} }
} }
@@ -25,7 +25,7 @@ private fun getDefaultSourceFile(f: Family): SourceFile = when (f) {
@TemplateDsl @TemplateDsl
class MemberBuilder( class MemberBuilder(
val allowedPlatforms: Set<Platform>, val allowedPlatforms: Set<Platform>,
val platform: Platform, val target: KotlinTarget,
var family: Family, var family: Family,
var sourceFile: SourceFile = getDefaultSourceFile(family), var sourceFile: SourceFile = getDefaultSourceFile(family),
var primitive: PrimitiveType? = null var primitive: PrimitiveType? = null
@@ -143,13 +143,18 @@ class MemberBuilder(
fun on(platform: Platform, action: () -> Unit) { fun on(platform: Platform, action: () -> Unit) {
require(platform in allowedPlatforms) { "Platform $platform is not in the list of allowed platforms $allowedPlatforms" } require(platform in allowedPlatforms) { "Platform $platform is not in the list of allowed platforms $allowedPlatforms" }
if (this.platform == platform) if (target.platform == platform)
action() action()
else { else {
hasPlatformSpecializations = true hasPlatformSpecializations = true
} }
} }
fun on(backend: Backend, action: () -> Unit) {
require(target.platform == Platform.JS)
if (target.backend == backend) action()
}
fun specialFor(f: Family, action: () -> Unit) { fun specialFor(f: Family, action: () -> Unit) {
if (family == f) if (family == f)
action() action()
@@ -165,14 +170,14 @@ class MemberBuilder(
val headerOnly: Boolean val headerOnly: Boolean
val isImpl: Boolean val isImpl: Boolean
if (!legacyMode) { if (!legacyMode) {
headerOnly = platform == Platform.Common && hasPlatformSpecializations headerOnly = target.platform == Platform.Common && hasPlatformSpecializations
isImpl = platform != Platform.Common && Platform.Common in allowedPlatforms isImpl = target.platform != Platform.Common && Platform.Common in allowedPlatforms
} }
else { else {
// legacy mode when all is headerOnly + no_impl // legacy mode when all is headerOnly + no_impl
// except functions with optional parameters - they are common + no_impl // except functions with optional parameters - they are common + no_impl
val hasOptionalParams = signature.contains("=") val hasOptionalParams = signature.contains("=")
headerOnly = platform == Platform.Common && !hasOptionalParams headerOnly = target.platform == Platform.Common && !hasOptionalParams
isImpl = false isImpl = false
} }
@@ -376,7 +381,7 @@ class MemberBuilder(
val body = (body ?: val body = (body ?:
deprecate?.replaceWith?.let { "return $it" } ?: deprecate?.replaceWith?.let { "return $it" } ?:
throw RuntimeException("$signature for ${platform.fullName}: no body specified for ${family to primitive}") throw RuntimeException("$signature for ${target.fullName}: no body specified for ${family to primitive}")
).trim('\n') ).trim('\n')
val indent: Int = body.takeWhile { it == ' ' }.length val indent: Int = body.takeWhile { it == ' ' }.length
@@ -53,7 +53,7 @@ interface MemberTemplate {
/** Specifies which platforms this member template should be generated for */ /** Specifies which platforms this member template should be generated for */
fun platforms(vararg platforms: Platform) fun platforms(vararg platforms: Platform)
fun instantiate(platforms: List<Platform> = Platform.values): Sequence<MemberBuilder> fun instantiate(targets: List<KotlinTarget> = KotlinTarget.values): Sequence<MemberBuilder>
/** Registers parameterless member builder function */ /** Registers parameterless member builder function */
fun builder(b: MemberBuildAction) fun builder(b: MemberBuildAction)
@@ -78,9 +78,9 @@ abstract class MemberTemplateDefinition<TParam> : MemberTemplate {
private val buildActions = mutableListOf<BuildAction>() private val buildActions = mutableListOf<BuildAction>()
private var targetPlatforms = setOf(*Platform.values()) private var allowedPlatforms = setOf(*Platform.values())
override fun platforms(vararg platforms: Platform) { override fun platforms(vararg platforms: Platform) {
targetPlatforms = setOf(*platforms) allowedPlatforms = setOf(*platforms)
} }
@@ -105,23 +105,24 @@ abstract class MemberTemplateDefinition<TParam> : MemberTemplate {
} ?: this } ?: this
override fun instantiate(platforms: List<Platform>): Sequence<MemberBuilder> { override fun instantiate(targets: List<KotlinTarget>): Sequence<MemberBuilder> {
val resultingPlatforms = platforms.intersect(targetPlatforms) val resultingTargets = targets.filter { it.platform in allowedPlatforms }
val specificPlatforms by lazy { resultingPlatforms - Platform.Common } val resultingPlatforms = resultingTargets.map { it.platform }.distinct()
val specificTargets by lazy { resultingTargets - KotlinTarget.Common }
fun platformMemberBuilders(family: Family, p: TParam) = fun platformMemberBuilders(family: Family, p: TParam) =
if (Platform.Common in targetPlatforms) { if (Platform.Common in allowedPlatforms) {
val commonMemberBuilder = createMemberBuilder(Platform.Common, family, p) val commonMemberBuilder = createMemberBuilder(KotlinTarget.Common, family, p)
mutableListOf<MemberBuilder>().also { builders -> mutableListOf<MemberBuilder>().also { builders ->
if (Platform.Common in resultingPlatforms) builders.add(commonMemberBuilder) if (Platform.Common in resultingPlatforms) builders.add(commonMemberBuilder)
if (commonMemberBuilder.hasPlatformSpecializations) { if (commonMemberBuilder.hasPlatformSpecializations) {
specificPlatforms.mapTo(builders) { specificTargets.mapTo(builders) {
createMemberBuilder(it, family, p) createMemberBuilder(it, family, p)
} }
} }
} }
} else { } else {
resultingPlatforms.map { createMemberBuilder(it, family, p) } resultingTargets.map { createMemberBuilder(it, family, p) }
} }
return parametrize() return parametrize()
@@ -130,8 +131,8 @@ abstract class MemberTemplateDefinition<TParam> : MemberTemplate {
.flatten() .flatten()
} }
private fun createMemberBuilder(platform: Platform, family: Family, p: TParam): MemberBuilder { private fun createMemberBuilder(target: KotlinTarget, family: Family, p: TParam): MemberBuilder {
return MemberBuilder(targetPlatforms, platform, family).also { builder -> return MemberBuilder(allowedPlatforms, target, family).also { builder ->
for (action in buildActions) { for (action in buildActions) {
when (action) { when (action) {
is BuildAction.Generic -> action(builder) is BuildAction.Generic -> action(builder)
@@ -29,37 +29,37 @@ fun readCopyrightNoticeFromProfile(copyrightProfile: File): String {
} }
data class PlatformSourceFile( data class TargetedSourceFile(
val platform: Platform, val target: KotlinTarget,
val sourceFile: SourceFile val sourceFile: SourceFile
) )
private val platformsToGenerate = Platform.values - Platform.Native private val targetsToGenerate = KotlinTarget.values - KotlinTarget.Native
@JvmName("groupByFileAndWriteGroups") @JvmName("groupByFileAndWriteGroups")
fun Sequence<TemplateGroup>.groupByFileAndWrite( fun Sequence<TemplateGroup>.groupByFileAndWrite(
fileNameBuilder: (PlatformSourceFile) -> File fileNameBuilder: (TargetedSourceFile) -> File
) { ) {
flatMap { group -> flatMap { group ->
group.invoke() group.invoke()
.flatMap { it.instantiate(platformsToGenerate) } .flatMap { it.instantiate(targetsToGenerate) }
.sortedBy { it.sortingSignature } .sortedBy { it.sortingSignature }
}.groupByFileAndWrite(fileNameBuilder) }.groupByFileAndWrite(fileNameBuilder)
} }
@JvmName("groupByFileAndWriteTemplates") @JvmName("groupByFileAndWriteTemplates")
fun Sequence<MemberTemplate>.groupByFileAndWrite( fun Sequence<MemberTemplate>.groupByFileAndWrite(
fileNameBuilder: (PlatformSourceFile) -> File fileNameBuilder: (TargetedSourceFile) -> File
) { ) {
flatMap { it.instantiate(platformsToGenerate) } flatMap { it.instantiate(targetsToGenerate) }
.groupByFileAndWrite(fileNameBuilder) .groupByFileAndWrite(fileNameBuilder)
} }
@JvmName("groupByFileAndWriteMembers") @JvmName("groupByFileAndWriteMembers")
fun Sequence<MemberBuilder>.groupByFileAndWrite( fun Sequence<MemberBuilder>.groupByFileAndWrite(
fileNameBuilder: (PlatformSourceFile) -> File fileNameBuilder: (TargetedSourceFile) -> File
) { ) {
val groupedMembers = groupBy { PlatformSourceFile(it.platform, it.sourceFile) } val groupedMembers = groupBy { TargetedSourceFile(it.target, it.sourceFile) }
for ((psf, members) in groupedMembers) { for ((psf, members) in groupedMembers) {
val file = fileNameBuilder(psf) val file = fileNameBuilder(psf)
@@ -67,14 +67,14 @@ fun Sequence<MemberBuilder>.groupByFileAndWrite(
} }
} }
fun List<MemberBuilder>.writeTo(file: File, platformSource: PlatformSourceFile) { fun List<MemberBuilder>.writeTo(file: File, targetedSource: TargetedSourceFile) {
val (platform, sourceFile) = platformSource val (target, sourceFile) = targetedSource
println("Generating file: $file") println("Generating file: $file")
file.parentFile.mkdirs() file.parentFile.mkdirs()
FileWriter(file).use { writer -> FileWriter(file).use { writer ->
writer.appendln(COPYRIGHT_NOTICE) writer.appendln(COPYRIGHT_NOTICE)
when (platform) { when (target.platform) {
Platform.Common, Platform.JVM -> { Platform.Common, Platform.JVM -> {
if (sourceFile.multifile) { if (sourceFile.multifile) {
writer.appendln("@file:kotlin.jvm.JvmMultifileClass") writer.appendln("@file:kotlin.jvm.JvmMultifileClass")
@@ -87,14 +87,14 @@ fun List<MemberBuilder>.writeTo(file: File, platformSource: PlatformSourceFile)
writer.append("package ${sourceFile.packageName ?: "kotlin"}\n\n") writer.append("package ${sourceFile.packageName ?: "kotlin"}\n\n")
writer.append("${COMMON_AUTOGENERATED_WARNING}\n\n") writer.append("${COMMON_AUTOGENERATED_WARNING}\n\n")
if (platform == Platform.JS) { if (target.platform == Platform.JS) {
writer.appendln("import kotlin.js.*") writer.appendln("import kotlin.js.*")
if (sourceFile == SourceFile.Arrays) { if (sourceFile == SourceFile.Arrays) {
writer.appendln("import primitiveArrayConcat") writer.appendln("import primitiveArrayConcat")
writer.appendln("import withType") writer.appendln("import withType")
} }
} }
if (platform == Platform.Common) { if (target.platform == Platform.Common) {
writer.appendln("import kotlin.random.*") writer.appendln("import kotlin.random.*")
} }