[ObjCExport] Fix property setter

KT-64953: Required part for enum translation
This commit is contained in:
eugene.levenetc
2024-02-13 16:23:57 +01:00
committed by Space Team
parent 576851e514
commit 8f2fc3d1e2
21 changed files with 306 additions and 83 deletions
@@ -1,25 +1,32 @@
package org.jetbrains.kotlin.objcexport
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtConstructorSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtPropertyGetterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportFunctionName
context(KtAnalysisSession, KtObjCExportSession)
fun KtFunctionLikeSymbol.getObjCFunctionName(): ObjCExportFunctionName {
val resolveObjCNameAnnotation = resolveObjCNameAnnotation()
val resolvedObjCNameAnnotation = resolveObjCNameAnnotation()
return ObjCExportFunctionName(
swiftName = getSwiftName(resolvedObjCNameAnnotation),
objCName = getObjCName(resolvedObjCNameAnnotation)
)
}
private fun KtFunctionLikeSymbol.getObjCName(resolvedNameAnnotation: KtResolvedObjCNameAnnotation?): String {
return resolvedNameAnnotation?.objCName ?: translationName
}
val name: String = when (this) {
is KtFunctionSymbol -> this.name.asString()
is KtConstructorSymbol -> "init"
is KtPropertyGetterSymbol -> "get" //TODO: implement properly getter since it doesn't have [name]
else -> "Undefined name for $this type"
}
private fun KtFunctionLikeSymbol.getSwiftName(resolvedNameAnnotation: KtResolvedObjCNameAnnotation?): String {
return resolvedNameAnnotation?.swiftName ?: translationName
}
return ObjCExportFunctionName(
resolveObjCNameAnnotation?.swiftName ?: name, resolveObjCNameAnnotation?.objCName ?: name
)
}
private val KtFunctionLikeSymbol.translationName: String
get() = when (this) {
is KtFunctionSymbol -> name.asString()
is KtConstructorSymbol -> "init"
is KtPropertyGetterSymbol -> ""
is KtAnonymousFunctionSymbol -> ""
is KtPropertySetterSymbol -> ""
is KtSamConstructorSymbol -> ""
}
@@ -14,5 +14,5 @@ internal fun KtType.translateToObjCFunctionType(typeBridge: BlockPointerBridge):
parameterTypes = listOfNotNull(this.receiverType).plus(this.parameterTypes).map { parameterType ->
parameterType.translateToObjCReferenceType()
}
)
).withNullabilityOf(this)
}
@@ -185,7 +185,7 @@ private fun <T : Any> getPredefined(method: KtFunctionLikeSymbol, predefinedForA
context(KtAnalysisSession, KtObjCExportSession)
fun KtFunctionLikeSymbol.getSelector(methodBridge: MethodBridge): String {
getPredefined(this, Predefined.anyMethodSelectors)?.let { return it }
getPredefined(this, anyMethodSelectors)?.let { return it }
val parameters = methodBridge.valueParametersAssociated(this)
@@ -231,56 +231,28 @@ fun KtFunctionLikeSymbol.getSelector(methodBridge: MethodBridge): String {
return sb.toString()
}
/**
* [org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportNamerImpl.getMangledName]
*/
context(KtAnalysisSession, KtObjCExportSession)
private fun KtFunctionLikeSymbol.getMangledName(forSwift: Boolean): String {
if (this.isConstructor) {
return if (isArrayConstructor && !forSwift) "array" else "init"
return if (this.isConstructor) {
if (isArrayConstructor && !forSwift) "array" else "init"
} else {
getObjCFunctionName().name(forSwift).handleSpecialNames("do")
}
val candidate = when (this) {
is KtPropertyGetterSymbol -> {
this.getObjCFunctionName().name(forSwift)
}
is KtPropertySetterSymbol -> {
this.getObjCFunctionName().name(forSwift)
//TODO: find replacement for [this.correspondingProperty]
// "set${
// this.correspondingProperty.getObjCName().asString(forSwift).replaceFirstChar(kotlin.Char::uppercaseChar)
// }".toIdentifier()
}
else -> {
this.getObjCFunctionName().name(forSwift)
}
}
return candidate.mangleIfSpecialFamily("do")
}
/**
* [org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportNamerImpl.mangleIfSpecialFamily]
*/
private fun String.mangleIfSpecialFamily(prefix: String): String {
private fun String.handleSpecialNames(prefix: String): String {
val trimmed = this.dropWhile { it == '_' }
for (family in listOf("alloc", "copy", "mutableCopy", "new", "init")) {
if (trimmed.startsWithWords(family)) {
// Then method can be detected as having special family by Objective-C compiler.
// mangle the name:
return prefix + this.replaceFirstChar(Char::uppercaseChar)
}
}
// TODO: handle clashes with NSObject methods etc.
return this
}
/**
* [org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportNamerImpl.startsWithWords]
*/
private fun String.startsWithWords(words: String) = this.startsWith(words) &&
(this.length == words.length || !this[words.length].isLowerCase())
/**
* [org.jetbrains.kotlin.backend.konan.objcexport.MethodBrideExtensionsKt.valueParametersAssociated]
*/
@@ -302,6 +274,8 @@ fun MethodBridge.valueParametersAssociated(
}
}
private fun String.startsWithWords(words: String) = this.startsWith(words) &&
(this.length == words.length || !this[words.length].isLowerCase())
/**
* [org.jetbrains.kotlin.backend.konan.objcexport.ObjCExportTranslatorImpl.mapReturnType]
@@ -9,7 +9,6 @@ import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCIdType
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCProperty
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCType
import org.jetbrains.kotlin.backend.konan.objcexport.swiftNameAttribute
import org.jetbrains.kotlin.objcexport.analysisApiUtils.getPropertyMethodBridge
import org.jetbrains.kotlin.objcexport.analysisApiUtils.isVisibleInObjC
@@ -48,7 +47,9 @@ fun KtPropertySymbol.buildProperty(): ObjCProperty {
setterName = null
}
val getterName = null //TODO: Fix and use getter.getSelector(), it should return name when it's available
val getterSelector = getter?.getSelector(bridge)
val getterName: String? = if (getterSelector != name && getterSelector?.isNotBlank() == true) getterSelector else null
val declarationAttributes = mutableListOf(getSwiftPrivateAttribute() ?: swiftNameAttribute(propertyName.swiftName))
@@ -61,7 +62,7 @@ fun KtPropertySymbol.buildProperty(): ObjCProperty {
origin = getObjCExportStubOrigin(),
type = type ?: ObjCIdType, //[ObjCIdType] temp fix, should be translated properly, see KT-65709
propertyAttributes = attributes,
setterName = setterName,
setterName = if (setterName.isNullOrBlank()) null else setterName,
getterName = getterName,
declarationAttributes = declarationAttributes
)
@@ -7,7 +7,6 @@ import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.types.KtErrorType
import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.analysis.api.types.KtTypeParameterType
@@ -161,29 +160,6 @@ internal fun KtType.translateTypeArgumentsToObjC(): List<ObjCNonNullReferenceTyp
}
}
context(KtAnalysisSession)
private fun ObjCNonNullReferenceType.withNullabilityOf(kotlinType: KtType): ObjCReferenceType {
return if (kotlinType.isBinaryRepresentationNullable()) {
ObjCNullableReferenceType(this)
} else {
this
}
}
context(KtAnalysisSession)
private fun KtType.isBinaryRepresentationNullable(): Boolean {
/* Convention to match K1 implementation */
if (this is KtErrorType) return false
if (fullyExpandedType.canBeNull) return true
getInlineTargetTypeOrNull()?.let { inlineTargetType ->
if (inlineTargetType.canBeNull) return true
}
return false
}
/**
* Types to be "hidden" during mapping, i.e., represented as `id`.
@@ -0,0 +1,36 @@
package org.jetbrains.kotlin.objcexport
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.types.KtErrorType
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCNonNullReferenceType
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCNullableReferenceType
import org.jetbrains.kotlin.backend.konan.objcexport.ObjCReferenceType
import org.jetbrains.kotlin.objcexport.analysisApiUtils.getInlineTargetTypeOrNull
/**
* [ObjCNonNullReferenceType] must be converted into [ObjCNullableReferenceType] if type is nullable
* So types could be marked with "_Nullable" in Objective-C
*/
context(KtAnalysisSession)
internal fun ObjCNonNullReferenceType.withNullabilityOf(kotlinType: KtType): ObjCReferenceType {
return if (kotlinType.isBinaryRepresentationNullable()) {
ObjCNullableReferenceType(this)
} else {
this
}
}
context(KtAnalysisSession)
internal fun KtType.isBinaryRepresentationNullable(): Boolean {
/* Convention to match K1 implementation */
if (this is KtErrorType) return false
if (fullyExpandedType.canBeNull) return true
getInlineTargetTypeOrNull()?.let { inlineTargetType ->
if (inlineTargetType.canBeNull) return true
}
return false
}
@@ -123,6 +123,11 @@ class ObjCExportHeaderGeneratorTest(private val generator: HeaderGenerator) {
doTest(headersTestDataDir.resolve("functionWithObjCNameAnnotation"))
}
@Test
fun `test - propertyWithObjCNameAnnotation`() {
doTest(headersTestDataDir.resolve("propertyWithObjCNameAnnotation"))
}
@Test
fun `test - classWithKDoc`() {
doTest(headersTestDataDir.resolve("classWithKDoc"))
@@ -282,6 +287,30 @@ class ObjCExportHeaderGeneratorTest(private val generator: HeaderGenerator) {
doTest(headersTestDataDir.resolve("companion"))
}
@Test
fun `test - anonymous functions`() {
doTest(headersTestDataDir.resolve("anonymousFunctions"))
}
@Test
fun `test - sam interface`() {
doTest(headersTestDataDir.resolve("samInterface"))
}
/**
* Requires some fixes: KT-65800
*/
@Test
@TodoAnalysisApi
fun `test - simple data class`() {
doTest(headersTestDataDir.resolve("simpleDataClass"))
}
@Test
fun `test - special function names`() {
doTest(headersTestDataDir.resolve("specialFunctionNames"))
}
private fun doTest(root: File, configuration: Configuration = Configuration()) {
if (!root.isDirectory) fail("Expected ${root.absolutePath} to be directory")
val generatedHeaders = generator.generateHeaders(root, configuration).toString()
@@ -0,0 +1,32 @@
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
NS_ASSUME_NONNULL_BEGIN
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wincompatible-property-type"
#pragma clang diagnostic ignored "-Wnullability"
#pragma push_macro("_Nullable_result")
#if !__has_feature(nullability_nullable_result)
#undef _Nullable_result
#define _Nullable_result _Nullable
#endif
__attribute__((objc_subclassing_restricted))
@interface FooKt : Base
+ (void)funParamParam:(void (^)(void))param __attribute__((swift_name("funParam(param:)")));
+ (void)funParamDefaultParam:(void (^)(void))param __attribute__((swift_name("funParamDefault(param:)")));
+ (void (^)(void))funReturnsFun __attribute__((swift_name("funReturnsFun()")));
+ (void (^ _Nullable)(void))funReturnsNullableFun __attribute__((swift_name("funReturnsNullableFun()")));
@property (class, readonly) void (^funProperty)(void) __attribute__((swift_name("funProperty")));
@end
#pragma pop_macro("_Nullable_result")
#pragma clang diagnostic pop
NS_ASSUME_NONNULL_END
@@ -0,0 +1,5 @@
val funProperty: () -> Unit = {}
fun funParam(param: () -> Unit) {}
fun funParamDefault(param: () -> Unit = {}) {}
fun funReturnsFun(): () -> Unit = {}
fun funReturnsNullableFun(): (() -> Unit)? = null
@@ -30,6 +30,11 @@ __attribute__((objc_subclassing_restricted))
- (instancetype)initWithA:(int32_t)a b:(int32_t)b c:(int32_t)c __attribute__((swift_name("init(a:b:c:)"))) __attribute__((objc_designated_initializer));
@end
__attribute__((objc_subclassing_restricted))
@interface ConstructorFunction : Base
- (instancetype)initWithFoo:(void (^)(void))foo __attribute__((swift_name("init(foo:)"))) __attribute__((objc_designated_initializer));
@end
__attribute__((objc_subclassing_restricted))
@interface ConstructorParam0 : Base
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
@@ -7,4 +7,6 @@ class ConstructorDouble(a: Int) {
constructor(a: Int): this(a)
constructor(a: Int, b: Int): this(b)
constructor(a: Int, b: Int, c: Int): this(c)
}
}
class ConstructorFunction(foo: () -> Unit)
@@ -0,0 +1,29 @@
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
NS_ASSUME_NONNULL_BEGIN
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wincompatible-property-type"
#pragma clang diagnostic ignored "-Wnullability"
#pragma push_macro("_Nullable_result")
#if !__has_feature(nullability_nullable_result)
#undef _Nullable_result
#define _Nullable_result _Nullable
#endif
__attribute__((objc_subclassing_restricted))
@interface FooKt : Base
@property (class, readonly) int32_t objcValName __attribute__((swift_name("swiftValName")));
@property (class) int32_t objcVaRName __attribute__((swift_name("swiftVaRName")));
@end
#pragma pop_macro("_Nullable_result")
#pragma clang diagnostic pop
NS_ASSUME_NONNULL_END
@@ -0,0 +1,9 @@
@file:OptIn(ExperimentalObjCName::class)
import kotlin.experimental.ExperimentalObjCName
@kotlin.native.ObjCName("objcValName", "swiftValName")
val valProperty = 42
@kotlin.native.ObjCName("objcVaRName", "swiftVaRName")
var varProperty = 42
@@ -0,0 +1,28 @@
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
NS_ASSUME_NONNULL_BEGIN
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wincompatible-property-type"
#pragma clang diagnostic ignored "-Wnullability"
#pragma push_macro("_Nullable_result")
#if !__has_feature(nullability_nullable_result)
#undef _Nullable_result
#define _Nullable_result _Nullable
#endif
@protocol Foo
@required
- (void)invoke __attribute__((swift_name("invoke()")));
@end
#pragma pop_macro("_Nullable_result")
#pragma clang diagnostic pop
NS_ASSUME_NONNULL_END
@@ -0,0 +1,3 @@
fun interface Foo {
fun invoke()
}
@@ -0,0 +1,37 @@
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
@class SimpleDataClass;
NS_ASSUME_NONNULL_BEGIN
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wincompatible-property-type"
#pragma clang diagnostic ignored "-Wnullability"
#pragma push_macro("_Nullable_result")
#if !__has_feature(nullability_nullable_result)
#undef _Nullable_result
#define _Nullable_result _Nullable
#endif
__attribute__((objc_subclassing_restricted))
@interface SimpleDataClass : Base
- (instancetype)initWithIntValue:(int32_t)intValue intVar:(int32_t)intVar nullableDefaultStringValue:(NSString * _Nullable)nullableDefaultStringValue __attribute__((swift_name("init(intValue:intVar:nullableDefaultStringValue:)"))) __attribute__((objc_designated_initializer));
- (SimpleDataClass *)doCopyIntValue:(int32_t)intValue intVar:(int32_t)intVar nullableDefaultStringValue:(NSString * _Nullable)nullableDefaultStringValue __attribute__((swift_name("doCopy(intValue:intVar:nullableDefaultStringValue:)")));
- (BOOL)isEqual:(id _Nullable)other __attribute__((swift_name("isEqual(_:)")));
- (NSUInteger)hash __attribute__((swift_name("hash()")));
- (NSString *)description __attribute__((swift_name("description()")));
@property (readonly) int32_t intValue __attribute__((swift_name("intValue")));
@property int32_t intVar __attribute__((swift_name("intVar")));
@property (readonly) NSString * _Nullable nullableDefaultStringValue __attribute__((swift_name("nullableDefaultStringValue")));
@end
#pragma pop_macro("_Nullable_result")
#pragma clang diagnostic pop
NS_ASSUME_NONNULL_END
@@ -0,0 +1,5 @@
data class SimpleDataClass(
val intValue: Int,
var intVar: Int,
val nullableDefaultStringValue: String? = ""
)
@@ -0,0 +1,36 @@
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
@class Foo;
NS_ASSUME_NONNULL_BEGIN
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-warning-option"
#pragma clang diagnostic ignored "-Wincompatible-property-type"
#pragma clang diagnostic ignored "-Wnullability"
#pragma push_macro("_Nullable_result")
#if !__has_feature(nullability_nullable_result)
#undef _Nullable_result
#define _Nullable_result _Nullable
#endif
__attribute__((objc_subclassing_restricted))
@interface Foo : Base
- (instancetype)init __attribute__((swift_name("init()"))) __attribute__((objc_designated_initializer));
+ (instancetype)new __attribute__((availability(swift, unavailable, message="use object initializers instead")));
- (void)doAlloc __attribute__((swift_name("doAlloc()")));
- (Foo *)doCopy __attribute__((swift_name("doCopy()")));
- (Foo *)doInit __attribute__((swift_name("doInit()")));
- (Foo *)doMutableCopy __attribute__((swift_name("doMutableCopy()")));
- (Foo *)doNew __attribute__((swift_name("doNew()")));
@end
#pragma pop_macro("_Nullable_result")
#pragma clang diagnostic pop
NS_ASSUME_NONNULL_END
@@ -0,0 +1,7 @@
class Foo {
fun alloc() {}
fun copy(): Foo = Foo()
fun mutableCopy(): Foo = Foo()
fun new(): Foo = Foo()
fun init(): Foo = Foo()
}
@@ -20,7 +20,8 @@ NS_ASSUME_NONNULL_BEGIN
__attribute__((objc_subclassing_restricted))
@interface FooKt : Base
@property (class, readonly) int32_t myTopLevelProperty __attribute__((swift_name("myTopLevelProperty")));
@property (class, readonly) int32_t topLevelVal __attribute__((swift_name("topLevelVal")));
@property (class) int32_t topLevelVar __attribute__((swift_name("topLevelVar")));
@end
#pragma pop_macro("_Nullable_result")
@@ -1 +1,2 @@
val myTopLevelProperty = 42
val topLevelVal = 42
var topLevelVar = 42