Merge branch 'master' into kotlin-mirror/master

# Conflicts:
#	backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ir/Ir.kt
#	backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/FunctionInlining.kt
This commit is contained in:
Pavel Punegov
2019-07-02 15:48:37 +03:00
103 changed files with 4368 additions and 2123 deletions
@@ -177,6 +177,18 @@ class K2Native : CLICompiler<K2NativeCompilerArguments>() {
put(ENABLE_ASSERTIONS, arguments.enableAssertions) put(ENABLE_ASSERTIONS, arguments.enableAssertions)
put(MEMORY_MODEL, when (arguments.memoryModel) {
"relaxed" -> {
configuration.report(STRONG_WARNING, "Relaxed memory model is not yet functional")
MemoryModel.RELAXED
}
"strict" -> MemoryModel.STRICT
else -> {
configuration.report(ERROR, "Unsupported memory model ${arguments.memoryModel}")
return
}
})
when { when {
arguments.generateWorkerTestRunner -> put(GENERATE_TEST_RUNNER, TestRunnerKind.WORKER) arguments.generateWorkerTestRunner -> put(GENERATE_TEST_RUNNER, TestRunnerKind.WORKER)
arguments.generateTestRunner -> put(GENERATE_TEST_RUNNER, TestRunnerKind.MAIN_THREAD) arguments.generateTestRunner -> put(GENERATE_TEST_RUNNER, TestRunnerKind.MAIN_THREAD)
@@ -206,9 +218,7 @@ class K2Native : CLICompiler<K2NativeCompilerArguments>() {
} }
} }
override fun createArguments(): K2NativeCompilerArguments { override fun createArguments() = K2NativeCompilerArguments()
return K2NativeCompilerArguments()
}
override fun executableScriptFileName() = "kotlinc-native" override fun executableScriptFileName() = "kotlinc-native"
@@ -5,7 +5,6 @@
package org.jetbrains.kotlin.cli.bc package org.jetbrains.kotlin.cli.bc
import org.jetbrains.kotlin.backend.konan.TestRunnerKind
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.arguments.Argument import org.jetbrains.kotlin.cli.common.arguments.Argument
import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.common.messages.MessageCollector
@@ -48,7 +47,10 @@ class K2NativeCompilerArguments : CommonCompilerArguments() {
@Argument(value = "-manifest", valueDescription = "<path>", description = "Provide a maniferst addend file") @Argument(value = "-manifest", valueDescription = "<path>", description = "Provide a maniferst addend file")
var manifestFile: String? = null var manifestFile: String? = null
@Argument(value="-module-name", deprecatedName = "-module_name", valueDescription = "<name>", description = "Spicify a name for the compilation module") @Argument(value="-memory-model", valueDescription = "<model>", description = "Memory model to use, 'strict' and 'relaxed' are currently supported")
var memoryModel: String? = "strict"
@Argument(value="-module-name", deprecatedName = "-module_name", valueDescription = "<name>", description = "Specify a name for the compilation module")
var moduleName: String? = null var moduleName: String? = null
@Argument(value = "-native-library", deprecatedName = "-nativelibrary", shortName = "-nl", valueDescription = "<path>", description = "Include the native bitcode library") @Argument(value = "-native-library", deprecatedName = "-nativelibrary", shortName = "-nl", valueDescription = "<path>", description = "Include the native bitcode library")
@@ -195,6 +197,8 @@ class K2NativeCompilerArguments : CommonCompilerArguments() {
super.configureAnalysisFlags(collector).also { super.configureAnalysisFlags(collector).also {
val useExperimental = it[AnalysisFlags.useExperimental] as List<*> val useExperimental = it[AnalysisFlags.useExperimental] as List<*>
it[AnalysisFlags.useExperimental] = useExperimental + listOf("kotlin.ExperimentalUnsignedTypes") it[AnalysisFlags.useExperimental] = useExperimental + listOf("kotlin.ExperimentalUnsignedTypes")
if (printIr)
phasesToDumpAfter = arrayOf("ALL")
} }
} }
@@ -104,8 +104,6 @@ internal val cKeywords = setOf(
"xor_eq" "xor_eq"
) )
private val cnameAnnotation = FqName("kotlin.native.CName")
private fun org.jetbrains.kotlin.types.KotlinType.isGeneric() = private fun org.jetbrains.kotlin.types.KotlinType.isGeneric() =
constructor.declarationDescriptor is TypeParameterDescriptor constructor.declarationDescriptor is TypeParameterDescriptor
@@ -143,7 +141,7 @@ private fun AnnotationDescriptor.properValue(key: String) =
private fun functionImplName(descriptor: DeclarationDescriptor, default: String, shortName: Boolean): String { private fun functionImplName(descriptor: DeclarationDescriptor, default: String, shortName: Boolean): String {
assert(descriptor is FunctionDescriptor) assert(descriptor is FunctionDescriptor)
val annotation = descriptor.annotations.findAnnotation(cnameAnnotation) ?: return default val annotation = descriptor.annotations.findAnnotation(RuntimeNames.cnameAnnotation) ?: return default
val key = if (shortName) "shortName" else "externName" val key = if (shortName) "shortName" else "externName"
val value = annotation.properValue(key) val value = annotation.properValue(key)
return value.takeIf { value != null && value.isNotEmpty() } ?: default return value.takeIf { value != null && value.isNotEmpty() } ?: default
@@ -265,9 +263,10 @@ private class ExportedElement(val kind: ElementKind,
val isFunction = declaration is FunctionDescriptor val isFunction = declaration is FunctionDescriptor
val isTopLevelFunction: Boolean val isTopLevelFunction: Boolean
get() { get() {
if (declaration !is FunctionDescriptor || !declaration.annotations.hasAnnotation(cnameAnnotation)) if (declaration !is FunctionDescriptor ||
!declaration.annotations.hasAnnotation(RuntimeNames.cnameAnnotation))
return false return false
val annotation = declaration.annotations.findAnnotation(cnameAnnotation)!! val annotation = declaration.annotations.findAnnotation(RuntimeNames.cnameAnnotation)!!
val externName = annotation.properValue("externName") val externName = annotation.properValue("externName")
return externName != null && externName.isNotEmpty() return externName != null && externName.isNotEmpty()
} }
@@ -193,6 +193,7 @@ internal class SpecialDeclarationsFactory(val context: Context) : KotlinMangler
} }
internal class Context(config: KonanConfig) : KonanBackendContext(config) { internal class Context(config: KonanConfig) : KonanBackendContext(config) {
lateinit var frontendServices: FrontendServices
lateinit var environment: KotlinCoreEnvironment lateinit var environment: KotlinCoreEnvironment
lateinit var bindingContext: BindingContext lateinit var bindingContext: BindingContext
@@ -426,20 +427,8 @@ internal class Context(config: KonanConfig) : KonanBackendContext(config) {
printIr() printIr()
printBitCode() printBitCode()
} }
fun shouldVerifyDescriptors() = config.configuration.getBoolean(KonanConfigKeys.VERIFY_DESCRIPTORS)
fun shouldVerifyIr() = config.configuration.getBoolean(KonanConfigKeys.VERIFY_IR)
fun shouldVerifyBitCode() = config.configuration.getBoolean(KonanConfigKeys.VERIFY_BITCODE) fun shouldVerifyBitCode() = config.configuration.getBoolean(KonanConfigKeys.VERIFY_BITCODE)
fun shouldPrintDescriptors() = config.configuration.getBoolean(KonanConfigKeys.PRINT_DESCRIPTORS)
fun shouldPrintIr() = config.configuration.getBoolean(KonanConfigKeys.PRINT_IR)
fun shouldPrintIrWithDescriptors()=
config.configuration.getBoolean(KonanConfigKeys.PRINT_IR_WITH_DESCRIPTORS)
fun shouldPrintBitCode() = config.configuration.getBoolean(KonanConfigKeys.PRINT_BITCODE) fun shouldPrintBitCode() = config.configuration.getBoolean(KonanConfigKeys.PRINT_BITCODE)
fun shouldPrintLocations() = config.configuration.getBoolean(KonanConfigKeys.PRINT_LOCATIONS) fun shouldPrintLocations() = config.configuration.getBoolean(KonanConfigKeys.PRINT_LOCATIONS)
@@ -450,6 +439,8 @@ internal class Context(config: KonanConfig) : KonanBackendContext(config) {
fun shouldOptimize() = config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION) fun shouldOptimize() = config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION)
val memoryModel = config.memoryModel
override var inVerbosePhase = false override var inVerbosePhase = false
override fun log(message: () -> String) { override fun log(message: () -> String) {
if (inVerbosePhase) { if (inVerbosePhase) {
@@ -10,11 +10,13 @@ import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportLazy
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportLazyImpl import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportLazyImpl
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportWarningCollector import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportWarningCollector
import org.jetbrains.kotlin.backend.konan.objcexport.dumpObjCHeader import org.jetbrains.kotlin.backend.konan.objcexport.dumpObjCHeader
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.container.* import org.jetbrains.kotlin.container.*
import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
internal fun StorageComponentContainer.initContainer(config: KonanConfig) { internal fun StorageComponentContainer.initContainer(config: KonanConfig) {
this.useImpl<FrontendServices>()
if (config.configuration.get(KonanConfigKeys.EMIT_LAZY_OBJC_HEADER_FILE) != null) { if (config.configuration.get(KonanConfigKeys.EMIT_LAZY_OBJC_HEADER_FILE) != null) {
this.useImpl<ObjCExportLazyImpl>() this.useImpl<ObjCExportLazyImpl>()
this.useInstance(ObjCExportWarningCollector.SILENT) this.useInstance(ObjCExportWarningCollector.SILENT)
@@ -35,8 +37,12 @@ internal fun StorageComponentContainer.initContainer(config: KonanConfig) {
} }
} }
internal fun ComponentProvider.postprocessComponents(configuration: CompilerConfiguration, files: Collection<KtFile>) { internal fun ComponentProvider.postprocessComponents(context: Context, files: Collection<KtFile>) {
configuration.get(KonanConfigKeys.EMIT_LAZY_OBJC_HEADER_FILE)?.let { context.frontendServices = this.get<FrontendServices>()
context.config.configuration.get(KonanConfigKeys.EMIT_LAZY_OBJC_HEADER_FILE)?.let {
this.get<ObjCExportLazy>().dumpObjCHeader(files, it) this.get<ObjCExportLazy>().dumpObjCHeader(files, it)
} }
} }
class FrontendServices(val deprecationResolver: DeprecationResolver)
@@ -46,6 +46,8 @@ class KonanConfig(val project: Project, val configuration: CompilerConfiguration
val debug: Boolean get() = configuration.getBoolean(KonanConfigKeys.DEBUG) val debug: Boolean get() = configuration.getBoolean(KonanConfigKeys.DEBUG)
val memoryModel: MemoryModel get() = configuration.get(KonanConfigKeys.MEMORY_MODEL)!!
init { init {
if (!platformManager.isEnabled(target)) { if (!platformManager.isEnabled(target)) {
error("Target ${target.visibleName} is not available on the ${HostManager.hostName} host") error("Target ${target.visibleName} is not available on the ${HostManager.hostName} host")
@@ -126,6 +128,7 @@ class KonanConfig(val project: Project, val configuration: CompilerConfiguration
internal val defaultNativeLibraries: List<String> = mutableListOf<String>().apply { internal val defaultNativeLibraries: List<String> = mutableListOf<String>().apply {
add(if (debug) "debug.bc" else "release.bc") add(if (debug) "debug.bc" else "release.bc")
add(if (memoryModel == MemoryModel.STRICT) "strict.bc" else "relaxed.bc")
if (produce == CompilerOutputKind.PROGRAM) { if (produce == CompilerOutputKind.PROGRAM) {
addAll(distribution.launcherFiles) addAll(distribution.launcherFiles)
} }
@@ -52,6 +52,8 @@ class KonanConfigKeys {
= CompilerConfigurationKey.create("list available targets") = CompilerConfigurationKey.create("list available targets")
val MANIFEST_FILE: CompilerConfigurationKey<String?> val MANIFEST_FILE: CompilerConfigurationKey<String?>
= CompilerConfigurationKey.create("provide manifest addend file") = CompilerConfigurationKey.create("provide manifest addend file")
val MEMORY_MODEL: CompilerConfigurationKey<MemoryModel>
= CompilerConfigurationKey.create("memory model")
val META_INFO: CompilerConfigurationKey<List<String>> val META_INFO: CompilerConfigurationKey<List<String>>
= CompilerConfigurationKey.create("generate metadata") = CompilerConfigurationKey.create("generate metadata")
val MODULE_KIND: CompilerConfigurationKey<ModuleKind> val MODULE_KIND: CompilerConfigurationKey<ModuleKind>
@@ -155,7 +155,8 @@ internal val sharedVariablesPhase = makeKonanFileLoweringPhase(
internal val localFunctionsPhase = makeKonanFileOpPhase( internal val localFunctionsPhase = makeKonanFileOpPhase(
op = { context, irFile -> op = { context, irFile ->
LocalDelegatedPropertiesLowering().lower(irFile) LocalDelegatedPropertiesLowering().lower(irFile)
LocalDeclarationsLowering(context).runOnFilePostfix(irFile) LocalDeclarationsLowering(context).lower(irFile)
LocalClassPopupLowering(context).lower(irFile)
}, },
name = "LocalFunctions", name = "LocalFunctions",
description = "Local function lowering", description = "Local function lowering",
@@ -0,0 +1,10 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
enum class MemoryModel(val suffix: String) {
STRICT("Strict"),
RELAXED("Relaxed")
}
@@ -3,14 +3,18 @@ package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqName
object RuntimeNames { object RuntimeNames {
val symbolName = FqName("kotlin.native.SymbolName") val symbolNameAnnotation = FqName("kotlin.native.SymbolName")
val cnameAnnotation = FqName("kotlin.native.CName")
val frozenAnnotation = FqName("kotlin.native.internal.Frozen")
val exportForCppRuntime = FqName("kotlin.native.internal.ExportForCppRuntime") val exportForCppRuntime = FqName("kotlin.native.internal.ExportForCppRuntime")
val exportForCompilerAnnotation = FqName("kotlin.native.internal.ExportForCompiler") val exportForCompilerAnnotation = FqName("kotlin.native.internal.ExportForCompiler")
val exportTypeInfoAnnotation = FqName("kotlin.native.internal.ExportTypeInfo") val exportTypeInfoAnnotation = FqName("kotlin.native.internal.ExportTypeInfo")
val cCall = FqName("kotlinx.cinterop.internal.CCall") val cCall = FqName("kotlinx.cinterop.internal.CCall")
val objCMethodAnnotation = FqName("kotlinx.cinterop.ObjCMethod")
val objCMethodImp = FqName("kotlinx.cinterop.ObjCMethodImp") val objCMethodImp = FqName("kotlinx.cinterop.ObjCMethodImp")
val independent = FqName("kotlin.native.internal.Independent") val independent = FqName("kotlin.native.internal.Independent")
val filterExceptions = FqName("kotlin.native.internal.FilterExceptions") val filterExceptions = FqName("kotlin.native.internal.FilterExceptions")
val kotlinNativeInternalPackageName = FqName.fromSegments(listOf("kotlin", "native", "internal")) val kotlinNativeInternalPackageName = FqName.fromSegments(listOf("kotlin", "native", "internal"))
val associatedObjectKey = FqName("kotlin.reflect.AssociatedObjectKey") val associatedObjectKey = FqName("kotlin.reflect.AssociatedObjectKey")
val typedIntrinsicAnnotation = FqName("kotlin.native.internal.TypedIntrinsic")
} }
@@ -2,8 +2,6 @@
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * 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 file. * that can be found in the LICENSE file.
*/ */
package org.jetbrains.kotlin.backend.konan package org.jetbrains.kotlin.backend.konan
enum class TestRunnerKind { enum class TestRunnerKind {
@@ -77,7 +77,7 @@ internal object TopDownAnalyzerFacadeForKonan {
) { ) {
initContainer(context.config) initContainer(context.config)
}.apply { }.apply {
postprocessComponents(context.config.configuration, files) postprocessComponents(context, files)
}.get<LazyTopDownAnalyzer>() }.get<LazyTopDownAnalyzer>()
analyzerForKonan.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files) analyzerForKonan.analyzeDeclarations(TopDownAnalysisMode.TopLevelDeclarations, files)
@@ -344,5 +344,8 @@ internal fun PhaseConfig.konanPhasesConfig(config: KonanConfig) {
switch(bitcodePhase, config.produce != CompilerOutputKind.LIBRARY) switch(bitcodePhase, config.produce != CompilerOutputKind.LIBRARY)
switch(linkPhase, config.produce.isNativeBinary) switch(linkPhase, config.produce.isNativeBinary)
switch(testProcessorPhase, getNotNull(KonanConfigKeys.GENERATE_TEST_RUNNER) != TestRunnerKind.NONE) switch(testProcessorPhase, getNotNull(KonanConfigKeys.GENERATE_TEST_RUNNER) != TestRunnerKind.NONE)
switch(buildDFGPhase, config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION))
switch(devirtualizationPhase, config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION))
switch(dcePhase, config.configuration.getBoolean(KonanConfigKeys.OPTIMIZATION))
} }
} }
@@ -216,19 +216,14 @@ fun CallableMemberDescriptor.findSourceFile(): SourceFile {
} }
} }
internal val TypedIntrinsic = FqName("kotlin.native.internal.TypedIntrinsic")
private val symbolNameAnnotation = FqName("kotlin.native.SymbolName")
private val objCMethodAnnotation = FqName("kotlinx.cinterop.ObjCMethod")
private val frozenAnnotation = FqName("kotlin.native.internal.Frozen")
internal val DeclarationDescriptor.isFrozen: Boolean internal val DeclarationDescriptor.isFrozen: Boolean
get() = this.annotations.hasAnnotation(frozenAnnotation) || get() = this.annotations.hasAnnotation(RuntimeNames.frozenAnnotation) ||
(this is org.jetbrains.kotlin.descriptors.ClassDescriptor (this is org.jetbrains.kotlin.descriptors.ClassDescriptor
// RTTI is used for non-reference type box or Objective-C object wrapper: // RTTI is used for non-reference type box or Objective-C object wrapper:
&& (!this.defaultType.binaryTypeIsReference() || this.isObjCClass())) && (!this.defaultType.binaryTypeIsReference() || this.isObjCClass()))
internal val FunctionDescriptor.isTypedIntrinsic: Boolean internal val FunctionDescriptor.isTypedIntrinsic: Boolean
get() = this.annotations.hasAnnotation(TypedIntrinsic) get() = this.annotations.hasAnnotation(RuntimeNames.typedIntrinsicAnnotation)
// TODO: coalesce all our annotation value getters into fewer functions. // TODO: coalesce all our annotation value getters into fewer functions.
fun getAnnotationValue(annotation: AnnotationDescriptor): String? { fun getAnnotationValue(annotation: AnnotationDescriptor): String? {
@@ -239,12 +234,12 @@ fun getAnnotationValue(annotation: AnnotationDescriptor): String? {
} }
fun CallableMemberDescriptor.externalSymbolOrThrow(): String? { fun CallableMemberDescriptor.externalSymbolOrThrow(): String? {
this.annotations.findAnnotation(symbolNameAnnotation)?.let { this.annotations.findAnnotation(RuntimeNames.symbolNameAnnotation)?.let {
return getAnnotationValue(it)!! return getAnnotationValue(it)!!
} }
if (this.annotations.hasAnnotation(objCMethodAnnotation)) return null if (this.annotations.hasAnnotation(RuntimeNames.objCMethodAnnotation)) return null
if (this.annotations.hasAnnotation(TypedIntrinsic)) return null if (this.annotations.hasAnnotation(RuntimeNames.typedIntrinsicAnnotation)) return null
if (this.annotations.hasAnnotation(RuntimeNames.cCall)) return null if (this.annotations.hasAnnotation(RuntimeNames.cCall)) return null
@@ -107,7 +107,7 @@ internal class KonanSymbols(context: Context, private val symbolTable: SymbolTab
val arrayList = symbolTable.referenceClass(getArrayListClassDescriptor(context)) val arrayList = symbolTable.referenceClass(getArrayListClassDescriptor(context))
val symbolName = topLevelClass(RuntimeNames.symbolName) val symbolName = topLevelClass(RuntimeNames.symbolNameAnnotation)
val filterExceptions = topLevelClass(RuntimeNames.filterExceptions) val filterExceptions = topLevelClass(RuntimeNames.filterExceptions)
val exportForCppRuntime = topLevelClass(RuntimeNames.exportForCppRuntime) val exportForCppRuntime = topLevelClass(RuntimeNames.exportForCppRuntime)
@@ -338,8 +338,6 @@ internal class KonanSymbols(context: Context, private val symbolTable: SymbolTab
override val suspendCoroutineUninterceptedOrReturn = konanSuspendCoroutineUninterceptedOrReturn override val suspendCoroutineUninterceptedOrReturn = konanSuspendCoroutineUninterceptedOrReturn
override val coroutineGetContext = konanCoroutineContextGetter
private val coroutinesIntrinsicsPackage = context.builtIns.builtInsModule.getPackage( private val coroutinesIntrinsicsPackage = context.builtIns.builtInsModule.getPackage(
context.config.configuration.languageVersionSettings.coroutinesIntrinsicsPackageFqName()).memberScope context.config.configuration.languageVersionSettings.coroutinesIntrinsicsPackageFqName()).memberScope
@@ -349,10 +347,13 @@ internal class KonanSymbols(context: Context, private val symbolTable: SymbolTab
val continuationClassDescriptor = coroutinesPackage val continuationClassDescriptor = coroutinesPackage
.getContributedClassifier(Name.identifier("Continuation"), NoLookupLocation.FROM_BACKEND) as ClassDescriptor .getContributedClassifier(Name.identifier("Continuation"), NoLookupLocation.FROM_BACKEND) as ClassDescriptor
override val coroutineContextGetter = symbolTable.referenceSimpleFunction(coroutinesPackage private val coroutineContextGetterDescriptor = coroutinesPackage
.getContributedVariables(Name.identifier("coroutineContext"), NoLookupLocation.FROM_BACKEND) .getContributedVariables(Name.identifier("coroutineContext"), NoLookupLocation.FROM_BACKEND)
.single() .single()
.getter!!) .getter!!
override val coroutineContextGetter = symbolTable.referenceSimpleFunction(coroutineContextGetterDescriptor)
override val coroutineGetContext = coroutineContextGetter
override val coroutineImpl get() = TODO() override val coroutineImpl get() = TODO()
@@ -16,20 +16,15 @@ import org.jetbrains.kotlin.backend.konan.ir.getObjCMethodInfo
import org.jetbrains.kotlin.backend.konan.ir.isObjCClassMethod import org.jetbrains.kotlin.backend.konan.ir.isObjCClassMethod
import org.jetbrains.kotlin.backend.konan.ir.isUnit import org.jetbrains.kotlin.backend.konan.ir.isUnit
import org.jetbrains.kotlin.backend.konan.llvm.KonanMangler.isExported import org.jetbrains.kotlin.backend.konan.llvm.KonanMangler.isExported
import org.jetbrains.kotlin.backend.konan.optimizations.DataFlowIR
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.symbols.IrTypeParameterSymbol
import org.jetbrains.kotlin.ir.types.* import org.jetbrains.kotlin.ir.types.*
import org.jetbrains.kotlin.ir.util.fqNameForIrSerialization import org.jetbrains.kotlin.ir.util.fqNameForIrSerialization
import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.types.getClass
import org.jetbrains.kotlin.ir.util.fqNameSafe
import org.jetbrains.kotlin.ir.util.isSuspend import org.jetbrains.kotlin.ir.util.isSuspend
import org.jetbrains.kotlin.ir.util.isVararg import org.jetbrains.kotlin.ir.util.isVararg
import org.jetbrains.kotlin.backend.konan.isInlinedNative import org.jetbrains.kotlin.backend.konan.isInlinedNative
import org.jetbrains.kotlin.konan.library.KonanLibrary import org.jetbrains.kotlin.konan.library.KonanLibrary
import org.jetbrains.kotlin.library.uniqueName import org.jetbrains.kotlin.library.uniqueName
import org.jetbrains.kotlin.name.FqName
// This file describes the ABI for Kotlin descriptors of exported declarations. // This file describes the ABI for Kotlin descriptors of exported declarations.
@@ -53,34 +48,25 @@ object KonanMangler : KotlinManglerImpl() {
override fun IrDeclaration.isPlatformSpecificExported(): Boolean { override fun IrDeclaration.isPlatformSpecificExported(): Boolean {
// TODO: revise // TODO: revise
val descriptorAnnotations = this.descriptor.annotations val descriptorAnnotations = this.descriptor.annotations
if (descriptorAnnotations.hasAnnotation(symbolNameAnnotation)) { if (descriptorAnnotations.hasAnnotation(RuntimeNames.symbolNameAnnotation)) {
// Treat any `@SymbolName` declaration as exported. // Treat any `@SymbolName` declaration as exported.
return true return true
} }
if (descriptorAnnotations.hasAnnotation(exportForCppRuntimeAnnotation)) { if (descriptorAnnotations.hasAnnotation(RuntimeNames.exportForCppRuntime)) {
// Treat any `@ExportForCppRuntime` declaration as exported. // Treat any `@ExportForCppRuntime` declaration as exported.
return true return true
} }
if (descriptorAnnotations.hasAnnotation(cnameAnnotation)) { if (descriptorAnnotations.hasAnnotation(RuntimeNames.cnameAnnotation)) {
// Treat `@CName` declaration as exported. // Treat `@CName` declaration as exported.
return true return true
} }
if (descriptorAnnotations.hasAnnotation(exportForCompilerAnnotation)) { if (descriptorAnnotations.hasAnnotation(RuntimeNames.exportForCompilerAnnotation)) {
return true return true
} }
return false return false
} }
private val symbolNameAnnotation = RuntimeNames.symbolName
private val cnameAnnotation = FqName("kotlin.native.CName")
private val exportForCppRuntimeAnnotation = RuntimeNames.exportForCppRuntime
private val exportForCompilerAnnotation = RuntimeNames.exportForCompilerAnnotation
override val IrFunction.argsPart get() = this.valueParameters.map { override val IrFunction.argsPart get() = this.valueParameters.map {
// TODO: there are clashes originating from ObjectiveC interop. // TODO: there are clashes originating from ObjectiveC interop.
@@ -128,7 +114,7 @@ object KonanMangler : KotlinManglerImpl() {
} }
} }
this.descriptor.annotations.findAnnotation(exportForCppRuntimeAnnotation)?.let { this.descriptor.annotations.findAnnotation(RuntimeNames.exportForCppRuntime)?.let {
val name = getAnnotationValue(it) ?: this.name.asString() val name = getAnnotationValue(it) ?: this.name.asString()
return name // no wrapping currently required return name // no wrapping currently required
} }
@@ -148,8 +134,6 @@ internal val IrClass.writableTypeInfoSymbolName: String
return "ktypew:" + this.fqNameForIrSerialization.toString() return "ktypew:" + this.fqNameForIrSerialization.toString()
} }
internal val theUnitInstanceName = "kobj:kotlin.Unit"
internal val IrClass.objectInstanceFieldSymbolName: String internal val IrClass.objectInstanceFieldSymbolName: String
get() { get() {
assert (this.isExported()) assert (this.isExported())
@@ -194,21 +178,9 @@ internal fun RuntimeAware.getLlvmFunctionType(function: IrFunction): LLVMTypeRef
return functionType(returnType, isVarArg = false, paramTypes = *paramTypes.toTypedArray()) return functionType(returnType, isVarArg = false, paramTypes = *paramTypes.toTypedArray())
} }
internal fun RuntimeAware.getLlvmFunctionType(symbol: DataFlowIR.FunctionSymbol): LLVMTypeRef {
val returnType = if (symbol.returnsUnit) voidType else getLLVMType(symbol.returnParameter.type)
val paramTypes = ArrayList(symbol.parameters.map { getLLVMType(it.type) })
if (isObjectType(returnType)) paramTypes.add(kObjHeaderPtrPtr)
return functionType(returnType, isVarArg = false, paramTypes = *paramTypes.toTypedArray())
}
internal val IrClass.typeInfoHasVtableAttached: Boolean internal val IrClass.typeInfoHasVtableAttached: Boolean
get() = !this.isAbstract() && !this.isExternalObjCClass() get() = !this.isAbstract() && !this.isExternalObjCClass()
internal fun ModuleDescriptor.privateFunctionSymbolName(index: Int, functionName: String?) = "private_functions_${name.asString()}_${functionName}_$index"
internal fun ModuleDescriptor.privateClassSymbolName(index: Int, className: String?) = "private_classes_${name.asString()}_${className}_$index"
internal val String.moduleConstructorName internal val String.moduleConstructorName
get() = "_Konan_init_${this}" get() = "_Konan_init_${this}"
@@ -155,6 +155,11 @@ private inline fun <R> generateFunctionBody(
functionGenerationContext.resetDebugLocation() functionGenerationContext.resetDebugLocation()
} }
/**
* There're cases when we don't need end position or it is meaningless.
*/
internal data class LocationInfoRange(var start: LocationInfo, var end: LocationInfo?)
internal class FunctionGenerationContext(val function: LLVMValueRef, internal class FunctionGenerationContext(val function: LLVMValueRef,
val codegen: CodeGenerator, val codegen: CodeGenerator,
startLocation: LocationInfo?, startLocation: LocationInfo?,
@@ -163,11 +168,11 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
override val context = codegen.context override val context = codegen.context
val vars = VariableManager(this) val vars = VariableManager(this)
private val basicBlockToLastLocation = mutableMapOf<LLVMBasicBlockRef, LocationInfo>() private val basicBlockToLastLocation = mutableMapOf<LLVMBasicBlockRef, LocationInfoRange>()
private fun update(block:LLVMBasicBlockRef, locationInfo: LocationInfo?) { private fun update(block:LLVMBasicBlockRef, locationInfo: LocationInfo?, endLocation: LocationInfo? = null) {
locationInfo ?: return locationInfo ?: return
basicBlockToLastLocation.put(block, locationInfo) basicBlockToLastLocation.put(block, LocationInfoRange(locationInfo, endLocation))
} }
var returnType: LLVMTypeRef? = LLVMGetReturnType(getFunctionType(function)) var returnType: LLVMTypeRef? = LLVMGetReturnType(getFunctionType(function))
@@ -209,9 +214,9 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
return bb return bb
} }
fun basicBlock(name:String = "label_" , locationInfo:LocationInfo?): LLVMBasicBlockRef { fun basicBlock(name:String = "label_", startLocationInfo:LocationInfo?, endLocationInfo: LocationInfo? = null): LLVMBasicBlockRef {
val result = LLVMInsertBasicBlock(this.currentBlock, name)!! val result = LLVMInsertBasicBlock(this.currentBlock, name)!!
update(result, locationInfo) update(result, startLocationInfo, endLocationInfo)
LLVMMoveBasicBlockAfter(result, this.currentBlock) LLVMMoveBasicBlockAfter(result, this.currentBlock)
return result return result
} }
@@ -307,12 +312,18 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
} }
private fun updateReturnRef(value: LLVMValueRef, address: LLVMValueRef) { private fun updateReturnRef(value: LLVMValueRef, address: LLVMValueRef) {
store(value, address) if (context.memoryModel == MemoryModel.STRICT)
store(value, address)
else
call(context.llvm.updateReturnRefFunction, listOf(address, value))
} }
private fun updateRef(value: LLVMValueRef, address: LLVMValueRef, onStack: Boolean) { private fun updateRef(value: LLVMValueRef, address: LLVMValueRef, onStack: Boolean) {
if (onStack) { if (onStack) {
store(value, address) if (context.memoryModel == MemoryModel.STRICT)
store(value, address)
else
call(context.llvm.updateStackRefFunction, listOf(address, value))
} else { } else {
call(context.llvm.updateHeapRefFunction, listOf(address, value)) call(context.llvm.updateHeapRefFunction, listOf(address, value))
} }
@@ -340,24 +351,6 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
SlotType.ANONYMOUS -> vars.createAnonymousSlot() SlotType.ANONYMOUS -> vars.createAnonymousSlot()
SlotType.RETURN_IF_ARENA -> returnSlot.let {
if (it != null)
call(context.llvm.getReturnSlotIfArenaFunction, listOf(it, vars.createAnonymousSlot()))
else {
// Return type is not an object type - can allocate locally.
localAllocs++
arenaSlot!!
}
}
is SlotType.PARAM_IF_ARENA ->
if (LLVMTypeOf(vars.load(resultLifetime.slotType.parameter)) != codegen.runtime.objHeaderPtrType)
vars.createAnonymousSlot()
else {
call(context.llvm.getParamSlotIfArenaFunction,
listOf(vars.load(resultLifetime.slotType.parameter), vars.createAnonymousSlot()))
}
else -> throw Error("Incorrect slot type: ${resultLifetime.slotType}") else -> throw Error("Incorrect slot type: ${resultLifetime.slotType}")
} }
args + resultSlot args + resultSlot
@@ -387,8 +380,11 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
} }
} }
val success = basicBlock("call_success", position()) val position = position()
val endLocation = position?.start.let { position?.end }
val success = basicBlock("call_success", endLocation)
val result = LLVMBuildInvoke(builder, llvmFunction, rargs, args.size, success, unwind, "")!! val result = LLVMBuildInvoke(builder, llvmFunction, rargs, args.size, success, unwind, "")!!
update(success, endLocation, endLocation)
positionAtEnd(success) positionAtEnd(success)
return result return result
} }
@@ -538,15 +534,15 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
} }
fun filteringExceptionHandler(codeContext: CodeContext): ExceptionHandler { fun filteringExceptionHandler(codeContext: CodeContext): ExceptionHandler {
val lpBlock = basicBlockInFunction("filteringExceptionHandler", position()) val lpBlock = basicBlockInFunction("filteringExceptionHandler", position()?.start)
appendingTo(lpBlock) { appendingTo(lpBlock) {
val landingpad = gxxLandingpad(2) val landingpad = gxxLandingpad(2)
LLVMAddClause(landingpad, kotlinExceptionRtti.llvm) LLVMAddClause(landingpad, kotlinExceptionRtti.llvm)
LLVMAddClause(landingpad, LLVMConstNull(kInt8Ptr)) LLVMAddClause(landingpad, LLVMConstNull(kInt8Ptr))
val fatalForeignExceptionBlock = basicBlock("fatalForeignException", position()) val fatalForeignExceptionBlock = basicBlock("fatalForeignException", position()?.start)
val forwardKotlinExceptionBlock = basicBlock("forwardKotlinException", position()) val forwardKotlinExceptionBlock = basicBlock("forwardKotlinException", position()?.start)
val isKotlinException = icmpEq( val isKotlinException = icmpEq(
extractValue(landingpad, 1), extractValue(landingpad, 1),
@@ -577,7 +573,7 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
call(context.llvm.cxxStdTerminate, emptyList()) call(context.llvm.cxxStdTerminate, emptyList())
// Note: unreachable instruction to be generated here, but debug information is improper in this case. // Note: unreachable instruction to be generated here, but debug information is improper in this case.
val loopBlock = basicBlock("loop", position()) val loopBlock = basicBlock("loop", position()?.start)
br(loopBlock) br(loopBlock)
appendingTo(loopBlock) { appendingTo(loopBlock) {
br(loopBlock) br(loopBlock)
@@ -638,12 +634,14 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
): LLVMValueRef { ): LLVMValueRef {
val resultType = thenValue.type val resultType = thenValue.type
val bbExit = basicBlock(locationInfo = position()) val position = position()
val endPosition = position()?.end
val bbExit = basicBlock(startLocationInfo = endPosition, endLocationInfo = endPosition)
val resultPhi = appendingTo(bbExit) { val resultPhi = appendingTo(bbExit) {
phi(resultType) phi(resultType)
} }
val bbElse = basicBlock(locationInfo = position()) val bbElse = basicBlock(startLocationInfo = position?.start, endLocationInfo = endPosition)
condBr(condition, bbExit, bbElse) condBr(condition, bbExit, bbElse)
assignPhis(resultPhi to thenValue) assignPhis(resultPhi to thenValue)
@@ -659,8 +657,9 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
} }
inline fun ifThen(condition: LLVMValueRef, thenBlock: () -> Unit) { inline fun ifThen(condition: LLVMValueRef, thenBlock: () -> Unit) {
val bbExit = basicBlock(locationInfo = position()) val endPosition = position()?.end
val bbThen = basicBlock(locationInfo = position()) val bbExit = basicBlock(startLocationInfo = endPosition, endLocationInfo = endPosition)
val bbThen = basicBlock(startLocationInfo = endPosition, endLocationInfo = endPosition)
condBr(condition, bbThen, bbExit) condBr(condition, bbThen, bbExit)
@@ -672,10 +671,10 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
positionAtEnd(bbExit) positionAtEnd(bbExit)
} }
internal fun debugLocation(locationInfo: LocationInfo): DILocationRef? { internal fun debugLocation(startLocationInfo: LocationInfo, endLocation: LocationInfo?): DILocationRef? {
if (!context.shouldContainDebugInfo()) return null if (!context.shouldContainDebugInfo()) return null
update(currentBlock, locationInfo) update(currentBlock, startLocationInfo, endLocation)
val debugLocation = codegen.generateLocationInfo(locationInfo) val debugLocation = codegen.generateLocationInfo(startLocationInfo)
currentPositionHolder.setBuilderDebugLocation(debugLocation) currentPositionHolder.setBuilderDebugLocation(debugLocation)
return debugLocation return debugLocation
} }
@@ -753,7 +752,8 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
fun getObjectValue( fun getObjectValue(
irClass: IrClass, irClass: IrClass,
exceptionHandler: ExceptionHandler, exceptionHandler: ExceptionHandler,
locationInfo: LocationInfo? startLocationInfo: LocationInfo?,
endLocationInfo: LocationInfo? = null
): LLVMValueRef { ): LLVMValueRef {
if (irClass.isUnit()) { if (irClass.isUnit()) {
return codegen.theUnitInstanceRef.llvm return codegen.theUnitInstanceRef.llvm
@@ -775,8 +775,8 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
val shared = irClass.objectIsShared && context.config.threadsAreAllowed val shared = irClass.objectIsShared && context.config.threadsAreAllowed
val objectPtr = codegen.getObjectInstanceStorage(irClass, shared) val objectPtr = codegen.getObjectInstanceStorage(irClass, shared)
val bbInit = basicBlock("label_init", locationInfo) val bbInit = basicBlock("label_init", startLocationInfo, endLocationInfo)
val bbExit = basicBlock("label_continue", locationInfo) val bbExit = basicBlock("label_continue", startLocationInfo, endLocationInfo)
val objectVal = loadSlot(objectPtr, false) val objectVal = loadSlot(objectPtr, false)
val objectInitialized = icmpUGt(ptrToInt(objectVal, codegen.intPtrType), codegen.immOneIntPtrType) val objectInitialized = icmpUGt(ptrToInt(objectVal, codegen.intPtrType), codegen.immOneIntPtrType)
val bbCurrent = currentBlock val bbCurrent = currentBlock
@@ -958,7 +958,7 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
releaseVars() releaseVars()
LLVMBuildRet(builder, returnPhi) LLVMBuildRet(builder, returnPhi)
} }
// Do nothing, all paths throw. // Do nothing, all paths throw.
else -> LLVMBuildUnreachable(builder) else -> LLVMBuildUnreachable(builder)
} }
} }
@@ -1046,7 +1046,7 @@ internal class FunctionGenerationContext(val function: LLVMValueRef,
fun positionAtEnd(block: LLVMBasicBlockRef) { fun positionAtEnd(block: LLVMBasicBlockRef) {
LLVMPositionBuilderAtEnd(builder, block) LLVMPositionBuilderAtEnd(builder, block)
basicBlockToLastLocation[block]?.let{ debugLocation(it) } basicBlockToLastLocation[block]?.let{ debugLocation(it.start, it.end) }
val lastInstr = LLVMGetLastInstruction(block) val lastInstr = LLVMGetLastInstruction(block)
isAfterTerminator = lastInstr != null && (LLVMIsATerminatorInst(lastInstr) != null) isAfterTerminator = lastInstr != null && (LLVMIsATerminatorInst(lastInstr) != null)
} }
@@ -260,7 +260,8 @@ internal class Llvm(val context: Context, val llvmModule: LLVMModuleRef) {
throw IllegalArgumentException("function $name already exists") throw IllegalArgumentException("function $name already exists")
} }
val externalFunction = LLVMGetNamedFunction(otherModule, name)!! val externalFunction = LLVMGetNamedFunction(otherModule, name) ?:
throw Error("function $name not found")
val functionType = getFunctionType(externalFunction) val functionType = getFunctionType(externalFunction)
val function = LLVMAddFunction(llvmModule, name, functionType)!! val function = LLVMAddFunction(llvmModule, name, functionType)!!
@@ -418,18 +419,20 @@ internal class Llvm(val context: Context, val llvmModule: LLVMModuleRef) {
} }
private fun importRtFunction(name: String) = importFunction(name, runtime.llvmModule) private fun importRtFunction(name: String) = importFunction(name, runtime.llvmModule)
private fun importModelSpecificRtFunction(name: String) =
importRtFunction(name + context.memoryModel.suffix)
private fun importRtGlobal(name: String) = importGlobal(name, runtime.llvmModule) private fun importRtGlobal(name: String) = importGlobal(name, runtime.llvmModule)
val allocInstanceFunction = importRtFunction("AllocInstance") val allocInstanceFunction = importModelSpecificRtFunction("AllocInstance")
val allocArrayFunction = importRtFunction("AllocArrayInstance") val allocArrayFunction = importModelSpecificRtFunction("AllocArrayInstance")
val initInstanceFunction = importRtFunction("InitInstance") val initInstanceFunction = importModelSpecificRtFunction("InitInstance")
val initSharedInstanceFunction = importRtFunction("InitSharedInstance") val initSharedInstanceFunction = importModelSpecificRtFunction("InitSharedInstance")
val updateHeapRefFunction = importRtFunction("UpdateHeapRef") val updateHeapRefFunction = importRtFunction("UpdateHeapRef")
val updateStackRefFunction = importRtFunction("UpdateStackRef")
val updateReturnRefFunction = importRtFunction("UpdateReturnRef")
val enterFrameFunction = importRtFunction("EnterFrame") val enterFrameFunction = importRtFunction("EnterFrame")
val leaveFrameFunction = importRtFunction("LeaveFrame") val leaveFrameFunction = importRtFunction("LeaveFrame")
val getReturnSlotIfArenaFunction = importRtFunction("GetReturnSlotIfArena")
val getParamSlotIfArenaFunction = importRtFunction("GetParamSlotIfArena")
val lookupOpenMethodFunction = importRtFunction("LookupOpenMethod") val lookupOpenMethodFunction = importRtFunction("LookupOpenMethod")
val isInstanceFunction = importRtFunction("IsInstance") val isInstanceFunction = importRtFunction("IsInstance")
val checkInstanceFunction = importRtFunction("CheckInstance") val checkInstanceFunction = importRtFunction("CheckInstance")
@@ -2,7 +2,7 @@ package org.jetbrains.kotlin.backend.konan.llvm
import kotlinx.cinterop.cValuesOf import kotlinx.cinterop.cValuesOf
import llvm.* import llvm.*
import org.jetbrains.kotlin.backend.konan.descriptors.TypedIntrinsic import org.jetbrains.kotlin.backend.konan.RuntimeNames
import org.jetbrains.kotlin.backend.konan.descriptors.isTypedIntrinsic import org.jetbrains.kotlin.backend.konan.descriptors.isTypedIntrinsic
import org.jetbrains.kotlin.backend.konan.llvm.objc.genObjCSelector import org.jetbrains.kotlin.backend.konan.llvm.objc.genObjCSelector
import org.jetbrains.kotlin.backend.konan.reportCompilationError import org.jetbrains.kotlin.backend.konan.reportCompilationError
@@ -113,7 +113,7 @@ internal fun tryGetIntrinsicType(callSite: IrFunctionAccessExpression): Intrinsi
private fun getIntrinsicType(callSite: IrFunctionAccessExpression): IntrinsicType { private fun getIntrinsicType(callSite: IrFunctionAccessExpression): IntrinsicType {
val function = callSite.symbol.owner val function = callSite.symbol.owner
val annotation = function.descriptor.annotations.findAnnotation(TypedIntrinsic)!! val annotation = function.descriptor.annotations.findAnnotation(RuntimeNames.typedIntrinsicAnnotation)!!
val value = annotation.allValueArguments.getValue(Name.identifier("kind")).value as String val value = annotation.allValueArguments.getValue(Name.identifier("kind")).value as String
return IntrinsicType.valueOf(value) return IntrinsicType.valueOf(value)
} }
@@ -11,8 +11,10 @@ import org.jetbrains.kotlin.backend.common.descriptors.allParameters
import org.jetbrains.kotlin.backend.common.ir.ir2string import org.jetbrains.kotlin.backend.common.ir.ir2string
import org.jetbrains.kotlin.backend.konan.* import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.* import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.backend.konan.descriptors.isArray
import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.backend.konan.ir.NaiveSourceBasedFileEntryImpl import org.jetbrains.kotlin.backend.konan.ir.NaiveSourceBasedFileEntryImpl
import org.jetbrains.kotlin.backend.konan.ir.containsNull
import org.jetbrains.kotlin.backend.konan.llvm.coverage.* import org.jetbrains.kotlin.backend.konan.llvm.coverage.*
import org.jetbrains.kotlin.backend.konan.llvm.objcexport.is64Bit import org.jetbrains.kotlin.backend.konan.llvm.objcexport.is64Bit
import org.jetbrains.kotlin.backend.konan.optimizations.* import org.jetbrains.kotlin.backend.konan.optimizations.*
@@ -467,7 +469,7 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
//-------------------------------------------------------------------------// //-------------------------------------------------------------------------//
private inner class LoopScope(val loop: IrLoop) : InnerScopeImpl() { private inner class LoopScope(val loop: IrLoop) : InnerScopeImpl() {
val loopExit = functionGenerationContext.basicBlock("loop_exit", loop.condition.startLocation) val loopExit = functionGenerationContext.basicBlock("loop_exit", loop.endLocation)
val loopCheck = functionGenerationContext.basicBlock("loop_check", loop.condition.startLocation) val loopCheck = functionGenerationContext.basicBlock("loop_check", loop.condition.startLocation)
override fun genBreak(destination: IrBreak) { override fun genBreak(destination: IrBreak) {
@@ -806,7 +808,8 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
functionGenerationContext.getObjectValue( functionGenerationContext.getObjectValue(
value.symbol.owner, value.symbol.owner,
currentCodeContext.exceptionHandler, currentCodeContext.exceptionHandler,
value.startLocation value.startLocation,
value.endLocation
) )
@@ -1052,7 +1055,7 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
val needsPhi = isUnconditional(expression.branches.last()) && !expression.type.isUnit() val needsPhi = isUnconditional(expression.branches.last()) && !expression.type.isUnit()
val llvmType = codegen.getLLVMType(expression.type) val llvmType = codegen.getLLVMType(expression.type)
val bbExit = lazy { functionGenerationContext.basicBlock("when_exit", expression.startLocation) } val bbExit = lazy { functionGenerationContext.basicBlock("when_exit", expression.endLocation) }
val resultPhi = lazy { val resultPhi = lazy {
functionGenerationContext.appendingTo(bbExit.value) { functionGenerationContext.appendingTo(bbExit.value) {
@@ -1070,7 +1073,7 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
val bbNext = if (it == expression.branches.last()) val bbNext = if (it == expression.branches.last())
null null
else else
functionGenerationContext.basicBlock("when_next", it.startLocation) functionGenerationContext.basicBlock("when_next", it.startLocation, it.endLocation)
generateWhenCase(whenEmittingContext, it, bbNext) generateWhenCase(whenEmittingContext, it, bbNext)
} }
@@ -1089,7 +1092,7 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
val brResult = if (isUnconditional(branch)) val brResult = if (isUnconditional(branch))
evaluateExpression(branch.result) evaluateExpression(branch.result)
else { else {
val bbCase = functionGenerationContext.basicBlock("when_case", branch.startLocation) val bbCase = functionGenerationContext.basicBlock("when_case", branch.startLocation, branch.endLocation)
val condition = evaluateExpression(branch.condition) val condition = evaluateExpression(branch.condition)
functionGenerationContext.condBr(condition, bbCase, bbNext ?: whenEmittingContext.bbExit.value) functionGenerationContext.condBr(condition, bbCase, bbNext ?: whenEmittingContext.bbExit.value)
functionGenerationContext.positionAtEnd(bbCase) functionGenerationContext.positionAtEnd(bbCase)
@@ -1236,6 +1239,7 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
IrTypeOperator.INSTANCEOF -> evaluateInstanceOf(value) IrTypeOperator.INSTANCEOF -> evaluateInstanceOf(value)
IrTypeOperator.NOT_INSTANCEOF -> evaluateNotInstanceOf(value) IrTypeOperator.NOT_INSTANCEOF -> evaluateNotInstanceOf(value)
IrTypeOperator.SAM_CONVERSION -> TODO(ir2string(value)) IrTypeOperator.SAM_CONVERSION -> TODO(ir2string(value))
IrTypeOperator.IMPLICIT_DYNAMIC_CAST -> TODO(ir2string(value))
} }
} }
@@ -1484,39 +1488,6 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
} }
//-------------------------------------------------------------------------// //-------------------------------------------------------------------------//
/*
in C:
struct ObjHeader *header = (struct ObjHeader *)ptr;
struct T* obj = (T*)&header[1];
return &obj->fieldX;
in llvm ir:
%struct.ObjHeader = type { i32, i32 }
%struct.Object = type { i32, i32 }
; Function Attrs: nounwind ssp uwtable
define i32 @fooField2(i8*) #0 {
%2 = alloca i8*, align 8
%3 = alloca %struct.ObjHeader*, align 8
%4 = alloca %struct.Object*, align 8
store i8* %0, i8** %2, align 8
%5 = load i8*, i8** %2, align 8
%6 = bitcast i8* %5 to %struct.ObjHeader*
store %struct.ObjHeader* %6, %struct.ObjHeader** %3, align 8
%7 = load %struct.ObjHeader*, %struct.ObjHeader** %3, align 8
%8 = getelementptr inbounds %struct.ObjHeader, %struct.ObjHeader* %7, i64 1; <- (T*)&header[1];
%9 = bitcast %struct.ObjHeader* %8 to %struct.Object*
store %struct.Object* %9, %struct.Object** %4, align 8
%10 = load %struct.Object*, %struct.Object** %4, align 8
%11 = getelementptr inbounds %struct.Object, %struct.Object* %10, i32 0, i32 0 <- &obj->fieldX
%12 = load i32, i32* %11, align 4
ret i32 %12
}
*/
private fun fieldPtrOfClass(thisPtr: LLVMValueRef, value: IrField): LLVMValueRef { private fun fieldPtrOfClass(thisPtr: LLVMValueRef, value: IrField): LLVMValueRef {
val fieldInfo = context.llvmDeclarations.forField(value) val fieldInfo = context.llvmDeclarations.forField(value)
@@ -1591,9 +1562,17 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
var bbExit : LLVMBasicBlockRef? = null var bbExit : LLVMBasicBlockRef? = null
var resultPhi : LLVMValueRef? = null var resultPhi : LLVMValueRef? = null
private val functionScope: DIScopeOpaqueRef?
get() = returnableBlock.inlineFunctionSymbol?.owner?.scope()
private val outerScope = currentCodeContext.scope()
private fun getExit(): LLVMBasicBlockRef { private fun getExit(): LLVMBasicBlockRef {
if (bbExit == null) bbExit = functionGenerationContext.basicBlock("returnable_block_exit", returnableBlock.startLocation) val location = returnableBlock.inlineFunctionSymbol?.let {
location(it.owner.endLine(), it.owner.endColumn())
} ?: returnableBlock.statements.lastOrNull()?.let {
location(it.endLine(), it.endColumn())
}
if (bbExit == null) bbExit = functionGenerationContext.basicBlock("returnable_block_exit", location)
return bbExit!! return bbExit!!
} }
@@ -1624,13 +1603,19 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
override fun location(line: Int, column: Int): LocationInfo? { override fun location(line: Int, column: Int): LocationInfo? {
return if (returnableBlock.inlineFunctionSymbol != null) { return if (returnableBlock.inlineFunctionSymbol != null) {
val diScope = returnableBlock.inlineFunctionSymbol?.owner?.scope() ?: return null val diScope = functionScope ?: return null
LocationInfo(diScope, line, column, outerContext.location(returnableBlock.startLine(), returnableBlock.endLine())) val outerFileEntry = outerFileEntry()
val inlinedAt = outerContext.location(outerFileEntry.line(returnableBlock.startOffset), outerFileEntry.column(returnableBlock.startOffset))
LocationInfo(diScope, line, column, inlinedAt)
} else { } else {
outerContext.location(line, column) outerContext.location(line, column)
} }
} }
private fun outerFileEntry() =
(outerContext.fileScope() as? FileScope)?.file?.fileEntry
?: error("returnable block should be inlined at some file")
/** /**
* Note: DILexicalBlocks aren't nested, they should be scoped with the parent function. * Note: DILexicalBlocks aren't nested, they should be scoped with the parent function.
@@ -1769,10 +1754,9 @@ internal class CodeGeneratorVisitor(val context: Context, val lifetimes: Map<IrE
private fun file() = (currentCodeContext.fileScope() as FileScope).file private fun file() = (currentCodeContext.fileScope() as FileScope).file
//-------------------------------------------------------------------------// //-------------------------------------------------------------------------//
private fun updateBuilderDebugLocation(element: IrElement): DILocationRef? { private fun updateBuilderDebugLocation(element: IrElement) {
if (!context.shouldContainDebugInfo() || currentCodeContext.functionScope() == null) return null if (!context.shouldContainDebugInfo() || currentCodeContext.functionScope() == null || element.startLocation == null) return
@Suppress("UNCHECKED_CAST") functionGenerationContext.debugLocation(element.startLocation!!, element.endLocation!!)
return element.startLocation?.let { functionGenerationContext.debugLocation(it) }
} }
private val IrElement.startLocation: LocationInfo? private val IrElement.startLocation: LocationInfo?
@@ -330,7 +330,7 @@ internal class RTTIGenerator(override val context: Context) : ContextUtils {
functionType(kObjHeaderPtr, false, kObjHeaderPtrPtr), functionType(kObjHeaderPtr, false, kObjHeaderPtrPtr),
"" ""
) { ) {
ret(getObjectValue(value, ExceptionHandler.Caller, locationInfo = null)) ret(getObjectValue(value, ExceptionHandler.Caller, startLocationInfo = null))
} }
Struct(runtime.associatedObjectTableRecordType, key.typeInfoPtr, constPointer(associatedObjectGetter)) Struct(runtime.associatedObjectTableRecordType, key.typeInfoPtr, constPointer(associatedObjectGetter))
@@ -1148,7 +1148,7 @@ private fun ObjCExportCodeGenerator.createObjectInstanceAdapter(
return generateObjCToKotlinSyntheticGetter(selector) { return generateObjCToKotlinSyntheticGetter(selector) {
initRuntimeIfNeeded() // For instance methods it gets called when allocating. initRuntimeIfNeeded() // For instance methods it gets called when allocating.
val value = getObjectValue(irClass, locationInfo = null, exceptionHandler = ExceptionHandler.Caller) val value = getObjectValue(irClass, startLocationInfo = null, exceptionHandler = ExceptionHandler.Caller)
ret(kotlinToObjC(value, ReferenceBridge)) ret(kotlinToObjC(value, ReferenceBridge))
} }
} }
@@ -74,7 +74,9 @@ internal class PropertyDelegationLowering(val context: Context) : FileLoweringPa
} }
override fun lower(irFile: IrFile) { override fun lower(irFile: IrFile) {
val kProperties = mutableMapOf<VariableDescriptorWithAccessors, Pair<IrExpression, Int>>() // Somehow there is no reasonable common ancestor for IrProperty and IrLocalDelegatedProperty,
// so index by IrDeclaration.
val kProperties = mutableMapOf<IrDeclaration, Pair<IrExpression, Int>>()
val arrayClass = context.ir.symbols.array.owner val arrayClass = context.ir.symbols.array.owner
@@ -121,7 +123,7 @@ internal class PropertyDelegationLowering(val context: Context) : FileLoweringPa
2 -> error("Callable reference to properties with two receivers is not allowed: ${expression.descriptor}") 2 -> error("Callable reference to properties with two receivers is not allowed: ${expression.descriptor}")
else -> { // Cache KProperties with no arguments. else -> { // Cache KProperties with no arguments.
val field = kProperties.getOrPut(expression.descriptor) { val field = kProperties.getOrPut(expression.symbol.owner) {
createKProperty(expression, this) to kProperties.size createKProperty(expression, this) to kProperties.size
} }
@@ -141,16 +143,14 @@ internal class PropertyDelegationLowering(val context: Context) : FileLoweringPa
val endOffset = expression.endOffset val endOffset = expression.endOffset
val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset) val irBuilder = context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, startOffset, endOffset)
irBuilder.run { irBuilder.run {
val propertyDescriptor = expression.descriptor
val receiversCount = listOf(expression.dispatchReceiver, expression.extensionReceiver).count { it != null } val receiversCount = listOf(expression.dispatchReceiver, expression.extensionReceiver).count { it != null }
if (receiversCount == 2) if (receiversCount == 2)
throw AssertionError("Callable reference to properties with two receivers is not allowed: $propertyDescriptor") throw AssertionError("Callable reference to properties with two receivers is not allowed: ${expression}")
else { // Cache KProperties with no arguments. else { // Cache KProperties with no arguments.
// TODO: what about `receiversCount == 1` case? // TODO: what about `receiversCount == 1` case?
val field = kProperties.getOrPut(propertyDescriptor) { val field = kProperties.getOrPut(expression.symbol.owner) {
createLocalKProperty( createLocalKProperty(
propertyDescriptor, expression.symbol.owner.name.asString(),
expression.getter.owner.returnType, expression.getter.owner.returnType,
this this
) to kProperties.size ) to kProperties.size
@@ -265,7 +265,7 @@ internal class PropertyDelegationLowering(val context: Context) : FileLoweringPa
} }
} }
private fun createLocalKProperty(propertyDescriptor: VariableDescriptorWithAccessors, private fun createLocalKProperty(propertyName: String,
propertyType: IrType, propertyType: IrType,
irBuilder: IrBuilderWithScope): IrExpression { irBuilder: IrBuilderWithScope): IrExpression {
irBuilder.run { irBuilder.run {
@@ -275,7 +275,7 @@ internal class PropertyDelegationLowering(val context: Context) : FileLoweringPa
isLocal = true, isLocal = true,
isMutable = false) isMutable = false)
val initializer = irCall(symbol.owner, constructorTypeArguments).apply { val initializer = irCall(symbol.owner, constructorTypeArguments).apply {
putValueArgument(0, irString(propertyDescriptor.name.asString())) putValueArgument(0, irString(propertyName))
putValueArgument(1, with(kTypeGenerator) { irKType(propertyType) }) putValueArgument(1, with(kTypeGenerator) { irKType(propertyType) })
} }
return initializer return initializer
@@ -17,6 +17,7 @@ import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.resolveFakeOverride import org.jetbrains.kotlin.backend.konan.descriptors.resolveFakeOverride
import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.config.languageVersionSettings import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.builders.irGet
@@ -25,9 +26,12 @@ import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.* import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.* import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrValueSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrReturnableBlockSymbolImpl import org.jetbrains.kotlin.ir.symbols.impl.IrReturnableBlockSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.util.OperatorNameConventions
@@ -70,7 +74,7 @@ internal class FunctionInlining(val context: Context) : IrElementTransformerVoid
descriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn(languageVersionSettings) -> descriptor.isBuiltInSuspendCoroutineUninterceptedOrReturn(languageVersionSettings) ->
context.ir.symbols.konanSuspendCoroutineUninterceptedOrReturn.owner context.ir.symbols.konanSuspendCoroutineUninterceptedOrReturn.owner
descriptor == context.ir.symbols.coroutineContextGetter.owner.descriptor -> symbol == context.ir.symbols.coroutineContextGetter ->
context.ir.symbols.konanCoroutineContextGetter.owner context.ir.symbols.konanCoroutineContextGetter.owner
else -> (symbol.owner as? IrSimpleFunction)?.resolveFakeOverride() ?: symbol.owner else -> (symbol.owner as? IrSimpleFunction)?.resolveFakeOverride() ?: symbol.owner
@@ -101,7 +105,7 @@ internal class FunctionInlining(val context: Context) : IrElementTransformerVoid
DeepCopyIrTreeWithSymbolsForInliner(context, typeArguments, parent) DeepCopyIrTreeWithSymbolsForInliner(context, typeArguments, parent)
} }
val substituteMap = mutableMapOf<IrValueParameter, IrExpression>() val substituteMap = mutableMapOf<IrValueParameter, IrElement>()
fun inline() = inlineFunction(callSite, callee) fun inline() = inlineFunction(callSite, callee)
@@ -125,7 +129,10 @@ internal class FunctionInlining(val context: Context) : IrElementTransformerVoid
val irReturnableBlockSymbol = IrReturnableBlockSymbolImpl(copiedCallee.descriptor.original) val irReturnableBlockSymbol = IrReturnableBlockSymbolImpl(copiedCallee.descriptor.original)
val startOffset = callee.startOffset val startOffset = callee.startOffset
val endOffset = callee.endOffset val endOffset = callee.endOffset
val irBuilder = context.createIrBuilder(irReturnableBlockSymbol, startOffset, endOffset) /* creates irBuilder appending to the end of the given returnable block: thus why we initialize
* irBuilder with (..., endOffset, endOffset).
*/
val irBuilder = context.createIrBuilder(irReturnableBlockSymbol, endOffset, endOffset)
if (callee.isInlineConstructor) { if (callee.isInlineConstructor) {
// Copier sets parent to be the current function but // Copier sets parent to be the current function but
@@ -197,9 +204,13 @@ internal class FunctionInlining(val context: Context) : IrElementTransformerVoid
override fun visitGetValue(expression: IrGetValue): IrExpression { override fun visitGetValue(expression: IrGetValue): IrExpression {
val newExpression = super.visitGetValue(expression) as IrGetValue val newExpression = super.visitGetValue(expression) as IrGetValue
val argument = substituteMap[newExpression.symbol.owner] ?: return newExpression val argument = substituteMap[newExpression.symbol.owner] ?: return newExpression
argument.transformChildrenVoid(this) // Default argument can contain subjects for substitution. argument.transformChildrenVoid(this) // Default argument can contain subjects for substitution.
return copyIrElement.copy(argument) as IrExpression return if (argument is IrVariable) {
IrGetValueImpl(startOffset = newExpression.startOffset,
endOffset = newExpression.endOffset,
symbol = argument.symbol)
} else (copyIrElement.copy(argument) as IrExpression)
} }
//-----------------------------------------------------------------// //-----------------------------------------------------------------//
@@ -403,13 +414,7 @@ internal class FunctionInlining(val context: Context) : IrElementTransformerVoid
isMutable = false) isMutable = false)
evaluationStatements.add(newVariable) evaluationStatements.add(newVariable)
val getVal = IrGetValueImpl( substituteMap[it.parameter] = newVariable
startOffset = currentScope.irElement.startOffset,
endOffset = currentScope.irElement.endOffset,
type = newVariable.type,
symbol = newVariable.symbol
)
substituteMap[it.parameter] = getVal
} }
return evaluationStatements return evaluationStatements
} }
@@ -19,6 +19,7 @@ import org.jetbrains.kotlin.backend.konan.descriptors.isInterface
import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName import org.jetbrains.kotlin.backend.konan.descriptors.synthesizedName
import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.backend.konan.ir.companionObject import org.jetbrains.kotlin.backend.konan.ir.companionObject
import org.jetbrains.kotlin.backend.konan.ir.containsNull
import org.jetbrains.kotlin.backend.konan.llvm.IntrinsicType import org.jetbrains.kotlin.backend.konan.llvm.IntrinsicType
import org.jetbrains.kotlin.backend.konan.llvm.llvmSymbolOrigin import org.jetbrains.kotlin.backend.konan.llvm.llvmSymbolOrigin
import org.jetbrains.kotlin.backend.konan.llvm.tryGetIntrinsicType import org.jetbrains.kotlin.backend.konan.llvm.tryGetIntrinsicType
@@ -34,7 +34,7 @@ internal class ReturnsInsertionLowering(val context: Context) : FileLoweringPass
val body = declaration.body val body = declaration.body
if ((declaration is IrConstructor || declaration.returnType.classifierOrNull == symbols.unit) && body != null) { if ((declaration is IrConstructor || declaration.returnType.classifierOrNull == symbols.unit) && body != null) {
val irBuilder = context.createIrBuilder(declaration.symbol, declaration.startOffset, declaration.endOffset) val irBuilder = context.createIrBuilder(declaration.symbol, declaration.endOffset, declaration.endOffset)
irBuilder.run { irBuilder.run {
(body as IrBlockBody).statements += irReturn(irGetObject(symbols.unit)) (body as IrBlockBody).statements += irReturn(irGetObject(symbols.unit))
} }
@@ -52,7 +52,7 @@ internal class ObjCExport(val context: Context, symbolTable: SymbolTable) {
val produceFramework = context.config.produce == CompilerOutputKind.FRAMEWORK val produceFramework = context.config.produce == CompilerOutputKind.FRAMEWORK
return if (produceFramework) { return if (produceFramework) {
val mapper = ObjCExportMapper() val mapper = ObjCExportMapper(context.frontendServices.deprecationResolver)
val moduleDescriptors = listOf(context.moduleDescriptor) + context.getExportedDependencies() val moduleDescriptors = listOf(context.moduleDescriptor) + context.getExportedDependencies()
val objcGenerics = context.configuration.getBoolean(KonanConfigKeys.OBJC_GENERICS) val objcGenerics = context.configuration.getBoolean(KonanConfigKeys.OBJC_GENERICS)
val namer = ObjCExportNamerImpl( val namer = ObjCExportNamerImpl(
@@ -17,6 +17,8 @@ import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.constants.ArrayValue import org.jetbrains.kotlin.resolve.constants.ArrayValue
import org.jetbrains.kotlin.resolve.constants.KClassValue import org.jetbrains.kotlin.resolve.constants.KClassValue
import org.jetbrains.kotlin.resolve.deprecation.Deprecation
import org.jetbrains.kotlin.resolve.deprecation.DeprecationLevelValue
import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.ErrorUtils
@@ -365,8 +367,7 @@ internal class ObjCExportTranslatorImpl(
?.forEach { ?.forEach {
val selector = getSelector(it) val selector = getSelector(it)
if (selector !in presentConstructors) { if (selector !in presentConstructors) {
val c = buildMethod(it, it, ObjCNoneExportScope) +buildMethod(it, it, ObjCNoneExportScope, unavailable = true)
+ObjCMethod(c.descriptor, c.isInstanceMethod, c.returnType, c.selectors, c.parameters, c.attributes + "unavailable")
if (selector == "init") { if (selector == "init") {
+ObjCMethod(null, false, ObjCInstanceType, listOf("new"), emptyList(), listOf("unavailable")) +ObjCMethod(null, false, ObjCInstanceType, listOf("new"), emptyList(), listOf("unavailable"))
@@ -598,13 +599,21 @@ internal class ObjCExportTranslatorImpl(
val getterSelector = getSelector(baseProperty.getter!!) val getterSelector = getSelector(baseProperty.getter!!)
val getterName: String? = if (getterSelector != name) getterSelector else null val getterName: String? = if (getterSelector != name) getterSelector else null
return ObjCProperty(name, property, type, attributes, setterName, getterName, listOf(swiftNameAttribute(name))) val declarationAttributes = mutableListOf(swiftNameAttribute(name))
declarationAttributes.addIfNotNull(mapper.getDeprecation(property)?.toDeprecationAttribute())
return ObjCProperty(name, property, type, attributes, setterName, getterName, declarationAttributes)
} }
private fun buildMethod(method: FunctionDescriptor, baseMethod: FunctionDescriptor, objCExportScope: ObjCExportScope): ObjCMethod { private fun buildMethod(
method: FunctionDescriptor,
baseMethod: FunctionDescriptor,
objCExportScope: ObjCExportScope,
unavailable: Boolean = false
): ObjCMethod {
fun collectParameters(baseMethodBridge: MethodBridge, method: FunctionDescriptor): List<ObjCParameter> { fun collectParameters(baseMethodBridge: MethodBridge, method: FunctionDescriptor): List<ObjCParameter> {
fun unifyName(initialName: String, usedNames: Set<String>): String { fun unifyName(initialName: String, usedNames: Set<String>): String {
var unique = initialName var unique = initialName.toValidObjCSwiftIdentifier()
while (unique in usedNames || unique in cKeywords) { while (unique in usedNames || unique in cKeywords) {
unique += "_" unique += "_"
} }
@@ -639,8 +648,14 @@ internal class ObjCExportTranslatorImpl(
MethodBridgeValueParameter.ErrorOutParameter -> MethodBridgeValueParameter.ErrorOutParameter ->
ObjCPointerType(ObjCNullableReferenceType(ObjCClassType("NSError")), nullable = true) ObjCPointerType(ObjCNullableReferenceType(ObjCClassType("NSError")), nullable = true)
is MethodBridgeValueParameter.KotlinResultOutParameter -> is MethodBridgeValueParameter.KotlinResultOutParameter -> {
ObjCPointerType(mapType(method.returnType!!, bridge.bridge, objCExportScope), nullable = true) val resultType = mapType(method.returnType!!, bridge.bridge, objCExportScope)
// Note: non-nullable reference or pointer type is unusable here
// when passing reference to local variable from Swift because it
// would require a non-null initializer then.
val pointeeType = resultType.makeNullableIfReferenceOrPointer()
ObjCPointerType(pointeeType, nullable = true)
}
} }
parameters += ObjCParameter(uniqueName, p, type) parameters += ObjCParameter(uniqueName, p, type)
@@ -666,6 +681,12 @@ internal class ObjCExportTranslatorImpl(
attributes += "objc_designated_initializer" attributes += "objc_designated_initializer"
} }
if (unavailable) {
attributes += "unavailable"
} else {
attributes.addIfNotNull(mapper.getDeprecation(method)?.toDeprecationAttribute())
}
return ObjCMethod(method, isInstanceMethod, returnType, selectorParts, parameters, attributes) return ObjCMethod(method, isInstanceMethod, returnType, selectorParts, parameters, attributes)
} }
@@ -783,8 +804,8 @@ internal class ObjCExportTranslatorImpl(
return mapObjCObjectReferenceTypeIgnoringNullability(classDescriptor) return mapObjCObjectReferenceTypeIgnoringNullability(classDescriptor)
} }
// Workaround for https://github.com/JetBrains/kotlin-native/issues/3053
if (!mapper.shouldBeExposed(classDescriptor)) { if (!mapper.shouldBeExposed(classDescriptor)) {
// There are number of tricky corner cases getting here.
return ObjCIdType return ObjCIdType
} }
@@ -889,7 +910,7 @@ internal class ObjCExportTranslatorImpl(
ObjCValueType.UNSIGNED_LONG_LONG -> ObjCPrimitiveType("uint64_t") ObjCValueType.UNSIGNED_LONG_LONG -> ObjCPrimitiveType("uint64_t")
ObjCValueType.FLOAT -> ObjCPrimitiveType("float") ObjCValueType.FLOAT -> ObjCPrimitiveType("float")
ObjCValueType.DOUBLE -> ObjCPrimitiveType("double") ObjCValueType.DOUBLE -> ObjCPrimitiveType("double")
ObjCValueType.POINTER -> ObjCPointerType(ObjCVoidType) ObjCValueType.POINTER -> ObjCPointerType(ObjCVoidType, kotlinType.binaryRepresentationIsNullable())
} }
// TODO: consider other namings. // TODO: consider other namings.
} }
@@ -977,6 +998,13 @@ abstract class ObjCExportHeaderGenerator internal constructor(
} }
add("NS_ASSUME_NONNULL_BEGIN") add("NS_ASSUME_NONNULL_BEGIN")
add("#pragma clang diagnostic push")
listOf(
"-Wunknown-warning-option",
"-Wnullability"
).forEach {
add("#pragma clang diagnostic ignored \"$it\"")
}
add("") add("")
stubs.forEach { stubs.forEach {
@@ -984,6 +1012,7 @@ abstract class ObjCExportHeaderGenerator internal constructor(
add("") add("")
} }
add("#pragma clang diagnostic pop")
add("NS_ASSUME_NONNULL_END") add("NS_ASSUME_NONNULL_END")
} }
@@ -1185,3 +1214,16 @@ internal fun Variance.objcDeclaration():String = when(this){
private fun computeSuperClassType(descriptor: ClassDescriptor): KotlinType? = descriptor.typeConstructor.supertypes.filter { !it.isInterface() }.firstOrNull() private fun computeSuperClassType(descriptor: ClassDescriptor): KotlinType? = descriptor.typeConstructor.supertypes.filter { !it.isInterface() }.firstOrNull()
internal const val OBJC_SUBCLASSING_RESTRICTED = "objc_subclassing_restricted" internal const val OBJC_SUBCLASSING_RESTRICTED = "objc_subclassing_restricted"
private fun Deprecation.toDeprecationAttribute(): String {
val attribute = when (deprecationLevel) {
DeprecationLevelValue.WARNING -> "deprecated"
DeprecationLevelValue.ERROR, DeprecationLevelValue.HIDDEN -> "unavailable"
}
// TODO: consider avoiding code generation for unavailable.
val message = this.message.orEmpty()
return "$attribute(\"$message\")"
}
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.BindingTraceContext import org.jetbrains.kotlin.resolve.BindingTraceContext
import org.jetbrains.kotlin.resolve.DescriptorResolver import org.jetbrains.kotlin.resolve.DescriptorResolver
import org.jetbrains.kotlin.resolve.TypeResolver import org.jetbrains.kotlin.resolve.TypeResolver
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.FileScopeProvider import org.jetbrains.kotlin.resolve.lazy.FileScopeProvider
import org.jetbrains.kotlin.resolve.lazy.ResolveSession import org.jetbrains.kotlin.resolve.lazy.ResolveSession
@@ -47,6 +48,7 @@ interface ObjCExportLazy {
fun translate(file: KtFile): List<ObjCTopLevel<*>> fun translate(file: KtFile): List<ObjCTopLevel<*>>
} }
@JvmOverloads
fun createObjCExportLazy( fun createObjCExportLazy(
configuration: ObjCExportLazy.Configuration, configuration: ObjCExportLazy.Configuration,
warningCollector: ObjCExportWarningCollector, warningCollector: ObjCExportWarningCollector,
@@ -54,7 +56,8 @@ fun createObjCExportLazy(
typeResolver: TypeResolver, typeResolver: TypeResolver,
descriptorResolver: DescriptorResolver, descriptorResolver: DescriptorResolver,
fileScopeProvider: FileScopeProvider, fileScopeProvider: FileScopeProvider,
builtIns: KotlinBuiltIns builtIns: KotlinBuiltIns,
deprecationResolver: DeprecationResolver? = null
): ObjCExportLazy = ObjCExportLazyImpl( ): ObjCExportLazy = ObjCExportLazyImpl(
configuration, configuration,
warningCollector, warningCollector,
@@ -62,7 +65,8 @@ fun createObjCExportLazy(
typeResolver, typeResolver,
descriptorResolver, descriptorResolver,
fileScopeProvider, fileScopeProvider,
builtIns builtIns,
deprecationResolver
) )
internal class ObjCExportLazyImpl( internal class ObjCExportLazyImpl(
@@ -72,14 +76,15 @@ internal class ObjCExportLazyImpl(
private val typeResolver: TypeResolver, private val typeResolver: TypeResolver,
private val descriptorResolver: DescriptorResolver, private val descriptorResolver: DescriptorResolver,
private val fileScopeProvider: FileScopeProvider, private val fileScopeProvider: FileScopeProvider,
builtIns: KotlinBuiltIns builtIns: KotlinBuiltIns,
deprecationResolver: DeprecationResolver?
) : ObjCExportLazy { ) : ObjCExportLazy {
private val namerConfiguration = createNamerConfiguration(configuration) private val namerConfiguration = createNamerConfiguration(configuration)
private val nameTranslator: ObjCExportNameTranslator = ObjCExportNameTranslatorImpl(namerConfiguration) private val nameTranslator: ObjCExportNameTranslator = ObjCExportNameTranslatorImpl(namerConfiguration)
private val mapper = ObjCExportMapper(local = true) private val mapper = ObjCExportMapper(deprecationResolver, local = true)
private val namer = ObjCExportNamerImpl(namerConfiguration, builtIns, mapper, local = true) private val namer = ObjCExportNamerImpl(namerConfiguration, builtIns, mapper, local = true)
@@ -99,7 +104,7 @@ internal class ObjCExportLazyImpl(
private fun translateClasses(container: KtDeclarationContainer): List<ObjCClass<*>> { private fun translateClasses(container: KtDeclarationContainer): List<ObjCClass<*>> {
val result = mutableListOf<ObjCClass<*>>() val result = mutableListOf<ObjCClass<*>>()
container.declarations.forEach { declaration -> container.declarations.forEach { declaration ->
// Supposed to be equivalent to ObjCExportMapper.shouldBeVisible. // Supposed to be true if ObjCExportMapper.shouldBeVisible is true.
if (declaration is KtClassOrObject && declaration.isPublic && declaration !is KtEnumEntry if (declaration is KtClassOrObject && declaration.isPublic && declaration !is KtEnumEntry
&& !declaration.hasExpectModifier()) { && !declaration.hasExpectModifier()) {
@@ -14,13 +14,19 @@ import org.jetbrains.kotlin.backend.konan.descriptors.isInterface
import org.jetbrains.kotlin.builtins.* import org.jetbrains.kotlin.builtins.*
import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.resolve.deprecation.Deprecation
import org.jetbrains.kotlin.resolve.deprecation.DeprecationLevelValue
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.* import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.isUnit
internal class ObjCExportMapper(private val local: Boolean = false) { internal class ObjCExportMapper(
internal val deprecationResolver: DeprecationResolver? = null,
private val local: Boolean = false
) {
companion object { companion object {
val maxFunctionTypeParameterCount get() = KONAN_FUNCTION_INTERFACES_MAX_PARAMETERS val maxFunctionTypeParameterCount get() = KONAN_FUNCTION_INTERFACES_MAX_PARAMETERS
} }
@@ -69,17 +75,66 @@ internal fun ObjCExportMapper.getClassIfCategory(extensionReceiverType: KotlinTy
// Note: partially duplicated in ObjCExportLazyImpl.translateTopLevels. // Note: partially duplicated in ObjCExportLazyImpl.translateTopLevels.
internal fun ObjCExportMapper.shouldBeExposed(descriptor: CallableMemberDescriptor): Boolean = internal fun ObjCExportMapper.shouldBeExposed(descriptor: CallableMemberDescriptor): Boolean =
descriptor.isEffectivelyPublicApi && !descriptor.isSuspend && !descriptor.isExpect descriptor.isEffectivelyPublicApi && !descriptor.isSuspend && !descriptor.isExpect &&
!isHiddenByDeprecation(descriptor)
internal fun ObjCExportMapper.shouldBeExposed(descriptor: ClassDescriptor): Boolean = internal fun ObjCExportMapper.shouldBeExposed(descriptor: ClassDescriptor): Boolean =
shouldBeVisible(descriptor) && !isSpecialMapped(descriptor) && !descriptor.defaultType.isObjCObjectType() shouldBeVisible(descriptor) && !isSpecialMapped(descriptor) && !descriptor.defaultType.isObjCObjectType()
// Note: the logic is duplicated in ObjCExportLazyImpl.translateClasses. private fun ObjCExportMapper.isHiddenByDeprecation(descriptor: CallableMemberDescriptor): Boolean {
// Note: ObjCExport generally expect overrides of exposed methods to be exposed.
// So don't hide a "deprecated hidden" method which overrides non-hidden one:
if (deprecationResolver != null && deprecationResolver.isDeprecatedHidden(descriptor) &&
descriptor.overriddenDescriptors.all { isHiddenByDeprecation(it) }) {
return true
}
// Note: ObjCExport expects members of unexposed classes to be unexposed too.
// So hide a declaration if it is from a hidden class:
val containingDeclaration = descriptor.containingDeclaration
if (containingDeclaration is ClassDescriptor && isHiddenByDeprecation(containingDeclaration)) {
return true
}
return false
}
internal fun ObjCExportMapper.getDeprecation(descriptor: DeclarationDescriptor): Deprecation? {
deprecationResolver?.getDeprecations(descriptor).orEmpty().maxBy {
when (it.deprecationLevel) {
DeprecationLevelValue.WARNING -> 1
DeprecationLevelValue.ERROR -> 2
DeprecationLevelValue.HIDDEN -> 3
}
}?.let { return it }
(descriptor as? ConstructorDescriptor)?.let {
// Note: a deprecation can't be applied to a class itself when generating header
// since the class can be referred from the header.
// Apply class deprecations to its constructors instead:
return getDeprecation(it.constructedClass)
}
return null
}
private tailrec fun ObjCExportMapper.isHiddenByDeprecation(descriptor: ClassDescriptor): Boolean {
if (deprecationResolver == null) return false
if (deprecationResolver.isDeprecatedHidden(descriptor)) return true
val superClass = descriptor.getSuperClassNotAny() ?: return false
// Note: ObjCExport requires super class of exposed class to be exposed.
// So hide a class if its super class is hidden:
return isHiddenByDeprecation(superClass)
}
// Note: the logic is partially duplicated in ObjCExportLazyImpl.translateClasses.
internal fun ObjCExportMapper.shouldBeVisible(descriptor: ClassDescriptor): Boolean = internal fun ObjCExportMapper.shouldBeVisible(descriptor: ClassDescriptor): Boolean =
descriptor.isEffectivelyPublicApi && when (descriptor.kind) { descriptor.isEffectivelyPublicApi && when (descriptor.kind) {
ClassKind.CLASS, ClassKind.INTERFACE, ClassKind.ENUM_CLASS, ClassKind.OBJECT -> true ClassKind.CLASS, ClassKind.INTERFACE, ClassKind.ENUM_CLASS, ClassKind.OBJECT -> true
ClassKind.ENUM_ENTRY, ClassKind.ANNOTATION_CLASS -> false ClassKind.ENUM_ENTRY, ClassKind.ANNOTATION_CLASS -> false
} && !descriptor.isExpect && !descriptor.isInlined() } && !descriptor.isExpect && !descriptor.isInlined() && !isHiddenByDeprecation(descriptor)
private fun ObjCExportMapper.isBase(descriptor: CallableMemberDescriptor): Boolean = private fun ObjCExportMapper.isBase(descriptor: CallableMemberDescriptor): Boolean =
descriptor.overriddenDescriptors.all { !shouldBeExposed(it) } descriptor.overriddenDescriptors.all { !shouldBeExposed(it) }
@@ -96,6 +96,7 @@ internal open class ObjCExportNameTranslatorImpl(
private fun getClassOrProtocolSwiftName( private fun getClassOrProtocolSwiftName(
ktClassOrObject: KtClassOrObject ktClassOrObject: KtClassOrObject
): String = buildString { ): String = buildString {
val ownName = ktClassOrObject.name!!.toIdentifier()
val outerClass = ktClassOrObject.getStrictParentOfType<KtClassOrObject>() val outerClass = ktClassOrObject.getStrictParentOfType<KtClassOrObject>()
if (outerClass != null) { if (outerClass != null) {
append(getClassOrProtocolSwiftName(outerClass)) append(getClassOrProtocolSwiftName(outerClass))
@@ -119,12 +120,12 @@ internal open class ObjCExportNameTranslatorImpl(
} }
if (importAsMember) { if (importAsMember) {
append(".").append(ktClassOrObject.name!!) append(".").append(ownName)
} else { } else {
append(ktClassOrObject.name!!.capitalize()) append(ownName.capitalize())
} }
} else { } else {
append(ktClassOrObject.name) append(ownName)
} }
} }
} }
@@ -133,7 +134,8 @@ private class ObjCExportNamingHelper(
private val topLevelNamePrefix: String private val topLevelNamePrefix: String
) { ) {
fun translateFileName(fileName: String): String = PackagePartClassUtils.getFilePartShortName(fileName) fun translateFileName(fileName: String): String =
PackagePartClassUtils.getFilePartShortName(fileName).toIdentifier()
fun translateFileName(file: KtFile): String = translateFileName(file.name) fun translateFileName(file: KtFile): String = translateFileName(file.name)
@@ -328,10 +330,11 @@ internal class ObjCExportNamerImpl(
else -> true else -> true
} }
val ownName = descriptor.name.asString().toIdentifier()
if (importAsMember) { if (importAsMember) {
append(".").append(descriptor.name.asString()) append(".").append(ownName)
} else { } else {
append(descriptor.name.asString().capitalize()) append(ownName.capitalize())
} }
} else if (containingDeclaration is PackageFragmentDescriptor) { } else if (containingDeclaration is PackageFragmentDescriptor) {
appendTopLevelClassBaseName(descriptor) appendTopLevelClassBaseName(descriptor)
@@ -364,7 +367,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().capitalize()) .append(descriptor.name.asString().toIdentifier().capitalize())
} else if (containingDeclaration is PackageFragmentDescriptor) { } else if (containingDeclaration is PackageFragmentDescriptor) {
append(topLevelNamePrefix).appendTopLevelClassBaseName(descriptor) append(topLevelNamePrefix).appendTopLevelClassBaseName(descriptor)
@@ -379,7 +382,7 @@ internal class ObjCExportNamerImpl(
configuration.getAdditionalPrefix(descriptor.module)?.let { configuration.getAdditionalPrefix(descriptor.module)?.let {
append(it) append(it)
} }
append(descriptor.name.asString()) append(descriptor.name.asString().toIdentifier())
} }
override fun getSelector(method: FunctionDescriptor): String = methodSelectors.getOrPut(method) { override fun getSelector(method: FunctionDescriptor): String = methodSelectors.getOrPut(method) {
@@ -400,7 +403,7 @@ internal class ObjCExportNamerImpl(
1 -> "" 1 -> ""
else -> "value" else -> "value"
} }
else -> it!!.name.asString() else -> it!!.name.asString().toIdentifier()
} }
MethodBridgeValueParameter.ErrorOutParameter -> "error" MethodBridgeValueParameter.ErrorOutParameter -> "error"
is MethodBridgeValueParameter.KotlinResultOutParameter -> "result" is MethodBridgeValueParameter.KotlinResultOutParameter -> "result"
@@ -451,7 +454,7 @@ internal class ObjCExportNamerImpl(
1 -> "_" 1 -> "_"
else -> "value" else -> "value"
} }
else -> it!!.name.asString() else -> it!!.name.asString().toIdentifier()
} }
MethodBridgeValueParameter.ErrorOutParameter -> continue@parameters MethodBridgeValueParameter.ErrorOutParameter -> continue@parameters
is MethodBridgeValueParameter.KotlinResultOutParameter -> "result" is MethodBridgeValueParameter.KotlinResultOutParameter -> "result"
@@ -482,7 +485,7 @@ internal class ObjCExportNamerImpl(
assert(mapper.isObjCProperty(property)) assert(mapper.isObjCProperty(property))
StringBuilder().apply { StringBuilder().apply {
append(property.name.asString()) append(property.name.asString().toIdentifier())
}.mangledSequence { }.mangledSequence {
append('_') append('_')
} }
@@ -492,7 +495,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().mangleIfSpecialFamily("get") val name = descriptor.name.asString().decapitalize().toIdentifier().mangleIfSpecialFamily("get")
StringBuilder(name).mangledBySuffixUnderscores() StringBuilder(name).mangledBySuffixUnderscores()
} }
@@ -506,7 +509,7 @@ internal class ObjCExportNamerImpl(
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.toLowerCase()
if (index == 0) lower else lower.capitalize() if (index == 0) lower else lower.capitalize()
}.joinToString("").mangleIfSpecialFamily("the") }.joinToString("").toIdentifier().mangleIfSpecialFamily("the")
StringBuilder(name).mangledBySuffixUnderscores() StringBuilder(name).mangledBySuffixUnderscores()
} }
@@ -515,7 +518,7 @@ internal class ObjCExportNamerImpl(
override fun getTypeParameterName(typeParameterDescriptor: TypeParameterDescriptor): String { override fun getTypeParameterName(typeParameterDescriptor: TypeParameterDescriptor): String {
return genericTypeParameterNameMapping.getOrPut(typeParameterDescriptor) { return genericTypeParameterNameMapping.getOrPut(typeParameterDescriptor) {
StringBuilder().apply { StringBuilder().apply {
append(typeParameterDescriptor.name.asString()) append(typeParameterDescriptor.name.asString().toIdentifier())
}.mangledSequence { }.mangledSequence {
append('_') append('_')
} }
@@ -580,7 +583,7 @@ internal class ObjCExportNamerImpl(
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().capitalize()}"
else -> this.name.asString() else -> this.name.asString()
} }.toIdentifier()
return candidate.mangleIfSpecialFamily("do") return candidate.mangleIfSpecialFamily("do")
} }
@@ -802,6 +805,10 @@ private fun ObjCExportMapper.canHaveSameName(first: PropertyDescriptor, second:
return false return false
} }
if (first.name != second.name) {
return false
}
return bridgePropertyType(first) == bridgePropertyType(second) return bridgePropertyType(first) == bridgePropertyType(second)
} }
@@ -821,3 +828,17 @@ internal fun abbreviate(name: String): String {
return normalizedName return normalizedName
} }
// Note: most usages of this method rely on the fact that concatenation of valid identifiers is valid identifier.
// This may sometimes be a bit conservative (since it requires mangling non-first character as if it was first);
// ignore this for simplicity as having Kotlin identifiers starting from digits is supposed to be rare case.
internal fun String.toValidObjCSwiftIdentifier(): String {
if (this.isEmpty()) return "__"
return this.replace('$', '_') // TODO: handle more special characters.
.let { if (it.first().isDigit()) "_$it" else it }
.let { if (it == "_") "__" else it }
}
// Private shortcut.
private fun String.toIdentifier(): String = this.toValidObjCSwiftIdentifier()
@@ -130,3 +130,11 @@ internal enum class ObjCValueType(val encoding: String) {
DOUBLE("d"), DOUBLE("d"),
POINTER("^v") POINTER("^v")
} }
internal fun ObjCType.makeNullableIfReferenceOrPointer(): ObjCType = when (this) {
is ObjCPointerType -> ObjCPointerType(this.pointee, nullable = true)
is ObjCNonNullReferenceType -> ObjCNullableReferenceType(this)
is ObjCNullableReferenceType, is ObjCRawType, is ObjCPrimitiveType, ObjCVoidType -> this
}
@@ -1413,12 +1413,13 @@ internal object Devirtualization {
val newSymbol = IrReturnableBlockSymbolImpl(expression.descriptor) val newSymbol = IrReturnableBlockSymbolImpl(expression.descriptor)
val transformedReturnableBlock = with(expression) { val transformedReturnableBlock = with(expression) {
IrReturnableBlockImpl( IrReturnableBlockImpl(
startOffset = startOffset, startOffset = startOffset,
endOffset = endOffset, endOffset = endOffset,
type = coercion.type, type = coercion.type,
symbol = newSymbol, symbol = newSymbol,
origin = origin, origin = origin,
statements = statements) statements = statements,
inlineFunctionSymbol = inlineFunctionSymbol)
} }
transformedReturnableBlock.transformChildrenVoid(object: IrElementTransformerVoid() { transformedReturnableBlock.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitExpression(expression: IrExpression): IrExpression { override fun visitExpression(expression: IrExpression): IrExpression {
+12
View File
@@ -127,6 +127,12 @@ task installTestLibrary(type: KlibInstall) {
dependsOn compileKonanTestLibraryHost dependsOn compileKonanTestLibraryHost
klib = konanArtifacts.testLibrary.getArtifactByTarget('host') klib = konanArtifacts.testLibrary.getArtifactByTarget('host')
repo = rootProject.file(testLibraryDir) repo = rootProject.file(testLibraryDir)
doLast {
// Remove the version in build/, so that we don't link two copies.
def file = project.file("build/konan/libs/${project.target.name}/testLibrary.klib")
file.delete()
}
} }
// Gets tests from the same Kotlin compiler build // Gets tests from the same Kotlin compiler build
@@ -370,6 +376,12 @@ task slackReportNightly(type:NightlyReporter) {
externalWindowsReport = "external_windows_results/reports.json" externalWindowsReport = "external_windows_results/reports.json"
} }
linkTest("localDelegatedPropertyLink") {
goldValue = "OK\n"
source = "lower/local_delegated_property_link/main.kt"
lib = "lower/local_delegated_property_link/lib.kt"
}
task sum(type: KonanLocalTest) { task sum(type: KonanLocalTest) {
source = "codegen/function/sum.kt" source = "codegen/function/sum.kt"
} }
@@ -297,7 +297,7 @@ __attribute__((swift_name("Bridge")))
- (ValuesKotlinNothing * _Nullable)foo1AndReturnError:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo1()"))); - (ValuesKotlinNothing * _Nullable)foo1AndReturnError:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo1()")));
- (BOOL)foo2AndReturnResult:(int32_t * _Nullable)result error:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo2(result:)"))); - (BOOL)foo2AndReturnResult:(int32_t * _Nullable)result error:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo2(result:)")));
- (BOOL)foo3AndReturnError:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo3()"))); - (BOOL)foo3AndReturnError:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo3()")));
- (BOOL)foo4AndReturnResult:(ValuesKotlinNothing ** _Nullable)result error:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo4(result:)"))); - (BOOL)foo4AndReturnResult:(ValuesKotlinNothing * _Nullable * _Nullable)result error:(NSError * _Nullable * _Nullable)error __attribute__((swift_name("foo4(result:)")));
@end; @end;
__attribute__((objc_subclassing_restricted)) __attribute__((objc_subclassing_restricted))
@@ -571,6 +571,294 @@ __attribute__((swift_name("TestSR10177Workaround")))
@required @required
@end; @end;
__attribute__((swift_name("TestClashes1")))
@protocol ValuesTestClashes1
@required
@property (readonly) int32_t clashingProperty __attribute__((swift_name("clashingProperty")));
@end;
__attribute__((swift_name("TestClashes2")))
@protocol ValuesTestClashes2
@required
@property (readonly) id clashingProperty __attribute__((swift_name("clashingProperty")));
@property (readonly) id clashingProperty_ __attribute__((swift_name("clashingProperty_")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestClashesImpl")))
@interface ValuesTestClashesImpl : KotlinBase <ValuesTestClashes1, ValuesTestClashes2>
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@property (readonly) int32_t clashingProperty __attribute__((swift_name("clashingProperty")));
@property (readonly) ValuesInt *clashingProperty_ __attribute__((swift_name("clashingProperty_")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestInvalidIdentifiers")))
@interface ValuesTestInvalidIdentifiers : KotlinBase
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (int32_t)a_d_d_1:(int32_t)_1 _2:(int32_t)_2 _3:(int32_t)_3 __attribute__((swift_name("a_d_d(_1:_2:_3:)")));
@property NSString *_status __attribute__((swift_name("_status")));
@property (readonly) unichar __ __attribute__((swift_name("__")));
@property (readonly) unichar __ __attribute__((swift_name("__")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestInvalidIdentifiers._Foo")))
@interface ValuesTestInvalidIdentifiers_Foo : KotlinBase
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestInvalidIdentifiers.Bar_")))
@interface ValuesTestInvalidIdentifiersBar_ : KotlinBase
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestInvalidIdentifiers.E")))
@interface ValuesTestInvalidIdentifiersE : ValuesKotlinEnum
+ (instancetype)alloc __attribute__((unavailable));
+ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable));
@property (class, readonly) ValuesTestInvalidIdentifiersE *_4_ __attribute__((swift_name("_4_")));
@property (class, readonly) ValuesTestInvalidIdentifiersE *_5_ __attribute__((swift_name("_5_")));
@property (class, readonly) ValuesTestInvalidIdentifiersE *__ __attribute__((swift_name("__")));
@property (class, readonly) ValuesTestInvalidIdentifiersE *__ __attribute__((swift_name("__")));
- (instancetype)initWithName:(NSString *)name ordinal:(int32_t)ordinal __attribute__((swift_name("init(name:ordinal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (int32_t)compareToOther:(ValuesTestInvalidIdentifiersE *)other __attribute__((swift_name("compareTo(other:)")));
@property (readonly) int32_t value __attribute__((swift_name("value")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestInvalidIdentifiers.Companion_")))
@interface ValuesTestInvalidIdentifiersCompanion_ : KotlinBase
+ (instancetype)alloc __attribute__((unavailable));
+ (instancetype)allocWithZone:(struct _NSZone *)zone __attribute__((unavailable));
+ (instancetype)companion_ __attribute__((swift_name("init()")));
@property (readonly) int32_t _42 __attribute__((swift_name("_42")));
@end;
__attribute__((swift_name("TestDeprecation")))
@interface ValuesTestDeprecation : KotlinBase
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer));
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (int32_t)callEffectivelyHiddenObj:(id)obj __attribute__((swift_name("callEffectivelyHidden(obj:)")));
- (id)getHidden __attribute__((swift_name("getHidden()")));
- (ValuesTestDeprecationError *)getError __attribute__((swift_name("getError()")));
- (void)error __attribute__((swift_name("error()"))) __attribute__((unavailable("error")));
- (void)openError __attribute__((swift_name("openError()"))) __attribute__((unavailable("error")));
- (ValuesTestDeprecationWarning *)getWarning __attribute__((swift_name("getWarning()")));
- (void)warning __attribute__((swift_name("warning()"))) __attribute__((deprecated("warning")));
- (void)openWarning __attribute__((swift_name("openWarning()"))) __attribute__((deprecated("warning")));
- (void)normal __attribute__((swift_name("normal()")));
- (int32_t)openNormal __attribute__((swift_name("openNormal()")));
@property (readonly) id _Nullable errorVal __attribute__((swift_name("errorVal"))) __attribute__((unavailable("error")));
@property id _Nullable errorVar __attribute__((swift_name("errorVar"))) __attribute__((unavailable("error")));
@property (readonly) id _Nullable openErrorVal __attribute__((swift_name("openErrorVal"))) __attribute__((unavailable("error")));
@property id _Nullable openErrorVar __attribute__((swift_name("openErrorVar"))) __attribute__((unavailable("error")));
@property (readonly) id _Nullable warningVal __attribute__((swift_name("warningVal"))) __attribute__((deprecated("warning")));
@property id _Nullable warningVar __attribute__((swift_name("warningVar"))) __attribute__((deprecated("warning")));
@property (readonly) id _Nullable openWarningVal __attribute__((swift_name("openWarningVal"))) __attribute__((deprecated("warning")));
@property id _Nullable openWarningVar __attribute__((swift_name("openWarningVar"))) __attribute__((deprecated("warning")));
@property (readonly) id _Nullable normalVal __attribute__((swift_name("normalVal")));
@property id _Nullable normalVar __attribute__((swift_name("normalVar")));
@property (readonly) id _Nullable openNormalVal __attribute__((swift_name("openNormalVal")));
@property id _Nullable openNormalVar __attribute__((swift_name("openNormalVar")));
@end;
__attribute__((swift_name("TestDeprecation.OpenHidden")))
@interface ValuesTestDeprecationOpenHidden : NSObject
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.ExtendingHidden")))
@interface ValuesTestDeprecationExtendingHidden : NSObject
@end;
__attribute__((swift_name("TestDeprecationHiddenInterface")))
@protocol ValuesTestDeprecationHiddenInterface
@required
@end;
__attribute__((swift_name("TestDeprecation.ImplementingHidden")))
@interface ValuesTestDeprecationImplementingHidden : KotlinBase
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (int32_t)effectivelyHidden __attribute__((swift_name("effectivelyHidden()")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.Hidden")))
@interface ValuesTestDeprecationHidden : NSObject
@end;
__attribute__((swift_name("TestDeprecation.OpenError")))
@interface ValuesTestDeprecationOpenError : ValuesTestDeprecation
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.ExtendingError")))
@interface ValuesTestDeprecationExtendingError : ValuesTestDeprecationOpenError
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@end;
__attribute__((swift_name("TestDeprecationErrorInterface")))
@protocol ValuesTestDeprecationErrorInterface
@required
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.ImplementingError")))
@interface ValuesTestDeprecationImplementingError : KotlinBase <ValuesTestDeprecationErrorInterface>
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.Error")))
@interface ValuesTestDeprecationError : ValuesTestDeprecation
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
@end;
__attribute__((swift_name("TestDeprecation.OpenWarning")))
@interface ValuesTestDeprecationOpenWarning : ValuesTestDeprecation
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.ExtendingWarning")))
@interface ValuesTestDeprecationExtendingWarning : ValuesTestDeprecationOpenWarning
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@end;
__attribute__((swift_name("TestDeprecationWarningInterface")))
@protocol ValuesTestDeprecationWarningInterface
@required
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.ImplementingWarning")))
@interface ValuesTestDeprecationImplementingWarning : KotlinBase <ValuesTestDeprecationWarningInterface>
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.Warning")))
@interface ValuesTestDeprecationWarning : ValuesTestDeprecation
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.HiddenOverride")))
@interface ValuesTestDeprecationHiddenOverride : ValuesTestDeprecation
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable));
- (void)openError __attribute__((swift_name("openError()"))) __attribute__((unavailable("hidden")));
- (void)openWarning __attribute__((swift_name("openWarning()"))) __attribute__((unavailable("hidden")));
- (int32_t)openNormal __attribute__((swift_name("openNormal()"))) __attribute__((unavailable("hidden")));
@property (readonly) id _Nullable openErrorVal __attribute__((swift_name("openErrorVal"))) __attribute__((unavailable("hidden")));
@property id _Nullable openErrorVar __attribute__((swift_name("openErrorVar"))) __attribute__((unavailable("hidden")));
@property (readonly) id _Nullable openWarningVal __attribute__((swift_name("openWarningVal"))) __attribute__((unavailable("hidden")));
@property id _Nullable openWarningVar __attribute__((swift_name("openWarningVar"))) __attribute__((unavailable("hidden")));
@property (readonly) id _Nullable openNormalVal __attribute__((swift_name("openNormalVal"))) __attribute__((unavailable("hidden")));
@property id _Nullable openNormalVar __attribute__((swift_name("openNormalVar"))) __attribute__((unavailable("hidden")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.ErrorOverride")))
@interface ValuesTestDeprecationErrorOverride : ValuesTestDeprecation
- (instancetype)initWithHidden:(int8_t)hidden __attribute__((swift_name("init(hidden:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((unavailable("error")));
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (void)openHidden __attribute__((swift_name("openHidden()"))) __attribute__((unavailable("error")));
- (void)openError __attribute__((swift_name("openError()"))) __attribute__((unavailable("error")));
- (void)openWarning __attribute__((swift_name("openWarning()"))) __attribute__((unavailable("error")));
- (int32_t)openNormal __attribute__((swift_name("openNormal()"))) __attribute__((unavailable("error")));
@property (readonly) id _Nullable openHiddenVal __attribute__((swift_name("openHiddenVal"))) __attribute__((unavailable("error")));
@property id _Nullable openHiddenVar __attribute__((swift_name("openHiddenVar"))) __attribute__((unavailable("error")));
@property (readonly) id _Nullable openErrorVal __attribute__((swift_name("openErrorVal"))) __attribute__((unavailable("error")));
@property id _Nullable openErrorVar __attribute__((swift_name("openErrorVar"))) __attribute__((unavailable("error")));
@property (readonly) id _Nullable openWarningVal __attribute__((swift_name("openWarningVal"))) __attribute__((unavailable("error")));
@property id _Nullable openWarningVar __attribute__((swift_name("openWarningVar"))) __attribute__((unavailable("error")));
@property (readonly) id _Nullable openNormalVal __attribute__((swift_name("openNormalVal"))) __attribute__((unavailable("error")));
@property id _Nullable openNormalVar __attribute__((swift_name("openNormalVar"))) __attribute__((unavailable("error")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.WarningOverride")))
@interface ValuesTestDeprecationWarningOverride : ValuesTestDeprecation
- (instancetype)initWithHidden:(int8_t)hidden __attribute__((swift_name("init(hidden:)"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer)) __attribute__((deprecated("warning")));
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (void)openHidden __attribute__((swift_name("openHidden()"))) __attribute__((deprecated("warning")));
- (void)openError __attribute__((swift_name("openError()"))) __attribute__((deprecated("warning")));
- (void)openWarning __attribute__((swift_name("openWarning()"))) __attribute__((deprecated("warning")));
- (int32_t)openNormal __attribute__((swift_name("openNormal()"))) __attribute__((deprecated("warning")));
@property (readonly) id _Nullable openHiddenVal __attribute__((swift_name("openHiddenVal"))) __attribute__((deprecated("warning")));
@property id _Nullable openHiddenVar __attribute__((swift_name("openHiddenVar"))) __attribute__((deprecated("warning")));
@property (readonly) id _Nullable openErrorVal __attribute__((swift_name("openErrorVal"))) __attribute__((deprecated("warning")));
@property id _Nullable openErrorVar __attribute__((swift_name("openErrorVar"))) __attribute__((deprecated("warning")));
@property (readonly) id _Nullable openWarningVal __attribute__((swift_name("openWarningVal"))) __attribute__((deprecated("warning")));
@property id _Nullable openWarningVar __attribute__((swift_name("openWarningVar"))) __attribute__((deprecated("warning")));
@property (readonly) id _Nullable openNormalVal __attribute__((swift_name("openNormalVal"))) __attribute__((deprecated("warning")));
@property id _Nullable openNormalVar __attribute__((swift_name("openNormalVar"))) __attribute__((deprecated("warning")));
@end;
__attribute__((objc_subclassing_restricted))
__attribute__((swift_name("TestDeprecation.NormalOverride")))
@interface ValuesTestDeprecationNormalOverride : ValuesTestDeprecation
- (instancetype)initWithHidden:(int8_t)hidden __attribute__((swift_name("init(hidden:)"))) __attribute__((objc_designated_initializer));
- (instancetype)initWithError:(int16_t)error __attribute__((swift_name("init(error:)"))) __attribute__((objc_designated_initializer));
- (instancetype)initWithWarning:(int32_t)warning __attribute__((swift_name("init(warning:)"))) __attribute__((objc_designated_initializer));
- (instancetype)initWithNormal:(int64_t)normal __attribute__((swift_name("init(normal:)"))) __attribute__((objc_designated_initializer));
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (void)openError __attribute__((swift_name("openError()"))) __attribute__((unavailable("Overrides deprecated member in 'conversions.TestDeprecation'. error")));
- (void)openWarning __attribute__((swift_name("openWarning()"))) __attribute__((deprecated("Overrides deprecated member in 'conversions.TestDeprecation'. warning")));
- (int32_t)openNormal __attribute__((swift_name("openNormal()")));
@property (readonly) id _Nullable openErrorVal __attribute__((swift_name("openErrorVal"))) __attribute__((unavailable("Overrides deprecated member in 'conversions.TestDeprecation'. error")));
@property id _Nullable openErrorVar __attribute__((swift_name("openErrorVar"))) __attribute__((unavailable("Overrides deprecated member in 'conversions.TestDeprecation'. error")));
@property (readonly) id _Nullable openWarningVal __attribute__((swift_name("openWarningVal"))) __attribute__((deprecated("Overrides deprecated member in 'conversions.TestDeprecation'. warning")));
@property id _Nullable openWarningVar __attribute__((swift_name("openWarningVar"))) __attribute__((deprecated("Overrides deprecated member in 'conversions.TestDeprecation'. warning")));
@property (readonly) id _Nullable openNormalVal __attribute__((swift_name("openNormalVal")));
@property id _Nullable openNormalVar __attribute__((swift_name("openNormalVar")));
@end;
@interface ValuesEnumeration (ValuesKt) @interface ValuesEnumeration (ValuesKt)
- (ValuesEnumeration *)getAnswer __attribute__((swift_name("getAnswer()"))); - (ValuesEnumeration *)getAnswer __attribute__((swift_name("getAnswer()")));
@end; @end;
@@ -647,6 +935,8 @@ __attribute__((swift_name("ValuesKt")))
+ (BOOL)isBlockNullBlock:(void (^ _Nullable)(void))block __attribute__((swift_name("isBlockNull(block:)"))); + (BOOL)isBlockNullBlock:(void (^ _Nullable)(void))block __attribute__((swift_name("isBlockNull(block:)")));
+ (void)takeForwardDeclaredClassObj:(ForwardDeclaredClass *)obj __attribute__((swift_name("takeForwardDeclaredClass(obj:)"))); + (void)takeForwardDeclaredClassObj:(ForwardDeclaredClass *)obj __attribute__((swift_name("takeForwardDeclaredClass(obj:)")));
+ (void)takeForwardDeclaredProtocolObj:(id<ForwardDeclared>)obj __attribute__((swift_name("takeForwardDeclaredProtocol(obj:)"))); + (void)takeForwardDeclaredProtocolObj:(id<ForwardDeclared>)obj __attribute__((swift_name("takeForwardDeclaredProtocol(obj:)")));
+ (void)error __attribute__((swift_name("error()"))) __attribute__((unavailable("error")));
+ (void)warning __attribute__((swift_name("warning()"))) __attribute__((deprecated("warning")));
@property (class, readonly) double dbl __attribute__((swift_name("dbl"))); @property (class, readonly) double dbl __attribute__((swift_name("dbl")));
@property (class, readonly) float flt __attribute__((swift_name("flt"))); @property (class, readonly) float flt __attribute__((swift_name("flt")));
@property (class, readonly) int32_t integer __attribute__((swift_name("integer"))); @property (class, readonly) int32_t integer __attribute__((swift_name("integer")));
@@ -673,5 +963,9 @@ __attribute__((swift_name("ValuesKt")))
@property (class) id anyValue __attribute__((swift_name("anyValue"))); @property (class) id anyValue __attribute__((swift_name("anyValue")));
@property (class, readonly) ValuesInt *(^sumLambda)(ValuesInt *, ValuesInt *) __attribute__((swift_name("sumLambda"))); @property (class, readonly) ValuesInt *(^sumLambda)(ValuesInt *, ValuesInt *) __attribute__((swift_name("sumLambda")));
@property (class, readonly) int32_t PROPERTY_NAME_MUST_NOT_BE_ALTERED_BY_SWIFT __attribute__((swift_name("PROPERTY_NAME_MUST_NOT_BE_ALTERED_BY_SWIFT"))); @property (class, readonly) int32_t PROPERTY_NAME_MUST_NOT_BE_ALTERED_BY_SWIFT __attribute__((swift_name("PROPERTY_NAME_MUST_NOT_BE_ALTERED_BY_SWIFT")));
@property (class, readonly) id _Nullable errorVal __attribute__((swift_name("errorVal"))) __attribute__((unavailable("error")));
@property (class) id _Nullable errorVar __attribute__((swift_name("errorVar"))) __attribute__((unavailable("error")));
@property (class, readonly) id _Nullable warningVal __attribute__((swift_name("warningVal"))) __attribute__((deprecated("warning")));
@property (class) id _Nullable warningVar __attribute__((swift_name("warningVar"))) __attribute__((deprecated("warning")));
@end; @end;
+211 -1
View File
@@ -450,4 +450,214 @@ abstract class ForwardC1 {
abstract fun getForwardC2(): ForwardC2 abstract fun getForwardC2(): ForwardC2
} }
interface TestSR10177Workaround interface TestSR10177Workaround
interface TestClashes1 {
val clashingProperty: Int
}
interface TestClashes2 {
val clashingProperty: Any
val clashingProperty_: Any
}
class TestClashesImpl : TestClashes1, TestClashes2 {
override val clashingProperty: Int
get() = 1
override val clashingProperty_: Int
get() = 2
}
class TestInvalidIdentifiers {
class `$Foo`
class `Bar$`
fun `a$d$d`(`$1`: Int, `2`: Int, `3`: Int): Int = `$1` + `2` + `3`
var `$status`: String = ""
enum class E(val value: Int) {
`4$`(4),
`5$`(5),
`_`(6),
`__`(7)
}
companion object `Companion$` {
val `42` = 42
}
val `$` = '$'
val `_` = '_'
}
@Suppress("UNUSED_PARAMETER")
open class TestDeprecation() {
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) open class OpenHidden : TestDeprecation()
@Suppress("DEPRECATION_ERROR") class ExtendingHidden : OpenHidden()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) interface HiddenInterface {
fun effectivelyHidden(): Any
}
@Suppress("DEPRECATION_ERROR") open class ImplementingHidden : Any(), HiddenInterface {
override fun effectivelyHidden(): Int = -1
}
@Suppress("DEPRECATION_ERROR")
fun callEffectivelyHidden(obj: Any): Int = (obj as HiddenInterface).effectivelyHidden() as Int
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) class Hidden : TestDeprecation()
@Suppress("DEPRECATION_ERROR") fun getHidden() = Hidden()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(hidden: Byte) : this()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hidden() {}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) val hiddenVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) var hiddenVar: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) open fun openHidden() {}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) open val openHiddenVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) open var openHiddenVar: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) open class OpenError : TestDeprecation()
@Suppress("DEPRECATION_ERROR") class ExtendingError : OpenError()
@Deprecated("error", level = DeprecationLevel.ERROR) interface ErrorInterface
@Suppress("DEPRECATION_ERROR") class ImplementingError : ErrorInterface
@Deprecated("error", level = DeprecationLevel.ERROR) class Error : TestDeprecation()
@Suppress("DEPRECATION_ERROR") fun getError() = Error()
@Deprecated("error", level = DeprecationLevel.ERROR) constructor(error: Short) : this()
@Deprecated("error", level = DeprecationLevel.ERROR) fun error() {}
@Deprecated("error", level = DeprecationLevel.ERROR) val errorVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) var errorVar: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) open fun openError() {}
@Deprecated("error", level = DeprecationLevel.ERROR) open val openErrorVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) open var openErrorVar: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) open class OpenWarning : TestDeprecation()
@Suppress("DEPRECATION") class ExtendingWarning : OpenWarning()
@Deprecated("warning", level = DeprecationLevel.WARNING) interface WarningInterface
@Suppress("DEPRECATION") class ImplementingWarning : WarningInterface
@Deprecated("warning", level = DeprecationLevel.WARNING) class Warning : TestDeprecation()
@Suppress("DEPRECATION") fun getWarning() = Warning()
@Deprecated("warning", level = DeprecationLevel.WARNING) constructor(warning: Int) : this()
@Deprecated("warning", level = DeprecationLevel.WARNING) fun warning() {}
@Deprecated("warning", level = DeprecationLevel.WARNING) val warningVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) var warningVar: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) open fun openWarning() {}
@Deprecated("warning", level = DeprecationLevel.WARNING) open val openWarningVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) open var openWarningVar: Any? = null
constructor(normal: Long) : this()
fun normal() {}
val normalVal: Any? = null
var normalVar: Any? = null
open fun openNormal(): Int = 1
open val openNormalVal: Any? = null
open var openNormalVar: Any? = null
class HiddenOverride() : TestDeprecation() {
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(hidden: Byte) : this()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openHidden() {}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openHiddenVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openHiddenVar: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(error: Short) : this()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openError() {}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openErrorVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openErrorVar: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(warning: Int) : this()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openWarning() {}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openWarningVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openWarningVar: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) constructor(normal: Long) : this()
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override fun openNormal(): Int = 2
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override val openNormalVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) override var openNormalVar: Any? = null
}
class ErrorOverride() : TestDeprecation() {
@Deprecated("error", level = DeprecationLevel.ERROR) constructor(hidden: Byte) : this()
@Deprecated("error", level = DeprecationLevel.ERROR) override fun openHidden() {}
@Deprecated("error", level = DeprecationLevel.ERROR) override val openHiddenVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) override var openHiddenVar: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) constructor(error: Short) : this()
@Deprecated("error", level = DeprecationLevel.ERROR) override fun openError() {}
@Deprecated("error", level = DeprecationLevel.ERROR) override val openErrorVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) override var openErrorVar: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) constructor(warning: Int) : this()
@Deprecated("error", level = DeprecationLevel.ERROR) override fun openWarning() {}
@Deprecated("error", level = DeprecationLevel.ERROR) override val openWarningVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) override var openWarningVar: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) constructor(normal: Long) : this()
@Deprecated("error", level = DeprecationLevel.ERROR) override fun openNormal(): Int = 3
@Deprecated("error", level = DeprecationLevel.ERROR) override val openNormalVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) override var openNormalVar: Any? = null
}
class WarningOverride() : TestDeprecation() {
@Deprecated("warning", level = DeprecationLevel.WARNING) constructor(hidden: Byte) : this()
@Deprecated("warning", level = DeprecationLevel.WARNING) override fun openHidden() {}
@Deprecated("warning", level = DeprecationLevel.WARNING) override val openHiddenVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) override var openHiddenVar: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) constructor(error: Short) : this()
@Deprecated("warning", level = DeprecationLevel.WARNING) override fun openError() {}
@Deprecated("warning", level = DeprecationLevel.WARNING) override val openErrorVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) override var openErrorVar: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) constructor(warning: Int) : this()
@Deprecated("warning", level = DeprecationLevel.WARNING) override fun openWarning() {}
@Deprecated("warning", level = DeprecationLevel.WARNING) override val openWarningVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) override var openWarningVar: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) constructor(normal: Long) : this()
@Deprecated("warning", level = DeprecationLevel.WARNING) override fun openNormal(): Int = 4
@Deprecated("warning", level = DeprecationLevel.WARNING) override val openNormalVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) override var openNormalVar: Any? = null
}
class NormalOverride() : TestDeprecation() {
constructor(hidden: Byte) : this()
override fun openHidden() {}
override val openHiddenVal: Any? = null
override var openHiddenVar: Any? = null
constructor(error: Short) : this()
override fun openError() {}
override val openErrorVal: Any? = null
override var openErrorVar: Any? = null
constructor(warning: Int) : this()
override fun openWarning() {}
override val openWarningVal: Any? = null
override var openWarningVar: Any? = null
constructor(normal: Long) : this()
override fun openNormal(): Int = 5
override val openNormalVal: Any? = null
override var openNormalVar: Any? = null
}
}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) fun hidden() {}
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) val hiddenVal: Any? = null
@Deprecated("hidden", level = DeprecationLevel.HIDDEN) var hiddenVar: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) fun error() {}
@Deprecated("error", level = DeprecationLevel.ERROR) val errorVal: Any? = null
@Deprecated("error", level = DeprecationLevel.ERROR) var errorVar: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) fun warning() {}
@Deprecated("warning", level = DeprecationLevel.WARNING) val warningVal: Any? = null
@Deprecated("warning", level = DeprecationLevel.WARNING) var warningVar: Any? = null
@@ -613,6 +613,59 @@ func testSR10177Workaround() throws {
try assertTrue(String(describing: test).contains("TestSR10177WorkaroundDerived")) try assertTrue(String(describing: test).contains("TestSR10177WorkaroundDerived"))
} }
func testClashes() throws {
let test = TestClashesImpl()
let test1: TestClashes1 = test
let test2: TestClashes2 = test
try assertEquals(actual: 1, expected: test1.clashingProperty)
try assertEquals(actual: 1, expected: test2.clashingProperty_ as! Int32)
try assertEquals(actual: 2, expected: test2.clashingProperty__ as! Int32)
}
func testInvalidIdentifiers() throws {
let test = TestInvalidIdentifiers()
try assertTrue(TestInvalidIdentifiers._Foo() is TestInvalidIdentifiers._Foo)
try assertFalse(TestInvalidIdentifiers.Bar_() is TestInvalidIdentifiers._Foo)
try assertEquals(actual: 42, expected: test.a_d_d(_1: 13, _2: 14, _3: 15))
test._status = "OK"
try assertEquals(actual: "OK", expected: test._status)
try assertEquals(actual: TestInvalidIdentifiers.E._4_.value, expected: 4)
try assertEquals(actual: TestInvalidIdentifiers.E._5_.value, expected: 5)
try assertEquals(actual: TestInvalidIdentifiers.E.__.value, expected: 6)
try assertEquals(actual: TestInvalidIdentifiers.E.___.value, expected: 7)
try assertEquals(actual: TestInvalidIdentifiers.Companion_()._42, expected: 42)
try assertEquals(actual: Set([test.__, test.___]), expected: Set(["$".utf16.first, "_".utf16.first]))
}
class ImplementingHiddenSubclass : TestDeprecation.ImplementingHidden {
override func effectivelyHidden() -> Int32 {
return -2
}
}
func testDeprecation() throws {
let test = TestDeprecation()
try assertEquals(actual: test.openNormal(), expected: 1)
let testHiddenOverride: TestDeprecation = TestDeprecation.HiddenOverride()
try assertEquals(actual: testHiddenOverride.openNormal(), expected: 2)
let testErrorOverride: TestDeprecation = TestDeprecation.ErrorOverride()
try assertEquals(actual: testErrorOverride.openNormal(), expected: 3)
let testWarningOverride: TestDeprecation = TestDeprecation.WarningOverride()
try assertEquals(actual: testWarningOverride.openNormal(), expected: 4)
try assertEquals(actual: test.callEffectivelyHidden(obj: ImplementingHiddenSubclass()), expected: -2)
}
// See https://github.com/JetBrains/kotlin-native/issues/2931 // See https://github.com/JetBrains/kotlin-native/issues/2931
func testGH2931() throws { func testGH2931() throws {
for i in 0..<50000 { for i in 0..<50000 {
@@ -678,6 +731,9 @@ class ValuesTests : TestProvider {
TestCase(name: "TestGH2959", method: withAutorelease(testGH2959)), TestCase(name: "TestGH2959", method: withAutorelease(testGH2959)),
TestCase(name: "TestKClass", method: withAutorelease(testKClass)), TestCase(name: "TestKClass", method: withAutorelease(testKClass)),
TestCase(name: "TestSR10177Workaround", method: withAutorelease(testSR10177Workaround)), TestCase(name: "TestSR10177Workaround", method: withAutorelease(testSR10177Workaround)),
TestCase(name: "TestClashes", method: withAutorelease(testClashes)),
TestCase(name: "TestInvalidIdentifiers", method: withAutorelease(testInvalidIdentifiers)),
TestCase(name: "TestDeprecation", method: withAutorelease(testDeprecation)),
TestCase(name: "TestGH2931", method: withAutorelease(testGH2931)), TestCase(name: "TestGH2931", method: withAutorelease(testGH2931)),
] ]
} }
@@ -0,0 +1,8 @@
fun foo(): String{
val bar: String by lazy {
"OK"
}
return bar
}
@@ -0,0 +1,3 @@
fun main() {
println(foo())
}
+82
View File
@@ -0,0 +1,82 @@
/*
* Copyright 2010-2019 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.
*/
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.util.Properties
plugins {
// We explicitly configure versions of plugins in settings.gradle.kts.
// due to https://github.com/gradle/gradle/issues/1697.
id("kotlin")
id("kotlinx-serialization")
groovy
`java-gradle-plugin`
}
val rootProperties = Properties().apply {
rootDir.resolve("../gradle.properties").reader().use(::load)
}
val kotlinVersion: String by rootProperties
val kotlinCompilerRepo: String by rootProperties
val buildKotlinVersion: String by rootProperties
val buildKotlinCompilerRepo: String by rootProperties
val konanVersion: String by rootProperties
group = "org.jetbrains.kotlin"
version = konanVersion
repositories {
maven(kotlinCompilerRepo)
maven(buildKotlinCompilerRepo)
maven("https://cache-redirector.jetbrains.com/maven-central")
maven("https://kotlin.bintray.com/kotlinx")
}
dependencies {
compileOnly(gradleApi())
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
implementation("com.ullink.slack:simpleslackapi:1.2.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.10.0")
implementation("io.ktor:ktor-client-auth:1.2.1")
implementation("io.ktor:ktor-client-core:1.2.1")
implementation("io.ktor:ktor-client-cio:1.2.1")
api("org.jetbrains.kotlin:kotlin-native-utils:$kotlinVersion")
// Located in <repo root>/shared and always provided by the composite build.
api("org.jetbrains.kotlin:kotlin-native-shared:$konanVersion")
}
sourceSets["main"].withConvention(KotlinSourceSet::class) {
kotlin.srcDir("$projectDir/../tools/benchmarks/shared/src")
}
gradlePlugin {
plugins {
create("benchmarkPlugin") {
id = "benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.BenchmarkingPlugin"
}
create("compileBenchmarking") {
id = "compile-benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.CompileBenchmarkingPlugin"
}
}
}
val compileKotlin: KotlinCompile by tasks
val compileGroovy: GroovyCompile by tasks
// Add Kotlin classes to a classpath for the Groovy compiler
compileGroovy.apply {
classpath += project.files(compileKotlin.destinationDir)
dependsOn(compileKotlin)
}
+28
View File
@@ -0,0 +1,28 @@
pluginManagement {
val rootProperties = java.util.Properties().apply {
rootDir.resolve("../gradle.properties").reader().use(::load)
}
val kotlinCompilerRepo: String by rootProperties
val kotlinVersion by rootProperties
repositories {
maven(kotlinCompilerRepo)
maven("https://cache-redirector.jetbrains.com/maven-central")
}
resolutionStrategy {
eachPlugin {
if (requested.id.id == "kotlin") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
if (requested.id.id == "kotlinx-serialization") {
useModule("org.jetbrains.kotlin:kotlin-serialization:$kotlinVersion")
}
}
}
}
rootProject.name = "kotlin-native-build-tools"
includeBuild("../shared")
@@ -443,9 +443,14 @@ class RunExternalTestGroup extends OldKonanTest {
} }
if (line.contains("$pkg.") && ! (line =~ packagePattern || line =~ importRegex) if (line.contains("$pkg.") && ! (line =~ packagePattern || line =~ importRegex)
&& ! vars.contains(pkg)) { && ! vars.contains(pkg)) {
def idx = line.indexOf("$pkg") def idx = 0
if (! (idx > 0 && Character.isJavaIdentifierPart(line.charAt(idx - 1))) ) { while ((idx = line.indexOf(pkg, idx)) >= 0) {
line = line.substring(0, idx) + "$sourceName.$pkg" + line.substring(idx + pkg.length()) if (!Character.isJavaIdentifierPart(line.charAt(idx - 1))) {
line = line.substring(0, idx) + "$sourceName.$pkg" + line.substring(idx + pkg.length())
idx += sourceName.length() + pkg.length() + 1
} else {
idx += pkg.length()
}
} }
} }
} }
@@ -74,7 +74,12 @@ open class FrameworkTest : DefaultTask() {
// Compile swift sources // Compile swift sources
val sources = swiftSources.map { Paths.get(it).toString() } + val sources = swiftSources.map { Paths.get(it).toString() } +
listOf(provider.toString(), swiftMain) listOf(provider.toString(), swiftMain)
val options = listOf("-g", "-Xlinker", "-rpath", "-Xlinker", frameworkParentDirPath, "-F", frameworkParentDirPath) val options = listOf(
"-g",
"-Xlinker", "-rpath", "-Xlinker", frameworkParentDirPath,
"-F", frameworkParentDirPath,
"-Xcc", "-Werror" // To fail compilation on warnings in framework header.
)
val testExecutable = Paths.get(testOutput, frameworkName, "swiftTestExecutable") val testExecutable = Paths.get(testOutput, frameworkName, "swiftTestExecutable")
compileSwift(project, project.testTarget, sources, options, testExecutable, fullBitcode) compileSwift(project, project.testTarget, sources, options, testExecutable, fullBitcode)
@@ -155,7 +155,7 @@ private class TeamCityTestPrinter(val project:Project) {
* Teamcity require escaping some symbols in pipe manner. * Teamcity require escaping some symbols in pipe manner.
* https://github.com/GitTools/GitVersion/issues/94 * https://github.com/GitTools/GitVersion/issues/94
*/ */
private fun String?.toTeamCityFormat(): String = this?.also { private fun String?.toTeamCityFormat(): String = this?.let {
it.replace("\\|", "||") it.replace("\\|", "||")
.replace("\r", "|r") .replace("\r", "|r")
.replace("\n", "|n") .replace("\n", "|n")
+4
View File
@@ -25,10 +25,14 @@ buildscript {
repositories { repositories {
maven { url kotlinCompilerRepo } maven { url kotlinCompilerRepo }
maven { url "https://kotlin.bintray.com/kotlinx" }
maven { url "https://cache-redirector.jetbrains.com/maven-central" }
} }
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-native-utils:$kotlinVersion"
classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion" classpath "org.jetbrains.kotlin:kotlin-native-shared:$konanVersion"
classpath "org.jetbrains.kotlin:kotlin-native-build-tools:$konanVersion"
} }
} }
import org.jetbrains.kotlin.konan.* import org.jetbrains.kotlin.konan.*
-44
View File
@@ -1,44 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
buildscript {
val rootBuildDirectory = "$rootDir/.."
extra["rootBuildDirectory"] = rootBuildDirectory
apply(from = "$rootBuildDirectory/gradle/loadRootProperties.gradle")
apply(from = "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle")
}
val buildKotlinCompilerRepo: String by project
val kotlinCompilerRepo: String by project
val repos = listOf(
buildKotlinCompilerRepo,
kotlinCompilerRepo,
"https://cache-redirector.jetbrains.com/maven-central",
"https://kotlin.bintray.com/kotlinx"
)
allprojects {
repositories {
repos.forEach { repoUrl ->
maven { setUrl(repoUrl) }
}
}
}
dependencies {
runtime(project(":plugins"))
}
-74
View File
@@ -1,74 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
apply plugin: 'groovy'
apply plugin: 'kotlin'
buildscript {
ext.rootBuildDirectory = "$rootDir/.."
apply from: "$rootBuildDirectory/gradle/loadRootProperties.gradle"
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
dependencies{
classpath "org.jetbrains.kotlin:kotlin-serialization:$buildKotlinVersion"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
apply plugin: 'kotlin'
apply plugin: 'kotlinx-serialization'
apply plugin: 'java-gradle-plugin'
/* don't use repositories: gradle will ignore it anyway, but may confuse gradle build engineer, see outer build.gradle */
dependencies {
compile gradleApi()
compile localGroovy()
compile "org.jetbrains.kotlin:kotlin-stdlib:$buildKotlinVersion"
compile "org.jetbrains.kotlin:kotlin-reflect:$buildKotlinVersion"
compile group: 'com.ullink.slack', name: 'simpleslackapi', version: '1.2.0'
// An artifact from the included build 'shared' cannot be used here due to https://github.com/gradle/gradle/issues/3768
implementation "org.jetbrains.kotlin:kotlin-gradle-plugin"
compile project(':shared')
compile "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.10.0"
implementation 'io.ktor:ktor-client-auth:1.2.1'
implementation 'io.ktor:ktor-client-core:1.2.1'
implementation 'io.ktor:ktor-client-cio:1.2.1'
}
sourceSets.main.kotlin.srcDirs = ["src", "$projectDir/../../tools/benchmarks/shared/src"]
rootProject.dependencies {
runtime project(path)
}
compileGroovy {
// Add Kotlin classes to a classpath for the Groovy compiler
classpath += project.files(compileKotlin.destinationDir)
}
gradlePlugin {
plugins {
benchmarkPlugin {
id = "benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.BenchmarkingPlugin"
}
compileBenchmarking {
id = "compile-benchmarking"
implementationClass = "org.jetbrains.kotlin.benchmark.CompileBenchmarkingPlugin"
}
}
}
-18
View File
@@ -1,18 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include(":plugins")
include(":shared")
-44
View File
@@ -1,44 +0,0 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
buildscript {
ext {
gradleProperties = new Properties()
gradleProperties.load(new FileInputStream("$projectDir/../../gradle.properties"))
buildKotlinVersion = gradleProperties."buildKotlinVersion"
buildKotlinCompilerRepo = gradleProperties."buildKotlinCompilerRepo"
}
apply from: '../../gradle/kotlinGradlePlugin.gradle'
}
apply plugin: 'kotlin'
// We reuse the source code from the Project in buildSrc.
sourceSets.main.kotlin.srcDirs = ["$projectDir/../../shared/src/main/kotlin"]
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$buildKotlinVersion"
compile "org.jetbrains.kotlin:kotlin-native-utils:$kotlinVersion"
}
rootProject.dependencies {
runtime project(path)
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
+5 -10
View File
@@ -1,5 +1,5 @@
# #
# Copyright 2010-2017 JetBrains s.r.o. # Copyright 2010-2019 JetBrains s.r.o.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -18,16 +18,11 @@
buildKotlinVersion=1.3.50-dev-787 buildKotlinVersion=1.3.50-dev-787
buildKotlinCompilerRepo=https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_dev_Compiler),number:1.3.50-dev-787,branch:default:any,pinned:true/artifacts/content/maven buildKotlinCompilerRepo=https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_dev_Compiler),number:1.3.50-dev-787,branch:default:any,pinned:true/artifacts/content/maven
remoteRoot=konan_tests remoteRoot=konan_tests
kotlinCompilerRepo=https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_dev_Compiler),number:1.3.50-dev-1455,branch:default:any,pinned:true/artifacts/content/maven kotlinCompilerRepo=https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_dev_Compiler),number:1.3.50-dev-1741,branch:default:any,pinned:true/artifacts/content/maven
kotlinVersion=1.3.50-dev-1455 kotlinVersion=1.3.50-dev-1741
kotlinStdlibRepo=https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_dev_Compiler),number:1.3.50-dev-1455,branch:default:any,pinned:true/artifacts/content/maven kotlinStdlibRepo=https://teamcity.jetbrains.com/guestAuth/app/rest/builds/buildType:(id:Kotlin_dev_Compiler),number:1.3.50-dev-1741,branch:default:any,pinned:true/artifacts/content/maven
kotlinStdlibVersion=1.3.50-dev-1455 kotlinStdlibVersion=1.3.50-dev-1741
testKotlinCompilerVersion=1.3.50-dev-1455 testKotlinCompilerVersion=1.3.50-dev-1455
konanVersion=1.3.50 konanVersion=1.3.50
org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.jvmargs='-Dfile.encoding=UTF-8'
org.gradle.workers.max=4 org.gradle.workers.max=4
#kotlinProjectPath=/Users/jetbrains/IdeaProjects/kotlin
#sharedProjectPath=/Users/jetbrains/IdeaProjects/kotlin-native-shared
#kotlinProjectPath=/Users/jetbrains/kotlin-native/kotlin
#sharedProjectPath=/Users/jetbrains/kotlin-native/kotlin-native-shared/kotlin-native-shared
+5 -6
View File
@@ -1,13 +1,12 @@
if (!hasProperty('buildKotlinVersion')) { def properties = ['buildKotlinVersion', 'buildKotlinCompilerRepo', 'kotlinVersion', 'kotlinCompilerRepo']
throw new GradleException('Please ensure the "buildKotlinVersion" property is defined before applying this script.')
}
if (!hasProperty('buildKotlinCompilerRepo')) { for (prop in properties) {
throw new GradleException('Please ensure the "buildKotlinCompilerRepo" property is defined before applying this script.') if (!hasProperty(prop)) {
throw new GradleException("Please ensure the '$prop' property is defined before applying this script.")
}
} }
project.buildscript.repositories { project.buildscript.repositories {
maven { maven {
url buildKotlinCompilerRepo url buildKotlinCompilerRepo
} }
+3 -11
View File
@@ -4,24 +4,16 @@ import org.jetbrains.kotlin.BuildRegister
import org.jetbrains.kotlin.MPPTools import org.jetbrains.kotlin.MPPTools
buildscript { buildscript {
ext.rootBuildDirectory = file('..') apply from: "$rootProject.projectDir/gradle/kotlinGradlePlugin.gradle"
apply from: "$rootBuildDirectory/gradle/loadRootProperties.gradle"
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
repositories { repositories {
maven { maven {
url 'https://cache-redirector.jetbrains.com/jcenter' url 'https://cache-redirector.jetbrains.com/jcenter'
} }
maven {
url kotlinCompilerRepo
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
} }
} }
def rootBuildDirectory = rootProject.projectDir
task konanRun { task konanRun {
subprojects.each { subprojects.each {
dependsOn it.getTasksByName('konanRun', true)[0] dependsOn it.getTasksByName('konanRun', true)[0]
+1 -11
View File
@@ -3,22 +3,12 @@ import org.jetbrains.kotlin.PlatformInfo
import org.jetbrains.kotlin.RunJvmTask import org.jetbrains.kotlin.RunJvmTask
buildscript { buildscript {
ext.rootBuildDirectory = file('../..') apply from: "$rootProject.projectDir/gradle/kotlinGradlePlugin.gradle"
apply from: "$rootBuildDirectory/gradle/loadRootProperties.gradle"
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
repositories { repositories {
maven { maven {
url 'https://cache-redirector.jetbrains.com/jcenter' url 'https://cache-redirector.jetbrains.com/jcenter'
} }
maven {
url kotlinCompilerRepo
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
} }
} }
+5 -1
View File
@@ -46,6 +46,8 @@ class RingLauncher(numWarmIterations: Int, numberOfAttempts: Int, prefix: String
val switchBenchmark = SwitchBenchmark() val switchBenchmark = SwitchBenchmark()
val withIndiciesBenchmark = WithIndiciesBenchmark() val withIndiciesBenchmark = WithIndiciesBenchmark()
val callsBenchmark = CallsBenchmark() val callsBenchmark = CallsBenchmark()
val coordinatesSolverBenchmark = CoordinatesSolverBenchmark()
val graphSolverBenchmark = GraphSolverBenchmark()
override val benchmarks = BenchmarksCollection( override val benchmarks = BenchmarksCollection(
mutableMapOf( mutableMapOf(
@@ -225,7 +227,9 @@ class RingLauncher(numWarmIterations: Int, numberOfAttempts: Int, prefix: String
"Calls.interfaceMethodBimorphic" to callsBenchmark::interfaceMethodCall_BimorphicCallsite, "Calls.interfaceMethodBimorphic" to callsBenchmark::interfaceMethodCall_BimorphicCallsite,
"Calls.interfaceMethodTrimorphic" to callsBenchmark::interfaceMethodCall_TrimorphicCallsite, "Calls.interfaceMethodTrimorphic" to callsBenchmark::interfaceMethodCall_TrimorphicCallsite,
"Calls.returnBoxUnboxFolding" to callsBenchmark::returnBoxUnboxFolding, "Calls.returnBoxUnboxFolding" to callsBenchmark::returnBoxUnboxFolding,
"Calls.parameterBoxUnboxFolding" to callsBenchmark::parameterBoxUnboxFolding "Calls.parameterBoxUnboxFolding" to callsBenchmark::parameterBoxUnboxFolding,
"CoordinatesSolver.solve" to coordinatesSolverBenchmark::solve,
"GraphSolver.solve" to graphSolverBenchmark::solve
) )
) )
} }
@@ -0,0 +1,348 @@
package org.jetbrains.ring
import kotlin.experimental.and
class CoordinatesSolverBenchmark {
val solver: Solver
init {
val inputValue = """
12 5 3 25 3 9 3 9 1 3
13 3 12 6 10 10 12 2 10 10
9 2 9 5 6 12 5 0 2 10
10 14 12 5 3 9 5 2 10 10
8 1 3 9 4 0 3 14 10 10
12 0 4 6 9 6 12 5 6 10
11 12 3 9 6 9 5 3 9 6
8 5 6 8 3 12 7 10 10 11
12 3 13 6 12 3 9 6 12 2
13 4 5 5 5 6 12 5 5 2
1""".trimIndent()
val input = readTillParsed(inputValue)
solver = Solver(input!!)
}
data class Coordinate(val x: Int, val y: Int)
@SinceKotlin("1.1")
data class Field(val x: Int, val y: Int, val value: Byte) {
fun northWall(): Boolean {
return value and 1 != 0.toByte()
}
fun eastWall(): Boolean {
return value and 2 != 0.toByte()
}
fun southWall(): Boolean {
return value and 4 != 0.toByte()
}
fun westWall(): Boolean {
return value and 8 != 0.toByte()
}
fun hasObject(): Boolean {
return value and 16 != 0.toByte()
}
}
class Input(val labyrinth: Labyrinth, val nObjects: Int)
class Labyrinth(val width: Int, val height: Int, val fields: Array<Field>) {
fun getField(x: Int, y: Int): Field {
return fields[x + y * width]
}
}
class Output(val steps: List<Coordinate?>)
class InputParser {
private val rows : MutableList<Array<Field>> = mutableListOf()
private var numObjects: Int = 0
private val input: Input
get() {
val width = rows[0].size
val fields = arrayOfNulls<Field>(width * rows.size)
for (y in rows.indices) {
val row = rows[y]
for (p in y*width until y*width + width) {
fields[p] = row[p-y*width]
}
}
val labyrinth = Labyrinth(width, rows.size, fields.requireNoNulls())
return Input(labyrinth, numObjects)
}
fun feedLine(line: String): Input? {
val items = line.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (items.size == 1) {
numObjects = items[0].toInt()
return input
} else if (items.size > 0) {
val rowNum = rows.size
val row = arrayOfNulls<Field>(items.size)
for (col in items.indices) {
row[col] = Field(rowNum, col, items[col].toByte())
}
rows.add(row.requireNoNulls())
}
return null
}
}
class Solver(private val input: Input) {
private val objects: List<Coordinate>
private val width: Int
private val height: Int
private val maze_end: Coordinate
private var counter: Long = 0
init {
objects = ArrayList()
for (f in input.labyrinth.fields) {
if (f.hasObject()) {
objects.add(Coordinate(f.x, f.y))
}
}
width = input.labyrinth.width
height = input.labyrinth.height
maze_end = Coordinate(width - 1, height - 1)
}
fun solve(): Output {
val steps = ArrayList<Coordinate>()
for (o in objects.indices) {
var limit = input.labyrinth.width + input.labyrinth.height - 2
var ss: List<Coordinate>? = null
while (ss == null) {
//println("o$o, limit: $limit")
if (o == 0) {
ss = solveWithLimit(limit, MAZE_START) { it[it.size - 1] == objects[0] }
} else {
ss = solveWithLimit(limit, objects[o - 1]) { it[it.size - 1] == objects[o] }
}
if (ss != null) {
steps.addAll(ss)
}
limit++
}
}
var limit = input.labyrinth.width + input.labyrinth.height - 2
var ss: List<Coordinate>? = null
while (ss == null) {
ss = solveWithLimit(limit, objects[objects.size - 1]) { it[it.size - 1] == maze_end }
if (ss != null) {
steps.addAll(ss)
}
limit++
}
return createOutput(steps)
}
private fun createOutput(steps: List<Coordinate>): Output {
val objects : MutableList<Coordinate> = this.objects.toMutableList()
val outSteps : MutableList<Coordinate?> = mutableListOf()
for (step in steps) {
outSteps.add(step)
if (objects.contains(step)) {
outSteps.add(null)
objects.remove(step)
}
}
return Output(outSteps)
}
private fun isValid(steps: List<Coordinate>): Boolean {
counter++
val (x, y) = steps[steps.size - 1]
return if (!(x == input.labyrinth.width - 1 && y == input.labyrinth.height - 1)) { // Jobb also a cel
false
} else steps.containsAll(objects)
}
private fun getPossibleSteps(now: Coordinate, previous: Coordinate?): ArrayList<Coordinate> {
val field = input.labyrinth.getField(now.x, now.y)
val possibleSteps = ArrayList<Coordinate>()
if (now.x != width - 1 && !field.eastWall()) {
possibleSteps.add(Coordinate(now.x + 1, now.y))
}
if (now.x != 0 && !field.westWall()) {
possibleSteps.add(Coordinate(now.x - 1, now.y))
}
if (now.y != 0 && !field.northWall()) {
possibleSteps.add(Coordinate(now.x, now.y - 1))
}
if (now.y != height - 1 && !field.southWall()) {
possibleSteps.add(Coordinate(now.x, now.y + 1))
}
if (!field.hasObject() && previous != null) {
possibleSteps.remove(previous)
}
return possibleSteps
}
private fun solveWithLimit(limit: Int, start: Coordinate, validFn: (List<Coordinate>) -> Boolean): List<Coordinate>? {
var steps: MutableList<Coordinate>? = findFirstLegitSteps(null, start, limit)
while (steps != null && !validFn(steps)) {
steps = alter(start, null, steps)
}
return steps
}
private fun findFirstLegitSteps(startPrev: Coordinate?, start: Coordinate, num: Int): MutableList<Coordinate>? {
var steps: MutableList<Coordinate>? = ArrayList()
var i = 0
while (i < num) {
val prev: Coordinate?
val state: Coordinate
if (i == 0) {
state = start
prev = startPrev
} else if (i == 1) {
state = steps!![i - 1]
prev = startPrev
} else {
state = steps!![i - 1]
prev = steps[i - 2]
}
val possibleSteps = getPossibleSteps(state, prev)
if (possibleSteps.size == 0) {
if (steps!!.size == 0) {
return null
}
steps = alter(start, startPrev, steps)
if (steps == null) {
return null
}
i--
i++
continue
}
val newStep = possibleSteps[0]
steps!!.add(newStep)
i++
}
return steps
}
private fun alter(start: Coordinate, startPrev: Coordinate?, steps: MutableList<Coordinate>): MutableList<Coordinate>? {
val size = steps.size
var i = size - 1
while (i >= 0) {
val current = steps[i]
val prev = if (i == 0) start else steps[i - 1]
val prevprev: Coordinate?
if (i > 1) {
prevprev = steps[i - 2]
} else if (i == 1) {
prevprev = start
} else {
prevprev = startPrev
}
val alternatives = getPossibleSteps(prev, prevprev)
val index = alternatives.indexOf(current)
if (index != alternatives.size - 1) {
val newItem = alternatives[index + 1]
steps[i] = newItem
val remainder = findFirstLegitSteps(prev, newItem, size - i - 1)
if (remainder == null) {
i++
i--
continue
}
removeAfterIndexExclusive(steps, i)
steps.addAll(remainder)
return steps
} else {
if (i == 0) {
return null
}
}
i--
}
return steps
}
companion object {
private val MAZE_START = Coordinate(0, 0)
private fun removeAfterIndexExclusive(list: MutableList<*>, index: Int) {
val rnum = list.size - 1 - index
for (i in 0 until rnum) {
list.removeAt(list.size - 1)
}
}
}
}
private fun readTillParsed(inputValue: String): Input? {
val parser = InputParser()
var input: Input? = null
inputValue.lines().forEach { line ->
input = parser.feedLine(line)
}
return input
}
fun solve() {
val output = solver.solve()
for (c in output.steps) {
val value = if (c == null) { "felvesz" } else { "${c.x} ${c.y}" }
}
}
}
File diff suppressed because it is too large Load Diff
@@ -51,6 +51,7 @@ abstract class Launcher(val numWarmIterations: Int, val numberOfAttempts: Int, v
var autoEvaluatedNumberOfMeasureIteration = 1 var autoEvaluatedNumberOfMeasureIteration = 1
while (true) { while (true) {
var j = autoEvaluatedNumberOfMeasureIteration var j = autoEvaluatedNumberOfMeasureIteration
cleanup()
val time = measureNanoTime { val time = measureNanoTime {
while (j-- > 0) { while (j-- > 0) {
benchmark() benchmark()
@@ -64,6 +65,7 @@ abstract class Launcher(val numWarmIterations: Int, val numberOfAttempts: Int, v
val samples = DoubleArray(numberOfAttempts) val samples = DoubleArray(numberOfAttempts)
for (k in samples.indices) { for (k in samples.indices) {
i = autoEvaluatedNumberOfMeasureIteration i = autoEvaluatedNumberOfMeasureIteration
cleanup()
val time = measureNanoTime { val time = measureNanoTime {
while (i-- > 0) { while (i-- > 0) {
benchmark() benchmark()
+1 -12
View File
@@ -6,22 +6,11 @@ import org.jetbrains.kotlin.UtilsKt
import java.nio.file.Paths import java.nio.file.Paths
buildscript { buildscript {
ext.rootBuildDirectory = file('../..') apply from: "$rootProject.projectDir/gradle/kotlinGradlePlugin.gradle"
apply from: "$rootBuildDirectory/gradle/loadRootProperties.gradle"
apply from: "$rootBuildDirectory/gradle/kotlinGradlePlugin.gradle"
repositories { repositories {
maven { maven {
url 'https://cache-redirector.jetbrains.com/jcenter' url 'https://cache-redirector.jetbrains.com/jcenter'
} }
maven {
url kotlinCompilerRepo
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
} }
} }
+15 -8
View File
@@ -4,8 +4,6 @@ import org.jetbrains.kotlin.konan.util.*
import static org.jetbrains.kotlin.konan.util.VisibleNamedKt.getVisibleName import static org.jetbrains.kotlin.konan.util.VisibleNamedKt.getVisibleName
apply plugin: 'konan'
buildscript { buildscript {
repositories { repositories {
maven { maven {
@@ -14,18 +12,27 @@ buildscript {
maven { maven {
url buildKotlinCompilerRepo url buildKotlinCompilerRepo
} }
maven {
url kotlinCompilerRepo
}
maven {
url "https://kotlin.bintray.com/kotlinx"
}
} }
dependencies { dependencies {
classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$gradlePluginVersion" classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$gradlePluginVersion"
classpath "org.jetbrains.kotlin:kotlin-native-build-tools:$konanVersion"
} }
ext.konanHome = distDir.absolutePath
def jvmArguments = [project.findProperty("platformLibsJvmArgs") ?: "-Xmx6G", *HostManager.defaultJvmArgs]
ext.jvmArgs = jvmArguments.join(" ")
ext.setProperty("org.jetbrains.kotlin.native.home", konanHome)
ext.setProperty("konan.jvmArgs", jvmArgs)
} }
// These properties are used by the 'konan' plugin, thus we set them before applying it.
ext.konanHome = distDir.absolutePath
def jvmArguments = [project.findProperty("platformLibsJvmArgs") ?: "-Xmx6G", *HostManager.defaultJvmArgs]
ext.jvmArgs = jvmArguments.join(" ")
ext.setProperty("org.jetbrains.kotlin.native.home", konanHome)
ext.setProperty("konan.jvmArgs", jvmArgs)
apply plugin: 'konan'
//#region Util functions. //#region Util functions.
private ArrayList<DefFile> targetDefFiles(KonanTarget target) { private ArrayList<DefFile> targetDefFiles(KonanTarget target) {
+16
View File
@@ -19,6 +19,8 @@ targetList.each { targetName ->
dependsOn "${targetName}Launcher" dependsOn "${targetName}Launcher"
dependsOn "${targetName}Debug" dependsOn "${targetName}Debug"
dependsOn "${targetName}Release" dependsOn "${targetName}Release"
dependsOn "${targetName}Strict"
dependsOn "${targetName}Relaxed"
target targetName target targetName
includeRuntime(delegate) includeRuntime(delegate)
linkerArgs project.file("../common/build/$targetName/hash.bc").path linkerArgs project.file("../common/build/$targetName/hash.bc").path
@@ -44,6 +46,20 @@ targetList.each { targetName ->
target targetName target targetName
includeRuntime(delegate) includeRuntime(delegate)
} }
task ("${targetName}Strict", type: CompileCppToBitcode) {
name "strict"
srcRoot file('src/strict')
target targetName
includeRuntime(delegate)
}
task ("${targetName}Relaxed", type: CompileCppToBitcode) {
name "relaxed"
srcRoot file('src/relaxed')
target targetName
includeRuntime(delegate)
}
} }
task hostRuntime(dependsOn: "${hostName}Runtime") task hostRuntime(dependsOn: "${hostName}Runtime")
+3 -2
View File
@@ -14,10 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
#include "KString.h"
#include "Memory.h" #include "Memory.h"
#include "Natives.h" #include "Natives.h"
#include "Porting.h"
#include "Runtime.h" #include "Runtime.h"
#include "KString.h"
#include "Types.h" #include "Types.h"
#ifdef KONAN_ANDROID #ifdef KONAN_ANDROID
@@ -212,7 +213,7 @@ extern "C" void RUNTIME_USED Konan_main(
ANativeActivity* activity, void* savedState, size_t savedStateSize) { ANativeActivity* activity, void* savedState, size_t savedStateSize) {
bool launchThread = activity->instance == nullptr; bool launchThread = activity->instance == nullptr;
if (launchThread) { if (launchThread) {
launcherState = (LauncherState*)calloc(sizeof(LauncherState), 1); launcherState = (LauncherState*)konan::calloc(sizeof(LauncherState), 1);
launcherState->nativeActivityState = {activity, savedState, savedStateSize, nullptr}; launcherState->nativeActivityState = {activity, savedState, savedStateSize, nullptr};
activity->instance = launcherState; activity->instance = launcherState;
activity->callbacks->onDestroy = onDestroy; activity->callbacks->onDestroy = onDestroy;
+2 -4
View File
@@ -443,8 +443,7 @@ OBJ_GETTER(Kotlin_CharArray_copyOf, KConstRef thiz, KInt newSize) {
if (newSize < 0) { if (newSize < 0) {
ThrowIllegalArgumentException(); ThrowIllegalArgumentException();
} }
ArrayHeader* result = AllocArrayInstance( ArrayHeader* result = AllocArrayInstance(array->type_info(), newSize, OBJ_RESULT)->array();
array->type_info(), newSize, OBJ_RESULT)->array();
KInt toCopy = array->count_ < newSize ? array->count_ : newSize; KInt toCopy = array->count_ < newSize ? array->count_ : newSize;
memcpy( memcpy(
PrimitiveArrayAddressOfElementAt<KChar>(result, 0), PrimitiveArrayAddressOfElementAt<KChar>(result, 0),
@@ -606,8 +605,7 @@ OBJ_GETTER(Kotlin_ImmutableBlob_toByteArray, KConstRef thiz, KInt startIndex, KI
ThrowArrayIndexOutOfBoundsException(); ThrowArrayIndexOutOfBoundsException();
} }
KInt count = endIndex - startIndex; KInt count = endIndex - startIndex;
ArrayHeader* result = AllocArrayInstance( ArrayHeader* result = AllocArrayInstance(theByteArrayTypeInfo, count, OBJ_RESULT)->array();
theByteArrayTypeInfo, count, OBJ_RESULT)->array();
memcpy(PrimitiveArrayAddressOfElementAt<KByte>(result, 0), memcpy(PrimitiveArrayAddressOfElementAt<KByte>(result, 0),
PrimitiveArrayAddressOfElementAt<KByte>(array, startIndex), PrimitiveArrayAddressOfElementAt<KByte>(array, startIndex),
count); count);
+1
View File
@@ -59,6 +59,7 @@ void RUNTIME_NORETURN ThrowIllegalStateException();
void RUNTIME_NORETURN ThrowInvalidMutabilityException(KConstRef where); void RUNTIME_NORETURN ThrowInvalidMutabilityException(KConstRef where);
void RUNTIME_NORETURN ThrowIncorrectDereferenceException(); void RUNTIME_NORETURN ThrowIncorrectDereferenceException();
void RUNTIME_NORETURN ThrowIllegalObjectSharingException(KConstNativePtr typeInfo, KConstNativePtr address); void RUNTIME_NORETURN ThrowIllegalObjectSharingException(KConstNativePtr typeInfo, KConstNativePtr address);
void RUNTIME_NORETURN ThrowFreezingException(KRef toFreeze, KRef blocker);
// Prints out message of Throwable. // Prints out message of Throwable.
void PrintThrowable(KRef); void PrintThrowable(KRef);
+105 -112
View File
@@ -728,6 +728,111 @@ void DisposeCString(char* cstring) {
} }
// String.kt // String.kt
OBJ_GETTER(Kotlin_String_replace, KString thiz, KChar oldChar, KChar newChar, KBoolean ignoreCase) {
auto count = thiz->count_;
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, count, OBJ_RESULT)->array();
const KChar* thizRaw = CharArrayAddressOfElementAt(thiz, 0);
KChar* resultRaw = CharArrayAddressOfElementAt(result, 0);
if (ignoreCase) {
KChar oldCharLower = towlower_Konan(oldChar);
for (KInt index = 0; index < count; ++index) {
KChar thizChar = *thizRaw++;
*resultRaw++ = towlower_Konan(thizChar) == oldCharLower ? newChar : thizChar;
}
} else {
for (KInt index = 0; index < count; ++index) {
KChar thizChar = *thizRaw++;
*resultRaw++ = thizChar == oldChar ? newChar : thizChar;
}
}
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_plusImpl, KString thiz, KString other) {
RuntimeAssert(thiz != nullptr, "this cannot be null");
RuntimeAssert(other != nullptr, "other cannot be null");
RuntimeAssert(thiz->type_info() == theStringTypeInfo, "Must be a string");
RuntimeAssert(other->type_info() == theStringTypeInfo, "Must be a string");
KInt result_length = thiz->count_ + other->count_;
if (result_length < thiz->count_ || result_length < other->count_) {
ThrowArrayIndexOutOfBoundsException();
}
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, result_length, OBJ_RESULT)->array();
memcpy(
CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(thiz, 0),
thiz->count_ * sizeof(KChar));
memcpy(
CharArrayAddressOfElementAt(result, thiz->count_),
CharArrayAddressOfElementAt(other, 0),
other->count_ * sizeof(KChar));
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_toUpperCase, KString thiz) {
auto count = thiz->count_;
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, count, OBJ_RESULT)->array();
const KChar* thizRaw = CharArrayAddressOfElementAt(thiz, 0);
KChar* resultRaw = CharArrayAddressOfElementAt(result, 0);
for (KInt index = 0; index < count; ++index) {
*resultRaw++ = towupper_Konan(*thizRaw++);
}
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_toLowerCase, KString thiz) {
auto count = thiz->count_;
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, count, OBJ_RESULT)->array();
const KChar* thizRaw = CharArrayAddressOfElementAt(thiz, 0);
KChar* resultRaw = CharArrayAddressOfElementAt(result, 0);
for (KInt index = 0; index < count; ++index) {
*resultRaw++ = towlower_Konan(*thizRaw++);
}
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_fromCharArray, KConstRef thiz, KInt start, KInt size) {
const ArrayHeader* array = thiz->array();
RuntimeAssert(array->type_info() == theCharArrayTypeInfo, "Must use a char array");
if (start < 0 || size < 0 || size > array->count_ - start) {
ThrowArrayIndexOutOfBoundsException();
}
if (size == 0) {
RETURN_RESULT_OF0(TheEmptyString);
}
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, size, OBJ_RESULT)->array();
memcpy(CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(array, start),
size * sizeof(KChar));
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_toCharArray, KString string, KInt start, KInt size) {
ArrayHeader* result = AllocArrayInstance(theCharArrayTypeInfo, size, OBJ_RESULT)->array();
memcpy(CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(string, start),
size * sizeof(KChar));
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_subSequence, KString thiz, KInt startIndex, KInt endIndex) {
if (startIndex < 0 || endIndex > thiz->count_ || startIndex > endIndex) {
// TODO: is it correct exception?
ThrowArrayIndexOutOfBoundsException();
}
if (startIndex == endIndex) {
RETURN_RESULT_OF0(TheEmptyString);
}
KInt length = endIndex - startIndex;
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, length, OBJ_RESULT)->array();
memcpy(CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(thiz, startIndex),
length * sizeof(KChar));
RETURN_OBJ(result->obj());
}
KInt Kotlin_String_compareTo(KString thiz, KString other) { KInt Kotlin_String_compareTo(KString thiz, KString other) {
int result = memcmp( int result = memcmp(
CharArrayAddressOfElementAt(thiz, 0), CharArrayAddressOfElementAt(thiz, 0),
@@ -806,56 +911,6 @@ OBJ_GETTER(Kotlin_String_toUtf8OrThrow, KString thiz, KInt start, KInt size) {
RETURN_RESULT_OF(utf16ToUtf8Impl<utf16toUtf8OrThrow>, thiz, start, size); RETURN_RESULT_OF(utf16ToUtf8Impl<utf16toUtf8OrThrow>, thiz, start, size);
} }
OBJ_GETTER(Kotlin_String_fromCharArray, KConstRef thiz, KInt start, KInt size) {
const ArrayHeader* array = thiz->array();
RuntimeAssert(array->type_info() == theCharArrayTypeInfo, "Must use a char array");
if (start < 0 || size < 0 || size > array->count_ - start) {
ThrowArrayIndexOutOfBoundsException();
}
if (size == 0) {
RETURN_RESULT_OF0(TheEmptyString);
}
ArrayHeader* result = AllocArrayInstance(
theStringTypeInfo, size, OBJ_RESULT)->array();
memcpy(CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(array, start),
size * sizeof(KChar));
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_toCharArray, KString string, KInt start, KInt size) {
ArrayHeader* result = AllocArrayInstance(
theCharArrayTypeInfo, size, OBJ_RESULT)->array();
memcpy(CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(string, start),
size * sizeof(KChar));
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_plusImpl, KString thiz, KString other) {
RuntimeAssert(thiz != nullptr, "this cannot be null");
RuntimeAssert(other != nullptr, "other cannot be null");
RuntimeAssert(thiz->type_info() == theStringTypeInfo, "Must be a string");
RuntimeAssert(other->type_info() == theStringTypeInfo, "Must be a string");
KInt result_length = thiz->count_ + other->count_;
if (result_length < thiz->count_ || result_length < other->count_) {
ThrowArrayIndexOutOfBoundsException();
}
ArrayHeader* result = AllocArrayInstance(
theStringTypeInfo, result_length, OBJ_RESULT)->array();
memcpy(
CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(thiz, 0),
thiz->count_ * sizeof(KChar));
memcpy(
CharArrayAddressOfElementAt(result, thiz->count_),
CharArrayAddressOfElementAt(other, 0),
other->count_ * sizeof(KChar));
RETURN_OBJ(result->obj());
}
KInt Kotlin_StringBuilder_insertString(KRef builder, KInt position, KString fromString) { KInt Kotlin_StringBuilder_insertString(KRef builder, KInt position, KString fromString) {
auto toArray = builder->array(); auto toArray = builder->array();
RuntimeAssert(toArray->count_ >= fromString->count_ + position, "must be true"); RuntimeAssert(toArray->count_ >= fromString->count_ + position, "must be true");
@@ -907,52 +962,6 @@ KBoolean Kotlin_String_equalsIgnoreCase(KString thiz, KConstRef other) {
return true; return true;
} }
OBJ_GETTER(Kotlin_String_replace, KString thiz, KChar oldChar, KChar newChar,
KBoolean ignoreCase) {
auto count = thiz->count_;
ArrayHeader* result = AllocArrayInstance(
theStringTypeInfo, count, OBJ_RESULT)->array();
const KChar* thizRaw = CharArrayAddressOfElementAt(thiz, 0);
KChar* resultRaw = CharArrayAddressOfElementAt(result, 0);
if (ignoreCase) {
KChar oldCharLower = towlower_Konan(oldChar);
for (KInt index = 0; index < count; ++index) {
KChar thizChar = *thizRaw++;
*resultRaw++ = towlower_Konan(thizChar) == oldCharLower ? newChar : thizChar;
}
} else {
for (KInt index = 0; index < count; ++index) {
KChar thizChar = *thizRaw++;
*resultRaw++ = thizChar == oldChar ? newChar : thizChar;
}
}
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_toUpperCase, KString thiz) {
auto count = thiz->count_;
ArrayHeader* result = AllocArrayInstance(
theStringTypeInfo, count, OBJ_RESULT)->array();
const KChar* thizRaw = CharArrayAddressOfElementAt(thiz, 0);
KChar* resultRaw = CharArrayAddressOfElementAt(result, 0);
for (KInt index = 0; index < count; ++index) {
*resultRaw++ = towupper_Konan(*thizRaw++);
}
RETURN_OBJ(result->obj());
}
OBJ_GETTER(Kotlin_String_toLowerCase, KString thiz) {
auto count = thiz->count_;
ArrayHeader* result = AllocArrayInstance(
theStringTypeInfo, count, OBJ_RESULT)->array();
const KChar* thizRaw = CharArrayAddressOfElementAt(thiz, 0);
KChar* resultRaw = CharArrayAddressOfElementAt(result, 0);
for (KInt index = 0; index < count; ++index) {
*resultRaw++ = towlower_Konan(*thizRaw++);
}
RETURN_OBJ(result->obj());
}
KBoolean Kotlin_String_regionMatches(KString thiz, KInt thizOffset, KBoolean Kotlin_String_regionMatches(KString thiz, KInt thizOffset,
KString other, KInt otherOffset, KString other, KInt otherOffset,
KInt length, KBoolean ignoreCase) { KInt length, KBoolean ignoreCase) {
@@ -1161,22 +1170,6 @@ KInt Kotlin_String_hashCode(KString thiz) {
CharArrayAddressOfElementAt(thiz, 0), thiz->count_ * sizeof(KChar)); CharArrayAddressOfElementAt(thiz, 0), thiz->count_ * sizeof(KChar));
} }
OBJ_GETTER(Kotlin_String_subSequence, KString thiz, KInt startIndex, KInt endIndex) {
if (startIndex < 0 || endIndex > thiz->count_ || startIndex > endIndex) {
// TODO: is it correct exception?
ThrowArrayIndexOutOfBoundsException();
}
if (startIndex == endIndex) {
RETURN_RESULT_OF0(TheEmptyString);
}
KInt length = endIndex - startIndex;
ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, length, OBJ_RESULT)->array();
memcpy(CharArrayAddressOfElementAt(result, 0),
CharArrayAddressOfElementAt(thiz, startIndex),
length * sizeof(KChar));
RETURN_OBJ(result->obj());
}
const KChar* Kotlin_String_utf16pointer(KString message) { const KChar* Kotlin_String_utf16pointer(KString message) {
RuntimeAssert(message->type_info() == theStringTypeInfo, "Must use a string"); RuntimeAssert(message->type_info() == theStringTypeInfo, "Must use a string");
const KChar* utf16 = CharArrayAddressOfElementAt(message, 0); const KChar* utf16 = CharArrayAddressOfElementAt(message, 0);
File diff suppressed because it is too large Load Diff
+21 -4
View File
@@ -426,11 +426,30 @@ void ResumeMemory(MemoryState* state);
// Escape analysis algorithm is the provider of information for decision on exact aux slot // Escape analysis algorithm is the provider of information for decision on exact aux slot
// selection, and comes from upper bound esteemation of object lifetime. // selection, and comes from upper bound esteemation of object lifetime.
// //
OBJ_GETTER(AllocInstanceStrict, const TypeInfo* type_info) RUNTIME_NOTHROW;
OBJ_GETTER(AllocInstanceRelaxed, const TypeInfo* type_info) RUNTIME_NOTHROW;
OBJ_GETTER(AllocInstance, const TypeInfo* type_info) RUNTIME_NOTHROW; OBJ_GETTER(AllocInstance, const TypeInfo* type_info) RUNTIME_NOTHROW;
OBJ_GETTER(AllocArrayInstanceStrict, const TypeInfo* type_info, int32_t elements);
OBJ_GETTER(AllocArrayInstanceRelaxed, const TypeInfo* type_info, int32_t elements);
OBJ_GETTER(AllocArrayInstance, const TypeInfo* type_info, int32_t elements); OBJ_GETTER(AllocArrayInstance, const TypeInfo* type_info, int32_t elements);
OBJ_GETTER(InitInstanceStrict,
ObjHeader** location, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*));
OBJ_GETTER(InitInstanceRelaxed,
ObjHeader** location, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*));
OBJ_GETTER(InitInstance,
ObjHeader** location, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*));
OBJ_GETTER(InitSharedInstanceStrict,
ObjHeader** location, ObjHeader** localLocation, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*));
OBJ_GETTER(InitSharedInstanceRelaxed,
ObjHeader** location, ObjHeader** localLocation, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*));
OBJ_GETTER(InitSharedInstance,
ObjHeader** location, ObjHeader** localLocation, const TypeInfo* typeInfo, void (*ctor)(ObjHeader*));
// Cleanup references inside object.
void DeinitInstanceBody(const TypeInfo* typeInfo, void* body); void DeinitInstanceBody(const TypeInfo* typeInfo, void* body);
OBJ_GETTER(InitInstance, ObjHeader** location, const TypeInfo* type_info,
void (*ctor)(ObjHeader*));
// Weak reference operations. // Weak reference operations.
// Atomically clears counter object reference. // Atomically clears counter object reference.
@@ -485,8 +504,6 @@ OBJ_GETTER(ReadHeapRefLocked, ObjHeader** location, int32_t* spinlock) RUNTIME_N
void EnterFrame(ObjHeader** start, int parameters, int count) RUNTIME_NOTHROW; void EnterFrame(ObjHeader** start, int parameters, int count) RUNTIME_NOTHROW;
// Called on frame leave, if it has object slots. // Called on frame leave, if it has object slots.
void LeaveFrame(ObjHeader** start, int parameters, int count) RUNTIME_NOTHROW; void LeaveFrame(ObjHeader** start, int parameters, int count) RUNTIME_NOTHROW;
// Collect garbage, which cannot be found by reference counting (cycles).
void GarbageCollect() RUNTIME_NOTHROW;
// Clears object subgraph references from memory subsystem, and optionally // Clears object subgraph references from memory subsystem, and optionally
// checks if subgraph referenced by given root is disjoint from the rest of // checks if subgraph referenced by given root is disjoint from the rest of
// object graph, i.e. no external references exists. // object graph, i.e. no external references exists.
+5
View File
@@ -19,7 +19,12 @@
#include "Memory.h" #include "Memory.h"
extern "C" {
void AddRefFromAssociatedObject(const ObjHeader* object) RUNTIME_NOTHROW; void AddRefFromAssociatedObject(const ObjHeader* object) RUNTIME_NOTHROW;
void ReleaseRefFromAssociatedObject(const ObjHeader* object) RUNTIME_NOTHROW; void ReleaseRefFromAssociatedObject(const ObjHeader* object) RUNTIME_NOTHROW;
void Kotlin_ObjCExport_releaseAssociatedObject(void* associatedObject);
} // extern "C"
#endif // RUNTIME_MEMORYPRIVATE_HPP #endif // RUNTIME_MEMORYPRIVATE_HPP
+2 -64
View File
@@ -84,72 +84,10 @@ inline const KRef* ArrayAddressOfElementAt(const ArrayHeader* obj, KInt index) {
extern "C" { extern "C" {
#endif #endif
// RuntimeUtils.kt.
OBJ_GETTER0(TheEmptyString); OBJ_GETTER0(TheEmptyString);
// Any.kt
KBoolean Kotlin_Any_equals(KConstRef thiz, KConstRef other);
KInt Kotlin_Any_hashCode(KConstRef thiz);
OBJ_GETTER(Kotlin_Any_toString, KConstRef thiz);
// Arrays.kt
// TODO: those must be compiler intrinsics afterwards.
OBJ_GETTER(Kotlin_Array_clone, KConstRef thiz);
OBJ_GETTER(Kotlin_Array_get, KConstRef thiz, KInt index);
void Kotlin_Array_set(KRef thiz, KInt index, KConstRef value);
KInt Kotlin_Array_getArrayLength(KConstRef thiz);
OBJ_GETTER(Kotlin_ByteArray_clone, KConstRef thiz);
KByte Kotlin_ByteArray_get(KConstRef thiz, KInt index);
void Kotlin_ByteArray_set(KRef thiz, KInt index, KByte value);
KInt Kotlin_ByteArray_getArrayLength(KConstRef thiz);
OBJ_GETTER(Kotlin_CharArray_clone, KConstRef thiz);
KChar Kotlin_CharArray_get(KConstRef thiz, KInt index);
void Kotlin_CharArray_set(KRef thiz, KInt index, KChar value);
KInt Kotlin_CharArray_getArrayLength(KConstRef thiz);
OBJ_GETTER(Kotlin_IntArray_clone, KConstRef thiz);
KInt Kotlin_IntArray_get(KConstRef thiz, KInt index);
void Kotlin_IntArray_set(KRef thiz, KInt index, KInt value);
KInt Kotlin_IntArray_getArrayLength(KConstRef thiz);
KLong Kotlin_LongArray_get(KConstRef thiz, KInt index);
void Kotlin_LongArray_set(KRef thiz, KInt index, KLong value);
KNativePtr Kotlin_NativePtrArray_get(KConstRef thiz, KInt index);
void Kotlin_NativePtrArray_set(KRef thiz, KInt index, KNativePtr value);
KInt Kotlin_NativePtrArray_getArrayLength(KConstRef thiz);
// io/Console.kt
void Kotlin_io_Console_print(KString message);
void Kotlin_io_Console_println(KString message);
void Kotlin_io_Console_println0(); void Kotlin_io_Console_println0();
OBJ_GETTER0(Kotlin_io_Console_readLine); void Kotlin_NativePtrArray_set(KRef thiz, KInt index, KNativePtr value);
KNativePtr Kotlin_NativePtrArray_get(KConstRef thiz, KInt index);
// Primitives.kt.
OBJ_GETTER(Kotlin_Int_toString, KInt value);
// String.kt
KInt Kotlin_String_hashCode(KString thiz);
KBoolean Kotlin_String_equals(KString thiz, KConstRef other);
KInt Kotlin_String_compareTo(KString thiz, KString other);
KInt Kotlin_String_compareToIgnoreCase(KString thiz, KConstRef other);
KChar Kotlin_String_get(KString thiz, KInt index);
OBJ_GETTER(Kotlin_String_fromUtf8Array, KConstRef array, KInt start, KInt size);
OBJ_GETTER(Kotlin_String_fromCharArray, KConstRef array, KInt start, KInt size);
OBJ_GETTER(Kotlin_String_plusImpl, KString thiz, KString other);
KInt Kotlin_String_getStringLength(KString thiz);
OBJ_GETTER(Kotlin_String_subSequence, KString thiz, KInt startIndex, KInt endIndex);
OBJ_GETTER0(Kotlin_getCurrentStackTrace);
OBJ_GETTER(Kotlin_getStackTraceStrings, KConstRef stackTrace);
OBJ_GETTER0(Kotlin_native_internal_undefined);
void Kotlin_native_internal_GC_suspend(KRef);
void Kotlin_native_internal_GC_resume(KRef);
#ifdef __cplusplus #ifdef __cplusplus
} }
+1
View File
@@ -104,6 +104,7 @@ extern "C" id Kotlin_ObjCExport_GetAssociatedObject(ObjHeader* obj) {
} }
inline static OBJ_GETTER(AllocInstanceWithAssociatedObject, const TypeInfo* typeInfo, id associatedObject) { inline static OBJ_GETTER(AllocInstanceWithAssociatedObject, const TypeInfo* typeInfo, id associatedObject) {
// TODO: memory model!
ObjHeader* result = AllocInstance(typeInfo, OBJ_RESULT); ObjHeader* result = AllocInstance(typeInfo, OBJ_RESULT);
SetAssociatedObject(result, associatedObject); SetAssociatedObject(result, associatedObject);
return result; return result;
+8 -8
View File
@@ -548,6 +548,14 @@ KInt getCanonicalClass(KInt ch) {
return canonicalClassesValues[index]; return canonicalClassesValues[index];
} }
const Decomposition* getDecomposition(KInt codePoint) {
int index = binarySearchRange(decompositionKeys, ARRAY_SIZE(decompositionKeys), codePoint);
if (decompositionKeys[index] != codePoint) {
return nullptr;
}
return &decompositionValues[index];
}
} // namespace } // namespace
extern "C" { extern "C" {
@@ -561,14 +569,6 @@ KBoolean Kotlin_text_regex_hasSingleCodepointDecompositionInternal(KInt ch) {
return singleDecompositions[index] == ch; return singleDecompositions[index] == ch;
} }
const Decomposition* getDecomposition(KInt codePoint) {
int index = binarySearchRange(decompositionKeys, ARRAY_SIZE(decompositionKeys), codePoint);
if (decompositionKeys[index] != codePoint) {
return nullptr;
}
return &decompositionValues[index];
}
OBJ_GETTER(Kotlin_text_regex_getDecompositionInternal, KInt ch) { OBJ_GETTER(Kotlin_text_regex_getDecompositionInternal, KInt ch) {
const Decomposition* decomposition = getDecomposition(ch); const Decomposition* decomposition = getDecomposition(ch);
if (decomposition == nullptr) { if (decomposition == nullptr) {
+1 -2
View File
@@ -76,8 +76,7 @@ OBJ_GETTER(Kotlin_Byte_toString, KByte value) {
} }
OBJ_GETTER(Kotlin_Char_toString, KChar value) { OBJ_GETTER(Kotlin_Char_toString, KChar value) {
ArrayHeader* result = AllocArrayInstance( ArrayHeader* result = AllocArrayInstance(theStringTypeInfo, 1, OBJ_RESULT)->array();
theStringTypeInfo, 1, OBJ_RESULT)->array();
*CharArrayAddressOfElementAt(result, 0) = value; *CharArrayAddressOfElementAt(result, 0) = value;
RETURN_OBJ(result->obj()); RETURN_OBJ(result->obj());
} }
+1 -1
View File
@@ -46,7 +46,7 @@ public final class String : Comparable<String>, CharSequence {
external private fun getStringLength(): Int external private fun getStringLength(): Int
@SymbolName("Kotlin_String_plusImpl") @SymbolName("Kotlin_String_plusImpl")
external private fun plusImpl(other: Any): String external private fun plusImpl(other: String): String
@SymbolName("Kotlin_String_equals") @SymbolName("Kotlin_String_equals")
external public override fun equals(other: Any?): Boolean external public override fun equals(other: Any?): Boolean
@@ -55,7 +55,6 @@ internal external fun stringEqualsIgnoreCase(thiz: String, other: String): Boole
public actual external fun String.replace( public actual external fun String.replace(
oldChar: Char, newChar: Char, ignoreCase: Boolean): String oldChar: Char, newChar: Char, ignoreCase: Boolean): String
/** /**
* Returns a new string obtained by replacing all occurrences of the [oldValue] substring in this string * Returns a new string obtained by replacing all occurrences of the [oldValue] substring in this string
* with the specified [newValue] string. * with the specified [newValue] string.

Some files were not shown because too many files have changed in this diff Show More