[K/N] Migrate compiler, interop and others to new case conversion api

This commit is contained in:
Abduqodiri Qurbonzoda
2021-04-08 02:34:32 +03:00
parent a4839b8548
commit 983985bc68
13 changed files with 32 additions and 31 deletions
@@ -224,12 +224,12 @@ object KotlinTypes {
private open class ClassifierAtPackage(val pkg: String) { private open class ClassifierAtPackage(val pkg: String) {
operator fun getValue(thisRef: KotlinTypes, property: KProperty<*>): Classifier = operator fun getValue(thisRef: KotlinTypes, property: KProperty<*>): Classifier =
Classifier.topLevel(pkg, property.name.capitalize()) Classifier.topLevel(pkg, property.name.replaceFirstChar(Char::uppercaseChar))
} }
private open class TypeAtPackage(val pkg: String) { private open class TypeAtPackage(val pkg: String) {
operator fun getValue(thisRef: KotlinTypes, property: KProperty<*>): KotlinClassifierType = operator fun getValue(thisRef: KotlinTypes, property: KProperty<*>): KotlinClassifierType =
Classifier.topLevel(pkg, property.name.capitalize()).type Classifier.topLevel(pkg, property.name.replaceFirstChar(Char::uppercaseChar)).type
} }
private object BuiltInType : TypeAtPackage("kotlin") private object BuiltInType : TypeAtPackage("kotlin")
@@ -56,7 +56,7 @@ private fun ObjCMethod.getFirstKotlinParameterNameCandidate(forConstructorOrFact
val selectorPart = this.selector.takeWhile { it != ':' }.trimStart('_') val selectorPart = this.selector.takeWhile { it != ':' }.trimStart('_')
if (selectorPart.startsWith("init")) { if (selectorPart.startsWith("init")) {
selectorPart.removePrefix("init").removePrefix("With") selectorPart.removePrefix("init").removePrefix("With")
.takeIf { it.isNotEmpty() }?.let { return it.decapitalize() } .takeIf { it.isNotEmpty() }?.let { return it.replaceFirstChar(Char::lowercaseChar) }
} }
} }
@@ -69,7 +69,7 @@ private fun ObjCMethod.getKotlinParameters(
): List<FunctionParameterStub> { ): List<FunctionParameterStub> {
if (this.isInit && this.parameters.isEmpty() && this.selector != "init") { if (this.isInit && this.parameters.isEmpty() && this.selector != "init") {
// Create synthetic Unit parameter, just like Swift does in this case: // Create synthetic Unit parameter, just like Swift does in this case:
val parameterName = this.selector.removePrefix("init").removePrefix("With").decapitalize() val parameterName = this.selector.removePrefix("init").removePrefix("With").replaceFirstChar(Char::lowercaseChar)
return listOf(FunctionParameterStub(parameterName, KotlinTypes.unit.toStubIrType())) return listOf(FunctionParameterStub(parameterName, KotlinTypes.unit.toStubIrType()))
// Note: this parameter is explicitly handled in compiler. // Note: this parameter is explicitly handled in compiler.
} }
@@ -392,7 +392,7 @@ internal class EnumStubBuilder(
) )
} }
private fun EnumConstant.isMoreCanonicalThan(other: EnumConstant): Boolean = with(other.name.toLowerCase()) { private fun EnumConstant.isMoreCanonicalThan(other: EnumConstant): Boolean = with(other.name.lowercase()) {
contains("min") || contains("max") || contains("min") || contains("max") ||
contains("first") || contains("last") || contains("first") || contains("last") ||
contains("begin") || contains("end") contains("begin") || contains("end")
@@ -128,7 +128,7 @@ class JSInteropArguments(argParser: ArgParser = ArgParser("jsinterop",
enum class TargetType { enum class TargetType {
WASM32; WASM32;
override fun toString() = name.toLowerCase() override fun toString() = name.lowercase()
} }
val target by argParser.option(ArgType.Choice<TargetType>(), val target by argParser.option(ArgType.Choice<TargetType>(),
description = "wasm target to compile to").default(TargetType.WASM32) description = "wasm target to compile to").default(TargetType.WASM32)
@@ -810,8 +810,8 @@ internal class CAdapterGenerator(val context: Context) : DeclarationDescriptorVi
val exportedSymbol = "${prefix}_symbols" val exportedSymbol = "${prefix}_symbols"
exportedSymbols += exportedSymbol exportedSymbols += exportedSymbol
output("#ifndef KONAN_${prefix.toUpperCase()}_H") output("#ifndef KONAN_${prefix.uppercase()}_H")
output("#define KONAN_${prefix.toUpperCase()}_H") output("#define KONAN_${prefix.uppercase()}_H")
// TODO: use namespace for C++ case? // TODO: use namespace for C++ case?
output(""" output("""
#ifdef __cplusplus #ifdef __cplusplus
@@ -882,7 +882,7 @@ internal class CAdapterGenerator(val context: Context) : DeclarationDescriptorVi
} /* extern "C" */ } /* extern "C" */
#endif""".trimIndent()) #endif""".trimIndent())
output("#endif /* KONAN_${prefix.toUpperCase()}_H */") output("#endif /* KONAN_${prefix.uppercase()}_H */")
outputStreamWriter.close() outputStreamWriter.close()
println("Produced library API in ${prefix}_api.h") println("Produced library API in ${prefix}_api.h")
@@ -32,7 +32,7 @@ class KonanReflectionTypes(module: ModuleDescriptor, internalPackage: FqName) {
private class ClassLookup(val memberScope: MemberScope) { private class ClassLookup(val memberScope: MemberScope) {
operator fun getValue(types: KonanReflectionTypes, property: KProperty<*>): ClassDescriptor { operator fun getValue(types: KonanReflectionTypes, property: KProperty<*>): ClassDescriptor {
return types.find(memberScope, property.name.capitalize()) return types.find(memberScope, property.name.replaceFirstChar(Char::uppercaseChar))
} }
} }
@@ -90,7 +90,7 @@ internal class KonanSymbols(
val integerConversions = allIntegerClasses.flatMap { fromClass -> val integerConversions = allIntegerClasses.flatMap { fromClass ->
allIntegerClasses.map { toClass -> allIntegerClasses.map { toClass ->
val name = Name.identifier("to${toClass.descriptor.name.asString().capitalize()}") val name = Name.identifier("to${toClass.descriptor.name.asString().replaceFirstChar(Char::uppercaseChar)}")
val descriptor = if (fromClass in signedIntegerClasses && toClass in unsignedIntegerClasses) { val descriptor = if (fromClass in signedIntegerClasses && toClass in unsignedIntegerClasses) {
builtInsPackage("kotlin") builtInsPackage("kotlin")
.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) .getContributedFunctions(name, NoLookupLocation.FROM_BACKEND)
@@ -222,11 +222,11 @@ internal class KonanSymbols(
val getNativeNullPtr = symbolTable.referenceSimpleFunction(context.getNativeNullPtr) val getNativeNullPtr = symbolTable.referenceSimpleFunction(context.getNativeNullPtr)
val boxCachePredicates = BoxCache.values().associate { val boxCachePredicates = BoxCache.values().associate {
it to internalFunction("in${it.name.toLowerCase().capitalize()}BoxCache") it to internalFunction("in${it.name.lowercase().replaceFirstChar(Char::uppercaseChar)}BoxCache")
} }
val boxCacheGetters = BoxCache.values().associate { val boxCacheGetters = BoxCache.values().associate {
it to internalFunction("getCached${it.name.toLowerCase().capitalize()}Box") it to internalFunction("getCached${it.name.lowercase().replaceFirstChar(Char::uppercaseChar)}Box")
} }
val immutableBlob = symbolTable.referenceClass( val immutableBlob = symbolTable.referenceClass(
@@ -289,7 +289,7 @@ private class InteropLoweringPart1(val context: Context) : BaseInteropIrTransfor
require(property.descriptor.type.isObjCObjectType()) { renderCompilerError(property) } require(property.descriptor.type.isObjCObjectType()) { renderCompilerError(property) }
val name = property.name.asString() val name = property.name.asString()
val selector = "set${name.capitalize()}:" val selector = "set${name.replaceFirstChar(Char::uppercaseChar)}:"
return generateFunctionImp(selector, property.setter!!) return generateFunctionImp(selector, property.setter!!)
} }
@@ -558,7 +558,7 @@ internal class ObjCExportTranslatorImpl(
// Note: the condition below is similar to "toObjCMethods" logic in [ObjCExportedInterface.createCodeSpec]. // Note: the condition below is similar to "toObjCMethods" logic in [ObjCExportedInterface.createCodeSpec].
if (propertySetter != null && mapper.shouldBeExposed(propertySetter)) { if (propertySetter != null && mapper.shouldBeExposed(propertySetter)) {
val setterSelector = mapper.getBaseMethods(propertySetter).map { namer.getSelector(it) }.distinct().single() val setterSelector = mapper.getBaseMethods(propertySetter).map { namer.getSelector(it) }.distinct().single()
setterName = if (setterSelector != "set" + name.capitalize() + ":") setterSelector else null setterName = if (setterSelector != "set" + name.replaceFirstChar(Char::uppercaseChar) + ":") setterSelector else null
} else { } else {
attributes += "readonly" attributes += "readonly"
setterName = null setterName = null
@@ -378,12 +378,12 @@ internal enum class NSNumberKind(val mappedKotlinClassId: ClassId?, val objCType
// UNSIGNED_SHORT -> unsignedShort // UNSIGNED_SHORT -> unsignedShort
private val kindName = this.name.split('_') private val kindName = this.name.split('_')
.joinToString("") { it.toLowerCase().capitalize() }.decapitalize() .joinToString("") { it.lowercase().replaceFirstChar(Char::uppercaseChar) }.replaceFirstChar(Char::lowercaseChar)
val valueSelector = kindName // unsignedShort val valueSelector = kindName // unsignedShort
val initSelector = "initWith${kindName.capitalize()}:" // initWithUnsignedShort: val initSelector = "initWith${kindName.replaceFirstChar(Char::uppercaseChar)}:" // initWithUnsignedShort:
val factorySelector = "numberWith${kindName.capitalize()}:" // numberWithUnsignedShort: val factorySelector = "numberWith${kindName.replaceFirstChar(Char::uppercaseChar)}:" // numberWithUnsignedShort:
constructor( constructor(
primitiveType: PrimitiveType, primitiveType: PrimitiveType,
@@ -155,7 +155,7 @@ private class ObjCExportNamingHelper(
ObjCExportNamer.ClassOrProtocolName(swiftName, buildString { ObjCExportNamer.ClassOrProtocolName(swiftName, buildString {
append(topLevelNamePrefix) append(topLevelNamePrefix)
swiftName.split('.').forEachIndexed { index, part -> swiftName.split('.').forEachIndexed { index, part ->
append(if (index == 0) part else part.capitalize()) append(if (index == 0) part else part.replaceFirstChar(Char::uppercaseChar))
} }
}) })
@@ -179,7 +179,7 @@ private class ObjCExportNamingHelper(
} else { } else {
// AB -> ABC // AB -> ABC
// A.B -> A.BC // A.B -> A.BC
append(ownName.capitalize()) append(ownName.replaceFirstChar(Char::uppercaseChar))
} }
} else { } else {
// AB, A.B -> ABC // AB, A.B -> ABC
@@ -188,9 +188,9 @@ private class ObjCExportNamingHelper(
append(containerName) append(containerName)
} else { } else {
append(containerName.substring(0, dotIndex)) append(containerName.substring(0, dotIndex))
append(containerName.substring(dotIndex + 1).capitalize()) append(containerName.substring(dotIndex + 1).replaceFirstChar(Char::uppercaseChar))
} }
append(ownName.capitalize()) append(ownName.replaceFirstChar(Char::uppercaseChar))
} }
} }
@@ -421,7 +421,7 @@ internal class ObjCExportNamerImpl(
val containingDeclaration = descriptor.containingDeclaration val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration is ClassDescriptor) { if (containingDeclaration is ClassDescriptor) {
append(getClassOrProtocolObjCName(containingDeclaration)) append(getClassOrProtocolObjCName(containingDeclaration))
.append(descriptor.name.asString().toIdentifier().capitalize()) .append(descriptor.name.asString().toIdentifier().replaceFirstChar(Char::uppercaseChar))
} else if (containingDeclaration is PackageFragmentDescriptor) { } else if (containingDeclaration is PackageFragmentDescriptor) {
append(topLevelNamePrefix).appendTopLevelClassBaseName(descriptor) append(topLevelNamePrefix).appendTopLevelClassBaseName(descriptor)
@@ -473,7 +473,7 @@ internal class ObjCExportNamerImpl(
else -> "" else -> ""
}) })
append(name.capitalize()) append(name.replaceFirstChar(Char::uppercaseChar))
} else { } else {
append(name) append(name)
} }
@@ -551,7 +551,7 @@ internal class ObjCExportNamerImpl(
assert(descriptor.kind == ClassKind.OBJECT) assert(descriptor.kind == ClassKind.OBJECT)
return objectInstanceSelectors.getOrPut(descriptor) { return objectInstanceSelectors.getOrPut(descriptor) {
val name = descriptor.name.asString().decapitalize().toIdentifier().mangleIfSpecialFamily("get") val name = descriptor.name.asString().replaceFirstChar(Char::lowercaseChar).toIdentifier().mangleIfSpecialFamily("get")
StringBuilder(name).mangledBySuffixUnderscores() StringBuilder(name).mangledBySuffixUnderscores()
} }
@@ -563,8 +563,8 @@ internal class ObjCExportNamerImpl(
return enumClassSelectors.getOrPut(descriptor) { return enumClassSelectors.getOrPut(descriptor) {
// FOO_BAR_BAZ -> fooBarBaz: // FOO_BAR_BAZ -> fooBarBaz:
val name = descriptor.name.asString().split('_').mapIndexed { index, s -> val name = descriptor.name.asString().split('_').mapIndexed { index, s ->
val lower = s.toLowerCase() val lower = s.lowercase()
if (index == 0) lower else lower.capitalize() if (index == 0) lower else lower.replaceFirstChar(Char::uppercaseChar)
}.joinToString("").toIdentifier().mangleIfSpecialFamily("the") }.joinToString("").toIdentifier().mangleIfSpecialFamily("the")
StringBuilder(name).mangledBySuffixUnderscores() StringBuilder(name).mangledBySuffixUnderscores()
@@ -655,7 +655,7 @@ internal class ObjCExportNamerImpl(
val candidate = when (this) { val candidate = when (this) {
is PropertyGetterDescriptor -> this.correspondingProperty.name.asString() is PropertyGetterDescriptor -> this.correspondingProperty.name.asString()
is PropertySetterDescriptor -> "set${this.correspondingProperty.name.asString().capitalize()}" is PropertySetterDescriptor -> "set${this.correspondingProperty.name.asString().replaceFirstChar(kotlin.Char::uppercaseChar)}"
else -> this.name.asString() else -> this.name.asString()
}.toIdentifier() }.toIdentifier()
@@ -668,7 +668,7 @@ internal class ObjCExportNamerImpl(
if (trimmed.startsWithWords(family)) { if (trimmed.startsWithWords(family)) {
// Then method can be detected as having special family by Objective-C compiler. // Then method can be detected as having special family by Objective-C compiler.
// mangle the name: // mangle the name:
return prefix + this.capitalize() return prefix + this.replaceFirstChar(Char::uppercaseChar)
} }
} }
@@ -894,7 +894,7 @@ internal val ModuleDescriptor.namePrefix: String get() {
fun abbreviate(name: String): String { fun abbreviate(name: String): String {
val normalizedName = name val normalizedName = name
.capitalize() .replaceFirstChar(Char::uppercaseChar)
.replace("-|\\.".toRegex(), "_") .replace("-|\\.".toRegex(), "_")
val uppers = normalizedName.filterIndexed { index, character -> index == 0 || character.isUpperCase() } val uppers = normalizedName.filterIndexed { index, character -> index == 0 || character.isUpperCase() }
@@ -79,7 +79,7 @@ abstract class ArgType<T : Any>(val hasParameter: kotlin.Boolean) {
enumValues<T>().find { e -> e.toString().equals(it, ignoreCase = true) } ?: enumValues<T>().find { e -> e.toString().equals(it, ignoreCase = true) } ?:
throw IllegalArgumentException("No enum constant $it") throw IllegalArgumentException("No enum constant $it")
}, },
noinline toString: (T) -> kotlin.String = { it.toString().toLowerCase() }): Choice<T> { noinline toString: (T) -> kotlin.String = { it.toString().lowercase() }): Choice<T> {
return Choice(enumValues<T>().toList(), toVariant, toString) return Choice(enumValues<T>().toList(), toVariant, toString)
} }
} }
@@ -23,6 +23,7 @@ interface RelocationModeFlags : TargetableExternalStorage {
val staticLibraryRelocationMode get() = targetString("staticLibraryRelocationMode").mode() val staticLibraryRelocationMode get() = targetString("staticLibraryRelocationMode").mode()
val executableRelocationMode get() = targetString("executableRelocationMode").mode() val executableRelocationMode get() = targetString("executableRelocationMode").mode()
@Suppress("DEPRECATION")
private fun String?.mode(): Mode = when (this?.toLowerCase()) { private fun String?.mode(): Mode = when (this?.toLowerCase()) {
null -> Mode.DEFAULT null -> Mode.DEFAULT
"pic" -> Mode.PIC "pic" -> Mode.PIC