1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
22 #include <Foundation/Foundation.h>
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/objc-api.h>
28 #include "cycript.hpp"
30 #include "ObjectiveC/Internal.hpp"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <JavaScriptCore/JSStringRefCF.h>
35 #include <objc/runtime.h>
39 #include "JavaScript.hpp"
41 #include "Execute.hpp"
49 #define CYObjectiveTry_ { \
51 #define CYObjectiveTry { \
52 JSContextRef context(context_); \
54 #define CYObjectiveCatch \
55 catch (const CYException &error) { \
56 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
62 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
64 #define CYPoolCatch(value) \
65 @catch (NSException *error) { \
66 _saved = [error retain]; \
67 throw CYJSError(context, CYCastJSValue(context, error)); \
72 [_saved autorelease]; \
78 #define CYSadCatch(value) \
79 @catch (NSException *error ) { \
80 throw CYJSError(context, CYCastJSValue(context, error)); \
85 #define class_getSuperclass GSObjCSuper
86 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
87 #define class_getName GSNameFromClass
89 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
91 #define ivar_getName(ivar) ((ivar)->ivar_name)
92 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
93 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
95 #define method_getName(method) ((method)->method_name)
96 #define method_getImplementation(method) ((method)->method_imp)
97 #define method_getTypeEncoding(method) ((method)->method_types)
98 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
101 #define objc_getClass GSClassFromName
103 #define objc_getProtocol GSProtocolFromName
105 #define object_getClass GSObjCClass
107 #define object_getInstanceVariable(object, name, value) ({ \
108 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
109 _assert(value != NULL); \
111 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
115 #define object_setIvar(object, ivar, value) ({ \
116 void *data = (value); \
117 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
120 #define protocol_getName(protocol) [(protocol) name]
123 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
124 static id (*$objc_getAssociatedObject)(id object, void *key);
125 static void (*$objc_removeAssociatedObjects)(id object);
127 struct BlockLiteral {
131 void (*invoke)(void *, ...);
135 struct BlockDescriptor1 {
136 unsigned long int reserved;
137 unsigned long int size;
140 struct BlockDescriptor2 {
141 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
142 void (*dispose_helper)(BlockLiteral *src);
145 struct BlockDescriptor3 {
146 const char *signature;
151 BLOCK_DEALLOCATING = 0x0001,
152 BLOCK_REFCOUNT_MASK = 0xfffe,
153 BLOCK_NEEDS_FREE = 1 << 24,
154 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
155 BLOCK_HAS_CTOR = 1 << 26,
156 BLOCK_IS_GC = 1 << 27,
157 BLOCK_IS_GLOBAL = 1 << 28,
158 BLOCK_HAS_STRET = 1 << 29,
159 BLOCK_HAS_SIGNATURE = 1 << 30,
162 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
164 /* Objective-C Pool Release {{{ */
165 void CYPoolRelease_(void *data) {
166 id object(reinterpret_cast<id>(data));
170 id CYPoolRelease_(CYPool *pool, id object) {
173 else if (pool == NULL)
174 return [object autorelease];
176 pool->atexit(CYPoolRelease_);
181 template <typename Type_>
182 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
183 return (Type_) CYPoolRelease_(pool, (id) object);
186 /* Objective-C Strings {{{ */
187 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
188 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
189 char *string(new(pool) char[size]);
190 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
191 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
195 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
197 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
200 return CYCopyJSString(CYPoolCString(pool, context, value));
204 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
207 // XXX: this definition scares me; is anyone using this?!
208 NSString *string([value description]);
209 return CYCopyJSString(context, string);
212 NSString *CYCopyNSString(const CYUTF8String &value) {
214 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
216 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
220 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
222 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
225 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
229 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
230 return CYCopyNSString(context, CYJSString(context, value));
233 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
234 return CYPoolRelease(pool, CYCopyNSString(value));
237 NSString *CYCastNSString(CYPool *pool, SEL sel) {
238 const char *name(sel_getName(sel));
239 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
242 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
243 return CYPoolRelease(pool, CYCopyNSString(context, value));
246 CYUTF8String CYCastUTF8String(NSString *value) {
247 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
248 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
252 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
254 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
255 if (exception == NULL)
257 *exception = CYCastJSValue(context, error);
260 size_t CYGetIndex(NSString *value) {
261 return CYGetIndex(CYCastUTF8String(value));
264 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
265 return CYGetOffset(CYPoolCString(pool, context, value), index);
268 static JSClassRef Instance_;
270 static JSClassRef ArrayInstance_;
271 static JSClassRef FunctionInstance_;
272 static JSClassRef ObjectInstance_;
273 static JSClassRef StringInstance_;
275 static JSClassRef Class_;
276 static JSClassRef Internal_;
277 static JSClassRef Message_;
278 static JSClassRef Messages_;
279 static JSClassRef Selector_;
280 static JSClassRef Super_;
282 static JSClassRef ObjectiveC_Classes_;
283 static JSClassRef ObjectiveC_Constants_;
284 static JSClassRef ObjectiveC_Protocols_;
287 static JSClassRef ObjectiveC_Image_Classes_;
288 static JSClassRef ObjectiveC_Images_;
292 static Class NSCFBoolean_;
293 static Class NSCFType_;
294 static Class NSGenericDeallocHandler_;
295 static Class NSZombie_;
297 static std::set<Class> banned_;
299 static Class NSBoolNumber_;
302 static Class NSArray_;
303 static Class NSBlock_;
304 static Class NSDictionary_;
305 static Class NSString_;
306 static Class Object_;
308 static Type_privateData *Object_type;
309 static Type_privateData *Selector_type;
311 Type_privateData *Instance::GetType() const {
315 Type_privateData *Selector_privateData::GetType() const {
316 return Selector_type;
319 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
321 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
323 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
324 else if (meta && !class_isMetaClass(self))
325 return CYGetCachedObject(context, CYJSString("Class_prototype"));
327 JSObjectRef global(CYGetGlobalObject(context));
328 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
331 sprintf(label, "i%p", self);
332 CYJSString name(label);
334 JSValueRef value(CYGetProperty(context, cy, name));
335 if (!JSValueIsUndefined(context, value))
338 JSClassRef _class(NULL);
339 JSValueRef prototype;
341 if (self == NSArray_)
342 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
343 else if (self == NSBlock_)
344 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
345 else if (self == NSDictionary_)
346 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
347 else if (self == NSString_)
348 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
350 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
352 JSObjectRef object(JSObjectMake(context, _class, NULL));
353 JSObjectSetPrototype(context, object, prototype);
354 CYSetProperty(context, cy, name, object);
359 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
360 return CYGetClassPrototype(context, self, class_isMetaClass(self));
363 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
364 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
365 if (Class super = class_getSuperclass(_class))
366 JSObjectSetPrototype(context, value, Messages::Make(context, super));
370 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
371 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
375 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
376 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
380 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
381 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
382 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
386 Instance::~Instance() {
387 if ((flags_ & Transient) == 0)
388 // XXX: does this handle background threads correctly?
389 // XXX: this simply does not work on the console because I'm stupid
390 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
393 struct Message_privateData :
398 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
399 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
405 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
406 Instance::Flags flags;
409 flags = Instance::Transient;
411 flags = Instance::None;
412 object = [object retain];
415 return Instance::Make(context, object, flags);
418 @interface NSMethodSignature (Cycript)
419 - (NSString *) _typeString;
422 @interface NSObject (Cycript)
424 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
425 - (JSType) cy$JSType;
427 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
428 - (NSString *) cy$toCYON:(bool)objective;
430 - (bool) cy$hasProperty:(NSString *)name;
431 - (NSObject *) cy$getProperty:(NSString *)name;
432 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
433 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
434 - (bool) cy$deleteProperty:(NSString *)name;
435 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
437 + (bool) cy$hasImplicitProperties;
443 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
446 NSString *CYCastNSCYON(id value, bool objective) {
452 Class _class(object_getClass(value));
453 SEL sel(@selector(cy$toCYON:));
455 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
456 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
457 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
458 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
459 string = [value cy$toCYON:objective];
464 else if (value == NSZombie_)
465 string = @"_NSZombie_";
466 else if (_class == NSZombie_)
467 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
468 // XXX: frowny /in/ the pants
469 else if (banned_.find(value) != banned_.end())
473 string = [NSString stringWithFormat:@"%@", value];
478 string = @"undefined";
485 struct PropertyAttributes {
490 const char *variable;
503 PropertyAttributes(objc_property_t property) :
515 name = property_getName(property);
516 const char *attributes(property_getAttributes(property));
518 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
519 if ((next = strchr(token, ',')) != NULL)
522 case 'R': readonly = true; break;
523 case 'C': copy = true; break;
524 case '&': retain = true; break;
525 case 'N': nonatomic = true; break;
526 case 'G': getter_ = token + 1; break;
527 case 'S': setter_ = token + 1; break;
528 case 'V': variable = token + 1; break;
532 /*if (variable == NULL) {
533 variable = property_getName(property);
534 size_t size(strlen(variable));
535 char *name(new(pool_) char[size + 2]);
537 memcpy(name + 1, variable, size);
538 name[size + 1] = '\0';
543 const char *Getter() {
545 getter_ = pool_.strdup(name);
549 const char *Setter() {
550 if (setter_ == NULL && !readonly) {
551 size_t length(strlen(name));
553 char *temp(new(pool_) char[length + 5]);
559 temp[3] = toupper(name[0]);
560 memcpy(temp + 4, name + 1, length - 1);
563 temp[length + 3] = ':';
564 temp[length + 4] = '\0';
574 @interface CYWebUndefined : NSObject {
577 + (CYWebUndefined *) undefined;
581 @implementation CYWebUndefined
583 + (CYWebUndefined *) undefined {
584 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
590 #define WebUndefined CYWebUndefined
592 /* Bridge: CYJSObject {{{ */
593 @interface CYJSObject : NSMutableDictionary {
595 JSGlobalContextRef context_;
598 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
600 - (NSUInteger) count;
601 - (id) objectForKey:(id)key;
602 - (NSEnumerator *) keyEnumerator;
603 - (void) setObject:(id)object forKey:(id)key;
604 - (void) removeObjectForKey:(id)key;
608 /* Bridge: CYJSArray {{{ */
609 @interface CYJSArray : NSMutableArray {
611 JSGlobalContextRef context_;
614 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
616 - (NSUInteger) count;
617 - (id) objectAtIndex:(NSUInteger)index;
619 - (void) addObject:(id)anObject;
620 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
621 - (void) removeLastObject;
622 - (void) removeObjectAtIndex:(NSUInteger)index;
623 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
628 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
629 return JSValueIsObjectOfClass(context, value, Instance_);
632 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
633 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
636 NSObject *CYMakeBlock(void (*invoke)(), sig::Signature &signature) {
637 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
641 BlockDescriptor1 one_;
642 BlockDescriptor2 two_;
643 BlockDescriptor3 three_;
649 Descriptor *descriptor(new Descriptor);
650 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
652 literal->isa = objc_getClass("__NSGlobalBlock__");
653 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
654 literal->reserved = 0;
655 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(invoke);
656 literal->descriptor = descriptor;
658 descriptor->d_.one_.size = sizeof(descriptor->d_);
659 descriptor->d_.three_.signature = sig::Unparse(descriptor->pool_, &signature);
661 return reinterpret_cast<NSObject *>(literal);
664 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
665 if (CYJSValueIsNSObject(context, object)) {
666 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
667 return internal->GetValue();
670 if (JSValueIsObjectOfClass(context, object, Functor_)) {
671 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
672 return CYMakeBlock(internal->GetValue(), internal->signature_);
675 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
676 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
677 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
680 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
681 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
685 @interface NSBoolNumber : NSNumber {
690 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
694 switch (JSType type = JSValueGetType(context, value)) {
695 case kJSTypeUndefined:
696 object = [WebUndefined undefined];
706 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
709 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
715 object = CYCopyNSNumber(context, value);
720 object = CYCopyNSString(context, value);
725 // XXX: this might could be more efficient
726 object = CYCastNSObject(pool, context, (JSObjectRef) value);
731 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
738 return CYPoolRelease(pool, object);
740 return [object retain];
743 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
744 return CYNSObject(pool, context, value, true);
747 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
748 return CYNSObject(&pool, context, value, false);
751 /* Bridge: NSArray {{{ */
752 @implementation NSArray (Cycript)
755 return [[self mutableCopy] autorelease];
758 - (NSString *) cy$toCYON:(bool)objective {
759 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
760 [json appendString:@"@["];
764 for (id object in self) {
766 for (size_t index(0), count([self count]); index != count; ++index) {
767 id object([self objectAtIndex:index]);
770 [json appendString:@","];
773 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
774 [json appendString:CYCastNSCYON(object, true)];
776 [json appendString:@","];
781 [json appendString:@"]"];
785 - (bool) cy$hasProperty:(NSString *)name {
786 if ([name isEqualToString:@"length"])
789 size_t index(CYGetIndex(name));
790 if (index == _not(size_t) || index >= [self count])
791 return [super cy$hasProperty:name];
796 - (NSObject *) cy$getProperty:(NSString *)name {
797 size_t index(CYGetIndex(name));
798 if (index == _not(size_t) || index >= [self count])
799 return [super cy$getProperty:name];
801 return [self objectAtIndex:index];
804 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
806 if ([name isEqualToString:@"length"])
807 return CYCastJSValue(context, [self count]);
810 return [super cy$getProperty:name inContext:context];
813 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
814 [super cy$getPropertyNames:names inContext:context];
816 for (size_t index(0), count([self count]); index != count; ++index) {
817 id object([self objectAtIndex:index]);
818 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
820 sprintf(name, "%zu", index);
821 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
826 + (bool) cy$hasImplicitProperties {
832 /* Bridge: NSBlock {{{ */
839 /* Bridge: NSBoolNumber {{{ */
841 @implementation NSBoolNumber (Cycript)
843 - (JSType) cy$JSType {
844 return kJSTypeBoolean;
847 - (NSString *) cy$toCYON:(bool)objective {
848 NSString *value([self boolValue] ? @"true" : @"false");
849 return objective ? value : [NSString stringWithFormat:@"@%@", value];
852 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
853 return CYCastJSValue(context, (bool) [self boolValue]);
859 /* Bridge: NSDictionary {{{ */
860 @implementation NSDictionary (Cycript)
863 return [[self mutableCopy] autorelease];
866 - (NSString *) cy$toCYON:(bool)objective {
867 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
868 [json appendString:@"@{"];
872 for (NSObject *key in self) {
874 NSEnumerator *keys([self keyEnumerator]);
875 while (NSObject *key = [keys nextObject]) {
878 [json appendString:@","];
881 [json appendString:CYCastNSCYON(key, true)];
882 [json appendString:@":"];
883 NSObject *object([self objectForKey:key]);
884 [json appendString:CYCastNSCYON(object, true)];
887 [json appendString:@"}"];
891 - (bool) cy$hasProperty:(NSString *)name {
892 return [self objectForKey:name] != nil;
895 - (NSObject *) cy$getProperty:(NSString *)name {
896 return [self objectForKey:name];
899 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
900 [super cy$getPropertyNames:names inContext:context];
903 for (NSObject *key in self) {
905 NSEnumerator *keys([self keyEnumerator]);
906 while (NSObject *key = [keys nextObject]) {
908 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
912 + (bool) cy$hasImplicitProperties {
918 /* Bridge: NSMutableArray {{{ */
919 @implementation NSMutableArray (Cycript)
921 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
922 if ([name isEqualToString:@"length"]) {
923 // XXX: is this not intelligent?
924 NSNumber *number(reinterpret_cast<NSNumber *>(value));
926 NSUInteger size([number unsignedIntegerValue]);
928 NSUInteger size([number unsignedIntValue]);
930 NSUInteger count([self count]);
932 [self removeObjectsInRange:NSMakeRange(size, count - size)];
933 else if (size != count) {
934 WebUndefined *undefined([WebUndefined undefined]);
935 for (size_t i(count); i != size; ++i)
936 [self addObject:undefined];
941 size_t index(CYGetIndex(name));
942 if (index == _not(size_t))
943 return [super cy$setProperty:name to:value];
945 id object(value ?: [NSNull null]);
947 size_t count([self count]);
949 [self replaceObjectAtIndex:index withObject:object];
951 if (index != count) {
952 WebUndefined *undefined([WebUndefined undefined]);
953 for (size_t i(count); i != index; ++i)
954 [self addObject:undefined];
957 [self addObject:object];
963 - (bool) cy$deleteProperty:(NSString *)name {
964 size_t index(CYGetIndex(name));
965 if (index == _not(size_t) || index >= [self count])
966 return [super cy$deleteProperty:name];
967 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
973 /* Bridge: NSMutableDictionary {{{ */
974 @implementation NSMutableDictionary (Cycript)
976 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
977 [self setObject:(value ?: [NSNull null]) forKey:name];
981 - (bool) cy$deleteProperty:(NSString *)name {
982 if ([self objectForKey:name] == nil)
985 [self removeObjectForKey:name];
992 /* Bridge: NSNumber {{{ */
993 @implementation NSNumber (Cycript)
995 - (JSType) cy$JSType {
997 // XXX: this just seems stupid
998 if ([self class] == NSCFBoolean_)
999 return kJSTypeBoolean;
1001 return kJSTypeNumber;
1004 - (NSString *) cy$toCYON:(bool)objective {
1005 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1006 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1009 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1010 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1011 } CYObjectiveCatch }
1015 /* Bridge: NSNull {{{ */
1016 @implementation NSNull (Cycript)
1018 - (JSType) cy$JSType {
1022 - (NSString *) cy$toCYON:(bool)objective {
1023 NSString *value(@"null");
1024 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1027 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1028 return CYJSNull(context);
1029 } CYObjectiveCatch }
1033 /* Bridge: NSObject {{{ */
1034 @implementation NSObject (Cycript)
1040 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1041 return [self cy$valueOfInContext:context];
1044 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1046 } CYObjectiveCatch }
1048 - (JSType) cy$JSType {
1049 return kJSTypeObject;
1052 - (NSString *) cy$toCYON:(bool)objective {
1053 return [[self description] cy$toCYON:objective];
1056 - (bool) cy$hasProperty:(NSString *)name {
1060 - (NSObject *) cy$getProperty:(NSString *)name {
1064 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1065 if (NSObject *value = [self cy$getProperty:name])
1066 return CYCastJSValue(context, value);
1068 } CYObjectiveCatch }
1070 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1074 - (bool) cy$deleteProperty:(NSString *)name {
1078 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1081 + (bool) cy$hasImplicitProperties {
1087 /* Bridge: NSProxy {{{ */
1088 @implementation NSProxy (Cycript)
1090 - (NSString *) cy$toCYON:(bool)objective {
1091 return [[self description] cy$toCYON:objective];
1096 /* Bridge: NSString {{{ */
1097 @implementation NSString (Cycript)
1100 return [[self copy] autorelease];
1103 - (JSType) cy$JSType {
1104 return kJSTypeString;
1107 - (NSString *) cy$toCYON:(bool)objective {
1108 std::ostringstream str;
1111 CYUTF8String string(CYCastUTF8String(self));
1112 CYStringify(str, string.data, string.size);
1113 std::string value(str.str());
1114 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1117 - (bool) cy$hasProperty:(NSString *)name {
1118 size_t index(CYGetIndex(name));
1119 if (index == _not(size_t) || index >= [self length])
1120 return [super cy$hasProperty:name];
1125 - (NSObject *) cy$getProperty:(NSString *)name {
1126 size_t index(CYGetIndex(name));
1127 if (index == _not(size_t) || index >= [self length])
1128 return [super cy$getProperty:name];
1130 return [self substringWithRange:NSMakeRange(index, 1)];
1133 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1134 [super cy$getPropertyNames:names inContext:context];
1136 for (size_t index(0), length([self length]); index != length; ++index) {
1138 sprintf(name, "%zu", index);
1139 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1143 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1144 return CYCastJSValue(context, CYJSString(context, self));
1145 } CYObjectiveCatch }
1149 /* Bridge: WebUndefined {{{ */
1150 @implementation WebUndefined (Cycript)
1152 - (JSType) cy$JSType {
1153 return kJSTypeUndefined;
1156 - (NSString *) cy$toCYON:(bool)objective {
1157 NSString *value(@"undefined");
1158 return value; // XXX: maybe use the below code, adding @undefined?
1159 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1162 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1163 return CYJSUndefined(context);
1164 } CYObjectiveCatch }
1169 static bool CYIsClass(id self) {
1171 return class_isMetaClass(object_getClass(self));
1173 return GSObjCIsClass(self);
1177 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1178 id self(CYCastNSObject(&pool, context, value));
1179 if (CYIsClass(self))
1180 return (Class) self;
1181 throw CYJSError(context, "got something that is not a Class");
1185 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1187 size_t size(JSPropertyNameArrayGetCount(names));
1188 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1189 for (size_t index(0); index != size; ++index)
1190 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1194 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1196 return CYJSNull(context);
1198 return CYMakeInstance(context, value, false);
1199 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1201 @implementation CYJSObject
1203 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1204 if ((self = [super init]) != nil) {
1206 context_ = CYGetJSContext(context);
1207 JSGlobalContextRetain(context_);
1208 JSValueProtect(context_, object_);
1210 } CYObjectiveCatch }
1212 - (void) dealloc { CYObjectiveTry {
1213 JSValueUnprotect(context_, object_);
1214 JSGlobalContextRelease(context_);
1216 } CYObjectiveCatch }
1218 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1220 const char *cyon(CYPoolCCYON(pool, context, object_));
1222 return [super cy$toCYON:objective];
1224 return [NSString stringWithUTF8String:cyon];
1225 } CYObjectiveCatch }
1227 - (NSUInteger) count { CYObjectiveTry {
1228 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1229 size_t size(JSPropertyNameArrayGetCount(names));
1230 JSPropertyNameArrayRelease(names);
1232 } CYObjectiveCatch }
1234 - (id) objectForKey:(id)key { CYObjectiveTry {
1235 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1236 if (JSValueIsUndefined(context, value))
1238 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1239 } CYObjectiveCatch }
1241 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1242 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1243 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1244 JSPropertyNameArrayRelease(names);
1246 } CYObjectiveCatch }
1248 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1249 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1250 } CYObjectiveCatch }
1252 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1253 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1254 } CYObjectiveCatch }
1258 @implementation CYJSArray
1260 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1262 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1263 } CYObjectiveCatch }
1265 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1266 if ((self = [super init]) != nil) {
1268 context_ = CYGetJSContext(context);
1269 JSGlobalContextRetain(context_);
1270 JSValueProtect(context_, object_);
1272 } CYObjectiveCatch }
1274 - (void) dealloc { CYObjectiveTry {
1275 JSValueUnprotect(context_, object_);
1276 JSGlobalContextRelease(context_);
1278 } CYObjectiveCatch }
1280 - (NSUInteger) count { CYObjectiveTry {
1281 return CYArrayLength(context, object_);
1282 } CYObjectiveCatch }
1284 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1285 size_t bounds([self count]);
1286 if (index >= bounds)
1287 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1288 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1289 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1290 } CYObjectiveCatch }
1292 - (void) addObject:(id)object { CYObjectiveTry {
1293 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1294 } CYObjectiveCatch }
1296 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1297 size_t bounds([self count] + 1);
1298 if (index >= bounds)
1299 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1300 JSValueRef arguments[3];
1301 arguments[0] = CYCastJSValue(context, index);
1302 arguments[1] = CYCastJSValue(context, 0);
1303 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1304 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1305 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1306 } CYObjectiveCatch }
1308 - (void) removeLastObject { CYObjectiveTry {
1309 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1310 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1311 } CYObjectiveCatch }
1313 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1314 size_t bounds([self count]);
1315 if (index >= bounds)
1316 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1317 JSValueRef arguments[2];
1318 arguments[0] = CYCastJSValue(context, index);
1319 arguments[1] = CYCastJSValue(context, 1);
1320 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1321 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1322 } CYObjectiveCatch }
1324 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1325 size_t bounds([self count]);
1326 if (index >= bounds)
1327 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1328 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1329 } CYObjectiveCatch }
1333 // XXX: inherit from or replace with CYJSObject
1334 @interface CYInternal : NSObject {
1335 JSGlobalContextRef context_;
1336 JSObjectRef object_;
1341 @implementation CYInternal
1343 - (void) dealloc { CYObjectiveTry {
1344 JSValueUnprotect(context_, object_);
1345 JSGlobalContextRelease(context_);
1347 } CYObjectiveCatch }
1349 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1350 if ((self = [super init]) != nil) {
1351 context_ = CYGetJSContext(context);
1352 JSGlobalContextRetain(context_);
1354 } CYObjectiveCatch }
1356 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1357 if (object_ == NULL)
1360 return JSObjectHasProperty(context, object_, name);
1363 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1364 if (object_ == NULL)
1367 return CYGetProperty(context, object_, name);
1370 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1371 @synchronized (self) {
1372 if (object_ == NULL) {
1373 object_ = JSObjectMake(context, NULL, NULL);
1374 JSValueProtect(context, object_);
1378 CYSetProperty(context, object_, name, value);
1381 + (CYInternal *) get:(id)object {
1382 if ($objc_getAssociatedObject == NULL)
1385 @synchronized (object) {
1386 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1393 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1394 if ($objc_getAssociatedObject == NULL)
1397 @synchronized (object) {
1398 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1401 if ($objc_setAssociatedObject == NULL)
1404 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1405 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1414 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1415 Selector_privateData *internal(new Selector_privateData(sel));
1416 return JSObjectMake(context, Selector_, internal);
1419 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1420 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1421 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1422 return reinterpret_cast<SEL>(internal->value_);
1424 return CYCastPointer<SEL>(context, value);
1427 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1428 return (void *) [[NSAutoreleasePool alloc] init];
1429 } CYSadCatch(NULL) }
1431 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1432 return [(NSAutoreleasePool *) handle release];
1435 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1437 return Instance::Make(context, nil);
1438 if (Class _class = objc_getClass(name.data))
1439 return CYMakeInstance(context, _class, true);
1440 if (Protocol *protocol = objc_getProtocol(name.data))
1441 return CYMakeInstance(context, protocol, true);
1443 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1445 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1446 ffi_call(cif, function, value, values);
1449 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1450 switch (type->primitive) {
1451 // XXX: do something epic about blocks
1454 case sig::typename_P:
1455 // XXX: this works for return values, but not for properties and fields
1456 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1459 case sig::selector_P:
1460 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1468 } CYSadCatch(false) }
1470 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1471 switch (type->primitive) {
1472 // XXX: do something epic about blocks
1475 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1476 JSValueRef value(CYCastJSValue(context, object));
1482 case sig::typename_P:
1483 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1485 case sig::selector_P:
1486 if (SEL sel = *reinterpret_cast<SEL *>(data))
1487 return CYMakeSelector(context, sel);
1491 return CYJSNull(context);
1495 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1497 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1498 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1501 #if OBJC_API_VERSION >= 2
1503 method_getReturnType(method, type, sizeof(type));
1505 const char *type(method_getTypeEncoding(method));
1511 // XXX: possibly use a more "awesome" check?
1515 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1517 return method_getTypeEncoding(method);
1519 const char *name(sel_getName(sel));
1520 size_t length(strlen(name));
1522 char keyed[length + 2];
1524 keyed[length + 1] = '\0';
1525 memcpy(keyed + 1, name, length);
1527 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1528 return entry->value_;
1533 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1534 JSObjectRef _this(CYCastJSObject(context, values[0]));
1535 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1538 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1539 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1542 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1543 Message_privateData *internal(new Message_privateData(sel, type, imp));
1544 return JSObjectMake(context, Message_, internal);
1547 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1548 JSObjectRef function(CYCastJSObject(context, value));
1549 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1550 // XXX: see notes in Library.cpp about needing to leak
1551 return reinterpret_cast<IMP>(internal->GetValue());
1554 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1555 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1556 Class _class(internal->GetValue());
1559 const char *name(CYPoolCString(pool, context, property));
1561 if (SEL sel = sel_getUid(name))
1562 if (class_getInstanceMethod(_class, sel) != NULL)
1568 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1569 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1570 Class _class(internal->GetValue());
1573 const char *name(CYPoolCString(pool, context, property));
1575 if (SEL sel = sel_getUid(name))
1576 if (objc_method *method = class_getInstanceMethod(_class, sel))
1577 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1582 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1583 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1584 Class _class(internal->GetValue());
1587 const char *name(CYPoolCString(pool, context, property));
1589 SEL sel(sel_registerName(name));
1591 objc_method *method(class_getInstanceMethod(_class, sel));
1596 if (JSValueIsObjectOfClass(context, value, Message_)) {
1597 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1598 type = sig::Unparse(pool, &message->signature_);
1599 imp = reinterpret_cast<IMP>(message->GetValue());
1601 type = CYPoolTypeEncoding(pool, context, sel, method);
1602 imp = CYMakeMessage(context, value, type);
1606 method_setImplementation(method, imp);
1609 GSMethodList list(GSAllocMethodList(1));
1610 GSAppendMethodToList(list, sel, type, imp, YES);
1611 GSAddMethodList(_class, list, YES);
1612 GSFlushMethodCacheForClass(_class);
1614 class_addMethod(_class, sel, imp, type);
1621 #if 0 && OBJC_API_VERSION < 2
1622 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1623 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1624 Class _class(internal->GetValue());
1627 const char *name(CYPoolCString(pool, context, property));
1629 if (SEL sel = sel_getUid(name))
1630 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1631 objc_method_list list = {NULL, 1, {method}};
1632 class_removeMethods(_class, &list);
1640 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1641 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1642 Class _class(internal->GetValue());
1644 #if OBJC_API_VERSION >= 2
1646 objc_method **data(class_copyMethodList(_class, &size));
1647 for (size_t i(0); i != size; ++i)
1648 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1651 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1652 for (int i(0); i != methods->method_count; ++i)
1653 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1657 static bool CYHasImplicitProperties(Class _class) {
1658 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1659 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1661 return [_class cy$hasImplicitProperties];
1664 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1665 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1666 id self(internal->GetValue());
1668 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1672 NSString *name(CYCastNSString(&pool, context, property));
1674 if (CYInternal *internal = [CYInternal get:self])
1675 if ([internal hasProperty:property inContext:context])
1678 Class _class(object_getClass(self));
1681 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1682 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1683 if ([self cy$hasProperty:name])
1685 } CYPoolCatch(false)
1687 const char *string(CYPoolCString(pool, context, name));
1690 if (class_getProperty(_class, string) != NULL)
1694 if (CYHasImplicitProperties(_class))
1695 if (SEL sel = sel_getUid(string))
1696 if (CYImplements(self, _class, sel, true))
1702 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1703 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1704 id self(internal->GetValue());
1706 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1707 return Internal::Make(context, self, object);
1710 NSString *name(CYCastNSString(&pool, context, property));
1712 if (CYInternal *internal = [CYInternal get:self])
1713 if (JSValueRef value = [internal getProperty:property inContext:context])
1717 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1721 const char *string(CYPoolCString(pool, context, name));
1722 Class _class(object_getClass(self));
1725 if (objc_property_t property = class_getProperty(_class, string)) {
1726 PropertyAttributes attributes(property);
1727 SEL sel(sel_registerName(attributes.Getter()));
1728 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1732 if (CYHasImplicitProperties(_class))
1733 if (SEL sel = sel_getUid(string))
1734 if (CYImplements(self, _class, sel, true))
1735 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1740 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1741 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1742 id self(internal->GetValue());
1746 NSString *name(CYCastNSString(&pool, context, property));
1747 NSObject *data(CYCastNSObject(&pool, context, value));
1750 if ([self cy$setProperty:name to:data])
1752 } CYPoolCatch(false)
1754 const char *string(CYPoolCString(pool, context, name));
1755 Class _class(object_getClass(self));
1758 if (objc_property_t property = class_getProperty(_class, string)) {
1759 PropertyAttributes attributes(property);
1760 if (const char *setter = attributes.Setter()) {
1761 SEL sel(sel_registerName(setter));
1762 JSValueRef arguments[1] = {value};
1763 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1769 size_t length(strlen(string));
1771 char set[length + 5];
1777 if (string[0] != '\0') {
1778 set[3] = toupper(string[0]);
1779 memcpy(set + 4, string + 1, length - 1);
1782 set[length + 3] = ':';
1783 set[length + 4] = '\0';
1785 if (SEL sel = sel_getUid(set))
1786 if (CYImplements(self, _class, sel)) {
1787 JSValueRef arguments[1] = {value};
1788 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1792 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1793 [internal setProperty:property toValue:value inContext:context];
1800 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1801 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1802 id self(internal->GetValue());
1805 NSString *name(CYCastNSString(NULL, context, property));
1806 return [self cy$deleteProperty:name];
1807 } CYPoolCatch(false)
1808 } CYCatch(false) return /*XXX*/ false; }
1810 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1811 const char *name(sel_getName(method_getName(method)));
1812 if (strchr(name, ':') != NULL)
1815 const char *type(method_getTypeEncoding(method));
1816 if (type == NULL || *type == '\0' || *type == 'v')
1819 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1822 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1823 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1824 id self(internal->GetValue());
1827 Class _class(object_getClass(self));
1832 objc_property_t *data(class_copyPropertyList(_class, &size));
1833 for (size_t i(0); i != size; ++i)
1834 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1839 if (CYHasImplicitProperties(_class))
1840 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1841 #if OBJC_API_VERSION >= 2
1843 objc_method **data(class_copyMethodList(current, &size));
1844 for (size_t i(0); i != size; ++i)
1845 Instance_getPropertyNames_message(names, data[i]);
1848 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1849 for (int i(0); i != methods->method_count; ++i)
1850 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1855 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1856 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1857 [self cy$getPropertyNames:names inContext:context];
1861 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1862 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1863 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1867 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1868 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1869 id self(internal->GetValue());
1871 if (![self isKindOfClass:NSBlock_])
1872 CYThrow("non-NSBlock object is not a function");
1873 // XXX: replace above logic with the following assertion
1874 //_assert([self isKindOfClass:NSBlock_]);
1875 // to do this, make it so FunctionInstance_ is the class of blocks
1876 // to do /that/, generalize the various "is exactly Instance_" checks
1877 // then, move Instance_callAsFunction to only be on FunctionInstance
1879 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1881 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1882 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1883 descriptor += sizeof(BlockDescriptor1);
1884 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1885 descriptor += sizeof(BlockDescriptor2);
1886 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1888 if (const char *type = descriptor3->signature) {
1894 sig::Signature signature;
1895 sig::Parse(pool, &signature, type, &Structor_);
1898 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1900 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1901 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1906 CYThrow("NSBlock without signature field passed arguments");
1910 } CYPoolCatch(NULL);
1915 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1916 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1917 Class _class(internal->GetValue());
1918 if (!CYIsClass(_class))
1921 if (CYJSValueIsNSObject(context, instance)) {
1922 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1923 // XXX: this isn't always safe
1924 return [linternal->GetValue() isKindOfClass:_class];
1930 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1932 throw CYJSError(context, "incorrect number of arguments to Instance");
1934 id value(CYCastNSObject(&pool, context, arguments[0]));
1936 value = [NSNull null];
1937 return CYCastJSValue(context, [value cy$box]);
1940 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1941 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1944 id self(internal->GetValue());
1945 const char *name(CYPoolCString(pool, context, property));
1947 if (object_getInstanceVariable(self, name, NULL) != NULL)
1953 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1954 length = CYCastDouble(encoding + 1);
1958 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1959 for (size_t i(0); i != size; ++i)
1960 if (ivars[i] == ivar)
1962 else if (ivar_getOffset(ivars[i]) == offset) {
1963 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1964 _assert(encoding[0] == 'b');
1965 shift += CYCastDouble(encoding + 1);
1970 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1971 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1974 id self(internal->GetValue());
1975 const char *name(CYPoolCString(pool, context, property));
1978 if (strcmp(name, "isa") == 0)
1979 return CYCastJSValue(context, object_getClass(self));
1982 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1983 ptrdiff_t offset(ivar_getOffset(ivar));
1984 void *data(reinterpret_cast<uint8_t *>(self) + offset);
1986 const char *encoding(ivar_getTypeEncoding(ivar));
1987 if (encoding[0] == 'b') {
1988 unsigned length, shift;
1989 CYBitField(length, shift, self, ivar, encoding, offset);
1990 _assert(shift + length <= sizeof(uintptr_t) * 8);
1991 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
1992 uintptr_t mask((1 << length) - 1);
1993 return CYCastJSValue(context, (field >> shift) & mask);
1995 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1996 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2003 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2004 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2007 id self(internal->GetValue());
2008 const char *name(CYPoolCString(pool, context, property));
2010 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2011 ptrdiff_t offset(ivar_getOffset(ivar));
2012 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2014 const char *encoding(ivar_getTypeEncoding(ivar));
2015 if (encoding[0] == 'b') {
2016 unsigned length, shift;
2017 CYBitField(length, shift, self, ivar, encoding, offset);
2018 _assert(shift + length <= sizeof(uintptr_t) * 8);
2019 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2020 uintptr_t mask((1 << length) - 1);
2021 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2023 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2024 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2032 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2033 if (Class super = class_getSuperclass(_class))
2034 Internal_getPropertyNames_(super, names);
2036 #if OBJC_API_VERSION >= 2
2038 objc_ivar **data(class_copyIvarList(_class, &size));
2039 for (size_t i(0); i != size; ++i)
2040 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2043 if (objc_ivar_list *ivars = _class->ivars)
2044 for (int i(0); i != ivars->ivar_count; ++i)
2045 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2049 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2050 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2053 id self(internal->GetValue());
2054 Class _class(object_getClass(self));
2056 Internal_getPropertyNames_(_class, names);
2059 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2060 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2061 return internal->GetOwner();
2064 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2066 NSString *name(CYCastNSString(&pool, context, property));
2067 if (Class _class = NSClassFromString(name))
2068 return CYMakeInstance(context, _class, true);
2072 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2074 size_t size(objc_getClassList(NULL, 0));
2075 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2078 size_t writ(objc_getClassList(data, size));
2081 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2087 for (size_t i(0); i != writ; ++i)
2088 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2094 while (Class _class = objc_next_class(&state))
2095 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2099 #if OBJC_API_VERSION >= 2
2100 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2101 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2104 const char *name(CYPoolCString(pool, context, property));
2106 const char **data(objc_copyClassNamesForImage(internal, &size));
2108 for (size_t i(0); i != size; ++i)
2109 if (strcmp(name, data[i]) == 0) {
2110 if (Class _class = objc_getClass(name)) {
2111 value = CYMakeInstance(context, _class, true);
2122 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2123 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2125 const char **data(objc_copyClassNamesForImage(internal, &size));
2126 for (size_t i(0); i != size; ++i)
2127 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2131 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2133 const char *name(CYPoolCString(pool, context, property));
2135 const char **data(objc_copyImageNames(&size));
2136 for (size_t i(0); i != size; ++i)
2137 if (strcmp(name, data[i]) == 0) {
2146 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2147 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2151 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2153 const char **data(objc_copyImageNames(&size));
2154 for (size_t i(0); i != size; ++i)
2155 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2160 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2162 const char *name(CYPoolCString(pool, context, property));
2163 if (Protocol *protocol = objc_getProtocol(name))
2164 return CYMakeInstance(context, protocol, true);
2168 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2169 #if OBJC_API_VERSION >= 2
2171 Protocol **data(objc_copyProtocolList(&size));
2172 for (size_t i(0); i != size; ++i)
2173 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2180 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2182 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2184 return Instance::Make(context, nil);
2188 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2189 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2193 #if defined(__i386__) || defined(__x86_64__)
2194 #define OBJC_MAX_STRUCT_BY_VALUE 8
2195 static int struct_forward_array[] = {
2196 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2197 #elif defined(__arm__)
2198 #define OBJC_MAX_STRUCT_BY_VALUE 1
2199 static int struct_forward_array[] = {
2201 #elif defined(__arm64__)
2204 #error missing objc-runtime-info
2208 static bool stret(ffi_type *ffi_type) {
2209 return ffi_type->type == FFI_TYPE_STRUCT && (
2210 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2211 struct_forward_array[ffi_type->size] != 0
2217 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2221 _class = object_getClass(self);
2225 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2226 imp = method_getImplementation(method);
2227 type = method_getTypeEncoding(method);
2232 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2234 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2235 type = CYPoolCString(pool, context, [method _typeString]);
2243 sig::Signature signature;
2244 sig::Parse(pool, &signature, type, &Structor_);
2246 size_t used(count + 3);
2247 if (used > signature.count) {
2248 sig::Element *elements(new (pool) sig::Element[used]);
2249 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2251 for (size_t index(signature.count); index != used; ++index) {
2252 sig::Element *element(&elements[index]);
2253 element->name = NULL;
2254 element->offset = _not(size_t);
2256 sig::Type *type(new (pool) sig::Type);
2257 memset(type, 0, sizeof(*type));
2258 type->primitive = sig::object_P;
2259 element->type = type;
2262 signature.elements = elements;
2263 signature.count = used;
2267 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2272 if (stret(cif.rtype))
2273 imp = class_getMethodImplementation_stret(_class, _cmd);
2276 imp = class_getMethodImplementation(_class, _cmd);
2278 objc_super super = {self, _class};
2279 imp = objc_msg_lookup_super(&super, _cmd);
2283 void (*function)() = reinterpret_cast<void (*)()>(imp);
2284 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2287 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2289 throw CYJSError(context, "too few arguments to objc_msgSend");
2299 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2300 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2301 self = internal->GetValue();
2302 _class = internal->class_;;
2303 uninitialized = false;
2304 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2305 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2306 self = internal->GetValue();
2308 uninitialized = internal->IsUninitialized();
2310 internal->value_ = nil;
2312 self = CYCastNSObject(&pool, context, arguments[0]);
2314 uninitialized = false;
2318 return CYJSNull(context);
2320 _cmd = CYCastSEL(context, arguments[1]);
2322 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2325 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2326 JSValueRef setup[count + 2];
2329 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2330 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2333 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2335 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2337 // XXX: handle Instance::Uninitialized?
2338 id self(CYCastNSObject(&pool, context, _this));
2342 setup[1] = &internal->sel_;
2344 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2347 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2349 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2351 id self(CYCastNSObject(&pool, context, arguments[0]));
2352 Class _class(CYCastClass(pool, context, arguments[1]));
2353 return cy::Super::Make(context, self, _class);
2356 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2358 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2360 const char *name(CYPoolCString(pool, context, arguments[0]));
2361 return CYMakeSelector(context, sel_registerName(name));
2364 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2366 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2367 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2368 return CYMakeInstance(context, self, false);
2371 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2372 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2373 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2376 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2377 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2378 Type_privateData *typical(internal->GetType());
2383 if (typical == NULL) {
2387 type = typical->type_;
2388 ffi = typical->ffi_;
2391 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2394 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2395 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2396 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2399 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2400 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2401 id self(internal->GetValue());
2402 if (!CYIsClass(self))
2403 return CYJSUndefined(context);
2404 return CYGetClassPrototype(context, self);
2407 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2408 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2409 id self(internal->GetValue());
2410 if (!CYIsClass(self))
2411 return CYJSUndefined(context);
2412 return Messages::Make(context, (Class) self);
2415 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2416 if (!CYJSValueIsNSObject(context, _this))
2419 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2420 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2423 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2424 if (!CYJSValueIsNSObject(context, _this))
2427 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2428 id value(internal->GetValue());
2435 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2437 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2438 return CYJSUndefined(context);
2439 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2442 return CYCastJSValue(context, CYJSString(context, [value description]));
2444 } CYCatch(NULL) return /*XXX*/ NULL; }
2446 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2447 if (!CYJSValueIsNSObject(context, _this))
2450 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2451 id value(internal->GetValue());
2453 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2456 if (JSValueRef result = [value cy$valueOfInContext:context])
2460 } CYCatch(NULL) return /*XXX*/ NULL; }
2462 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2463 if (!CYJSValueIsNSObject(context, _this))
2466 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2467 // XXX: but... but... THIS ISN'T A POINTER! :(
2468 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2469 } CYCatch(NULL) return /*XXX*/ NULL; }
2471 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2472 if (!CYJSValueIsNSObject(context, _this))
2475 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2476 id value(internal->GetValue());
2479 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2480 return CYCastJSValue(context, CYJSString(context, [value description]));
2482 } CYCatch(NULL) return /*XXX*/ NULL; }
2484 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2485 if (!CYJSValueIsNSObject(context, _this))
2488 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2489 id value(internal->GetValue());
2491 if (!CYIsClass(value))
2492 CYThrow("non-Class object cannot be used as Type");
2494 // XXX: this is a very silly implementation
2496 std::ostringstream type;
2498 type << class_getName(value);
2502 return CYMakeType(context, type.str().c_str());
2504 } CYCatch(NULL) return /*XXX*/ NULL; }
2506 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2507 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2508 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2511 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2512 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2515 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2516 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2517 const char *name(sel_getName(internal->GetValue()));
2520 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2521 return CYCastJSValue(context, CYJSString(context, string));
2523 } CYCatch(NULL) return /*XXX*/ NULL; }
2525 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2527 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2530 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2531 SEL sel(internal->GetValue());
2533 objc_method *method;
2534 if (Class _class = CYCastClass(pool, context, arguments[0]))
2535 method = class_getInstanceMethod(_class, sel);
2539 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2540 return CYCastJSValue(context, CYJSString(type));
2542 return CYJSNull(context);
2545 static JSStaticValue Selector_staticValues[2] = {
2546 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2547 {NULL, NULL, NULL, 0}
2550 static JSStaticValue Instance_staticValues[5] = {
2551 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2552 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2553 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2554 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2555 {NULL, NULL, NULL, 0}
2558 static JSStaticFunction Instance_staticFunctions[7] = {
2559 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2560 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2561 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2562 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2563 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2564 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2568 static JSStaticFunction Class_staticFunctions[2] = {
2569 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2573 static JSStaticFunction Internal_staticFunctions[2] = {
2574 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2578 static JSStaticFunction Selector_staticFunctions[5] = {
2579 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2580 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2581 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2582 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2587 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2588 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2589 } CYObjectiveCatch }
2592 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2593 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2594 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2595 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2597 CYPool &pool(CYGetGlobalPool());
2599 Object_type = new(pool) Type_privateData("@");
2600 Selector_type = new(pool) Type_privateData(":");
2602 NSArray_ = objc_getClass("NSArray");
2603 NSBlock_ = objc_getClass("NSBlock");
2604 NSDictionary_ = objc_getClass("NSDictionary");
2605 NSString_ = objc_getClass("NSString");
2606 Object_ = objc_getClass("Object");
2609 // XXX: apparently, iOS now has both of these
2610 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2611 if (NSCFBoolean_ == nil)
2612 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2614 NSCFType_ = objc_getClass("NSCFType");
2616 NSZombie_ = objc_getClass("_NSZombie_");
2618 banned_.insert(Object_);
2619 banned_.insert(objc_getClass("__NSAtom"));
2620 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2621 banned_.insert(objc_getClass("NSMessageBuilder"));
2622 banned_.insert(objc_getClass("__NSMessageBuilder"));
2624 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2627 JSClassDefinition definition;
2629 definition = kJSClassDefinitionEmpty;
2630 definition.className = "Instance";
2631 definition.staticValues = Instance_staticValues;
2632 definition.staticFunctions = Instance_staticFunctions;
2633 definition.hasProperty = &Instance_hasProperty;
2634 definition.getProperty = &Instance_getProperty;
2635 definition.setProperty = &Instance_setProperty;
2636 definition.deleteProperty = &Instance_deleteProperty;
2637 definition.getPropertyNames = &Instance_getPropertyNames;
2638 definition.callAsConstructor = &Instance_callAsConstructor;
2639 definition.callAsFunction = &Instance_callAsFunction;
2640 definition.hasInstance = &Instance_hasInstance;
2641 definition.finalize = &CYFinalize;
2642 Instance_ = JSClassCreate(&definition);
2644 definition.className = "ArrayInstance";
2645 ArrayInstance_ = JSClassCreate(&definition);
2647 definition.className = "FunctionInstance";
2648 FunctionInstance_ = JSClassCreate(&definition);
2650 definition.className = "ObjectInstance";
2651 ObjectInstance_ = JSClassCreate(&definition);
2653 definition.className = "StringInstance";
2654 StringInstance_ = JSClassCreate(&definition);
2656 definition = kJSClassDefinitionEmpty;
2657 definition.className = "Class";
2658 definition.staticFunctions = Class_staticFunctions;
2659 Class_ = JSClassCreate(&definition);
2661 definition = kJSClassDefinitionEmpty;
2662 definition.className = "Internal";
2663 definition.staticFunctions = Internal_staticFunctions;
2664 definition.hasProperty = &Internal_hasProperty;
2665 definition.getProperty = &Internal_getProperty;
2666 definition.setProperty = &Internal_setProperty;
2667 definition.getPropertyNames = &Internal_getPropertyNames;
2668 definition.finalize = &CYFinalize;
2669 Internal_ = JSClassCreate(&definition);
2671 definition = kJSClassDefinitionEmpty;
2672 definition.className = "Message";
2673 definition.staticFunctions = cy::Functor::StaticFunctions;
2674 definition.callAsFunction = &Message_callAsFunction;
2675 definition.finalize = &CYFinalize;
2676 Message_ = JSClassCreate(&definition);
2678 definition = kJSClassDefinitionEmpty;
2679 definition.className = "Messages";
2680 definition.hasProperty = &Messages_hasProperty;
2681 definition.getProperty = &Messages_getProperty;
2682 definition.setProperty = &Messages_setProperty;
2683 #if 0 && OBJC_API_VERSION < 2
2684 definition.deleteProperty = &Messages_deleteProperty;
2686 definition.getPropertyNames = &Messages_getPropertyNames;
2687 definition.finalize = &CYFinalize;
2688 Messages_ = JSClassCreate(&definition);
2690 definition = kJSClassDefinitionEmpty;
2691 definition.className = "Selector";
2692 definition.staticValues = Selector_staticValues;
2693 definition.staticFunctions = Selector_staticFunctions;
2694 definition.callAsFunction = &Selector_callAsFunction;
2695 definition.finalize = &CYFinalize;
2696 Selector_ = JSClassCreate(&definition);
2698 definition = kJSClassDefinitionEmpty;
2699 definition.className = "Super";
2700 definition.staticFunctions = Internal_staticFunctions;
2701 definition.finalize = &CYFinalize;
2702 Super_ = JSClassCreate(&definition);
2704 definition = kJSClassDefinitionEmpty;
2705 definition.className = "ObjectiveC::Classes";
2706 definition.getProperty = &ObjectiveC_Classes_getProperty;
2707 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2708 ObjectiveC_Classes_ = JSClassCreate(&definition);
2710 definition = kJSClassDefinitionEmpty;
2711 definition.className = "ObjectiveC::Constants";
2712 definition.getProperty = &ObjectiveC_Constants_getProperty;
2713 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2714 ObjectiveC_Constants_ = JSClassCreate(&definition);
2716 #if OBJC_API_VERSION >= 2
2717 definition = kJSClassDefinitionEmpty;
2718 definition.className = "ObjectiveC::Images";
2719 definition.getProperty = &ObjectiveC_Images_getProperty;
2720 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2721 ObjectiveC_Images_ = JSClassCreate(&definition);
2723 definition = kJSClassDefinitionEmpty;
2724 definition.className = "ObjectiveC::Image::Classes";
2725 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2726 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2727 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2730 definition = kJSClassDefinitionEmpty;
2731 definition.className = "ObjectiveC::Protocols";
2732 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2733 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2734 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2737 // XXX: this is horrible; there has to be a better way to do this
2739 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2741 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2746 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2747 JSObjectRef global(CYGetGlobalObject(context));
2748 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2749 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2750 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2751 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2753 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2754 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2756 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2757 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2758 CYArrayPush(context, alls, protocols);
2760 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2761 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2762 CYArrayPush(context, alls, classes);
2764 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2765 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2766 CYArrayPush(context, alls, constants);
2768 #if OBJC_API_VERSION >= 2
2769 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2772 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2773 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2774 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2775 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2776 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2778 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2779 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2781 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2782 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2783 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2784 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2785 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2787 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2788 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2789 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2790 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2791 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2793 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2794 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2795 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2796 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2797 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2799 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2800 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2801 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2802 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2803 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2805 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2806 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2807 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2809 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2810 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2811 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2813 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2814 CYSetProperty(context, Instance, CYJSString("box"), box);
2816 #if defined(__APPLE__) && defined(__arm__) && 0
2817 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2820 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2822 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2823 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2826 static CYHooks CYObjectiveCHooks = {
2827 &CYObjectiveC_ExecuteStart,
2828 &CYObjectiveC_ExecuteEnd,
2829 &CYObjectiveC_CallFunction,
2830 &CYObjectiveC_Initialize,
2831 &CYObjectiveC_SetupContext,
2832 &CYObjectiveC_PoolFFI,
2833 &CYObjectiveC_FromFFI,
2836 struct CYObjectiveC {
2838 hooks_ = &CYObjectiveCHooks;
2839 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2840 _assert(hooks_ != NULL);