Unify generation of Primitives files for all backends

This commit is contained in:
Ivan Kylchik
2023-01-26 12:41:07 +01:00
committed by Space Team
parent e80b4c530d
commit 07ca981632
18 changed files with 4437 additions and 1618 deletions
@@ -0,0 +1,623 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
import org.jetbrains.kotlin.generators.builtins.generateBuiltIns.BuiltInsGenerator
import java.io.PrintWriter
abstract class BasePrimitivesGenerator(private val writer: PrintWriter) : BuiltInsGenerator {
companion object {
internal val binaryOperators: List<String> = listOf(
"plus",
"minus",
"times",
"div",
"rem",
)
internal val unaryPlusMinusOperators: Map<String, String> = mapOf(
"unaryPlus" to "Returns this value.",
"unaryMinus" to "Returns the negative of this value."
)
internal val shiftOperators: Map<String, String> = mapOf(
"shl" to "Shifts this value left by the [bitCount] number of bits.",
"shr" to "Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with copies of the sign bit.",
"ushr" to "Shifts this value right by the [bitCount] number of bits, filling the leftmost bits with zeros.")
internal val bitwiseOperators: Map<String, String> = mapOf(
"and" to "Performs a bitwise AND operation between the two values.",
"or" to "Performs a bitwise OR operation between the two values.",
"xor" to "Performs a bitwise XOR operation between the two values.")
internal fun shiftOperatorsDocDetail(kind: PrimitiveType): String {
val bitsUsed = when (kind) {
PrimitiveType.INT -> "five"
PrimitiveType.LONG -> "six"
else -> throw IllegalArgumentException("Bit shift operation is not implemented for $kind")
}
return """
Note that only the $bitsUsed lowest-order bits of the [bitCount] are used as the shift distance.
The shift distance actually used is therefore always in the range `0..${kind.bitSize - 1}`.
""".trimIndent()
}
internal fun incDecOperatorsDoc(name: String): String {
val diff = if (name == "inc") "incremented" else "decremented"
return """
Returns this value $diff by one.
@sample samples.misc.Builtins.$name
""".trimIndent()
}
internal fun binaryOperatorDoc(operator: String, operand1: PrimitiveType, operand2: PrimitiveType): String = when (operator) {
"plus" -> "Adds the other value to this value."
"minus" -> "Subtracts the other value from this value."
"times" -> "Multiplies this value by the other value."
"div" -> {
if (operand1.isIntegral && operand2.isIntegral)
"Divides this value by the other value, truncating the result to an integer that is closer to zero."
else
"Divides this value by the other value."
}
"floorDiv" ->
"Divides this value by the other value, flooring the result to an integer that is closer to negative infinity."
"rem" -> {
"""
Calculates the remainder of truncating division of this value (dividend) by the other value (divisor).
The result is either zero or has the same sign as the _dividend_ and has the absolute value less than the absolute value of the divisor.
""".trimIndent()
}
"mod" -> {
"""
Calculates the remainder of flooring division of this value (dividend) by the other value (divisor).
The result is either zero or has the same sign as the _divisor_ and has the absolute value less than the absolute value of the divisor.
""".trimIndent() + if (operand1.isFloatingPoint)
"\n\n" + "If the result cannot be represented exactly, it is rounded to the nearest representable number. In this case the absolute value of the result can be less than or _equal to_ the absolute value of the divisor."
else ""
}
else -> error("No documentation for operator $operator")
}
private fun compareByDomainCapacity(type1: PrimitiveType, type2: PrimitiveType): Int {
return if (type1.isIntegral && type2.isIntegral) type1.byteSize - type2.byteSize else type1.ordinal - type2.ordinal
}
private fun docForConversionFromFloatingToIntegral(fromFloating: PrimitiveType, toIntegral: PrimitiveType): String {
require(fromFloating.isFloatingPoint)
require(toIntegral.isIntegral)
val thisName = fromFloating.capitalized
val otherName = toIntegral.capitalized
return if (compareByDomainCapacity(toIntegral, PrimitiveType.INT) < 0) {
"""
The resulting `$otherName` value is equal to `this.toInt().to$otherName()`.
""".trimIndent()
} else {
"""
The fractional part, if any, is rounded down towards zero.
Returns zero if this `$thisName` value is `NaN`, [$otherName.MIN_VALUE] if it's less than `$otherName.MIN_VALUE`,
[$otherName.MAX_VALUE] if it's bigger than `$otherName.MAX_VALUE`.
""".trimIndent()
}
}
private fun docForConversionFromFloatingToFloating(fromFloating: PrimitiveType, toFloating: PrimitiveType): String {
require(fromFloating.isFloatingPoint)
require(toFloating.isFloatingPoint)
val thisName = fromFloating.capitalized
val otherName = toFloating.capitalized
return if (compareByDomainCapacity(toFloating, fromFloating) < 0) {
"""
The resulting value is the closest `$otherName` to this `$thisName` value.
In case when this `$thisName` value is exactly between two `$otherName`s,
the one with zero at least significant bit of mantissa is selected.
""".trimIndent()
} else {
"""
The resulting `$otherName` value represents the same numerical value as this `$thisName`.
""".trimIndent()
}
}
private fun docForConversionFromIntegralToIntegral(fromIntegral: PrimitiveType, toIntegral: PrimitiveType): String {
require(fromIntegral.isIntegral)
require(toIntegral.isIntegral)
val thisName = fromIntegral.capitalized
val otherName = toIntegral.capitalized
return if (toIntegral == PrimitiveType.CHAR) {
if (fromIntegral == PrimitiveType.SHORT) {
"""
The resulting `Char` code is equal to this value reinterpreted as an unsigned number,
i.e. it has the same binary representation as this `Short`.
""".trimIndent()
} else if (fromIntegral == PrimitiveType.BYTE) {
"""
If this value is non-negative, the resulting `Char` code is equal to this value.
The least significant 8 bits of the resulting `Char` code are the same as the bits of this `Byte` value,
whereas the most significant 8 bits are filled with the sign bit of this value.
""".trimIndent()
} else {
"""
If this value is in the range of `Char` codes `Char.MIN_VALUE..Char.MAX_VALUE`,
the resulting `Char` code is equal to this value.
The resulting `Char` code is represented by the least significant 16 bits of this `$thisName` value.
""".trimIndent()
}
} else if (compareByDomainCapacity(toIntegral, fromIntegral) < 0) {
"""
If this value is in [$otherName.MIN_VALUE]..[$otherName.MAX_VALUE], the resulting `$otherName` value represents
the same numerical value as this `$thisName`.
The resulting `$otherName` value is represented by the least significant ${toIntegral.bitSize} bits of this `$thisName` value.
""".trimIndent()
} else {
"""
The resulting `$otherName` value represents the same numerical value as this `$thisName`.
The least significant ${fromIntegral.bitSize} bits of the resulting `$otherName` value are the same as the bits of this `$thisName` value,
whereas the most significant ${toIntegral.bitSize - fromIntegral.bitSize} bits are filled with the sign bit of this value.
""".trimIndent()
}
}
private fun docForConversionFromIntegralToFloating(fromIntegral: PrimitiveType, toFloating: PrimitiveType): String {
require(fromIntegral.isIntegral)
require(toFloating.isFloatingPoint)
val thisName = fromIntegral.capitalized
val otherName = toFloating.capitalized
return if (fromIntegral == PrimitiveType.LONG || fromIntegral == PrimitiveType.INT && toFloating == PrimitiveType.FLOAT) {
"""
The resulting value is the closest `$otherName` to this `$thisName` value.
In case when this `$thisName` value is exactly between two `$otherName`s,
the one with zero at least significant bit of mantissa is selected.
""".trimIndent()
} else {
"""
The resulting `$otherName` value represents the same numerical value as this `$thisName`.
""".trimIndent()
}
}
private fun maxByDomainCapacity(type1: PrimitiveType, type2: PrimitiveType): PrimitiveType {
return if (type1.ordinal > type2.ordinal) type1 else type2
}
fun getOperatorReturnType(kind1: PrimitiveType, kind2: PrimitiveType): PrimitiveType {
require(kind1 != PrimitiveType.BOOLEAN) { "kind1 must not be BOOLEAN" }
require(kind2 != PrimitiveType.BOOLEAN) { "kind2 must not be BOOLEAN" }
return maxByDomainCapacity(maxByDomainCapacity(kind1, kind2), PrimitiveType.INT)
}
}
private val typeDescriptions: Map<PrimitiveType, String> = mapOf(
PrimitiveType.DOUBLE to "double-precision 64-bit IEEE 754 floating point number",
PrimitiveType.FLOAT to "single-precision 32-bit IEEE 754 floating point number",
PrimitiveType.LONG to "64-bit signed integer",
PrimitiveType.INT to "32-bit signed integer",
PrimitiveType.SHORT to "16-bit signed integer",
PrimitiveType.BYTE to "8-bit signed integer",
PrimitiveType.CHAR to "16-bit Unicode character"
)
open fun primitiveConstants(type: PrimitiveType): List<Any> = when (type) {
PrimitiveType.INT -> listOf(java.lang.Integer.MIN_VALUE, java.lang.Integer.MAX_VALUE)
PrimitiveType.BYTE -> listOf(java.lang.Byte.MIN_VALUE, java.lang.Byte.MAX_VALUE)
PrimitiveType.SHORT -> listOf(java.lang.Short.MIN_VALUE, java.lang.Short.MAX_VALUE)
PrimitiveType.LONG -> listOf((java.lang.Long.MIN_VALUE + 1).toString() + "L - 1L", java.lang.Long.MAX_VALUE.toString() + "L")
PrimitiveType.DOUBLE -> listOf(java.lang.Double.MIN_VALUE, java.lang.Double.MAX_VALUE, "1.0/0.0", "-1.0/0.0", "-(0.0/0.0)")
PrimitiveType.FLOAT -> listOf(java.lang.Float.MIN_VALUE, java.lang.Float.MAX_VALUE, "1.0F/0.0F", "-1.0F/0.0F", "-(0.0F/0.0F)").map { it as? String ?: "${it}F" }
else -> throw IllegalArgumentException("type: $type")
}
open fun PrimitiveType.shouldGenerate(): Boolean = true
override fun generate() {
writer.print(FileDescription(classes = generateClasses()).apply { this.modifyGeneratedFile() }.toString())
}
private fun generateClasses(): List<ClassDescription> {
return buildList {
for (thisKind in PrimitiveType.onlyNumeric.filter { it.shouldGenerate() }) {
val className = thisKind.capitalized
val doc = "Represents a ${typeDescriptions[thisKind]}."
val methods = buildList {
this.addAll(generateCompareTo(thisKind))
this.addAll(generateBinaryOperators(thisKind))
this.addAll(generateUnaryOperators(thisKind))
this.addAll(generateRangeTo(thisKind))
this.addAll(generateRangeUntil(thisKind))
if (thisKind == PrimitiveType.INT || thisKind == PrimitiveType.LONG) {
this.addAll(generateBitShiftOperators(thisKind))
this.addAll(generateBitwiseOperators(thisKind))
}
this.addAll(generateConversions(thisKind))
this += generateEquals(thisKind)
this += generateToString(thisKind)
this.addAll(generateAdditionalMethods(thisKind))
}
this += ClassDescription(
doc,
annotations = mutableListOf(),
name = className,
companionObject = generateCompanionObject(thisKind),
methods = methods
).apply { this.modifyGeneratedClass(thisKind) }
}
}
}
private fun generateCompanionObject(thisKind: PrimitiveType): CompanionObjectDescription {
val properties = buildList {
val className = thisKind.capitalized
if (thisKind == PrimitiveType.FLOAT || thisKind == PrimitiveType.DOUBLE) {
val (minValue, maxValue, posInf, negInf, nan) = primitiveConstants(thisKind)
this += PropertyDescription(
doc = "A constant holding the smallest *positive* nonzero value of $className.",
name = "MIN_VALUE",
type = className,
value = minValue.toString()
)
this += PropertyDescription(
doc = "A constant holding the largest positive finite value of $className.",
name = "MAX_VALUE",
type = className,
value = maxValue.toString()
)
this += PropertyDescription(
doc = "A constant holding the positive infinity value of $className.",
name = "POSITIVE_INFINITY",
type = className,
value = posInf.toString()
)
this += PropertyDescription(
doc = "A constant holding the negative infinity value of $className.",
name = "NEGATIVE_INFINITY",
type = className,
value = negInf.toString()
)
this += PropertyDescription(
doc = "A constant holding the \"not a number\" value of $className.",
name = "NaN",
type = className,
value = nan.toString()
)
}
if (thisKind == PrimitiveType.INT || thisKind == PrimitiveType.LONG || thisKind == PrimitiveType.SHORT || thisKind == PrimitiveType.BYTE) {
val (minValue, maxValue) = primitiveConstants(thisKind)
this += PropertyDescription(
doc = "A constant holding the minimum value an instance of $className can have.",
name = "MIN_VALUE",
type = className,
value = minValue.toString()
)
this += PropertyDescription(
doc = "A constant holding the maximum value an instance of $className can have.",
name = "MAX_VALUE",
type = className,
value = maxValue.toString()
)
}
val sizeSince = if (thisKind.isFloatingPoint) "1.4" else "1.3"
this += PropertyDescription(
doc = "The number of bytes used to represent an instance of $className in a binary form.",
annotations = mutableListOf("SinceKotlin(\"$sizeSince\")"),
name = "SIZE_BYTES",
type = "Int",
value = thisKind.byteSize.toString()
)
this += PropertyDescription(
doc = "The number of bits used to represent an instance of $className in a binary form.",
annotations = mutableListOf("SinceKotlin(\"$sizeSince\")"),
name = "SIZE_BITS",
type = "Int",
value = thisKind.bitSize.toString()
)
}
properties.forEach { it.modifyGeneratedCompanionObjectProperty(thisKind) }
return CompanionObjectDescription(properties = properties).apply { this.modifyGeneratedCompanionObject(thisKind) }
}
private fun generateCompareTo(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for (otherKind in PrimitiveType.onlyNumeric) {
val doc = """
Compares this value with the specified value for order.
Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
or a positive number if it's greater than other.
""".trimIndent()
val signature = MethodSignature(
isOverride = otherKind == thisKind,
isOperator = true,
name = "compareTo",
arg = MethodParameter("other", otherKind.capitalized),
returnType = PrimitiveType.INT.capitalized
)
this += MethodDescription(
doc = doc,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = signature
).apply { this.modifyGeneratedCompareTo(thisKind, otherKind) }
}
}
}
private fun generateBinaryOperators(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for (name in binaryOperators) {
this += generateOperator(name, thisKind)
}
}
}
private fun generateOperator(name: String, thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for (otherKind in PrimitiveType.onlyNumeric) {
val returnType = getOperatorReturnType(thisKind, otherKind)
val annotations = buildList {
if (name == "rem") add("SinceKotlin(\"1.1\")")
add("kotlin.internal.IntrinsicConstEvaluation")
}
this += MethodDescription(
doc = binaryOperatorDoc(name, thisKind, otherKind),
annotations = annotations.toMutableList(),
signature = MethodSignature(
isOperator = true,
name = name,
arg = MethodParameter("other", otherKind.capitalized),
returnType = returnType.capitalized
)
).apply { this.modifyGeneratedBinaryOperation(thisKind, otherKind) }
}
}
}
private fun generateUnaryOperators(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for (name in listOf("inc", "dec")) {
this += MethodDescription(
doc = incDecOperatorsDoc(name),
signature = MethodSignature(isOperator = true, name = name, arg = null, returnType = thisKind.capitalized)
).apply { this.modifyGeneratedUnaryOperation(thisKind) }
}
for ((name, doc) in unaryPlusMinusOperators) {
val returnType = when (thisKind) {
in listOf(PrimitiveType.SHORT, PrimitiveType.BYTE, PrimitiveType.CHAR) -> PrimitiveType.INT.capitalized
else -> thisKind.capitalized
}
this += MethodDescription(
doc = doc,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(isOperator = true, name = name, arg = null, returnType = returnType)
).apply { this.modifyGeneratedUnaryOperation(thisKind) }
}
}
}
private fun generateRangeTo(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for (otherKind in PrimitiveType.onlyNumeric) {
val returnType = maxByDomainCapacity(maxByDomainCapacity(thisKind, otherKind), PrimitiveType.INT)
if (returnType == PrimitiveType.DOUBLE || returnType == PrimitiveType.FLOAT) {
continue
}
this += MethodDescription(
doc = "Creates a range from this value to the specified [other] value.",
signature = MethodSignature(
isOperator = true,
name = "rangeTo",
arg = MethodParameter("other", otherKind.capitalized),
returnType = "${returnType.capitalized}Range"
)
).apply { this.modifyGeneratedRangeTo(thisKind) }
}
}
}
private fun generateRangeUntil(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for (otherKind in PrimitiveType.onlyNumeric) {
val returnType = maxByDomainCapacity(maxByDomainCapacity(thisKind, otherKind), PrimitiveType.INT)
if (returnType == PrimitiveType.DOUBLE || returnType == PrimitiveType.FLOAT) {
continue
}
this += MethodDescription(
doc = """
Creates a range from this value up to but excluding the specified [other] value.
If the [other] value is less than or equal to `this` value, then the returned range is empty.
""".trimIndent(),
annotations = mutableListOf("SinceKotlin(\"1.7\")", "ExperimentalStdlibApi"),
signature = MethodSignature(
isOperator = true,
name = "rangeUntil",
arg = MethodParameter("other", otherKind.capitalized),
returnType = "${returnType.capitalized}Range"
)
).apply { this.modifyGeneratedRangeUntil(thisKind) }
}
}
}
private fun generateBitShiftOperators(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
val className = thisKind.capitalized
val detail = shiftOperatorsDocDetail(thisKind)
for ((name, doc) in shiftOperators) {
this += MethodDescription(
doc = doc + END_LINE + END_LINE + detail,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
isInfix = true,
name = name,
arg = MethodParameter("bitCount", PrimitiveType.INT.capitalized),
returnType = className
)
).apply { this.modifyGeneratedBitShiftOperators(thisKind) }
}
}
}
private fun generateBitwiseOperators(thisKind: PrimitiveType): List<MethodDescription> {
return buildList {
for ((name, doc) in bitwiseOperators) {
this += MethodDescription(
doc = doc,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
isInfix = true,
name = name,
arg = MethodParameter("other", thisKind.capitalized),
returnType = thisKind.capitalized
)
).apply { this.modifyGeneratedBitwiseOperators(thisKind) }
}
this += MethodDescription(
doc = "Inverts the bits in this value.",
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
name = "inv",
arg = null,
returnType = thisKind.capitalized
)
).apply { this.modifyGeneratedBitwiseOperators(thisKind) }
}
}
private fun generateConversions(thisKind: PrimitiveType): List<MethodDescription> {
fun isFpToIntConversionDeprecated(otherKind: PrimitiveType): Boolean {
return thisKind in PrimitiveType.floatingPoint && otherKind in listOf(PrimitiveType.BYTE, PrimitiveType.SHORT)
}
fun isCharConversionDeprecated(otherKind: PrimitiveType): Boolean {
return thisKind != PrimitiveType.INT && otherKind == PrimitiveType.CHAR
}
return buildList {
val thisName = thisKind.capitalized
for (otherKind in PrimitiveType.exceptBoolean) {
val otherName = otherKind.capitalized
val doc = if (thisKind == otherKind) {
"Returns this value."
} else {
val detail = if (thisKind in PrimitiveType.integral) {
if (otherKind.isIntegral) {
docForConversionFromIntegralToIntegral(thisKind, otherKind)
} else {
docForConversionFromIntegralToFloating(thisKind, otherKind)
}
} else {
if (otherKind.isIntegral) {
docForConversionFromFloatingToIntegral(thisKind, otherKind)
} else {
docForConversionFromFloatingToFloating(thisKind, otherKind)
}
}
"Converts this [$thisName] value to [$otherName].$END_LINE$END_LINE" + detail
}
val annotations = mutableListOf<String>()
if (isFpToIntConversionDeprecated(otherKind)) {
annotations += "Deprecated(\"Unclear conversion. To achieve the same result convert to Int explicitly and then to $otherName.\", ReplaceWith(\"toInt().to$otherName()\"))"
annotations += "DeprecatedSinceKotlin(warningSince = \"1.3\", errorSince = \"1.5\")"
}
if (isCharConversionDeprecated(otherKind)) {
annotations += "Deprecated(\"Direct conversion to Char is deprecated. Use toInt().toChar() or Char constructor instead.\", ReplaceWith(\"this.toInt().toChar()\"))"
annotations += "DeprecatedSinceKotlin(warningSince = \"1.5\")"
}
annotations += "kotlin.internal.IntrinsicConstEvaluation"
this += MethodDescription(
doc = doc,
annotations = annotations,
signature = MethodSignature(
isOverride = true,
name = "to$otherName",
arg = null,
returnType = otherName
)
).apply { this.modifyGeneratedConversions(thisKind) }
}
}
}
private fun generateEquals(thisKind: PrimitiveType): MethodDescription {
return MethodDescription(
doc = null,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
isOverride = true,
name = "equals",
arg = MethodParameter("other", "Any?"),
returnType = "Boolean"
)
).apply { this.modifyGeneratedEquals(thisKind) }
}
private fun generateToString(thisKind: PrimitiveType): MethodDescription {
return MethodDescription(
doc = null,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
isOverride = true,
name = "toString",
arg = null,
returnType = "String"
)
).apply { modifyGeneratedToString(thisKind) }
}
internal open fun FileDescription.modifyGeneratedFile() {}
internal open fun ClassDescription.modifyGeneratedClass(thisKind: PrimitiveType) {}
internal open fun CompanionObjectDescription.modifyGeneratedCompanionObject(thisKind: PrimitiveType) {}
internal open fun PropertyDescription.modifyGeneratedCompanionObjectProperty(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedCompareTo(thisKind: PrimitiveType, otherKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedBinaryOperation(thisKind: PrimitiveType, otherKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedUnaryOperation(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedRangeTo(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedRangeUntil(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedBitShiftOperators(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedBitwiseOperators(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedConversions(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedEquals(thisKind: PrimitiveType) {}
internal open fun MethodDescription.modifyGeneratedToString(thisKind: PrimitiveType) {}
internal open fun generateAdditionalMethods(thisKind: PrimitiveType): List<MethodDescription> = emptyList()
}
@@ -0,0 +1,39 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
import java.io.PrintWriter
class JsPrimitivesGenerator(writer: PrintWriter) : BasePrimitivesGenerator(writer) {
override fun PrimitiveType.shouldGenerate(): Boolean {
return this != PrimitiveType.LONG
}
override fun FileDescription.modifyGeneratedFile() {
addSuppress("NON_ABSTRACT_FUNCTION_WITH_NO_BODY")
addSuppress("UNUSED_PARAMETER")
}
override fun PropertyDescription.modifyGeneratedCompanionObjectProperty(thisKind: PrimitiveType) {
if (this.name in setOf("POSITIVE_INFINITY", "NEGATIVE_INFINITY", "NaN")) {
this.addAnnotation("Suppress(\"DIVISION_BY_ZERO\")")
}
}
override fun generateAdditionalMethods(thisKind: PrimitiveType): List<MethodDescription> {
val hashCode = MethodDescription(
doc = null,
signature = MethodSignature(
isOverride = true,
name = "hashCode",
arg = null,
returnType = PrimitiveType.INT.capitalized
)
)
return listOf(hashCode)
}
}
@@ -0,0 +1,15 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
import java.io.PrintWriter
class JvmPrimitivesGenerator(writer: PrintWriter) : BasePrimitivesGenerator(writer) {
override fun ClassDescription.modifyGeneratedClass(thisKind: PrimitiveType) {
this.addDoc("On the JVM, non-nullable values of this type are represented as values of the primitive type `${thisKind.name.lowercase()}`.")
}
}
@@ -0,0 +1,249 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
import java.io.PrintWriter
import java.util.*
class NativePrimitivesGenerator(writer: PrintWriter) : BasePrimitivesGenerator(writer) {
override fun FileDescription.modifyGeneratedFile() {
this.addSuppress("OVERRIDE_BY_INLINE")
this.addSuppress("NOTHING_TO_INLINE")
this.addImport("kotlin.native.internal.*")
}
override fun ClassDescription.modifyGeneratedClass(thisKind: PrimitiveType) {
this.isFinal = true
}
override fun CompanionObjectDescription.modifyGeneratedCompanionObject(thisKind: PrimitiveType) {
if (thisKind !in PrimitiveType.floatingPoint) {
this.addAnnotation("CanBePrecreated")
}
}
override fun primitiveConstants(type: PrimitiveType): List<Any> {
return when (type) {
PrimitiveType.FLOAT -> listOf(
String.format(Locale.US, "%.17eF", java.lang.Float.MIN_VALUE),
String.format(Locale.US, "%.17eF", java.lang.Float.MAX_VALUE),
"1.0F/0.0F", "-1.0F/0.0F", "-(0.0F/0.0F)"
)
else -> super.primitiveConstants(type)
}
}
override fun PropertyDescription.modifyGeneratedCompanionObjectProperty(thisKind: PrimitiveType) {
if (this.name in setOf("POSITIVE_INFINITY", "NEGATIVE_INFINITY", "NaN")) {
this.addAnnotation("Suppress(\"DIVISION_BY_ZERO\")")
}
}
override fun MethodDescription.modifyGeneratedCompareTo(thisKind: PrimitiveType, otherKind: PrimitiveType) {
if (otherKind == thisKind) {
if (thisKind in PrimitiveType.floatingPoint) {
val argName = this.signature.arg!!.name
"""
// if any of values in NaN both comparisons return false
if (this > $argName) return 1
if (this < $argName) return -1
val thisBits = this.toBits()
val otherBits = $argName.toBits()
// Canonical NaN bits representation higher than any other bit represent value
return thisBits.compareTo(otherBits)
""".trimIndent().addAsMultiLineBody()
} else {
setAsExternal()
}
return
}
this.signature.isInline = thisKind !in PrimitiveType.floatingPoint
val thisCasted = "this" + thisKind.castToIfNecessary(otherKind)
val otherCasted = this.signature.arg!!.name + otherKind.castToIfNecessary(thisKind)
if (thisKind == PrimitiveType.FLOAT && otherKind == PrimitiveType.DOUBLE) {
"- ${otherCasted}.compareTo(this)"
} else {
"$thisCasted.compareTo($otherCasted)"
}.addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedBinaryOperation(thisKind: PrimitiveType, otherKind: PrimitiveType) {
val sign = this.signature.name.asSign()
if (thisKind != PrimitiveType.BYTE && thisKind != PrimitiveType.SHORT && thisKind == otherKind) {
return setAsExternal()
}
this.signature.isInline = true
val returnTypeAsPrimitive = PrimitiveType.valueOf(this.signature.returnType.uppercase())
val thisCasted = "this" + thisKind.castToIfNecessary(returnTypeAsPrimitive)
val otherCasted = this.signature.arg!!.name + this.signature.arg.getTypeAsPrimitive().castToIfNecessary(returnTypeAsPrimitive)
"$thisCasted $sign $otherCasted".addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedUnaryOperation(thisKind: PrimitiveType) {
if (this.signature.name in setOf("inc", "dec") || thisKind == PrimitiveType.INT ||
thisKind in PrimitiveType.floatingPoint || (this.signature.name == "unaryMinus" && thisKind == PrimitiveType.LONG)
) {
return setAsExternal()
}
this.signature.isInline = true
val returnTypeAsPrimitive = PrimitiveType.valueOf(this.signature.returnType.uppercase())
val thisCasted = "this" + thisKind.castToIfNecessary(returnTypeAsPrimitive)
val sign = if (this.signature.name == "unaryMinus") "-" else ""
"$sign$thisCasted".addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedRangeTo(thisKind: PrimitiveType) {
val rangeType = PrimitiveType.valueOf(this.signature.returnType.replace("Range", "").uppercase())
val thisCasted = "this" + thisKind.castToIfNecessary(rangeType)
val otherCasted = this.signature.arg!!.name + this.signature.arg.getTypeAsPrimitive().castToIfNecessary(rangeType)
"return ${this.signature.returnType}($thisCasted, $otherCasted)".addAsMultiLineBody()
}
override fun MethodDescription.modifyGeneratedRangeUntil(thisKind: PrimitiveType) {
"this until ${this.signature.arg!!.name}".addAsSingleLineBody(bodyOnNewLine = false)
}
override fun MethodDescription.modifyGeneratedBitShiftOperators(thisKind: PrimitiveType) {
setAsExternal()
}
override fun MethodDescription.modifyGeneratedBitwiseOperators(thisKind: PrimitiveType) {
setAsExternal()
}
override fun MethodDescription.modifyGeneratedConversions(thisKind: PrimitiveType) {
val returnTypeAsPrimitive = PrimitiveType.valueOf(this.signature.returnType.uppercase())
when {
returnTypeAsPrimitive == thisKind -> {
this.signature.isInline = true
"this".addAsSingleLineBody(bodyOnNewLine = true)
}
thisKind !in PrimitiveType.floatingPoint -> {
this.signature.isExternal = true
val intrinsicType = when {
returnTypeAsPrimitive in PrimitiveType.floatingPoint -> "SIGNED_TO_FLOAT"
returnTypeAsPrimitive.byteSize < thisKind.byteSize -> "INT_TRUNCATE"
returnTypeAsPrimitive.byteSize > thisKind.byteSize -> "SIGN_EXTEND"
else -> "ZERO_EXTEND"
}
this.addAnnotation("TypedIntrinsic(IntrinsicType.$intrinsicType)")
}
else -> {
if (returnTypeAsPrimitive in setOf(PrimitiveType.BYTE, PrimitiveType.SHORT, PrimitiveType.CHAR)) {
"this.toInt().to${this.signature.returnType}()".addAsSingleLineBody(bodyOnNewLine = false)
return
}
this.signature.isExternal = true
when {
returnTypeAsPrimitive in setOf(PrimitiveType.INT, PrimitiveType.LONG) -> {
this.addAnnotation("GCUnsafeCall(\"Kotlin_${thisKind.capitalized}_to${this.signature.returnType}\")")
}
thisKind.byteSize > returnTypeAsPrimitive.byteSize -> {
this.addAnnotation("TypedIntrinsic(IntrinsicType.FLOAT_TRUNCATE)")
}
thisKind.byteSize < returnTypeAsPrimitive.byteSize -> {
this.addAnnotation("TypedIntrinsic(IntrinsicType.FLOAT_EXTEND)")
}
}
}
}
}
override fun MethodDescription.modifyGeneratedEquals(thisKind: PrimitiveType) {
val argName = this.signature.arg!!.name
val additionalCheck = if (thisKind in PrimitiveType.floatingPoint) {
"this.equals(other)"
} else {
"kotlin.native.internal.areEqualByValue(this, $argName)"
}
" $argName is ${thisKind.capitalized} && $additionalCheck".addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedToString(thisKind: PrimitiveType) {
if (thisKind in PrimitiveType.floatingPoint) {
"NumberConverter.convert(this)".addAsSingleLineBody(bodyOnNewLine = false)
} else {
this.signature.isExternal = true
this.addAnnotation("GCUnsafeCall(\"Kotlin_${thisKind.capitalized}_toString\")")
}
}
override fun generateAdditionalMethods(thisKind: PrimitiveType): List<MethodDescription> {
val hashCode = MethodDescription(
doc = null,
signature = MethodSignature(
isOverride = true,
name = "hashCode",
arg = null,
returnType = PrimitiveType.INT.capitalized
)
).apply {
when (thisKind) {
PrimitiveType.LONG -> "return ((this ushr 32) xor this).toInt()".addAsMultiLineBody()
PrimitiveType.FLOAT -> "toBits()".addAsSingleLineBody()
PrimitiveType.DOUBLE -> "toBits().hashCode()".addAsSingleLineBody()
else -> "return this${thisKind.castToIfNecessary(PrimitiveType.INT)}".addAsMultiLineBody()
}
}
val customEquals = MethodDescription(
doc = null,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
name = "equals",
arg = MethodParameter("other", thisKind.capitalized),
returnType = PrimitiveType.BOOLEAN.capitalized
)
).apply {
when (thisKind) {
in PrimitiveType.floatingPoint -> "toBits() == other.toBits()".addAsSingleLineBody(bodyOnNewLine = false)
else -> "kotlin.native.internal.areEqualByValue(this, other)".addAsSingleLineBody(bodyOnNewLine = false)
}
}
val bits = MethodDescription(
doc = null,
signature = MethodSignature(
isExternal = true,
visibility = MethodVisibility.INTERNAL,
name = "bits",
arg = null,
returnType = if (thisKind == PrimitiveType.FLOAT) PrimitiveType.INT.capitalized else PrimitiveType.LONG.capitalized
)
).apply {
this.addAnnotation("TypedIntrinsic(IntrinsicType.REINTERPRET)")
this.addAnnotation("PublishedApi")
}
return if (thisKind in PrimitiveType.floatingPoint) {
listOf(customEquals, hashCode, bits)
} else {
listOf(customEquals, hashCode)
}
}
companion object {
private fun String.toNativeOperator(): String {
if (this == "div" || this == "rem") return "SIGNED_${this.uppercase(Locale.getDefault())}"
if (this == "compareTo") return "SIGNED_COMPARE_TO"
if (this.startsWith("unary")) return "UNARY_${this.replace("unary", "").uppercase(Locale.getDefault())}"
return this.uppercase(Locale.getDefault())
}
private fun MethodDescription.setAsExternal() {
addAnnotation("TypedIntrinsic(IntrinsicType.${this.signature.name.toNativeOperator()})")
this.signature.isExternal = true
}
}
}
@@ -0,0 +1,349 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
import java.io.PrintWriter
import java.util.*
class WasmPrimitivesGenerator(writer: PrintWriter) : BasePrimitivesGenerator(writer) {
override fun FileDescription.modifyGeneratedFile() {
this.addSuppress("OVERRIDE_BY_INLINE")
this.addSuppress("NOTHING_TO_INLINE")
this.addSuppress("unused")
this.addSuppress("UNUSED_PARAMETER")
this.addImport("kotlin.wasm.internal.*")
}
override fun ClassDescription.modifyGeneratedClass(thisKind: PrimitiveType) {
addAnnotation("WasmAutoboxed")
// used here little hack with name extension just to avoid creation of specialized "ConstructorParameterDescription"
constructorArg = MethodParameter("private val value", thisKind.capitalized)
}
override fun CompanionObjectDescription.modifyGeneratedCompanionObject(thisKind: PrimitiveType) {
isPublic = true
}
override fun primitiveConstants(type: PrimitiveType): List<Any> {
return when (type) {
PrimitiveType.FLOAT -> listOf(
String.format(Locale.US, "%.17eF", java.lang.Float.MIN_VALUE),
String.format(Locale.US, "%.17eF", java.lang.Float.MAX_VALUE),
"1.0F/0.0F", "-1.0F/0.0F", "-(0.0F/0.0F)"
)
else -> super.primitiveConstants(type)
}
}
override fun PropertyDescription.modifyGeneratedCompanionObjectProperty(thisKind: PrimitiveType) {
if (this.name in setOf("POSITIVE_INFINITY", "NEGATIVE_INFINITY", "NaN")) {
this.addAnnotation("Suppress(\"DIVISION_BY_ZERO\")")
}
}
override fun MethodDescription.modifyGeneratedCompareTo(thisKind: PrimitiveType, otherKind: PrimitiveType) {
if (thisKind != otherKind || thisKind !in PrimitiveType.floatingPoint) {
this.signature.isInline = true
}
val argName = this.signature.arg!!.name
if (otherKind == thisKind) {
if (thisKind in PrimitiveType.floatingPoint) {
"""
// if any of values in NaN both comparisons return false
if (this > $argName) return 1
if (this < $argName) return -1
val thisBits = this.toBits()
val otherBits = $argName.toBits()
// Canonical NaN bits representation higher than any other bit represent value
return thisBits.compareTo(otherBits)
""".trimIndent().addAsMultiLineBody()
} else {
val body = when (thisKind) {
PrimitiveType.BYTE -> "wasm_i32_compareTo(this.toInt(), $argName.toInt())"
PrimitiveType.SHORT -> "this.toInt().compareTo($argName.toInt())"
PrimitiveType.INT, PrimitiveType.LONG -> "wasm_${thisKind.prefixLowercase}_compareTo(this, $argName)"
else -> throw IllegalArgumentException("Unsupported type $thisKind for generation `compareTo` method")
}
body.addAsSingleLineBody(bodyOnNewLine = true)
}
return
}
val thisCasted = "this" + thisKind.castToIfNecessary(otherKind)
val otherCasted = argName + otherKind.castToIfNecessary(thisKind)
when {
thisKind == PrimitiveType.FLOAT && otherKind == PrimitiveType.DOUBLE -> "- ${otherCasted}.compareTo(this)"
else -> "$thisCasted.compareTo($otherCasted)"
}.addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedBinaryOperation(thisKind: PrimitiveType, otherKind: PrimitiveType) {
val sign = this.signature.name.asSign()
val argName = this.signature.arg!!.name
if (thisKind != PrimitiveType.BYTE && thisKind != PrimitiveType.SHORT && thisKind == otherKind) {
val type = thisKind.capitalized
when (val methodName = this.signature.name) {
"div" -> {
val oneConst = if (thisKind == PrimitiveType.LONG) "-1L" else "-1"
when (thisKind) {
PrimitiveType.INT, PrimitiveType.LONG -> "if (this == $type.MIN_VALUE && $argName == $oneConst) $type.MIN_VALUE else wasm_${thisKind.prefixLowercase}_div_s(this, $argName)"
else -> return implementAsIntrinsic(thisKind, methodName)
}
}
"rem" -> when (thisKind) {
in PrimitiveType.floatingPoint -> "this - (wasm_${thisKind.prefixLowercase}_nearest(this / $argName) * $argName)"
else -> return implementAsIntrinsic(thisKind, methodName)
}
else -> return implementAsIntrinsic(thisKind, methodName)
}.addAsSingleLineBody(bodyOnNewLine = true)
return
}
this.signature.isInline = true
val returnTypeAsPrimitive = PrimitiveType.valueOf(this.signature.returnType.uppercase())
val thisCasted = "this" + thisKind.castToIfNecessary(returnTypeAsPrimitive)
val otherCasted = argName + this.signature.arg.getTypeAsPrimitive().castToIfNecessary(returnTypeAsPrimitive)
"$thisCasted $sign $otherCasted".addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedUnaryOperation(thisKind: PrimitiveType) {
val methodName = this.signature.name
if (thisKind == PrimitiveType.INT && methodName == "dec") {
setAdditionalDoc("TODO: Fix test compiler/testData/codegen/box/functions/invoke/invoke.kt with inline dec")
} else {
this.signature.isInline = true
}
if (methodName in setOf("inc", "dec")) {
val sign = if (methodName == "inc") "+" else "-"
when (thisKind) {
PrimitiveType.BYTE, PrimitiveType.SHORT -> "(this $sign 1).to${thisKind.capitalized}()".addAsSingleLineBody(bodyOnNewLine = true)
PrimitiveType.INT -> "this $sign 1".addAsSingleLineBody(bodyOnNewLine = true)
PrimitiveType.LONG -> "this $sign 1L".addAsSingleLineBody(bodyOnNewLine = true)
PrimitiveType.FLOAT -> "this $sign 1.0f".addAsSingleLineBody(bodyOnNewLine = true)
PrimitiveType.DOUBLE -> "this $sign 1.0".addAsSingleLineBody(bodyOnNewLine = true)
else -> Unit
}
}
if (methodName in setOf("unaryMinus", "unaryPlus")) {
if (thisKind in PrimitiveType.floatingPoint && methodName == "unaryMinus") {
return implementAsIntrinsic(thisKind, methodName)
}
val returnTypeAsPrimitive = PrimitiveType.valueOf(this.signature.returnType.uppercase())
val thisCasted = "this" + thisKind.castToIfNecessary(returnTypeAsPrimitive)
val sign = if (methodName == "unaryMinus") {
when (thisKind) {
PrimitiveType.INT -> "0 - "
PrimitiveType.LONG -> "0L - "
else -> "-"
}
} else ""
"$sign$thisCasted".addAsSingleLineBody(bodyOnNewLine = true)
}
}
override fun MethodDescription.modifyGeneratedRangeTo(thisKind: PrimitiveType) {
val rangeType = PrimitiveType.valueOf(this.signature.returnType.replace("Range", "").uppercase())
val thisCasted = "this" + thisKind.castToIfNecessary(rangeType)
val otherCasted = this.signature.arg!!.name + this.signature.arg.getTypeAsPrimitive().castToIfNecessary(rangeType)
"return ${this.signature.returnType}($thisCasted, $otherCasted)".addAsMultiLineBody()
}
override fun MethodDescription.modifyGeneratedRangeUntil(thisKind: PrimitiveType) {
"this until ${this.signature.arg!!.name}".addAsSingleLineBody(bodyOnNewLine = false)
}
override fun MethodDescription.modifyGeneratedBitShiftOperators(thisKind: PrimitiveType) {
if (thisKind == PrimitiveType.INT) {
implementAsIntrinsic(thisKind, this.signature.name)
} else if (thisKind == PrimitiveType.LONG) {
this.signature.isInline = true
"wasm_i64_${this.signature.name.toWasmOperator().lowercase()}(this, ${signature.arg!!.name}.toLong())".addAsSingleLineBody(bodyOnNewLine = true)
}
}
override fun MethodDescription.modifyGeneratedBitwiseOperators(thisKind: PrimitiveType) {
if (this.signature.name == "inv") {
this.signature.isInline = true
val oneConst = if (thisKind == PrimitiveType.LONG) "-1L" else "-1"
"this.xor($oneConst)".addAsSingleLineBody(bodyOnNewLine = true)
return
}
implementAsIntrinsic(thisKind, this.signature.name)
}
override fun MethodDescription.modifyGeneratedConversions(thisKind: PrimitiveType) {
val returnTypeAsPrimitive = PrimitiveType.valueOf(this.signature.returnType.uppercase())
if (returnTypeAsPrimitive == thisKind) {
this.signature.isInline = true
"this".addAsSingleLineBody(bodyOnNewLine = true)
return
}
when (thisKind) {
PrimitiveType.BYTE, PrimitiveType.SHORT -> when (returnTypeAsPrimitive) {
// byte to byte conversion impossible here due to earlier check on type equality
PrimitiveType.BYTE -> "this.toInt().toByte()".also { this.signature.isInline = true }
PrimitiveType.CHAR -> "reinterpretAsInt().reinterpretAsChar()"
PrimitiveType.SHORT -> "reinterpretAsInt().reinterpretAsShort()"
PrimitiveType.INT -> "reinterpretAsInt()"
PrimitiveType.LONG -> "wasm_i64_extend_i32_s(this.toInt())"
PrimitiveType.FLOAT -> "wasm_f32_convert_i32_s(this.toInt())"
PrimitiveType.DOUBLE -> "wasm_f64_convert_i32_s(this.toInt())"
else -> throw IllegalArgumentException("Unsupported type $returnTypeAsPrimitive for generation conversion method from type $thisKind")
}
PrimitiveType.INT -> when (returnTypeAsPrimitive) {
PrimitiveType.BYTE -> "((this shl 24) shr 24).reinterpretAsByte()"
PrimitiveType.CHAR -> "(this and 0xFFFF).reinterpretAsChar()"
PrimitiveType.SHORT -> "((this shl 16) shr 16).reinterpretAsShort()"
PrimitiveType.LONG -> "wasm_i64_extend_i32_s(this)"
PrimitiveType.FLOAT -> "wasm_f32_convert_i32_s(this)"
PrimitiveType.DOUBLE -> "wasm_f64_convert_i32_s(this)"
else -> throw IllegalArgumentException("Unsupported type $returnTypeAsPrimitive for generation conversion method from type $thisKind")
}
PrimitiveType.LONG -> when (returnTypeAsPrimitive) {
PrimitiveType.BYTE, PrimitiveType.CHAR, PrimitiveType.SHORT -> "this.toInt().to${returnTypeAsPrimitive.capitalized}()"
.also { this.signature.isInline = true }
PrimitiveType.INT -> "wasm_i32_wrap_i64(this)"
PrimitiveType.FLOAT -> "wasm_f32_convert_i64_s(this)"
PrimitiveType.DOUBLE -> "wasm_f64_convert_i64_s(this)"
else -> throw IllegalArgumentException("Unsupported type $returnTypeAsPrimitive for generation conversion method from type $thisKind")
}
in PrimitiveType.floatingPoint -> when (returnTypeAsPrimitive) {
PrimitiveType.BYTE, PrimitiveType.CHAR, PrimitiveType.SHORT -> "this.toInt().to${returnTypeAsPrimitive.capitalized}()"
.also { this.signature.isInline = true }
PrimitiveType.INT -> "wasm_i32_trunc_sat_${thisKind.prefixLowercase}_s(this)"
PrimitiveType.LONG -> "wasm_i64_trunc_sat_${thisKind.prefixLowercase}_s(this)"
PrimitiveType.FLOAT -> "wasm_f32_demote_f64(this)"
PrimitiveType.DOUBLE -> "wasm_f64_promote_f32(this)"
else -> throw IllegalArgumentException("Unsupported type $returnTypeAsPrimitive for generation conversion method from type $thisKind")
}
else -> throw IllegalArgumentException("Unsupported type $thisKind to generate conversion methods")
}.addAsSingleLineBody(bodyOnNewLine = false)
}
override fun MethodDescription.modifyGeneratedEquals(thisKind: PrimitiveType) {
val argName = this.signature.arg!!.name
val additionalCheck = when (thisKind) {
PrimitiveType.LONG -> "wasm_i64_eq(this, $argName)"
PrimitiveType.FLOAT -> "this.equals(other)"
PrimitiveType.DOUBLE -> "this.toBits() == other.toBits()"
else -> {
"wasm_i32_eq(this${thisKind.castToIfNecessary(PrimitiveType.INT)}, $argName${thisKind.castToIfNecessary(PrimitiveType.INT)})"
}
}
"\t$argName is ${thisKind.capitalized} && $additionalCheck".addAsSingleLineBody(bodyOnNewLine = true)
}
override fun MethodDescription.modifyGeneratedToString(thisKind: PrimitiveType) {
when (thisKind) {
in PrimitiveType.floatingPoint -> "dtoa(this${thisKind.castToIfNecessary(PrimitiveType.DOUBLE)})"
PrimitiveType.INT, PrimitiveType.LONG -> "itoa${thisKind.bitSize}(this, 10)"
else -> "this.toInt().toString()"
}.addAsSingleLineBody(bodyOnNewLine = true)
}
override fun generateAdditionalMethods(thisKind: PrimitiveType): List<MethodDescription> {
val hashCode = MethodDescription(
doc = null,
signature = MethodSignature(
isOverride = true,
isInline = true,
name = "hashCode",
arg = null,
returnType = PrimitiveType.INT.capitalized
)
).apply {
when (thisKind) {
PrimitiveType.LONG -> "return ((this ushr 32) xor this).toInt()".addAsMultiLineBody()
PrimitiveType.FLOAT -> "toBits()".addAsSingleLineBody()
PrimitiveType.DOUBLE -> "toBits().hashCode()".addAsSingleLineBody()
else -> "return this${thisKind.castToIfNecessary(PrimitiveType.INT)}".addAsMultiLineBody()
}
}
val customEquals = MethodDescription(
doc = null,
annotations = mutableListOf("kotlin.internal.IntrinsicConstEvaluation"),
signature = MethodSignature(
isInline = thisKind in PrimitiveType.floatingPoint,
name = "equals",
arg = MethodParameter("other", thisKind.capitalized),
returnType = PrimitiveType.BOOLEAN.capitalized
)
).apply {
when (thisKind) {
in PrimitiveType.floatingPoint -> "toBits() == other.toBits()".addAsSingleLineBody(bodyOnNewLine = false)
else -> implementAsIntrinsic(thisKind, this.signature.name)
}
}
val reinterprets = setOf(PrimitiveType.INT, PrimitiveType.BOOLEAN, PrimitiveType.BYTE, PrimitiveType.SHORT, PrimitiveType.CHAR)
.map {
MethodDescription(
doc = null,
annotations = mutableListOf("WasmNoOpCast", "PublishedApi"),
signature = MethodSignature(
visibility = MethodVisibility.INTERNAL,
name = "reinterpretAs${it.capitalized}",
arg = null,
returnType = it.capitalized
)
).apply { "implementedAsIntrinsic".addAsSingleLineBody(bodyOnNewLine = true) }
}
val reinterpretInt = reinterprets.first()
val otherReinterprets = reinterprets.drop(1).toTypedArray()
return when (thisKind) {
PrimitiveType.BYTE, PrimitiveType.SHORT -> listOf(customEquals, hashCode, reinterpretInt)
PrimitiveType.INT -> listOf(customEquals, hashCode, *otherReinterprets)
else -> listOf(customEquals, hashCode)
}
}
companion object {
private fun String.toWasmOperator(): String {
return when (this) {
"plus" -> "ADD"
"minus" -> "SUB"
"times" -> "MUL"
"rem" -> "REM_S"
"unaryMinus" -> "NEG"
"shr" -> "SHR_S"
"ushr" -> "SHR_U"
"equals" -> "EQ"
else -> this.uppercase()
}
}
private fun MethodDescription.implementAsIntrinsic(thisKind: PrimitiveType, methodName: String) {
this.signature.isInline = false
addAnnotation("WasmOp(WasmOp.${thisKind.prefixUppercase}_${methodName.toWasmOperator()})")
"implementedAsIntrinsic".addAsSingleLineBody(bodyOnNewLine = true)
}
private val PrimitiveType.prefixUppercase: String
get() = when (this) {
PrimitiveType.BYTE, PrimitiveType.SHORT, PrimitiveType.INT -> "I32"
PrimitiveType.LONG -> "I64"
PrimitiveType.FLOAT -> "F32"
PrimitiveType.DOUBLE -> "F64"
else -> ""
}
private val PrimitiveType.prefixLowercase: String
get() = prefixUppercase.lowercase()
}
}
@@ -0,0 +1,214 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
import java.io.File
internal val END_LINE = "\n"
private fun String.shift(): String {
return this.split(END_LINE).joinToString(separator = END_LINE) { if (it.isEmpty()) it else " $it" }
}
internal abstract class AnnotatedAndDocumented {
protected abstract var doc: String?
protected abstract val annotations: MutableList<String>
private var additionalDoc: String? = null
fun addDoc(doc: String) {
if (this.doc == null) {
this.doc = doc
} else {
this.doc += "$END_LINE$doc"
}
}
fun addAnnotation(annotation: String) {
annotations += annotation
}
fun setAdditionalDoc(doc: String) {
additionalDoc = doc
}
fun StringBuilder.printDocumentationAndAnnotations(forceMultiLineDoc: Boolean = false) {
if (doc != null) {
appendLine(doc!!.printAsDoc(forceMultiLineDoc))
}
if (annotations.isNotEmpty()) {
appendLine(annotations.joinToString(separator = END_LINE) { "@$it" })
}
if (additionalDoc != null) {
appendLine("// $additionalDoc")
}
}
private fun String.printAsDoc(forceMultiLine: Boolean = false): String {
if (this.contains(END_LINE) || forceMultiLine) {
return this.split(END_LINE).joinToString(
separator = END_LINE, prefix = "/**$END_LINE", postfix = "$END_LINE */"
) { if (it.isEmpty()) " *" else " * $it" }
}
return "/** $this */"
}
}
internal data class FileDescription(
private val suppresses: MutableList<String> = mutableListOf(),
private val imports: MutableList<String> = mutableListOf(),
val classes: List<ClassDescription>
) {
fun addSuppress(suppress: String) {
suppresses += suppress
}
fun addImport(newImport: String) {
imports += newImport
}
override fun toString(): String {
return buildString {
appendLine(File("license/COPYRIGHT_HEADER.txt").readText())
appendLine()
appendLine("// Auto-generated file. DO NOT EDIT!")
appendLine()
if (suppresses.isNotEmpty()) {
appendLine(suppresses.joinToString(separator = ", ", prefix = "@file:Suppress(", postfix = ")") { "\"$it\"" })
appendLine()
}
appendLine("package kotlin")
appendLine()
if (imports.isNotEmpty()) {
appendLine(imports.joinToString(separator = END_LINE) { "import $it" })
appendLine()
}
append(classes.joinToString(separator = END_LINE))
}
}
}
internal data class ClassDescription(
override var doc: String?,
override val annotations: MutableList<String>,
var isFinal: Boolean = false,
val name: String,
var constructorArg: MethodParameter? = null,
val companionObject: CompanionObjectDescription,
val methods: List<MethodDescription>
) : AnnotatedAndDocumented() {
override fun toString(): String {
return buildString {
this.printDocumentationAndAnnotations()
append("public ")
if (isFinal) append("final ")
appendLine("class $name private constructor(${constructorArg?.toString() ?: ""}) : Number(), Comparable<$name> {")
appendLine(companionObject.toString().shift())
appendLine(methods.joinToString(separator = END_LINE + END_LINE) { it.toString().shift() })
appendLine("}")
}
}
}
internal data class CompanionObjectDescription(
override var doc: String? = null,
override val annotations: MutableList<String> = mutableListOf(),
var isPublic: Boolean = false,
val properties: List<PropertyDescription>
) : AnnotatedAndDocumented() {
override fun toString(): String {
return buildString {
printDocumentationAndAnnotations()
if (isPublic) append("public ")
appendLine("companion object {")
appendLine(properties.joinToString(separator = END_LINE + END_LINE) { it.toString().shift() })
appendLine("}")
}
}
}
internal data class MethodSignature(
var isExternal: Boolean = false,
val visibility: MethodVisibility = MethodVisibility.PUBLIC,
var isOverride: Boolean = false,
var isInline: Boolean = false,
var isInfix: Boolean = false,
var isOperator: Boolean = false,
val name: String,
val arg: MethodParameter?,
val returnType: String
) {
override fun toString(): String {
return buildString {
if (isExternal) append("external ")
append("${visibility.name.lowercase()} ")
if (isOverride) append("override ")
if (isInline) append("inline ")
if (isInfix) append("infix ")
if (isOperator) append("operator ")
append("fun $name(${arg ?: ""}): $returnType")
}
}
}
internal enum class MethodVisibility {
PUBLIC, INTERNAL, PRIVATE
}
internal data class MethodParameter(val name: String, val type: String) {
fun getTypeAsPrimitive(): PrimitiveType = PrimitiveType.valueOf(type.uppercase())
override fun toString(): String {
return "$name: $type"
}
}
internal data class MethodDescription(
override var doc: String?,
override val annotations: MutableList<String> = mutableListOf(),
val signature: MethodSignature,
private var body: String? = null
) : AnnotatedAndDocumented() {
override fun toString(): String {
return buildString {
printDocumentationAndAnnotations()
append(signature)
append(body ?: "")
}
}
fun String.addAsSingleLineBody(bodyOnNewLine: Boolean = false) {
val skip = if (bodyOnNewLine) "$END_LINE\t" else ""
body = " = $skip$this"
}
fun String.addAsMultiLineBody() {
body = " {$END_LINE${this.shift()}$END_LINE}"
}
}
internal data class PropertyDescription(
override var doc: String?,
override val annotations: MutableList<String> = mutableListOf(),
val name: String,
val type: String,
val value: String
) : AnnotatedAndDocumented() {
override fun toString(): String {
return buildString {
printDocumentationAndAnnotations(forceMultiLineDoc = true)
append("public const val $name: $type = $value")
}
}
}
+33
View File
@@ -0,0 +1,33 @@
/*
* 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 org.jetbrains.kotlin.generators.builtins.numbers.primitives
import org.jetbrains.kotlin.generators.builtins.PrimitiveType
internal fun PrimitiveType.castToIfNecessary(otherType: PrimitiveType): String {
if (this !in PrimitiveType.onlyNumeric || otherType !in PrimitiveType.onlyNumeric) {
throw IllegalArgumentException("Cannot cast to non-numeric type")
}
if (this == otherType) return ""
if (this.ordinal < otherType.ordinal) {
return ".to${otherType.capitalized}()"
}
return ""
}
internal fun String.asSign(): String {
return when (this) {
"plus" -> "+"
"minus" -> "-"
"times" -> "*"
"div" -> "/"
"rem" -> "%"
else -> throw IllegalArgumentException("Unsupported binary operation: ${this}")
}
}