diff --git a/NativeScript/runtime/ClassBuilder.h b/NativeScript/runtime/ClassBuilder.h index d6a353279..1b122fe0a 100644 --- a/NativeScript/runtime/ClassBuilder.h +++ b/NativeScript/runtime/ClassBuilder.h @@ -35,12 +35,21 @@ class ClassBuilder { v8::Local context); static void RegisterNativeTypeScriptExtendsFunction( v8::Local context); + // Clears `*encodable` instead of asserting when a type has no compiler + // encoding the runtime can reproduce. static std::string GetTypeEncoding(const TypeEncoding* typeEncoding, - int argsCount); + int argsCount, bool* encodable = nullptr); + // A JS-implemented property accessor's encoding, or `fallback` when its + // types have no compiler encoding the runtime can reproduce. + static std::string GetAccessorTypeEncoding(const TypeEncoding* typeEncoding, + int argsCount, + const char* fallback); // `klass` or its nearest superclass not defined from JS. static Class FindNativeClass(Class klass); // The implementation of `method` from FindNativeClass(klass). static IMP FindNotOverridenMethod(Class klass, SEL method); + // Whether `klass`, not one of its superclasses, implements `selector`. + static bool ImplementsItself(Class klass, SEL selector); private: static std::atomic classNameCounter_; @@ -73,7 +82,13 @@ class ClassBuilder { v8::Local implementationObject, v8::Local getter, v8::Local setter); - static std::string GetTypeEncoding(const TypeEncoding* typeEncoding); + // Follows clang: a struct behind a pointer is expanded only when that + // pointer is the outermost type, otherwise it is named only ("{Name}"), + // which also bounds self-referential structs. + static std::string GetTypeEncoding(const TypeEncoding* typeEncoding, + bool* encodable, + bool expandStructures = true, + bool expandPointedToStructures = true); static BinaryTypeEncodingType GetTypeEncodingType(v8::Isolate* isolate, v8::Local value); diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 47c77ea43..0605ff4ef 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -435,7 +435,8 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { implementationObject); } -std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding) { +std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, bool* encodable, + bool expandStructures, bool expandPointedToStructures) { BinaryTypeEncodingType type = typeEncoding->type; switch (type) { case BinaryTypeEncodingType::VoidEncoding: { @@ -504,7 +505,14 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } case BinaryTypeEncodingType::StructDeclarationReference: { const char* structName = typeEncoding->details.declarationReference.name.valuePtr(); + if (!expandStructures) { + return std::string("{") + structName + "}"; + } const Meta* meta = ArgConverter::GetMeta(structName); + if (encodable != nullptr && (meta == nullptr || meta->type() != MetaType::Struct)) { + *encodable = false; + return ""; + } tns::Assert(meta != nullptr && meta->type() == MetaType::Struct); const StructMeta* structMeta = static_cast(meta); const TypeEncoding* fieldEncoding = structMeta->fieldsEncodings()->first(); @@ -512,7 +520,7 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "{" << structName << "="; for (int i = 0; i < structMeta->fieldsCount(); i++) { - ss << GetTypeEncoding(fieldEncoding); + ss << GetTypeEncoding(fieldEncoding, encodable, true, false); fieldEncoding = fieldEncoding->next(); } ss << "}"; @@ -522,14 +530,15 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { std::stringstream ss; ss << "^"; const TypeEncoding* innerType = typeEncoding->details.pointer.getInnerType(); - ss << GetTypeEncoding(innerType); + ss << GetTypeEncoding(innerType, encodable, expandPointedToStructures, false); return ss.str(); } case BinaryTypeEncodingType::ConstantArrayEncoding: { const TypeEncoding* innerType = typeEncoding->details.constantArray.getInnerType(); std::stringstream ss; ss << "["; - ss << typeEncoding->details.constantArray.size << GetTypeEncoding(innerType); + ss << typeEncoding->details.constantArray.size + << GetTypeEncoding(innerType, encodable, expandStructures, false); ss << "]"; return ss.str(); } @@ -537,9 +546,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const TypeEncoding* innerType = typeEncoding->details.incompleteArray.getInnerType(); std::stringstream ss; ss << "^"; - ss << GetTypeEncoding(innerType); + ss << GetTypeEncoding(innerType, encodable, expandStructures, false); return ss.str(); } + case BinaryTypeEncodingType::FunctionPointerEncoding: { + return "^?"; + } case BinaryTypeEncodingType::ProtocolEncoding: case BinaryTypeEncodingType::InterfaceDeclarationReference: case BinaryTypeEncodingType::InstanceTypeEncoding: @@ -549,24 +561,36 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { default: // TODO: Handle the other possible types + if (encodable != nullptr) { + *encodable = false; + return ""; + } tns::Assert(false); return ""; } } -std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount) { +std::string ClassBuilder::GetTypeEncoding(const TypeEncoding* typeEncoding, int argsCount, + bool* encodable) { std::stringstream compilerEncoding; - compilerEncoding << GetTypeEncoding(typeEncoding); + compilerEncoding << GetTypeEncoding(typeEncoding, encodable); compilerEncoding << "@:"; // id self, SEL _cmd for (int i = 0; i < argsCount; i++) { typeEncoding = typeEncoding->next(); - compilerEncoding << GetTypeEncoding(typeEncoding); + compilerEncoding << GetTypeEncoding(typeEncoding, encodable); } return compilerEncoding.str(); } +std::string ClassBuilder::GetAccessorTypeEncoding(const TypeEncoding* typeEncoding, int argsCount, + const char* fallback) { + bool encodable = true; + std::string encoding = GetTypeEncoding(typeEncoding, argsCount, &encodable); + return encodable ? encoding : fallback; +} + BinaryTypeEncodingType ClassBuilder::GetTypeEncodingType(Isolate* isolate, Local value) { if (BaseDataWrapper* wrapper = tns::GetValue(isolate, value)) { if (wrapper->Type() == WrapperType::ObjCClass) { @@ -883,6 +907,20 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { } } +// Reads the class's own method list: class_getInstanceMethod asks the class to +// resolve a selector nothing implements, which initializes a class that is +// still being built. +bool ClassBuilder::ImplementsItself(Class klass, SEL selector) { + unsigned int count = 0; + Method* methods = class_copyMethodList(klass, &count); + bool found = false; + for (unsigned int i = 0; i < count && !found; i++) { + found = method_getName(methods[i]) == selector; + } + free(methods); + return found; +} + void ClassBuilder::ExposeProperties(Isolate* isolate, Class extendedClass, std::vector propertyMetas, Local implementationObject, Local getter, @@ -891,8 +929,12 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const PropertyMeta* propertyMeta = propertyMetas[j]; std::string propertyName = propertyMeta->name(); - bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter(); - bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter(); + // An accessor the class already implements itself came from an earlier + // metadata entry or exposedMethods; class_addMethod would refuse it. + bool hasGetter = !getter.IsEmpty() && getter->IsFunction() && propertyMeta->hasGetter() && + !ImplementsItself(extendedClass, propertyMeta->getter()->selector()); + bool hasSetter = !setter.IsEmpty() && setter->IsFunction() && propertyMeta->hasSetter() && + !ImplementsItself(extendedClass, propertyMeta->setter()->selector()); std::shared_ptr> poImplementationObject; if (hasGetter || hasSetter) { @@ -950,8 +992,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { }; const TypeEncoding* typeEncoding = propertyMeta->getter()->encodings()->first(); IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData); + std::string types = GetAccessorTypeEncoding(typeEncoding, 0, "@@:"); - class_addMethod(extendedClass, propertyMeta->getter()->selector(), impGetter, "@@:"); + class_addMethod(extendedClass, propertyMeta->getter()->selector(), impGetter, types.c_str()); } if (hasSetter) { @@ -1002,8 +1045,9 @@ void ScopeClassNameToIsolate(std::string& name, int isolateId) { const TypeEncoding* typeEncoding = propertyMeta->setter()->encodings()->first(); IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData); + std::string types = GetAccessorTypeEncoding(typeEncoding, 1, "v@:@"); - class_addMethod(extendedClass, propertyMeta->setter()->selector(), impSetter, "v@:@"); + class_addMethod(extendedClass, propertyMeta->setter()->selector(), impSetter, types.c_str()); } } } diff --git a/NativeScript/runtime/MetadataBuilder.mm b/NativeScript/runtime/MetadataBuilder.mm index c27caa1ba..cac616fd7 100644 --- a/NativeScript/runtime/MetadataBuilder.mm +++ b/NativeScript/runtime/MetadataBuilder.mm @@ -1366,6 +1366,30 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, } } +namespace { + +// The native implementation `klass` answered `selector` with stays reachable +// under the swizzled-prefixed selector that native calls from JS prefer. A +// class that only inherits `selector` below a replaced ancestor takes that +// ancestor's alias: its selector resolves to the ancestor's JS replacement, +// and an alias naming a native override in between would be re-entered when +// that override calls super. Every replaced class gets an alias of its own, +// which a later replacement keeps, so it never names an earlier replacement. +void ReplaceKeepingOriginal(Class klass, SEL selector, const char* selectorName, IMP imp, + const char* types) { + SEL alias = sel_registerName((Constants::SwizzledPrefix + selectorName).c_str()); + bool inheritsAlias = + !ClassBuilder::ImplementsItself(klass, selector) && class_respondsToSelector(klass, alias); + Method method = class_getInstanceMethod(klass, inheritsAlias ? alias : selector); + IMP original = method != nullptr ? method_getImplementation(method) : nullptr; + class_replaceMethod(klass, selector, imp, types); + if (original != nullptr) { + class_addMethod(klass, alias, original, types); + } +} + +} // namespace + v8::Intercepted MetadataBuilder::SwizzledInstanceMethodCallback( Local property, Local value, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); @@ -1402,13 +1426,8 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, Interop::ConsumedObjectArgumentIndex(methodMeta->selector(), typeEncoding, argsCount)); IMP methodBody = Interop::CreateMethod(2, argsCount, typeEncoding, ArgConverter::MethodCallback, userData); - IMP nativeImp = - class_replaceMethod(klass, methodMeta->selector(), methodBody, compilerEncoding.c_str()); - if (nativeImp) { - std::string selector = methodMeta->selectorAsString(); - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding.c_str()); - } + ReplaceKeepingOriginal(klass, methodMeta->selector(), methodMeta->selectorAsString(), methodBody, + compilerEncoding.c_str()); // Not intercepted: the native write is done, but V8 must still perform // the ordinary store, which is what the old void-returning callback did // by falling through without setting a return value. @@ -1493,8 +1512,8 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, } }; - const char* compilerEncoding = "@@:"; const TypeEncoding* typeEncoding = propertyMeta->getter()->encodings()->first(); + std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 0, "@@:"); Local getter = desc.get(); std::shared_ptr> poGetterFunc = @@ -1502,11 +1521,9 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, PropertyCallbackContext* userData = new PropertyCallbackContext(isolate, poGetterFunc, nullptr, propertyMeta); IMP impGetter = Interop::CreateMethod(2, 0, typeEncoding, getterCallback, userData); - IMP nativeImp = - class_replaceMethod(klass, propertyMeta->getter()->selector(), impGetter, compilerEncoding); - std::string selector = propertyMeta->getter()->selectorAsString(); - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding); + ReplaceKeepingOriginal(klass, propertyMeta->getter()->selector(), + propertyMeta->getter()->selectorAsString(), impGetter, + compilerEncoding.c_str()); } if (desc.has_set()) { @@ -1566,12 +1583,10 @@ CMethodCall methodCall(context, item->userData_, typeEncoding, args, new PropertyCallbackContext(isolate, poSetterFunc, nullptr, propertyMeta); IMP impSetter = Interop::CreateMethod(2, 1, typeEncoding, setterCallback, userData); - const char* compilerEncoding = "v@:@"; - IMP nativeImp = - class_replaceMethod(klass, propertyMeta->setter()->selector(), impSetter, compilerEncoding); - std::string selector = propertyMeta->setter()->selectorAsString(); - SEL nativeSelector = sel_registerName((Constants::SwizzledPrefix + selector).c_str()); - class_addMethod(klass, nativeSelector, nativeImp, compilerEncoding); + std::string compilerEncoding = ClassBuilder::GetAccessorTypeEncoding(typeEncoding, 1, "v@:@"); + ReplaceKeepingOriginal(klass, propertyMeta->setter()->selector(), + propertyMeta->setter()->selectorAsString(), impSetter, + compilerEncoding.c_str()); } // Not intercepted: the native write is done, but V8 must still perform // the ordinary store, which is what the old void-returning callback did diff --git a/TestFixtures/Api/TNSApi.h b/TestFixtures/Api/TNSApi.h index 58ed3b310..3c82b9a20 100644 --- a/TestFixtures/Api/TNSApi.h +++ b/TestFixtures/Api/TNSApi.h @@ -1,3 +1,5 @@ +#import + typedef NS_ENUM(NSInteger, TNSEnums) { TNSEnum1 = -1, TNSEnum2, @@ -77,3 +79,184 @@ typedef NSError* _Nullable TNSNullableError; @interface RectClass : NSObject @end + +@interface TNSAccessorTypes : NSObject +@property(nonatomic) BOOL boolProperty; +@property(nonatomic) NSUInteger unsignedProperty; +@property(nonatomic) NSInteger integerProperty; +@property(nonatomic) short shortProperty; +@property(nonatomic) unichar unicharProperty; +@property(nonatomic) char charProperty; +@property(nonatomic) unsigned char unsignedCharProperty; +@property(nonatomic) long long longLongProperty; +@property(nonatomic) float floatProperty; +@property(nonatomic) double doubleProperty; +@property(nonatomic) CGRect rectProperty; +@property(nonatomic) CGPoint pointProperty; +@property(nonatomic) SEL selectorProperty; +@property(nonatomic, strong) Class classProperty; +@property(nonatomic, copy) void (^blockProperty)(void); +@property(nonatomic) void* pointerProperty; +@property(nonatomic) int (*functionPointerProperty)(int); +@property(nonatomic) simd_float4 vectorProperty; +@property(nonatomic, copy) NSString* objectProperty; +@property(nonatomic, strong) id protocolObjectProperty; +@end + +@interface TNSAccessorSwizzleBase : NSObject +@property(nonatomic, readonly) double doubleProperty; +@property(nonatomic, readonly) BOOL boolProperty; +@end + +// Readwrite redeclarations keep these properties in this class's metadata, +// while their getters stay implemented by the superclass only. +@interface TNSAccessorSwizzleDerived : TNSAccessorSwizzleBase +@property(nonatomic, readwrite) double doubleProperty; +@property(nonatomic, readwrite) BOOL boolProperty; +@end + +@interface TNSInheritedSwizzleBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSInheritedSwizzleDerived : TNSInheritedSwizzleBase +@end + +// Compatible redeclarations with other types keep these members in this +// class's metadata, while only the superclass implements them. +@interface TNSInheritedSwizzleDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSInheritedSwizzleSubclass : TNSInheritedSwizzleDerived +@end + +@interface TNSInheritedSwizzleTwice : TNSInheritedSwizzleBase +@end + +@interface TNSInheritedSwizzleTwice (Redeclared) +@property(nonatomic) TNSEnums scalarValue; +@end + +// Families for specs that replace members on a class and on its subclass. +@interface TNSSwizzleChainBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSSwizzleChainDerived : TNSSwizzleChainBase +@end + +@interface TNSSwizzleChainDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSSwizzleReverseBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSSwizzleReverseDerived : TNSSwizzleReverseBase +@end + +@interface TNSSwizzleReverseDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSSwizzleRepeatBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +@interface TNSSwizzleRepeatDerived : TNSSwizzleRepeatBase +@end + +@interface TNSSwizzleRepeatDerived (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSSwizzleMiddleBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +// Overrides every member of its superclass natively, without calling it. +@interface TNSSwizzleMiddle : TNSSwizzleMiddleBase +@end + +@interface TNSSwizzleMiddleLeaf : TNSSwizzleMiddle +@end + +@interface TNSSwizzleMiddleLeaf (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +@interface TNSSwizzleSuperBase : NSObject +@property(nonatomic, strong) id objectValue; +@property(nonatomic) NSInteger scalarValue; +- (id)describeValue:(int)value; +- (id)storedObjectValue; +- (NSInteger)storedScalarValue; +@end + +// Overrides every member of its superclass natively, calling it. +@interface TNSSwizzleSuperMiddle : TNSSwizzleSuperBase +@end + +@interface TNSSwizzleSuperLeaf : TNSSwizzleSuperMiddle +@end + +@interface TNSSwizzleSuperLeaf (Redeclared) +@property(nonatomic, strong) NSString* objectValue; +@property(nonatomic) TNSEnums scalarValue; +- (NSString*)describeValue:(int)value; +@end + +typedef struct TNSLinkedNode { + int value; + struct TNSLinkedNode* next; +} TNSLinkedNode; + +typedef struct TNSLinkedLeaf { + int value; +} TNSLinkedLeaf; + +typedef struct TNSLinkedHolder { + TNSLinkedNode* node; + TNSLinkedLeaf* leaf; + int count; +} TNSLinkedHolder; + +@interface TNSLinkedTypes : NSObject +@property(nonatomic) TNSLinkedNode* nodeProperty; +@property(nonatomic) TNSLinkedHolder holderProperty; +@property(nonatomic) TNSLinkedLeaf* leafProperty; +- (TNSLinkedNode*)nextOf:(TNSLinkedNode*)node; +- (TNSLinkedHolder)holderWithLeaf:(TNSLinkedLeaf*)leaf; +@end diff --git a/TestFixtures/Api/TNSApi.m b/TestFixtures/Api/TNSApi.m index 2085b567d..fcdc6eafc 100644 --- a/TestFixtures/Api/TNSApi.m +++ b/TestFixtures/Api/TNSApi.m @@ -106,3 +106,210 @@ - (CGRect)getRect { } @end + +@implementation TNSAccessorTypes +@end + +@implementation TNSAccessorSwizzleBase +@end + +@implementation TNSAccessorSwizzleDerived { + double _derivedDouble; + BOOL _derivedBool; +} +@dynamic doubleProperty, boolProperty; + +- (void)setDoubleProperty:(double)value { + _derivedDouble = value; +} + +- (void)setBoolProperty:(BOOL)value { + _derivedBool = value; +} + +@end + +@implementation TNSInheritedSwizzleBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSInheritedSwizzleDerived +@end + +@implementation TNSInheritedSwizzleSubclass +@end + +@implementation TNSInheritedSwizzleTwice +@end + +@implementation TNSSwizzleChainBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleChainDerived +@end + +@implementation TNSSwizzleReverseBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleReverseDerived +@end + +@implementation TNSSwizzleRepeatBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleRepeatDerived +@end + +@implementation TNSSwizzleMiddleBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleMiddle { + id _middleObject; + NSInteger _middleScalar; +} + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"middle %d", value]; +} + +- (id)objectValue { + return [NSString stringWithFormat:@"middle %@", _middleObject]; +} + +- (void)setObjectValue:(id)value { + _middleObject = [NSString stringWithFormat:@"%@ via middle", value]; +} + +- (NSInteger)scalarValue { + return _middleScalar + 1000; +} + +- (void)setScalarValue:(NSInteger)value { + _middleScalar = value * 3; +} + +@end + +@implementation TNSSwizzleMiddleLeaf +@end + +@implementation TNSSwizzleSuperBase + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"base %d", value]; +} + +- (id)storedObjectValue { + return _objectValue; +} + +- (NSInteger)storedScalarValue { + return _scalarValue; +} + +@end + +@implementation TNSSwizzleSuperMiddle + +- (id)describeValue:(int)value { + return [NSString stringWithFormat:@"middle %@", [super describeValue:value]]; +} + +- (id)objectValue { + return [NSString stringWithFormat:@"middle %@", [super objectValue]]; +} + +- (void)setObjectValue:(id)value { + [super setObjectValue:[NSString stringWithFormat:@"%@ via middle", value]]; +} + +- (NSInteger)scalarValue { + return [super scalarValue] + 1000; +} + +- (void)setScalarValue:(NSInteger)value { + [super setScalarValue:value * 3]; +} + +@end + +@implementation TNSSwizzleSuperLeaf +@end + +static TNSLinkedNode sharedLinkedNodes[2] = {{1, &sharedLinkedNodes[1]}, {2, NULL}}; + +@implementation TNSLinkedTypes + +- (TNSLinkedNode*)nextOf:(TNSLinkedNode*)node { + return node != NULL ? node->next : NULL; +} + +- (TNSLinkedHolder)holderWithLeaf:(TNSLinkedLeaf*)leaf { + return (TNSLinkedHolder){&sharedLinkedNodes[0], leaf, 1}; +} + +@end diff --git a/TestRunner/app/tests/JSAccessorEncodingTests.js b/TestRunner/app/tests/JSAccessorEncodingTests.js new file mode 100644 index 000000000..89aedff0f --- /dev/null +++ b/TestRunner/app/tests/JSAccessorEncodingTests.js @@ -0,0 +1,747 @@ +// Native code that introspects a method (KVC, NSMethodSignature) must see a +// JS-implemented property accessor with the property's own type. +describe("JS-implemented native property accessors", function () { + var rect = { origin: { x: 1, y: 2 }, size: { width: 3, height: 4 } }; + var point = { x: 5, y: 6 }; + + // Every TNSAccessorTypes property, with the value its JS getter answers. + var answers = { + boolProperty: true, + unsignedProperty: 4000000000, + integerProperty: -3, + shortProperty: -2, + unicharProperty: 65, + charProperty: 7, + unsignedCharProperty: 200, + longLongProperty: -5, + floatProperty: 1.5, + doubleProperty: 2.5, + rectProperty: rect, + pointProperty: point, + selectorProperty: "description", + classProperty: NSObject, + blockProperty: function () {}, + pointerProperty: null, + functionPointerProperty: null, + vectorProperty: [1, 2, 3, 4], + objectProperty: "text", + protocolObjectProperty: null + }; + + function typeString(cString) { + return NSString.stringWithUTF8String(cString).toString(); + } + + function setterName(property) { + return "set" + property[0].toUpperCase() + property.slice(1) + ":"; + } + + function accessorDescriptors(state) { + var descriptors = { + hash: { + get: function () { + return 7; + }, + configurable: true, + enumerable: true + } + }; + Object.keys(answers).forEach(function (property) { + descriptors[property] = { + get: function () { + return answers[property]; + }, + set: function (value) { + state.received[property] = value; + }, + configurable: true, + enumerable: true + }; + }); + return descriptors; + } + + function makeExtended(name, state) { + return TNSAccessorTypes.extend(Object.defineProperties({}, accessorDescriptors(state)), { name: name }); + } + + function makeTypeScript(name, state) { + var Klass = (function (_super) { + __extends(Klass, _super); + function Klass() { + return (_super !== null && _super.apply(this, arguments)) || this; + } + Object.defineProperties(Klass.prototype, accessorDescriptors(state)); + return Klass; + })(TNSAccessorTypes); + return Klass; + } + + function expectRect(value, expected) { + expect([value.origin.x, value.origin.y, value.size.width, value.size.height]) + .toEqual([expected.origin.x, expected.origin.y, expected.size.width, expected.size.height]); + } + + [ + { title: ".extend()", make: makeExtended, name: "JSAccessorEncodingExtended" }, + { title: "__extends", make: makeTypeScript, name: "JSAccessorEncodingTypeScript" } + ].forEach(function (variant) { + describe("of a class made with " + variant.title, function () { + var state = { received: {} }; + var Klass = variant.make(variant.name, state); + + beforeEach(function () { + state.received = {}; + }); + + it("answer valueForKey: with an NSUInteger", function () { + var obj = Klass.new(); + expect(obj.valueForKey("hash")).toBe(7); + expect(obj.valueForKey("unsignedProperty")).toBe(4000000000); + }); + + it("answer -[NSArray valueForKey:] with an NSUInteger", function () { + var values = NSArray.arrayWithArray([Klass.new(), Klass.new()]).valueForKey("hash"); + expect(values.count).toBe(2); + expect(values.objectAtIndex(0)).toBe(7); + expect(values.objectAtIndex(1)).toBe(7); + }); + + it("answer valueForKey: with a BOOL", function () { + expect(Klass.new().valueForKey("boolProperty")).toBe(true); + }); + + it("answer valueForKey: with a double", function () { + expect(Klass.new().valueForKey("doubleProperty")).toBe(2.5); + }); + + it("answer valueForKey: with a struct", function () { + var obj = Klass.new(); + expectRect(obj.valueForKey("rectProperty").CGRectValue, rect); + var boxedPoint = obj.valueForKey("pointProperty").CGPointValue; + expect([boxedPoint.x, boxedPoint.y]).toEqual([point.x, point.y]); + }); + + it("answer valueForKey: with an object", function () { + expect(Klass.new().valueForKey("objectProperty")).toBe("text"); + }); + + it("receive a number from setValue:forKey:", function () { + var obj = Klass.new(); + obj.setValueForKey(4000000001, "unsignedProperty"); + expect(state.received.unsignedProperty).toBe(4000000001); + obj.setValueForKey(-1.25, "doubleProperty"); + expect(state.received.doubleProperty).toBe(-1.25); + }); + + it("receive a BOOL from setValue:forKey:", function () { + var obj = Klass.new(); + obj.setValueForKey(true, "boolProperty"); + expect(state.received.boolProperty).toBe(true); + obj.setValueForKey(false, "boolProperty"); + expect(state.received.boolProperty).toBe(false); + }); + + it("receive a struct from setValue:forKey:", function () { + var obj = Klass.new(); + var other = { origin: { x: 10, y: 20 }, size: { width: 30, height: 40 } }; + obj.setValueForKey(NSValue.valueWithCGRect(other), "rectProperty"); + expectRect(state.received.rectProperty, other); + }); + + it("receive an object from setValue:forKey:", function () { + Klass.new().setValueForKey("other text", "objectProperty"); + expect(state.received.objectProperty).toBe("other text"); + }); + + // The compiler's encoding of a vector type is not one the runtime + // can reproduce, so vectorProperty is left out. + it("report the property's own types in their method signatures", function () { + var obj = Klass.new(); + var selectors = ["hash"]; + Object.keys(answers).forEach(function (property) { + if (property !== "vectorProperty") { + selectors.push(property, setterName(property)); + } + }); + selectors.forEach(function (selector) { + var expected = TNSAccessorTypes.instanceMethodSignatureForSelector(selector); + var registered = method_getTypeEncoding(class_getInstanceMethod(Klass.class(), selector)); + var signatures = [ + Klass.instanceMethodSignatureForSelector(selector), + obj.methodSignatureForSelector(selector), + NSMethodSignature.signatureWithObjCTypes(registered) + ]; + signatures.forEach(function (signature) { + expect([selector, typeString(signature.methodReturnType)]).toEqual([selector, typeString(expected.methodReturnType)]); + expect([selector, signature.numberOfArguments]).toEqual([selector, expected.numberOfArguments]); + for (var i = 2; i < expected.numberOfArguments; i++) { + expect([selector, typeString(signature.getArgumentTypeAtIndex(i))]) + .toEqual([selector, typeString(expected.getArgumentTypeAtIndex(i))]); + } + }); + }); + }); + }); + }); + + // The replacement is installed for the rest of the run, on a class no other + // spec uses. + describe("replaced on a native class's prototype", function () { + var installed = false; + + function install() { + if (installed) { + return; + } + installed = true; + Object.defineProperty(TNSAccessorSwizzleDerived.prototype, "doubleProperty", { + get: function () { + return 3.5; + }, + configurable: true + }); + Object.defineProperty(TNSAccessorSwizzleDerived.prototype, "boolProperty", { + get: function () { + return true; + }, + configurable: true + }); + } + + it("answer valueForKey: with the property's own type when the class inherits the accessor", function () { + install(); + var obj = TNSAccessorSwizzleDerived.new(); + expect(obj.valueForKey("doubleProperty")).toBe(3.5); + expect(obj.valueForKey("boolProperty")).toBe(true); + }); + + it("report the property's own type in the method signature when the class inherits the accessor", function () { + install(); + ["doubleProperty", "boolProperty"].forEach(function (selector) { + var expected = TNSAccessorSwizzleBase.instanceMethodSignatureForSelector(selector).methodReturnType; + var signature = TNSAccessorSwizzleDerived.instanceMethodSignatureForSelector(selector); + expect([selector, typeString(signature.methodReturnType)]).toEqual([selector, typeString(expected)]); + }); + }); + }); + + // TNSDerivedInterface declares baseProperty through its base class and + // through a protocol, so two property metadata entries name each accessor. + it("run once per native call when the class and a protocol declare the property", function () { + var counts = { get: 0, set: 0, value: 0 }; + var Klass = TNSDerivedInterface.extend({ + get baseProperty() { + counts.get++; + return 41; + }, + set baseProperty(value) { + counts.set++; + counts.value = value; + } + }, { name: "JSAccessorEncodingSharedSelector" }); + var obj = Klass.new(); + expect(obj.valueForKey("baseProperty")).toBe(41); + obj.setValueForKey(7, "baseProperty"); + expect([counts.get, counts.set, counts.value]).toEqual([1, 1, 7]); + expect(typeString(Klass.instanceMethodSignatureForSelector("baseProperty").methodReturnType)).toBe("i"); + }); + + // TNSInheritedSwizzleDerived lists members only its superclass implements. + // The replacements stay installed for the rest of the run, on classes no + // other spec uses. + // The prototype of a class whose redeclaration keeps the accessor count of + // its superclass's property does not define it again. + function inheritedDescriptor(proto, name) { + for (var current = proto; current !== null; current = Object.getPrototypeOf(current)) { + var descriptor = Object.getOwnPropertyDescriptor(current, name); + if (descriptor !== undefined) { + return descriptor; + } + } + return undefined; + } + + describe("replaced on a native class that inherits them", function () { + var installed = false; + + function install() { + if (installed) { + return; + } + installed = true; + var proto = TNSInheritedSwizzleDerived.prototype; + var objectOriginal = inheritedDescriptor(proto, "objectValue"); + Object.defineProperty(proto, "objectValue", { + get: function () { + var value = objectOriginal.get.call(this); + return value === null ? null : "js " + value; + }, + set: function (value) { + objectOriginal.set.call(this, value + "!"); + }, + configurable: true + }); + var scalarOriginal = inheritedDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + return scalarOriginal.get.call(this) * 2; + }, + set: function (value) { + scalarOriginal.set.call(this, value + 1); + }, + configurable: true + }); + var describeOriginal = proto.describeValue; + proto.describeValue = function (value) { + return "js " + describeOriginal.call(this, value); + }; + } + + it("reach the inherited implementation of a method from JS", function () { + install(); + expect(TNSInheritedSwizzleDerived.new().describeValue(3)).toBe("js base 3"); + expect(TNSInheritedSwizzleSubclass.new().describeValue(4)).toBe("js base 4"); + expect(TNSInheritedSwizzleBase.new().describeValue(5)).toBe("base 5"); + }); + + it("reach the inherited accessors of an object property from JS", function () { + install(); + [TNSInheritedSwizzleDerived, TNSInheritedSwizzleSubclass].forEach(function (Klass) { + var obj = Klass.new(); + obj.objectValue = "a"; + expect(obj.storedObjectValue()).toBe("a!"); + expect(obj.objectValue).toBe("js a!"); + expect(obj.valueForKey("objectValue")).toBe("js a!"); + obj.setValueForKey("b", "objectValue"); + expect(obj.storedObjectValue()).toBe("b!"); + }); + var base = TNSInheritedSwizzleBase.new(); + base.objectValue = "a"; + base.setValueForKey("b", "objectValue"); + expect([base.storedObjectValue(), base.objectValue, base.valueForKey("objectValue")]).toEqual(["b", "b", "b"]); + }); + + it("reach the inherited accessors of a scalar property from JS", function () { + install(); + [TNSInheritedSwizzleDerived, TNSInheritedSwizzleSubclass].forEach(function (Klass) { + var obj = Klass.new(); + obj.scalarValue = 5; + expect(obj.storedScalarValue()).toBe(6); + expect(obj.scalarValue).toBe(12); + expect(obj.valueForKey("scalarValue")).toBe(12); + obj.setValueForKey(7, "scalarValue"); + expect(obj.storedScalarValue()).toBe(8); + }); + var base = TNSInheritedSwizzleBase.new(); + base.scalarValue = 5; + base.setValueForKey(7, "scalarValue"); + expect([base.storedScalarValue(), base.scalarValue, base.valueForKey("scalarValue")]).toEqual([7, 7, 7]); + }); + + it("reach the replacement and then the inherited implementation from a JS subclass calling super", function () { + install(); + var Klass = TNSInheritedSwizzleDerived.extend({ + describeValue: function (value) { + return "sub " + this.super.describeValue(value); + }, + get objectValue() { + return "sub " + this.super.objectValue; + }, + set objectValue(value) { + this.super.objectValue = value + "?"; + } + }, { name: "JSAccessorEncodingSwizzledSuper" }); + var obj = Klass.new(); + expect(obj.describeValue(6)).toBe("sub js base 6"); + obj.objectValue = "a"; + expect(obj.storedObjectValue()).toBe("a?!"); + expect(obj.objectValue).toBe("sub js a?!"); + expect(obj.valueForKey("objectValue")).toBe("sub js a?!"); + obj.setValueForKey("b", "objectValue"); + expect(obj.storedObjectValue()).toBe("b?!"); + }); + + it("reach the inherited accessors after a second replacement", function () { + var proto = TNSInheritedSwizzleTwice.prototype; + var original = inheritedDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + return original.get.call(this) * 2; + }, + set: function (value) { + original.set.call(this, value + 1); + }, + configurable: true + }); + var first = Object.getOwnPropertyDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + return first.get.call(this) * 10; + }, + set: function (value) { + first.set.call(this, value + 100); + }, + configurable: true + }); + var obj = TNSInheritedSwizzleTwice.new(); + obj.scalarValue = 5; + expect(obj.storedScalarValue()).toBe(106); + expect(obj.scalarValue).toBe(2120); + expect(obj.valueForKey("scalarValue")).toBe(2120); + }); + }); + + // Each family is replaced by one spec group for the rest of the run. A + // replacement records its tag in `trace` and calls the original it looked + // up when it was installed: describeValue wraps the result in "tag(...)", + // the object accessors wrap what they read and write, the scalar ones + // append the tag's digit. + describe("replaced on a class and on its subclass", function () { + var trace = []; + + function replaceMembers(Klass, tag, digit) { + var proto = Klass.prototype; + var describeOriginal = proto.describeValue; + proto.describeValue = function (value) { + trace.push(tag); + return tag + "(" + describeOriginal.call(this, value) + ")"; + }; + var objectOriginal = inheritedDescriptor(proto, "objectValue"); + Object.defineProperty(proto, "objectValue", { + get: function () { + trace.push(tag + " get"); + return tag + "(" + objectOriginal.get.call(this) + ")"; + }, + set: function (value) { + trace.push(tag + " set"); + objectOriginal.set.call(this, tag + "(" + value + ")"); + }, + configurable: true + }); + var scalarOriginal = inheritedDescriptor(proto, "scalarValue"); + Object.defineProperty(proto, "scalarValue", { + get: function () { + trace.push(tag + " get"); + return scalarOriginal.get.call(this) * 10 + digit; + }, + set: function (value) { + trace.push(tag + " set"); + scalarOriginal.set.call(this, value * 10 + digit); + }, + configurable: true + }); + return { describe: describeOriginal, object: objectOriginal, scalar: scalarOriginal }; + } + + function installer(replace) { + var originals = null; + return function () { + if (originals === null) { + originals = replace(); + } + trace.length = 0; + return originals; + }; + } + + function traced(action) { + trace.length = 0; + var result = action(); + return { result: result, trace: trace.slice() }; + } + + // The subclass's replacements find native members as their originals, + // which run the superclass's native implementation, not its + // replacement. + describe("the superclass first", function () { + var install = installer(function () { + return { base: replaceMembers(TNSSwizzleChainBase, "B", 1), derived: replaceMembers(TNSSwizzleChainDerived, "D", 2) }; + }); + + it("reach the native method from both replacements", function () { + var originals = install(); + var derived = TNSSwizzleChainDerived.new(); + expect(traced(function () { return derived.describeValue(1); })).toEqual({ result: "D(base 1)", trace: ["D"] }); + expect(traced(function () { return originals.base.describe.call(derived, 2); })).toEqual({ result: "base 2", trace: [] }); + expect(traced(function () { return TNSSwizzleChainBase.new().describeValue(3); })).toEqual({ result: "B(base 3)", trace: ["B"] }); + }); + + it("reach the native accessors of an object property from both replacements", function () { + var originals = install(); + var derived = TNSSwizzleChainDerived.new(); + expect(traced(function () { derived.objectValue = "x"; return derived.storedObjectValue(); })) + .toEqual({ result: "D(x)", trace: ["D set"] }); + expect(traced(function () { return derived.objectValue; })).toEqual({ result: "D(D(x))", trace: ["D get"] }); + expect(traced(function () { return derived.valueForKey("objectValue"); })).toEqual({ result: "D(D(x))", trace: ["D get"] }); + expect(traced(function () { return originals.base.object.get.call(derived); })).toEqual({ result: "D(x)", trace: [] }); + var base = TNSSwizzleChainBase.new(); + base.objectValue = "y"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(y)", "B(B(y))"]); + }); + + it("reach the native accessors of a scalar property from both replacements", function () { + var originals = install(); + var derived = TNSSwizzleChainDerived.new(); + expect(traced(function () { derived.scalarValue = 5; return derived.storedScalarValue(); })) + .toEqual({ result: 52, trace: ["D set"] }); + expect(traced(function () { return derived.valueForKey("scalarValue"); })).toEqual({ result: 522, trace: ["D get"] }); + expect(traced(function () { return originals.base.scalar.get.call(derived); })).toEqual({ result: 52, trace: [] }); + var base = TNSSwizzleChainBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + + // The subclass's replacement finds the native implementation as its + // original, so the superclass's later replacement is not part of it. + describe("the subclass first", function () { + var install = installer(function () { + return { derived: replaceMembers(TNSSwizzleReverseDerived, "D", 2), base: replaceMembers(TNSSwizzleReverseBase, "B", 1) }; + }); + + it("reach the native method", function () { + install(); + expect(traced(function () { return TNSSwizzleReverseDerived.new().describeValue(1); })).toEqual({ result: "D(base 1)", trace: ["D"] }); + expect(traced(function () { return TNSSwizzleReverseBase.new().describeValue(2); })).toEqual({ result: "B(base 2)", trace: ["B"] }); + }); + + it("reach the native accessors of an object property", function () { + install(); + var derived = TNSSwizzleReverseDerived.new(); + derived.objectValue = "x"; + expect([derived.storedObjectValue(), derived.valueForKey("objectValue")]).toEqual(["D(x)", "D(D(x))"]); + var base = TNSSwizzleReverseBase.new(); + base.objectValue = "y"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(y)", "B(B(y))"]); + }); + + it("reach the native accessors of a scalar property", function () { + install(); + var derived = TNSSwizzleReverseDerived.new(); + derived.scalarValue = 5; + expect([derived.storedScalarValue(), derived.valueForKey("scalarValue")]).toEqual([52, 522]); + var base = TNSSwizzleReverseBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + + // The subclass's second replacement finds the first one as its + // original, and the first one still finds the native members. + describe("the superclass once, then the subclass twice", function () { + var install = installer(function () { + return { + base: replaceMembers(TNSSwizzleRepeatBase, "B", 1), + first: replaceMembers(TNSSwizzleRepeatDerived, "D", 2), + second: replaceMembers(TNSSwizzleRepeatDerived, "E", 3) + }; + }); + + it("reach the native method through both of the subclass's replacements", function () { + var originals = install(); + var derived = TNSSwizzleRepeatDerived.new(); + expect(traced(function () { return derived.describeValue(1); })).toEqual({ result: "E(D(base 1))", trace: ["E", "D"] }); + expect(traced(function () { return originals.first.describe.call(derived, 2); })).toEqual({ result: "base 2", trace: [] }); + expect(traced(function () { return originals.base.describe.call(derived, 3); })).toEqual({ result: "base 3", trace: [] }); + expect(traced(function () { return TNSSwizzleRepeatBase.new().describeValue(4); })).toEqual({ result: "B(base 4)", trace: ["B"] }); + }); + + it("reach the native accessors of an object property through both of the subclass's replacements", function () { + var originals = install(); + var derived = TNSSwizzleRepeatDerived.new(); + expect(traced(function () { derived.objectValue = "x"; return derived.storedObjectValue(); })) + .toEqual({ result: "D(E(x))", trace: ["E set", "D set"] }); + expect(traced(function () { return derived.objectValue; })).toEqual({ result: "E(D(D(E(x))))", trace: ["E get", "D get"] }); + expect(traced(function () { return derived.valueForKey("objectValue"); })).toEqual({ result: "E(D(D(E(x))))", trace: ["E get", "D get"] }); + expect(traced(function () { return originals.first.object.get.call(derived); })).toEqual({ result: "D(E(x))", trace: [] }); + expect(traced(function () { return originals.base.object.get.call(derived); })).toEqual({ result: "D(E(x))", trace: [] }); + var base = TNSSwizzleRepeatBase.new(); + base.objectValue = "y"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(y)", "B(B(y))"]); + }); + + it("reach the native accessors of a scalar property through both of the subclass's replacements", function () { + var originals = install(); + var derived = TNSSwizzleRepeatDerived.new(); + expect(traced(function () { derived.scalarValue = 5; return derived.storedScalarValue(); })) + .toEqual({ result: 532, trace: ["E set", "D set"] }); + expect(traced(function () { return derived.valueForKey("scalarValue"); })).toEqual({ result: 53223, trace: ["E get", "D get"] }); + expect(traced(function () { return originals.first.scalar.get.call(derived); })).toEqual({ result: 532, trace: [] }); + expect(traced(function () { return originals.base.scalar.get.call(derived); })).toEqual({ result: 532, trace: [] }); + var base = TNSSwizzleRepeatBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + + // TNSSwizzleMiddle overrides every member natively, between the + // replaced superclass and the replaced leaf. The leaf's originals run + // the superclass's native members, not the middle class's overrides. + describe("the superclass first, with a native override in between", function () { + var install = installer(function () { + return { base: replaceMembers(TNSSwizzleMiddleBase, "B", 1), leaf: replaceMembers(TNSSwizzleMiddleLeaf, "L", 3) }; + }); + + it("reach the superclass's native method", function () { + var originals = install(); + var leaf = TNSSwizzleMiddleLeaf.new(); + expect(traced(function () { return leaf.describeValue(1); })).toEqual({ result: "L(base 1)", trace: ["L"] }); + expect(traced(function () { return originals.base.describe.call(leaf, 2); })).toEqual({ result: "base 2", trace: [] }); + }); + + it("reach the superclass's native accessors of an object property", function () { + install(); + var leaf = TNSSwizzleMiddleLeaf.new(); + leaf.objectValue = "x"; + expect(leaf.storedObjectValue()).toBe("L(x)"); + expect(leaf.valueForKey("objectValue")).toBe("L(L(x))"); + }); + + it("reach the superclass's native accessors of a scalar property", function () { + install(); + var leaf = TNSSwizzleMiddleLeaf.new(); + leaf.scalarValue = 5; + expect(leaf.storedScalarValue()).toBe(53); + expect(leaf.valueForKey("scalarValue")).toBe(533); + }); + }); + + // TNSSwizzleSuperMiddle overrides every member natively and calls the + // superclass's, which is replaced; so is the leaf below it. + describe("the superclass first, with a native override calling super in between", function () { + var install = installer(function () { + return { base: replaceMembers(TNSSwizzleSuperBase, "B", 1), leaf: replaceMembers(TNSSwizzleSuperLeaf, "L", 3) }; + }); + + it("reach the superclass's native method from the leaf", function () { + var originals = install(); + var leaf = TNSSwizzleSuperLeaf.new(); + expect(traced(function () { return leaf.describeValue(1); })).toEqual({ result: "L(base 1)", trace: ["L"] }); + expect(traced(function () { return originals.base.describe.call(leaf, 2); })).toEqual({ result: "base 2", trace: [] }); + }); + + it("reach the superclass's native accessors of an object property", function () { + install(); + var leaf = TNSSwizzleSuperLeaf.new(); + expect(traced(function () { leaf.objectValue = "x"; return leaf.storedObjectValue(); })).toEqual({ result: "L(x)", trace: ["L set"] }); + expect(traced(function () { return leaf.valueForKey("objectValue"); })).toEqual({ result: "L(L(x))", trace: ["L get"] }); + var middle = TNSSwizzleSuperMiddle.new(); + expect(traced(function () { middle.setValueForKey("y", "objectValue"); return middle.storedObjectValue(); })) + .toEqual({ result: "B(y via middle)", trace: ["B set"] }); + expect(traced(function () { return middle.valueForKey("objectValue"); })).toEqual({ result: "middle B(B(y via middle))", trace: ["B get"] }); + var base = TNSSwizzleSuperBase.new(); + base.objectValue = "z"; + expect([base.storedObjectValue(), base.valueForKey("objectValue")]).toEqual(["B(z)", "B(B(z))"]); + }); + + it("reach the superclass's native accessors of a scalar property", function () { + install(); + var leaf = TNSSwizzleSuperLeaf.new(); + expect(traced(function () { leaf.scalarValue = 5; return leaf.storedScalarValue(); })).toEqual({ result: 53, trace: ["L set"] }); + expect(traced(function () { return leaf.valueForKey("scalarValue"); })).toEqual({ result: 533, trace: ["L get"] }); + var middle = TNSSwizzleSuperMiddle.new(); + expect(traced(function () { middle.setValueForKey(5, "scalarValue"); return middle.storedScalarValue(); })) + .toEqual({ result: 151, trace: ["B set"] }); + expect(traced(function () { return middle.valueForKey("scalarValue"); })).toEqual({ result: 2511, trace: ["B get"] }); + var base = TNSSwizzleSuperBase.new(); + base.scalarValue = 5; + expect([base.storedScalarValue(), base.valueForKey("scalarValue")]).toEqual([51, 511]); + }); + }); + }); + + // TNSLinkedNode refers to itself through a pointer field. + describe("of self-referential struct types", function () { + var state = {}; + var Klass = null; + + function linkedClass() { + if (Klass === null) { + Klass = TNSLinkedTypes.extend({ + get nodeProperty() { + return state.node; + }, + set nodeProperty(value) { + state.node = value; + }, + get holderProperty() { + return { node: null, leaf: null, count: 3 }; + }, + set holderProperty(value) { + state.holder = value; + }, + get leafProperty() { + return null; + }, + set leafProperty(value) { + state.leaf = value; + }, + nextOf: function (node) { + return null; + }, + holderWithLeaf: function (leaf) { + return { node: null, leaf: leaf, count: 0 }; + } + }, { name: "JSAccessorEncodingLinked" }); + } + return Klass; + } + + function address(value) { + return value ? interop.handleof(value).toNumber() : 0; + } + + function outcome(action) { + try { + return { value: action() }; + } catch (e) { + return { error: e.nativeException ? e.nativeException.name : String(e) }; + } + } + + it("report the compiler's types in the signatures of JS accessors and methods", function () { + var Linked = linkedClass(); + [ + "nodeProperty", "setNodeProperty:", "holderProperty", "setHolderProperty:", + "leafProperty", "setLeafProperty:", "nextOf:", "holderWithLeaf:" + ].forEach(function (selector) { + var expected = TNSLinkedTypes.instanceMethodSignatureForSelector(selector); + var registered = NSMethodSignature.signatureWithObjCTypes(method_getTypeEncoding(class_getInstanceMethod(Linked.class(), selector))); + expect([selector, typeString(registered.methodReturnType)]).toEqual([selector, typeString(expected.methodReturnType)]); + expect([selector, registered.numberOfArguments]).toEqual([selector, expected.numberOfArguments]); + for (var i = 2; i < expected.numberOfArguments; i++) { + expect([selector, typeString(registered.getArgumentTypeAtIndex(i))]) + .toEqual([selector, typeString(expected.getArgumentTypeAtIndex(i))]); + } + }); + }); + + // KVC answers NSUnknownKeyException for pointer-typed keys. + it("read and write a pointer property through KVC as the base class does", function () { + var Linked = linkedClass(); + var node = interop.alloc(16); + var base = TNSLinkedTypes.new(); + var obj = Linked.new(); + state.node = null; + + function read(target) { + return outcome(function () { + var boxed = target.valueForKey("nodeProperty"); + return [typeString(boxed.objCType), address(boxed.pointerValue)]; + }); + } + expect(read(obj)).toEqual(read(base)); + + var written = outcome(function () { + base.setValueForKey(NSValue.valueWithPointer(node), "nodeProperty"); + return address(base.nodeProperty); + }); + var writtenByJS = outcome(function () { + obj.setValueForKey(NSValue.valueWithPointer(node), "nodeProperty"); + return address(state.node); + }); + expect(writtenByJS).toEqual(written); + }); + }); +}); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index bb93113c4..aefe1e5e6 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -137,6 +137,7 @@ require("./NsUrlTests"); require("./NsInteropTests"); require("./GCFinalizerTests"); require("./NativeCallbackSelfTests"); +require("./JSAccessorEncodingTests"); require("./BlockCacheRaceTests"); require("./WorkerConcurrentStartupTests"); require("./WorkerOptionsTests");