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 <WebKit/WebScriptObject.h>
36 #include <objc/runtime.h>
40 #include "JavaScript.hpp"
42 #include "Execute.hpp"
49 #define CYObjectiveTry_(context) { \
50 JSContextRef context_(context); \
52 #define CYObjectiveTry { \
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, JSValueRef *exception);
164 /* Objective-C Pool Release {{{ */
165 apr_status_t CYPoolRelease_(void *data) {
166 id object(reinterpret_cast<id>(data));
171 id CYPoolRelease_(CYPool *pool, id object) {
174 else if (pool == NULL)
175 return [object autorelease];
177 apr_pool_cleanup_register(*pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
182 template <typename Type_>
183 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
184 return (Type_) CYPoolRelease_(pool, (id) object);
187 /* Objective-C Strings {{{ */
188 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
190 return [value UTF8String];
192 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
193 char *string(new(pool) char[size]);
194 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
195 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
200 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
202 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
205 return CYCopyJSString(CYPoolCString(pool, context, value));
209 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
212 // XXX: this definition scares me; is anyone using this?!
213 NSString *string([value description]);
214 return CYCopyJSString(context, string);
217 NSString *CYCopyNSString(const CYUTF8String &value) {
219 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
221 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
225 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
227 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
230 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
234 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
235 return CYCopyNSString(context, CYJSString(context, value));
238 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
239 return CYPoolRelease(pool, CYCopyNSString(value));
242 NSString *CYCastNSString(CYPool *pool, SEL sel) {
243 const char *name(sel_getName(sel));
244 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
247 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
248 return CYPoolRelease(pool, CYCopyNSString(context, value));
251 CYUTF8String CYCastUTF8String(NSString *value) {
252 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
253 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
257 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
259 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
260 if (exception == NULL)
262 *exception = CYCastJSValue(context, error);
265 size_t CYGetIndex(NSString *value) {
266 return CYGetIndex(CYCastUTF8String(value));
269 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
270 return CYGetOffset(CYPoolCString(pool, context, value), index);
273 static JSClassRef Instance_;
275 static JSClassRef ArrayInstance_;
276 static JSClassRef FunctionInstance_;
277 static JSClassRef ObjectInstance_;
278 static JSClassRef StringInstance_;
280 static JSClassRef Class_;
281 static JSClassRef Internal_;
282 static JSClassRef Message_;
283 static JSClassRef Messages_;
284 static JSClassRef Selector_;
285 static JSClassRef Super_;
287 static JSClassRef ObjectiveC_Classes_;
288 static JSClassRef ObjectiveC_Constants_;
289 static JSClassRef ObjectiveC_Protocols_;
292 static JSClassRef ObjectiveC_Image_Classes_;
293 static JSClassRef ObjectiveC_Images_;
297 static Class NSCFBoolean_;
298 static Class NSCFType_;
299 static Class NSGenericDeallocHandler_;
300 static Class NSMessageBuilder_;
301 static Class NSZombie_;
303 static Class NSBoolNumber_;
306 static Class NSArray_;
307 static Class NSBlock_;
308 static Class NSDictionary_;
309 static Class NSString_;
310 static Class Object_;
312 static Type_privateData *Object_type;
313 static Type_privateData *Selector_type;
315 Type_privateData *Instance::GetType() const {
319 Type_privateData *Selector_privateData::GetType() const {
320 return Selector_type;
323 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
325 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
327 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
328 else if (meta && !class_isMetaClass(self))
329 return CYGetCachedObject(context, CYJSString("Class_prototype"));
331 JSObjectRef global(CYGetGlobalObject(context));
332 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
335 sprintf(label, "i%p", self);
336 CYJSString name(label);
338 JSValueRef value(CYGetProperty(context, cy, name));
339 if (!JSValueIsUndefined(context, value))
342 JSClassRef _class(NULL);
343 JSValueRef prototype;
345 if (self == NSArray_)
346 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
347 else if (self == NSBlock_)
348 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
349 else if (self == NSDictionary_)
350 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
351 else if (self == NSString_)
352 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
354 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
356 JSObjectRef object(JSObjectMake(context, _class, NULL));
357 JSObjectSetPrototype(context, object, prototype);
358 CYSetProperty(context, cy, name, object);
363 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
364 return CYGetClassPrototype(context, self, class_isMetaClass(self));
367 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
368 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
369 if (Class super = class_getSuperclass(_class))
370 JSObjectSetPrototype(context, value, Messages::Make(context, super));
374 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
375 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
379 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
380 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
384 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
385 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
386 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
390 Instance::~Instance() {
391 if ((flags_ & Transient) == 0)
392 // XXX: does this handle background threads correctly?
393 // XXX: this simply does not work on the console because I'm stupid
394 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
397 struct Message_privateData :
402 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
403 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
409 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
410 Instance::Flags flags;
413 flags = Instance::Transient;
415 flags = Instance::None;
416 object = [object retain];
419 return Instance::Make(context, object, flags);
422 @interface NSMethodSignature (Cycript)
423 - (NSString *) _typeString;
426 @interface NSObject (Cycript)
428 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
429 - (JSType) cy$JSType;
431 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
432 - (NSString *) cy$toCYON:(bool)objective;
434 - (bool) cy$hasProperty:(NSString *)name;
435 - (NSObject *) cy$getProperty:(NSString *)name;
436 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
437 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
438 - (bool) cy$deleteProperty:(NSString *)name;
439 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
441 + (bool) cy$hasImplicitProperties;
447 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
450 NSString *CYCastNSCYON(id value, bool objective) {
456 Class _class(object_getClass(value));
457 SEL sel(@selector(cy$toCYON:));
459 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
460 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
461 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
462 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
463 string = [value cy$toCYON:objective];
468 else if (value == NSZombie_)
469 string = @"_NSZombie_";
470 else if (_class == NSZombie_)
471 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
472 // XXX: frowny /in/ the pants
473 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
477 string = [NSString stringWithFormat:@"%@", value];
482 string = @"undefined";
489 struct PropertyAttributes {
494 const char *variable;
507 PropertyAttributes(objc_property_t property) :
519 name = property_getName(property);
520 const char *attributes(property_getAttributes(property));
522 for (char *state, *token(apr_strtok(pool_.strdup(attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
524 case 'R': readonly = true; break;
525 case 'C': copy = true; break;
526 case '&': retain = true; break;
527 case 'N': nonatomic = true; break;
528 case 'G': getter_ = token + 1; break;
529 case 'S': setter_ = token + 1; break;
530 case 'V': variable = token + 1; break;
534 /*if (variable == NULL) {
535 variable = property_getName(property);
536 size_t size(strlen(variable));
537 char *name(new(pool_) char[size + 2]);
539 memcpy(name + 1, variable, size);
540 name[size + 1] = '\0';
545 const char *Getter() {
547 getter_ = pool_.strdup(name);
551 const char *Setter() {
552 if (setter_ == NULL && !readonly) {
553 size_t length(strlen(name));
555 char *temp(new(pool_) char[length + 5]);
561 temp[3] = toupper(name[0]);
562 memcpy(temp + 4, name + 1, length - 1);
565 temp[length + 3] = ':';
566 temp[length + 4] = '\0';
577 @interface CYWebUndefined : NSObject {
580 + (CYWebUndefined *) undefined;
584 @implementation CYWebUndefined
586 + (CYWebUndefined *) undefined {
587 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
593 #define WebUndefined CYWebUndefined
596 /* Bridge: CYJSObject {{{ */
597 @interface CYJSObject : NSMutableDictionary {
599 JSGlobalContextRef context_;
602 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
604 - (NSUInteger) count;
605 - (id) objectForKey:(id)key;
606 - (NSEnumerator *) keyEnumerator;
607 - (void) setObject:(id)object forKey:(id)key;
608 - (void) removeObjectForKey:(id)key;
612 /* Bridge: CYJSArray {{{ */
613 @interface CYJSArray : NSMutableArray {
615 JSGlobalContextRef context_;
618 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
620 - (NSUInteger) count;
621 - (id) objectAtIndex:(NSUInteger)index;
623 - (void) addObject:(id)anObject;
624 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
625 - (void) removeLastObject;
626 - (void) removeObjectAtIndex:(NSUInteger)index;
627 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
632 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
633 return JSValueIsObjectOfClass(context, value, Instance_);
636 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
637 JSValueRef exception(NULL);
638 JSObjectRef constructor(CYGetCachedObject(context, cache));
639 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
640 CYThrow(context, exception);
644 NSObject *CYMakeBlock(void (*invoke)(), sig::Signature &signature) {
645 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
649 BlockDescriptor1 one_;
650 BlockDescriptor2 two_;
651 BlockDescriptor3 three_;
657 Descriptor *descriptor(new Descriptor);
658 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
660 literal->isa = objc_getClass("__NSGlobalBlock__");
661 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
662 literal->reserved = 0;
663 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(invoke);
664 literal->descriptor = descriptor;
666 descriptor->d_.one_.size = sizeof(descriptor->d_);
667 descriptor->d_.three_.signature = sig::Unparse(descriptor->pool_, &signature);
669 return reinterpret_cast<NSObject *>(literal);
672 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
673 if (CYJSValueIsNSObject(context, object)) {
674 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
675 return internal->GetValue();
678 if (JSValueIsObjectOfClass(context, object, Functor_)) {
679 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
680 return CYMakeBlock(internal->GetValue(), internal->signature_);
683 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
684 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
685 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
688 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
689 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
693 @interface NSBoolNumber : NSNumber {
698 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
702 switch (JSType type = JSValueGetType(context, value)) {
703 case kJSTypeUndefined:
704 object = [WebUndefined undefined];
714 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
717 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
723 object = CYCopyNSNumber(context, value);
728 object = CYCopyNSString(context, value);
733 // XXX: this might could be more efficient
734 object = CYCastNSObject(pool, context, (JSObjectRef) value);
739 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
746 return CYPoolRelease(pool, object);
748 return [object retain];
751 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
752 return CYNSObject(pool, context, value, true);
755 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
756 return CYNSObject(&pool, context, value, false);
759 /* Bridge: NSArray {{{ */
760 @implementation NSArray (Cycript)
763 return [[self mutableCopy] autorelease];
766 - (NSString *) cy$toCYON:(bool)objective {
767 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
768 [json appendString:@"@["];
772 for (id object in self) {
774 for (size_t index(0), count([self count]); index != count; ++index) {
775 id object([self objectAtIndex:index]);
778 [json appendString:@","];
781 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
782 [json appendString:CYCastNSCYON(object, true)];
784 [json appendString:@","];
789 [json appendString:@"]"];
793 - (bool) cy$hasProperty:(NSString *)name {
794 if ([name isEqualToString:@"length"])
797 size_t index(CYGetIndex(name));
798 if (index == _not(size_t) || index >= [self count])
799 return [super cy$hasProperty:name];
804 - (NSObject *) cy$getProperty:(NSString *)name {
805 size_t index(CYGetIndex(name));
806 if (index == _not(size_t) || index >= [self count])
807 return [super cy$getProperty:name];
809 return [self objectAtIndex:index];
812 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
813 CYObjectiveTry_(context) {
814 if ([name isEqualToString:@"length"])
815 return CYCastJSValue(context, [self count]);
818 return [super cy$getProperty:name inContext:context];
821 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
822 [super cy$getPropertyNames:names inContext:context];
824 for (size_t index(0), count([self count]); index != count; ++index) {
825 id object([self objectAtIndex:index]);
826 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
828 sprintf(name, "%zu", index);
829 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
834 + (bool) cy$hasImplicitProperties {
840 /* Bridge: NSBlock {{{ */
847 /* Bridge: NSBoolNumber {{{ */
849 @implementation NSBoolNumber (Cycript)
851 - (JSType) cy$JSType {
852 return kJSTypeBoolean;
855 - (NSString *) cy$toCYON:(bool)objective {
856 NSString *value([self boolValue] ? @"true" : @"false");
857 return objective ? value : [NSString stringWithFormat:@"@%@", value];
860 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
861 return CYCastJSValue(context, (bool) [self boolValue]);
867 /* Bridge: NSDictionary {{{ */
868 @implementation NSDictionary (Cycript)
871 return [[self mutableCopy] autorelease];
874 - (NSString *) cy$toCYON:(bool)objective {
875 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
876 [json appendString:@"@{"];
880 for (NSObject *key in self) {
882 NSEnumerator *keys([self keyEnumerator]);
883 while (NSObject *key = [keys nextObject]) {
886 [json appendString:@","];
889 [json appendString:CYCastNSCYON(key, true)];
890 [json appendString:@":"];
891 NSObject *object([self objectForKey:key]);
892 [json appendString:CYCastNSCYON(object, true)];
895 [json appendString:@"}"];
899 - (bool) cy$hasProperty:(NSString *)name {
900 return [self objectForKey:name] != nil;
903 - (NSObject *) cy$getProperty:(NSString *)name {
904 return [self objectForKey:name];
907 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
908 [super cy$getPropertyNames:names inContext:context];
911 for (NSObject *key in self) {
913 NSEnumerator *keys([self keyEnumerator]);
914 while (NSObject *key = [keys nextObject]) {
916 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
920 + (bool) cy$hasImplicitProperties {
926 /* Bridge: NSMutableArray {{{ */
927 @implementation NSMutableArray (Cycript)
929 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
930 if ([name isEqualToString:@"length"]) {
931 // XXX: is this not intelligent?
932 NSNumber *number(reinterpret_cast<NSNumber *>(value));
934 NSUInteger size([number unsignedIntegerValue]);
936 NSUInteger size([number unsignedIntValue]);
938 NSUInteger count([self count]);
940 [self removeObjectsInRange:NSMakeRange(size, count - size)];
941 else if (size != count) {
942 WebUndefined *undefined([WebUndefined undefined]);
943 for (size_t i(count); i != size; ++i)
944 [self addObject:undefined];
949 size_t index(CYGetIndex(name));
950 if (index == _not(size_t))
951 return [super cy$setProperty:name to:value];
953 id object(value ?: [NSNull null]);
955 size_t count([self count]);
957 [self replaceObjectAtIndex:index withObject:object];
959 if (index != count) {
960 WebUndefined *undefined([WebUndefined undefined]);
961 for (size_t i(count); i != index; ++i)
962 [self addObject:undefined];
965 [self addObject:object];
971 - (bool) cy$deleteProperty:(NSString *)name {
972 size_t index(CYGetIndex(name));
973 if (index == _not(size_t) || index >= [self count])
974 return [super cy$deleteProperty:name];
975 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
981 /* Bridge: NSMutableDictionary {{{ */
982 @implementation NSMutableDictionary (Cycript)
984 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
985 [self setObject:(value ?: [NSNull null]) forKey:name];
989 - (bool) cy$deleteProperty:(NSString *)name {
990 if ([self objectForKey:name] == nil)
993 [self removeObjectForKey:name];
1000 /* Bridge: NSNumber {{{ */
1001 @implementation NSNumber (Cycript)
1003 - (JSType) cy$JSType {
1005 // XXX: this just seems stupid
1006 if ([self class] == NSCFBoolean_)
1007 return kJSTypeBoolean;
1009 return kJSTypeNumber;
1012 - (NSString *) cy$toCYON:(bool)objective {
1013 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1014 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1017 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1018 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1019 } CYObjectiveCatch }
1023 /* Bridge: NSNull {{{ */
1024 @implementation NSNull (Cycript)
1026 - (JSType) cy$JSType {
1030 - (NSString *) cy$toCYON:(bool)objective {
1031 NSString *value(@"null");
1032 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1035 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1036 return CYJSNull(context);
1037 } CYObjectiveCatch }
1041 /* Bridge: NSObject {{{ */
1042 @implementation NSObject (Cycript)
1048 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1049 return [self cy$valueOfInContext:context];
1052 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1054 } CYObjectiveCatch }
1056 - (JSType) cy$JSType {
1057 return kJSTypeObject;
1060 - (NSString *) cy$toCYON:(bool)objective {
1061 return [[self description] cy$toCYON:objective];
1064 - (bool) cy$hasProperty:(NSString *)name {
1068 - (NSObject *) cy$getProperty:(NSString *)name {
1072 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_(context) {
1073 if (NSObject *value = [self cy$getProperty:name])
1074 return CYCastJSValue(context, value);
1076 } CYObjectiveCatch }
1078 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1082 - (bool) cy$deleteProperty:(NSString *)name {
1086 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1089 + (bool) cy$hasImplicitProperties {
1095 /* Bridge: NSProxy {{{ */
1096 @implementation NSProxy (Cycript)
1098 - (NSString *) cy$toCYON:(bool)objective {
1099 return [[self description] cy$toCYON:objective];
1104 /* Bridge: NSString {{{ */
1105 @implementation NSString (Cycript)
1108 return [[self copy] autorelease];
1111 - (JSType) cy$JSType {
1112 return kJSTypeString;
1115 - (NSString *) cy$toCYON:(bool)objective {
1116 std::ostringstream str;
1119 CYUTF8String string(CYCastUTF8String(self));
1120 CYStringify(str, string.data, string.size);
1121 std::string value(str.str());
1122 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1125 - (bool) cy$hasProperty:(NSString *)name {
1126 size_t index(CYGetIndex(name));
1127 if (index == _not(size_t) || index >= [self length])
1128 return [super cy$hasProperty:name];
1133 - (NSObject *) cy$getProperty:(NSString *)name {
1134 size_t index(CYGetIndex(name));
1135 if (index == _not(size_t) || index >= [self length])
1136 return [super cy$getProperty:name];
1138 return [self substringWithRange:NSMakeRange(index, 1)];
1141 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1142 [super cy$getPropertyNames:names inContext:context];
1144 for (size_t index(0), length([self length]); index != length; ++index) {
1146 sprintf(name, "%zu", index);
1147 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1151 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1152 return CYCastJSValue(context, CYJSString(context, self));
1153 } CYObjectiveCatch }
1157 /* Bridge: WebUndefined {{{ */
1158 @implementation WebUndefined (Cycript)
1160 - (JSType) cy$JSType {
1161 return kJSTypeUndefined;
1164 - (NSString *) cy$toCYON:(bool)objective {
1165 NSString *value(@"undefined");
1166 return value; // XXX: maybe use the below code, adding @undefined?
1167 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1170 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1171 return CYJSUndefined(context);
1172 } CYObjectiveCatch }
1177 static bool CYIsClass(id self) {
1179 return class_isMetaClass(object_getClass(self));
1181 return GSObjCIsClass(self);
1185 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1186 id self(CYCastNSObject(&pool, context, value));
1187 if (CYIsClass(self))
1188 return (Class) self;
1189 throw CYJSError(context, "got something that is not a Class");
1193 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1195 size_t size(JSPropertyNameArrayGetCount(names));
1196 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1197 for (size_t index(0); index != size; ++index)
1198 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1202 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1204 return CYJSNull(context);
1206 return CYMakeInstance(context, value, false);
1207 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1209 @implementation CYJSObject
1211 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1212 if ((self = [super init]) != nil) {
1214 context_ = CYGetJSContext(context);
1215 JSGlobalContextRetain(context_);
1216 JSValueProtect(context_, object_);
1218 } CYObjectiveCatch }
1220 - (void) dealloc { CYObjectiveTry {
1221 JSValueUnprotect(context_, object_);
1222 JSGlobalContextRelease(context_);
1224 } CYObjectiveCatch }
1226 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1228 JSValueRef exception(NULL);
1229 const char *cyon(CYPoolCCYON(pool, context_, object_));
1230 CYThrow(context_, exception);
1232 return [super cy$toCYON:objective];
1234 return [NSString stringWithUTF8String:cyon];
1235 } CYObjectiveCatch }
1237 - (NSUInteger) count { CYObjectiveTry {
1238 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1239 size_t size(JSPropertyNameArrayGetCount(names));
1240 JSPropertyNameArrayRelease(names);
1242 } CYObjectiveCatch }
1244 - (id) objectForKey:(id)key { CYObjectiveTry {
1245 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1246 if (JSValueIsUndefined(context_, value))
1248 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1249 } CYObjectiveCatch }
1251 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1252 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1253 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1254 JSPropertyNameArrayRelease(names);
1256 } CYObjectiveCatch }
1258 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1259 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1260 } CYObjectiveCatch }
1262 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1263 JSValueRef exception(NULL);
1264 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1265 CYThrow(context_, exception);
1266 } CYObjectiveCatch }
1270 @implementation CYJSArray
1272 - (NSString *) cy$toCYON:(bool)objective {
1274 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1277 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1278 if ((self = [super init]) != nil) {
1280 context_ = CYGetJSContext(context);
1281 JSGlobalContextRetain(context_);
1282 JSValueProtect(context_, object_);
1284 } CYObjectiveCatch }
1286 - (void) dealloc { CYObjectiveTry {
1287 JSValueUnprotect(context_, object_);
1288 JSGlobalContextRelease(context_);
1290 } CYObjectiveCatch }
1292 - (NSUInteger) count { CYObjectiveTry {
1293 return CYArrayLength(context_, object_);
1294 } CYObjectiveCatch }
1296 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1297 size_t bounds([self count]);
1298 if (index >= bounds)
1299 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1300 JSValueRef exception(NULL);
1301 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1302 CYThrow(context_, exception);
1303 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1304 } CYObjectiveCatch }
1306 - (void) addObject:(id)object { CYObjectiveTry {
1307 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1308 } CYObjectiveCatch }
1310 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1311 size_t bounds([self count] + 1);
1312 if (index >= bounds)
1313 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1314 JSValueRef exception(NULL);
1315 JSValueRef arguments[3];
1316 arguments[0] = CYCastJSValue(context_, index);
1317 arguments[1] = CYCastJSValue(context_, 0);
1318 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1319 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1320 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1321 CYThrow(context_, exception);
1322 } CYObjectiveCatch }
1324 - (void) removeLastObject { CYObjectiveTry {
1325 JSValueRef exception(NULL);
1326 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1327 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1328 CYThrow(context_, exception);
1329 } CYObjectiveCatch }
1331 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1332 size_t bounds([self count]);
1333 if (index >= bounds)
1334 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1335 JSValueRef exception(NULL);
1336 JSValueRef arguments[2];
1337 arguments[0] = CYCastJSValue(context_, index);
1338 arguments[1] = CYCastJSValue(context_, 1);
1339 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1340 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1341 CYThrow(context_, exception);
1342 } CYObjectiveCatch }
1344 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1345 size_t bounds([self count]);
1346 if (index >= bounds)
1347 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1348 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1349 } CYObjectiveCatch }
1353 // XXX: inherit from or replace with CYJSObject
1354 @interface CYInternal : NSObject {
1355 JSGlobalContextRef context_;
1356 JSObjectRef object_;
1361 @implementation CYInternal
1364 JSValueUnprotect(context_, object_);
1365 JSGlobalContextRelease(context_);
1369 - (id) initInContext:(JSContextRef)context {
1370 if ((self = [super init]) != nil) {
1371 context_ = CYGetJSContext(context);
1372 JSGlobalContextRetain(context_);
1376 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1377 if (object_ == NULL)
1380 return JSObjectHasProperty(context, object_, name);
1383 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1384 if (object_ == NULL)
1387 return CYGetProperty(context, object_, name);
1390 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1391 @synchronized (self) {
1392 if (object_ == NULL) {
1393 object_ = JSObjectMake(context, NULL, NULL);
1394 JSValueProtect(context, object_);
1398 CYSetProperty(context, object_, name, value);
1401 + (CYInternal *) get:(id)object {
1402 if ($objc_getAssociatedObject == NULL)
1405 @synchronized (object) {
1406 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1413 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1414 if ($objc_getAssociatedObject == NULL)
1417 @synchronized (object) {
1418 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1421 if ($objc_setAssociatedObject == NULL)
1424 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1425 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1434 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1435 Selector_privateData *internal(new Selector_privateData(sel));
1436 return JSObjectMake(context, Selector_, internal);
1439 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1440 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1441 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1442 return reinterpret_cast<SEL>(internal->value_);
1444 return CYCastPointer<SEL>(context, value);
1447 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1448 return (void *) [[NSAutoreleasePool alloc] init];
1449 } CYSadCatch(NULL) }
1451 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1452 return [(NSAutoreleasePool *) handle release];
1455 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1457 return Instance::Make(context, nil);
1458 if (Class _class = objc_getClass(name.data))
1459 return CYMakeInstance(context, _class, true);
1460 if (Protocol *protocol = objc_getProtocol(name.data))
1461 return CYMakeInstance(context, protocol, true);
1463 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1465 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1466 ffi_call(cif, function, value, values);
1469 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1470 switch (type->primitive) {
1471 // XXX: do something epic about blocks
1474 case sig::typename_P:
1475 // XXX: this works for return values, but not for properties and fields
1476 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1479 case sig::selector_P:
1480 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1488 } CYSadCatch(false) }
1490 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1491 switch (type->primitive) {
1492 // XXX: do something epic about blocks
1495 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1496 JSValueRef value(CYCastJSValue(context, object));
1502 case sig::typename_P:
1503 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1505 case sig::selector_P:
1506 if (SEL sel = *reinterpret_cast<SEL *>(data))
1507 return CYMakeSelector(context, sel);
1511 return CYJSNull(context);
1515 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1517 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1518 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1521 #if OBJC_API_VERSION >= 2
1523 method_getReturnType(method, type, sizeof(type));
1525 const char *type(method_getTypeEncoding(method));
1531 // XXX: possibly use a more "awesome" check?
1535 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1537 return method_getTypeEncoding(method);
1539 const char *name(sel_getName(sel));
1540 size_t length(strlen(name));
1542 char keyed[length + 2];
1544 keyed[length + 1] = '\0';
1545 memcpy(keyed + 1, name, length);
1547 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1548 return entry->value_;
1553 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1554 JSObjectRef _this(CYCastJSObject(context, values[0]));
1555 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1558 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1559 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1562 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1563 Message_privateData *internal(new Message_privateData(sel, type, imp));
1564 return JSObjectMake(context, Message_, internal);
1567 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1568 JSObjectRef function(CYCastJSObject(context, value));
1569 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1570 // XXX: see notes in Library.cpp about needing to leak
1571 return reinterpret_cast<IMP>(internal->GetValue());
1574 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1575 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1576 Class _class(internal->GetValue());
1579 const char *name(CYPoolCString(pool, context, property));
1581 if (SEL sel = sel_getUid(name))
1582 if (class_getInstanceMethod(_class, sel) != NULL)
1588 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1589 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1590 Class _class(internal->GetValue());
1593 const char *name(CYPoolCString(pool, context, property));
1595 if (SEL sel = sel_getUid(name))
1596 if (objc_method *method = class_getInstanceMethod(_class, sel))
1597 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1602 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1603 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1604 Class _class(internal->GetValue());
1607 const char *name(CYPoolCString(pool, context, property));
1609 SEL sel(sel_registerName(name));
1611 objc_method *method(class_getInstanceMethod(_class, sel));
1616 if (JSValueIsObjectOfClass(context, value, Message_)) {
1617 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1618 type = sig::Unparse(pool, &message->signature_);
1619 imp = reinterpret_cast<IMP>(message->GetValue());
1621 type = CYPoolTypeEncoding(pool, context, sel, method);
1622 imp = CYMakeMessage(context, value, type);
1626 method_setImplementation(method, imp);
1629 GSMethodList list(GSAllocMethodList(1));
1630 GSAppendMethodToList(list, sel, type, imp, YES);
1631 GSAddMethodList(_class, list, YES);
1632 GSFlushMethodCacheForClass(_class);
1634 class_addMethod(_class, sel, imp, type);
1641 #if 0 && OBJC_API_VERSION < 2
1642 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1643 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1644 Class _class(internal->GetValue());
1647 const char *name(CYPoolCString(pool, context, property));
1649 if (SEL sel = sel_getUid(name))
1650 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1651 objc_method_list list = {NULL, 1, {method}};
1652 class_removeMethods(_class, &list);
1660 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1661 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1662 Class _class(internal->GetValue());
1664 #if OBJC_API_VERSION >= 2
1666 objc_method **data(class_copyMethodList(_class, &size));
1667 for (size_t i(0); i != size; ++i)
1668 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1671 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1672 for (int i(0); i != methods->method_count; ++i)
1673 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1677 static bool CYHasImplicitProperties(Class _class) {
1678 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1679 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1681 return [_class cy$hasImplicitProperties];
1684 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1685 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1686 id self(internal->GetValue());
1688 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1692 NSString *name(CYCastNSString(&pool, context, property));
1694 if (CYInternal *internal = [CYInternal get:self])
1695 if ([internal hasProperty:property inContext:context])
1698 Class _class(object_getClass(self));
1701 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1702 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1703 if ([self cy$hasProperty:name])
1705 } CYPoolCatch(false)
1707 const char *string(CYPoolCString(pool, context, name));
1710 if (class_getProperty(_class, string) != NULL)
1714 if (CYHasImplicitProperties(_class))
1715 if (SEL sel = sel_getUid(string))
1716 if (CYImplements(self, _class, sel, true))
1722 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1723 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1724 id self(internal->GetValue());
1726 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1727 return Internal::Make(context, self, object);
1730 NSString *name(CYCastNSString(&pool, context, property));
1732 if (CYInternal *internal = [CYInternal get:self])
1733 if (JSValueRef value = [internal getProperty:property inContext:context])
1737 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1741 const char *string(CYPoolCString(pool, context, name));
1742 Class _class(object_getClass(self));
1745 if (objc_property_t property = class_getProperty(_class, string)) {
1746 PropertyAttributes attributes(property);
1747 SEL sel(sel_registerName(attributes.Getter()));
1748 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1752 if (CYHasImplicitProperties(_class))
1753 if (SEL sel = sel_getUid(string))
1754 if (CYImplements(self, _class, sel, true))
1755 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1760 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1761 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1762 id self(internal->GetValue());
1766 NSString *name(CYCastNSString(&pool, context, property));
1767 NSObject *data(CYCastNSObject(&pool, context, value));
1770 if ([self cy$setProperty:name to:data])
1772 } CYPoolCatch(false)
1774 const char *string(CYPoolCString(pool, context, name));
1775 Class _class(object_getClass(self));
1778 if (objc_property_t property = class_getProperty(_class, string)) {
1779 PropertyAttributes attributes(property);
1780 if (const char *setter = attributes.Setter()) {
1781 SEL sel(sel_registerName(setter));
1782 JSValueRef arguments[1] = {value};
1783 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1789 size_t length(strlen(string));
1791 char set[length + 5];
1797 if (string[0] != '\0') {
1798 set[3] = toupper(string[0]);
1799 memcpy(set + 4, string + 1, length - 1);
1802 set[length + 3] = ':';
1803 set[length + 4] = '\0';
1805 if (SEL sel = sel_getUid(set))
1806 if (CYImplements(self, _class, sel)) {
1807 JSValueRef arguments[1] = {value};
1808 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1812 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1813 [internal setProperty:property toValue:value inContext:context];
1820 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1821 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1822 id self(internal->GetValue());
1825 NSString *name(CYCastNSString(NULL, context, property));
1826 return [self cy$deleteProperty:name];
1827 } CYPoolCatch(false)
1828 } CYCatch(false) return /*XXX*/ false; }
1830 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1831 const char *name(sel_getName(method_getName(method)));
1832 if (strchr(name, ':') != NULL)
1835 const char *type(method_getTypeEncoding(method));
1836 if (type == NULL || *type == '\0' || *type == 'v')
1839 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1842 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1843 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1844 id self(internal->GetValue());
1847 Class _class(object_getClass(self));
1852 objc_property_t *data(class_copyPropertyList(_class, &size));
1853 for (size_t i(0); i != size; ++i)
1854 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1859 if (CYHasImplicitProperties(_class))
1860 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1861 #if OBJC_API_VERSION >= 2
1863 objc_method **data(class_copyMethodList(current, &size));
1864 for (size_t i(0); i != size; ++i)
1865 Instance_getPropertyNames_message(names, data[i]);
1868 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1869 for (int i(0); i != methods->method_count; ++i)
1870 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1875 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1876 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1877 [self cy$getPropertyNames:names inContext:context];
1881 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1882 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1883 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1887 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1888 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1889 id self(internal->GetValue());
1891 if (![self isKindOfClass:NSBlock_])
1892 CYThrow("non-NSBlock object is not a function");
1893 // XXX: replace above logic with the following assertion
1894 //_assert([self isKindOfClass:NSBlock_]);
1895 // to do this, make it so FunctionInstance_ is the class of blocks
1896 // to do /that/, generalize the various "is exactly Instance_" checks
1897 // then, move Instance_callAsFunction to only be on FunctionInstance
1899 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1901 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1902 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1903 descriptor += sizeof(BlockDescriptor1);
1904 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1905 descriptor += sizeof(BlockDescriptor2);
1906 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1908 if (const char *type = descriptor3->signature) {
1914 sig::Signature signature;
1915 sig::Parse(pool, &signature, type, &Structor_);
1918 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1920 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1921 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1926 CYThrow("NSBlock without signature field passed arguments");
1930 } CYPoolCatch(NULL);
1935 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1936 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1937 Class _class(internal->GetValue());
1938 if (!CYIsClass(_class))
1941 if (CYJSValueIsNSObject(context, instance)) {
1942 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1943 // XXX: this isn't always safe
1944 return [linternal->GetValue() isKindOfClass:_class];
1950 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1952 throw CYJSError(context, "incorrect number of arguments to Instance");
1954 id value(CYCastNSObject(&pool, context, arguments[0]));
1956 value = [NSNull null];
1957 return CYCastJSValue(context, [value cy$box]);
1960 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1961 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1964 id self(internal->GetValue());
1965 const char *name(CYPoolCString(pool, context, property));
1967 if (object_getInstanceVariable(self, name, NULL) != NULL)
1973 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1974 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1977 id self(internal->GetValue());
1978 const char *name(CYPoolCString(pool, context, property));
1980 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1981 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1982 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1983 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1989 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1990 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1993 id self(internal->GetValue());
1994 const char *name(CYPoolCString(pool, context, property));
1996 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1997 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1998 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2005 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2006 if (Class super = class_getSuperclass(_class))
2007 Internal_getPropertyNames_(super, names);
2009 #if OBJC_API_VERSION >= 2
2011 objc_ivar **data(class_copyIvarList(_class, &size));
2012 for (size_t i(0); i != size; ++i)
2013 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2016 if (objc_ivar_list *ivars = _class->ivars)
2017 for (int i(0); i != ivars->ivar_count; ++i)
2018 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2022 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2023 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2026 id self(internal->GetValue());
2027 Class _class(object_getClass(self));
2029 Internal_getPropertyNames_(_class, names);
2032 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2033 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2034 return internal->GetOwner();
2037 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2039 NSString *name(CYCastNSString(&pool, context, property));
2040 if (Class _class = NSClassFromString(name))
2041 return CYMakeInstance(context, _class, true);
2045 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2047 size_t size(objc_getClassList(NULL, 0));
2048 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2051 size_t writ(objc_getClassList(data, size));
2054 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2060 for (size_t i(0); i != writ; ++i)
2061 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2067 while (Class _class = objc_next_class(&state))
2068 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2072 #if OBJC_API_VERSION >= 2
2073 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2074 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2077 const char *name(CYPoolCString(pool, context, property));
2079 const char **data(objc_copyClassNamesForImage(internal, &size));
2081 for (size_t i(0); i != size; ++i)
2082 if (strcmp(name, data[i]) == 0) {
2083 if (Class _class = objc_getClass(name)) {
2084 value = CYMakeInstance(context, _class, true);
2095 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2096 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2098 const char **data(objc_copyClassNamesForImage(internal, &size));
2099 for (size_t i(0); i != size; ++i)
2100 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2104 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2106 const char *name(CYPoolCString(pool, context, property));
2108 const char **data(objc_copyImageNames(&size));
2109 for (size_t i(0); i != size; ++i)
2110 if (strcmp(name, data[i]) == 0) {
2119 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2120 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2124 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2126 const char **data(objc_copyImageNames(&size));
2127 for (size_t i(0); i != size; ++i)
2128 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2133 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2135 const char *name(CYPoolCString(pool, context, property));
2136 if (Protocol *protocol = objc_getProtocol(name))
2137 return CYMakeInstance(context, protocol, true);
2141 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2142 #if OBJC_API_VERSION >= 2
2144 Protocol **data(objc_copyProtocolList(&size));
2145 for (size_t i(0); i != size; ++i)
2146 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2153 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2155 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2157 return Instance::Make(context, nil);
2161 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2162 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2166 #if defined(__i386__) || defined(__x86_64__)
2167 #define OBJC_MAX_STRUCT_BY_VALUE 8
2168 static int struct_forward_array[] = {
2169 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2170 #elif defined(__arm__)
2171 #define OBJC_MAX_STRUCT_BY_VALUE 1
2172 static int struct_forward_array[] = {
2175 #error missing objc-runtime-info
2178 static bool stret(ffi_type *ffi_type) {
2179 return ffi_type->type == FFI_TYPE_STRUCT && (
2180 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2181 struct_forward_array[ffi_type->size] != 0
2186 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) { CYTry {
2190 _class = object_getClass(self);
2194 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2195 imp = method_getImplementation(method);
2196 type = method_getTypeEncoding(method);
2201 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2203 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2204 type = CYPoolCString(pool, context, [method _typeString]);
2212 sig::Signature signature;
2213 sig::Parse(pool, &signature, type, &Structor_);
2215 size_t used(count + 3);
2216 if (used > signature.count) {
2217 sig::Element *elements(new (pool) sig::Element[used]);
2218 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2220 for (size_t index(signature.count); index != used; ++index) {
2221 sig::Element *element(&elements[index]);
2222 element->name = NULL;
2223 element->offset = _not(size_t);
2225 sig::Type *type(new (pool) sig::Type);
2226 memset(type, 0, sizeof(*type));
2227 type->primitive = sig::object_P;
2228 element->type = type;
2231 signature.elements = elements;
2232 signature.count = used;
2236 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2240 if (stret(cif.rtype))
2241 imp = class_getMethodImplementation_stret(_class, _cmd);
2243 imp = class_getMethodImplementation(_class, _cmd);
2245 objc_super super = {self, _class};
2246 imp = objc_msg_lookup_super(&super, _cmd);
2250 void (*function)() = reinterpret_cast<void (*)()>(imp);
2251 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2254 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2256 throw CYJSError(context, "too few arguments to objc_msgSend");
2266 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2267 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2268 self = internal->GetValue();
2269 _class = internal->class_;;
2270 uninitialized = false;
2271 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2272 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2273 self = internal->GetValue();
2275 uninitialized = internal->IsUninitialized();
2277 internal->value_ = nil;
2279 self = CYCastNSObject(&pool, context, arguments[0]);
2281 uninitialized = false;
2285 return CYJSNull(context);
2287 _cmd = CYCastSEL(context, arguments[1]);
2289 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2292 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2293 JSValueRef setup[count + 2];
2296 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2297 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2300 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2302 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2304 // XXX: handle Instance::Uninitialized?
2305 id self(CYCastNSObject(&pool, context, _this));
2309 setup[1] = &internal->sel_;
2311 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2314 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2316 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2318 id self(CYCastNSObject(&pool, context, arguments[0]));
2319 Class _class(CYCastClass(pool, context, arguments[1]));
2320 return cy::Super::Make(context, self, _class);
2323 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2325 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2327 const char *name(CYPoolCString(pool, context, arguments[0]));
2328 return CYMakeSelector(context, sel_registerName(name));
2331 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2333 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2334 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2335 return CYMakeInstance(context, self, false);
2338 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2339 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2340 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2343 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2344 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2345 Type_privateData *typical(internal->GetType());
2350 if (typical == NULL) {
2354 type = typical->type_;
2355 ffi = typical->ffi_;
2358 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2361 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2362 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2363 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2366 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2367 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2368 id self(internal->GetValue());
2369 if (!CYIsClass(self))
2370 return CYJSUndefined(context);
2371 return CYGetClassPrototype(context, self);
2374 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2375 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2376 id self(internal->GetValue());
2377 if (!CYIsClass(self))
2378 return CYJSUndefined(context);
2379 return Messages::Make(context, (Class) self);
2382 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2383 if (!CYJSValueIsNSObject(context, _this))
2386 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2387 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2390 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2391 if (!CYJSValueIsNSObject(context, _this))
2394 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2395 id value(internal->GetValue());
2402 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2404 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2405 return CYJSUndefined(context);
2406 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2409 return CYCastJSValue(context, CYJSString(context, [value description]));
2411 } CYCatch(NULL) return /*XXX*/ NULL; }
2413 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2414 if (!CYJSValueIsNSObject(context, _this))
2417 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2418 id value(internal->GetValue());
2420 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2423 if (JSValueRef result = [value cy$valueOfInContext:context])
2427 } CYCatch(NULL) return /*XXX*/ NULL; }
2429 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2430 if (!CYJSValueIsNSObject(context, _this))
2433 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2434 // XXX: but... but... THIS ISN'T A POINTER! :(
2435 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2436 } CYCatch(NULL) return /*XXX*/ NULL; }
2438 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2439 if (!CYJSValueIsNSObject(context, _this))
2442 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2443 id value(internal->GetValue());
2446 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2447 return CYCastJSValue(context, CYJSString(context, [value description]));
2449 } CYCatch(NULL) return /*XXX*/ NULL; }
2451 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2452 if (!CYJSValueIsNSObject(context, _this))
2455 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2456 id value(internal->GetValue());
2458 if (!CYIsClass(value))
2459 CYThrow("non-Class object cannot be used as Type");
2461 // XXX: this is a very silly implementation
2463 std::ostringstream type;
2465 type << class_getName(value);
2469 return CYMakeType(context, type.str().c_str());
2471 } CYCatch(NULL) return /*XXX*/ NULL; }
2473 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2474 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2475 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2478 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2479 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2482 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2483 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2484 const char *name(sel_getName(internal->GetValue()));
2487 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2488 return CYCastJSValue(context, CYJSString(context, string));
2490 } CYCatch(NULL) return /*XXX*/ NULL; }
2492 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2494 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2497 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2498 SEL sel(internal->GetValue());
2500 objc_method *method;
2501 if (Class _class = CYCastClass(pool, context, arguments[0]))
2502 method = class_getInstanceMethod(_class, sel);
2506 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2507 return CYCastJSValue(context, CYJSString(type));
2509 return CYJSNull(context);
2512 static JSStaticValue Selector_staticValues[2] = {
2513 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2514 {NULL, NULL, NULL, 0}
2517 static JSStaticValue Instance_staticValues[5] = {
2518 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2519 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2520 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2521 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2522 {NULL, NULL, NULL, 0}
2525 static JSStaticFunction Instance_staticFunctions[7] = {
2526 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2527 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2528 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2529 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2530 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2531 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2535 static JSStaticFunction Class_staticFunctions[2] = {
2536 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2540 static JSStaticFunction Internal_staticFunctions[2] = {
2541 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2545 static JSStaticFunction Selector_staticFunctions[5] = {
2546 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2547 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2548 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2549 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2554 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_(context) {
2555 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2556 } CYObjectiveCatch }
2559 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2560 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2561 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2562 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2564 CYPool &pool(CYGetGlobalPool());
2566 Object_type = new(pool) Type_privateData("@");
2567 Selector_type = new(pool) Type_privateData(":");
2570 // XXX: apparently, iOS now has both of these
2571 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2572 if (NSCFBoolean_ == nil)
2573 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2575 NSCFType_ = objc_getClass("NSCFType");
2576 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2577 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2578 NSZombie_ = objc_getClass("_NSZombie_");
2580 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2583 NSArray_ = objc_getClass("NSArray");
2584 NSBlock_ = objc_getClass("NSBlock");
2585 NSDictionary_ = objc_getClass("NSDictionary");
2586 NSString_ = objc_getClass("NSString");
2587 Object_ = objc_getClass("Object");
2589 JSClassDefinition definition;
2591 definition = kJSClassDefinitionEmpty;
2592 definition.className = "Instance";
2593 definition.staticValues = Instance_staticValues;
2594 definition.staticFunctions = Instance_staticFunctions;
2595 definition.hasProperty = &Instance_hasProperty;
2596 definition.getProperty = &Instance_getProperty;
2597 definition.setProperty = &Instance_setProperty;
2598 definition.deleteProperty = &Instance_deleteProperty;
2599 definition.getPropertyNames = &Instance_getPropertyNames;
2600 definition.callAsConstructor = &Instance_callAsConstructor;
2601 definition.callAsFunction = &Instance_callAsFunction;
2602 definition.hasInstance = &Instance_hasInstance;
2603 definition.finalize = &CYFinalize;
2604 Instance_ = JSClassCreate(&definition);
2606 definition.className = "ArrayInstance";
2607 ArrayInstance_ = JSClassCreate(&definition);
2609 definition.className = "FunctionInstance";
2610 FunctionInstance_ = JSClassCreate(&definition);
2612 definition.className = "ObjectInstance";
2613 ObjectInstance_ = JSClassCreate(&definition);
2615 definition.className = "StringInstance";
2616 StringInstance_ = JSClassCreate(&definition);
2618 definition = kJSClassDefinitionEmpty;
2619 definition.className = "Class";
2620 definition.staticFunctions = Class_staticFunctions;
2621 Class_ = JSClassCreate(&definition);
2623 definition = kJSClassDefinitionEmpty;
2624 definition.className = "Internal";
2625 definition.staticFunctions = Internal_staticFunctions;
2626 definition.hasProperty = &Internal_hasProperty;
2627 definition.getProperty = &Internal_getProperty;
2628 definition.setProperty = &Internal_setProperty;
2629 definition.getPropertyNames = &Internal_getPropertyNames;
2630 definition.finalize = &CYFinalize;
2631 Internal_ = JSClassCreate(&definition);
2633 definition = kJSClassDefinitionEmpty;
2634 definition.className = "Message";
2635 definition.staticFunctions = cy::Functor::StaticFunctions;
2636 definition.callAsFunction = &Message_callAsFunction;
2637 definition.finalize = &CYFinalize;
2638 Message_ = JSClassCreate(&definition);
2640 definition = kJSClassDefinitionEmpty;
2641 definition.className = "Messages";
2642 definition.hasProperty = &Messages_hasProperty;
2643 definition.getProperty = &Messages_getProperty;
2644 definition.setProperty = &Messages_setProperty;
2645 #if 0 && OBJC_API_VERSION < 2
2646 definition.deleteProperty = &Messages_deleteProperty;
2648 definition.getPropertyNames = &Messages_getPropertyNames;
2649 definition.finalize = &CYFinalize;
2650 Messages_ = JSClassCreate(&definition);
2652 definition = kJSClassDefinitionEmpty;
2653 definition.className = "Selector";
2654 definition.staticValues = Selector_staticValues;
2655 definition.staticFunctions = Selector_staticFunctions;
2656 definition.callAsFunction = &Selector_callAsFunction;
2657 definition.finalize = &CYFinalize;
2658 Selector_ = JSClassCreate(&definition);
2660 definition = kJSClassDefinitionEmpty;
2661 definition.className = "Super";
2662 definition.staticFunctions = Internal_staticFunctions;
2663 definition.finalize = &CYFinalize;
2664 Super_ = JSClassCreate(&definition);
2666 definition = kJSClassDefinitionEmpty;
2667 definition.className = "ObjectiveC::Classes";
2668 definition.getProperty = &ObjectiveC_Classes_getProperty;
2669 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2670 ObjectiveC_Classes_ = JSClassCreate(&definition);
2672 definition = kJSClassDefinitionEmpty;
2673 definition.className = "ObjectiveC::Constants";
2674 definition.getProperty = &ObjectiveC_Constants_getProperty;
2675 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2676 ObjectiveC_Constants_ = JSClassCreate(&definition);
2678 #if OBJC_API_VERSION >= 2
2679 definition = kJSClassDefinitionEmpty;
2680 definition.className = "ObjectiveC::Images";
2681 definition.getProperty = &ObjectiveC_Images_getProperty;
2682 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2683 ObjectiveC_Images_ = JSClassCreate(&definition);
2685 definition = kJSClassDefinitionEmpty;
2686 definition.className = "ObjectiveC::Image::Classes";
2687 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2688 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2689 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2692 definition = kJSClassDefinitionEmpty;
2693 definition.className = "ObjectiveC::Protocols";
2694 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2695 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2696 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2699 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2703 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2704 JSObjectRef global(CYGetGlobalObject(context));
2705 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2706 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2707 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2708 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2710 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2711 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2713 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2714 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2715 CYArrayPush(context, alls, protocols);
2717 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2718 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2719 CYArrayPush(context, alls, classes);
2721 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2722 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2723 CYArrayPush(context, alls, constants);
2725 #if OBJC_API_VERSION >= 2
2726 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2729 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2730 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2731 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2732 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2733 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2735 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2736 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2738 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2739 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2740 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2741 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2742 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2744 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2745 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2746 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2747 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2748 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2750 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2751 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2752 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2753 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2754 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2756 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2757 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2758 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2759 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2760 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2762 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2763 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2764 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2766 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2767 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2768 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2770 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2771 CYSetProperty(context, Instance, CYJSString("box"), box);
2773 #if defined(__APPLE__) && defined(__arm__) && 0
2774 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2777 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2779 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2780 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2783 static CYHooks CYObjectiveCHooks = {
2784 &CYObjectiveC_ExecuteStart,
2785 &CYObjectiveC_ExecuteEnd,
2786 &CYObjectiveC_CallFunction,
2787 &CYObjectiveC_Initialize,
2788 &CYObjectiveC_SetupContext,
2789 &CYObjectiveC_PoolFFI,
2790 &CYObjectiveC_FromFFI,
2793 struct CYObjectiveC {
2795 hooks_ = &CYObjectiveCHooks;
2796 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2797 _assert(hooks_ != NULL);