3 #include "ObjectiveC/Internal.hpp"
6 #include <Foundation/Foundation.h>
10 #include "ObjectiveC/Internal.hpp"
13 #include <CoreFoundation/CoreFoundation.h>
14 #include <CoreFoundation/CFLogUtilities.h>
15 #include <JavaScriptCore/JSStringRefCF.h>
16 #include <WebKit/WebScriptObject.h>
20 #include "JavaScript.hpp"
25 #define CYObjectiveTry_(context) { \
26 JSContextRef context_(context); \
28 #define CYObjectiveTry { \
30 #define CYObjectiveCatch \
31 catch (const CYException &error) { \
32 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
38 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
40 #define CYPoolCatch(value) \
41 @catch (NSException *error) { \
42 _saved = [error retain]; \
43 throw CYJSError(context, CYCastJSValue(context, error)); \
48 [_saved autorelease]; \
53 #define class_getSuperclass GSObjCSuper
54 #define object_getClass GSObjCClass
57 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
59 extern sqlite3 *Bridge_;
61 /* Objective-C Pool Release {{{ */
62 apr_status_t CYPoolRelease_(void *data) {
63 id object(reinterpret_cast<id>(data));
68 id CYPoolRelease_(apr_pool_t *pool, id object) {
71 else if (pool == NULL)
72 return [object autorelease];
74 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
79 template <typename Type_>
80 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
81 return (Type_) CYPoolRelease_(pool, (id) object);
84 /* Objective-C Strings {{{ */
85 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
87 return [value UTF8String];
89 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
90 char *string(new(pool) char[size]);
91 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
92 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
97 JSStringRef CYCopyJSString_(NSString *value) {
99 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
102 return CYCopyJSString(CYPoolCString(pool, value));
106 JSStringRef CYCopyJSString(id value) {
109 // XXX: this definition scares me; is anyone using this?!
110 NSString *string([value description]);
111 return CYCopyJSString_(string);
114 NSString *CYCopyNSString(const CYUTF8String &value) {
116 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
118 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
122 NSString *CYCopyNSString(JSStringRef value) {
124 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
126 return CYCopyNSString(CYCastCString_(value));
130 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
131 return CYCopyNSString(CYJSString(context, value));
134 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
135 return CYPoolRelease(pool, CYCopyNSString(value));
138 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
139 const char *name(sel_getName(sel));
140 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
143 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
144 return CYPoolRelease(pool, CYCopyNSString(value));
147 CYUTF8String CYCastUTF8String(NSString *value) {
148 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
149 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
153 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
154 if (exception == NULL)
156 *exception = CYCastJSValue(context, error);
159 size_t CYGetIndex(NSString *value) {
160 return CYGetIndex(CYCastUTF8String(value));
163 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
164 return CYGetOffset(CYPoolCString(pool, context, value), index);
167 static JSClassRef Instance_;
168 static JSClassRef Internal_;
169 static JSClassRef Message_;
170 static JSClassRef Messages_;
171 static JSClassRef Selector_;
172 static JSClassRef Super_;
174 static JSClassRef ObjectiveC_Classes_;
175 static JSClassRef ObjectiveC_Image_Classes_;
176 static JSClassRef ObjectiveC_Images_;
177 static JSClassRef ObjectiveC_Protocols_;
179 static JSObjectRef Instance_prototype_;
182 static Class NSCFBoolean_;
183 static Class NSCFType_;
186 static Class NSArray_;
187 static Class NSDictionary_;
188 static Class NSMessageBuilder_;
189 static Class NSZombie_;
190 static Class Object_;
192 static Type_privateData *Object_type;
193 static Type_privateData *Selector_type;
195 Type_privateData *Instance::GetType() const {
199 Type_privateData *Selector_privateData::GetType() const {
200 return Selector_type;
203 // XXX: trick this out with associated objects!
204 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
206 return Instance_prototype_;
208 // XXX: I need to think through multi-context
209 typedef std::map<id, JSValueRef> CacheMap;
210 static CacheMap cache_;
212 JSValueRef &value(cache_[self]);
216 JSClassRef _class(NULL);
217 JSValueRef prototype;
219 if (self == NSArray_)
220 prototype = Array_prototype_;
221 else if (self == NSDictionary_)
222 prototype = Object_prototype_;
224 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
226 JSObjectRef object(JSObjectMake(context, _class, NULL));
227 JSObjectSetPrototype(context, object, prototype);
229 JSValueProtect(context, object);
234 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
235 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
236 if (_class == NSArray_)
238 if (Class super = class_getSuperclass(_class))
239 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
241 JSObjectSetPrototype(context, value, Array_prototype_);*/
245 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
246 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
250 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
251 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
255 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
256 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
257 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
261 Instance::~Instance() {
262 if ((flags_ & Transient) == 0)
263 // XXX: does this handle background threads correctly?
264 // XXX: this simply does not work on the console because I'm stupid
265 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
268 struct Message_privateData :
273 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
274 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
280 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
281 Instance::Flags flags;
284 flags = Instance::Transient;
286 flags = Instance::None;
287 object = [object retain];
290 return Instance::Make(context, object, flags);
293 @interface NSMethodSignature (Cycript)
294 - (NSString *) _typeString;
297 @interface NSObject (Cycript)
299 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
300 - (JSType) cy$JSType;
302 - (NSObject *) cy$toJSON:(NSString *)key;
303 - (NSString *) cy$toCYON;
304 - (NSString *) cy$toKey;
306 - (bool) cy$hasProperty:(NSString *)name;
307 - (NSObject *) cy$getProperty:(NSString *)name;
308 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
309 - (bool) cy$deleteProperty:(NSString *)name;
314 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
317 NSString *CYCastNSCYON(id value) {
323 Class _class(object_getClass(value));
324 SEL sel(@selector(cy$toCYON));
326 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
327 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
328 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
329 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
330 string = [value cy$toCYON];
333 if (value == NSZombie_)
334 string = @"_NSZombie_";
335 else if (_class == NSZombie_)
336 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
337 // XXX: frowny /in/ the pants
338 else if (value == NSMessageBuilder_ || value == Object_)
341 string = [NSString stringWithFormat:@"%@", value];
346 string = @"undefined";
353 struct PropertyAttributes {
358 const char *variable;
371 PropertyAttributes(objc_property_t property) :
383 name = property_getName(property);
384 const char *attributes(property_getAttributes(property));
386 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
388 case 'R': readonly = true; break;
389 case 'C': copy = true; break;
390 case '&': retain = true; break;
391 case 'N': nonatomic = true; break;
392 case 'G': getter_ = token + 1; break;
393 case 'S': setter_ = token + 1; break;
394 case 'V': variable = token + 1; break;
398 /*if (variable == NULL) {
399 variable = property_getName(property);
400 size_t size(strlen(variable));
401 char *name(new(pool_) char[size + 2]);
403 memcpy(name + 1, variable, size);
404 name[size + 1] = '\0';
409 const char *Getter() {
411 getter_ = apr_pstrdup(pool_, name);
415 const char *Setter() {
416 if (setter_ == NULL && !readonly) {
417 size_t length(strlen(name));
419 char *temp(new(pool_) char[length + 5]);
425 temp[3] = toupper(name[0]);
426 memcpy(temp + 4, name + 1, length - 1);
429 temp[length + 3] = ':';
430 temp[length + 4] = '\0';
441 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
442 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
447 @interface CYWebUndefined : NSObject {
450 + (CYWebUndefined *) undefined;
454 @implementation CYWebUndefined
456 + (CYWebUndefined *) undefined {
457 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
463 #define WebUndefined CYWebUndefined
466 /* Bridge: CYJSObject {{{ */
467 @interface CYJSObject : NSMutableDictionary {
469 JSContextRef context_;
472 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
474 - (NSObject *) cy$toJSON:(NSString *)key;
476 - (NSUInteger) count;
477 - (id) objectForKey:(id)key;
478 - (NSEnumerator *) keyEnumerator;
479 - (void) setObject:(id)object forKey:(id)key;
480 - (void) removeObjectForKey:(id)key;
484 /* Bridge: CYJSArray {{{ */
485 @interface CYJSArray : NSMutableArray {
487 JSContextRef context_;
490 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
492 - (NSUInteger) count;
493 - (id) objectAtIndex:(NSUInteger)index;
495 - (void) addObject:(id)anObject;
496 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
497 - (void) removeLastObject;
498 - (void) removeObjectAtIndex:(NSUInteger)index;
499 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
504 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
505 JSValueRef exception(NULL);
506 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
507 CYThrow(context, exception);
508 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
509 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
512 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
513 if (!JSValueIsObjectOfClass(context, object, Instance_))
514 return CYCastNSObject_(pool, context, object);
516 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
517 return internal->GetValue();
521 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
522 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
525 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
529 switch (JSType type = JSValueGetType(context, value)) {
530 case kJSTypeUndefined:
531 object = [WebUndefined undefined];
541 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
544 object = [[NSNumber alloc] initWithBool:CYCastBool(context, value)];
550 object = CYCopyNSNumber(context, value);
555 object = CYCopyNSString(context, value);
560 // XXX: this might could be more efficient
561 object = CYCastNSObject(pool, context, (JSObjectRef) value);
566 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
573 return CYPoolRelease(pool, object);
575 return [object retain];
578 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
579 return CYNSObject(pool, context, value, true);
582 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
583 return CYNSObject(pool, context, value, false);
586 /* Bridge: NSArray {{{ */
587 @implementation NSArray (Cycript)
589 - (NSString *) cy$toCYON {
590 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
591 [json appendString:@"["];
595 for (id object in self) {
597 for (size_t index(0), count([self count]); index != count; ++index) {
598 id object([self objectAtIndex:index]);
601 [json appendString:@","];
604 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
605 [json appendString:CYCastNSCYON(object)];
607 [json appendString:@","];
612 [json appendString:@"]"];
616 - (bool) cy$hasProperty:(NSString *)name {
617 if ([name isEqualToString:@"length"])
620 size_t index(CYGetIndex(name));
621 if (index == _not(size_t) || index >= [self count])
622 return [super cy$hasProperty:name];
627 - (NSObject *) cy$getProperty:(NSString *)name {
628 if ([name isEqualToString:@"length"]) {
629 NSUInteger count([self count]);
631 return [NSNumber numberWithUnsignedInteger:count];
633 return [NSNumber numberWithUnsignedInt:count];
637 size_t index(CYGetIndex(name));
638 if (index == _not(size_t) || index >= [self count])
639 return [super cy$getProperty:name];
641 return [self objectAtIndex:index];
646 /* Bridge: NSDictionary {{{ */
647 @implementation NSDictionary (Cycript)
649 - (NSString *) cy$toCYON {
650 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
651 [json appendString:@"{"];
655 for (id key in self) {
657 NSEnumerator *keys([self keyEnumerator]);
658 while (id key = [keys nextObject]) {
661 [json appendString:@","];
664 [json appendString:[key cy$toKey]];
665 [json appendString:@":"];
666 NSObject *object([self objectForKey:key]);
667 [json appendString:CYCastNSCYON(object)];
670 [json appendString:@"}"];
674 - (bool) cy$hasProperty:(NSString *)name {
675 return [self objectForKey:name] != nil;
678 - (NSObject *) cy$getProperty:(NSString *)name {
679 return [self objectForKey:name];
684 /* Bridge: NSMutableArray {{{ */
685 @implementation NSMutableArray (Cycript)
687 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
688 if ([name isEqualToString:@"length"]) {
689 // XXX: is this not intelligent?
690 NSNumber *number(reinterpret_cast<NSNumber *>(value));
692 NSUInteger size([number unsignedIntegerValue]);
694 NSUInteger size([number unsignedIntValue]);
696 NSUInteger count([self count]);
698 [self removeObjectsInRange:NSMakeRange(size, count - size)];
699 else if (size != count) {
700 WebUndefined *undefined([WebUndefined undefined]);
701 for (size_t i(count); i != size; ++i)
702 [self addObject:undefined];
707 size_t index(CYGetIndex(name));
708 if (index == _not(size_t))
709 return [super cy$setProperty:name to:value];
711 id object(value ?: [NSNull null]);
713 size_t count([self count]);
715 [self replaceObjectAtIndex:index withObject:object];
717 if (index != count) {
718 WebUndefined *undefined([WebUndefined undefined]);
719 for (size_t i(count); i != index; ++i)
720 [self addObject:undefined];
723 [self addObject:object];
729 - (bool) cy$deleteProperty:(NSString *)name {
730 size_t index(CYGetIndex(name));
731 if (index == _not(size_t) || index >= [self count])
732 return [super cy$deleteProperty:name];
733 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
739 /* Bridge: NSMutableDictionary {{{ */
740 @implementation NSMutableDictionary (Cycript)
742 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
743 [self setObject:(value ?: [NSNull null]) forKey:name];
747 - (bool) cy$deleteProperty:(NSString *)name {
748 if ([self objectForKey:name] == nil)
751 [self removeObjectForKey:name];
758 /* Bridge: NSNumber {{{ */
759 @implementation NSNumber (Cycript)
761 - (JSType) cy$JSType {
763 // XXX: this just seems stupid
764 if ([self class] == NSCFBoolean_)
765 return kJSTypeBoolean;
767 return kJSTypeNumber;
770 - (NSObject *) cy$toJSON:(NSString *)key {
774 - (NSString *) cy$toCYON {
775 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
778 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
779 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
784 /* Bridge: NSNull {{{ */
785 @implementation NSNull (Cycript)
787 - (JSType) cy$JSType {
791 - (NSObject *) cy$toJSON:(NSString *)key {
795 - (NSString *) cy$toCYON {
801 /* Bridge: NSObject {{{ */
802 @implementation NSObject (Cycript)
804 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
805 return CYMakeInstance(context, self, false);
808 - (JSType) cy$JSType {
809 return kJSTypeObject;
812 - (NSObject *) cy$toJSON:(NSString *)key {
813 return [self description];
816 - (NSString *) cy$toCYON {
817 return [[self cy$toJSON:@""] cy$toCYON];
820 - (NSString *) cy$toKey {
821 return [self cy$toCYON];
824 - (bool) cy$hasProperty:(NSString *)name {
828 - (NSObject *) cy$getProperty:(NSString *)name {
832 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
836 - (bool) cy$deleteProperty:(NSString *)name {
842 /* Bridge: NSProxy {{{ */
843 @implementation NSProxy (Cycript)
845 - (NSObject *) cy$toJSON:(NSString *)key {
846 return [self description];
849 - (NSString *) cy$toCYON {
850 return [[self cy$toJSON:@""] cy$toCYON];
855 /* Bridge: NSString {{{ */
856 @implementation NSString (Cycript)
858 - (JSType) cy$JSType {
859 return kJSTypeString;
862 - (NSObject *) cy$toJSON:(NSString *)key {
866 - (NSString *) cy$toCYON {
867 std::ostringstream str;
868 CYUTF8String string(CYCastUTF8String(self));
869 CYStringify(str, string.data, string.size);
870 std::string value(str.str());
871 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
874 - (NSString *) cy$toKey {
875 if (CYIsKey(CYCastUTF8String(self)))
877 return [self cy$toCYON];
882 /* Bridge: WebUndefined {{{ */
883 @implementation WebUndefined (Cycript)
885 - (JSType) cy$JSType {
886 return kJSTypeUndefined;
889 - (NSObject *) cy$toJSON:(NSString *)key {
893 - (NSString *) cy$toCYON {
897 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
898 return CYJSUndefined(context);
904 static bool CYIsClass(id self) {
905 // XXX: this is a lame object_isClass
906 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
909 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
910 id self(CYCastNSObject(pool, context, value));
913 throw CYJSError(context, "got something that is not a Class");
917 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
919 size_t size(JSPropertyNameArrayGetCount(names));
920 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
921 for (size_t index(0); index != size; ++index)
922 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
926 JSValueRef CYCastJSValue(JSContextRef context, id value) { CYPoolTry {
928 return CYJSNull(context);
929 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
930 return [value cy$JSValueInContext:context];
932 return CYMakeInstance(context, value, false);
933 } CYPoolCatch(NULL) }
935 @implementation CYJSObject
937 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
938 if ((self = [super init]) != nil) {
941 JSValueProtect(context_, object_);
945 - (void) dealloc { CYObjectiveTry {
946 JSValueUnprotect(context_, object_);
950 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
951 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
952 if (!CYIsCallable(context_, toJSON))
953 return [super cy$toJSON:key];
955 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
956 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
957 // XXX: do I really want an NSNull here?!
958 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
962 - (NSString *) cy$toCYON { CYObjectiveTry {
964 JSValueRef exception(NULL);
965 const char *cyon(CYPoolCCYON(pool, context_, object_));
966 CYThrow(context_, exception);
968 return [super cy$toCYON];
970 return [NSString stringWithUTF8String:cyon];
973 - (NSUInteger) count { CYObjectiveTry {
974 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
975 size_t size(JSPropertyNameArrayGetCount(names));
976 JSPropertyNameArrayRelease(names);
980 - (id) objectForKey:(id)key { CYObjectiveTry {
981 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
982 if (JSValueIsUndefined(context_, value))
984 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
987 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
988 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
989 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
990 JSPropertyNameArrayRelease(names);
994 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
995 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
998 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
999 JSValueRef exception(NULL);
1000 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1001 CYThrow(context_, exception);
1002 } CYObjectiveCatch }
1006 @implementation CYJSArray
1008 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1009 if ((self = [super init]) != nil) {
1012 JSValueProtect(context_, object_);
1014 } CYObjectiveCatch }
1016 - (void) dealloc { CYObjectiveTry {
1017 JSValueUnprotect(context_, object_);
1019 } CYObjectiveCatch }
1021 - (NSUInteger) count { CYObjectiveTry {
1022 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1023 } CYObjectiveCatch }
1025 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1026 size_t bounds([self count]);
1027 if (index >= bounds)
1028 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1029 JSValueRef exception(NULL);
1030 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1031 CYThrow(context_, exception);
1032 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1033 } CYObjectiveCatch }
1035 - (void) addObject:(id)object { CYObjectiveTry {
1036 JSValueRef exception(NULL);
1037 JSValueRef arguments[1];
1038 arguments[0] = CYCastJSValue(context_, object);
1039 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1040 CYThrow(context_, exception);
1041 } CYObjectiveCatch }
1043 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1044 size_t bounds([self count] + 1);
1045 if (index >= bounds)
1046 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1047 JSValueRef exception(NULL);
1048 JSValueRef arguments[3];
1049 arguments[0] = CYCastJSValue(context_, index);
1050 arguments[1] = CYCastJSValue(context_, 0);
1051 arguments[2] = CYCastJSValue(context_, object);
1052 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1053 CYThrow(context_, exception);
1054 } CYObjectiveCatch }
1056 - (void) removeLastObject { CYObjectiveTry {
1057 JSValueRef exception(NULL);
1058 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1059 CYThrow(context_, exception);
1060 } CYObjectiveCatch }
1062 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1063 size_t bounds([self count]);
1064 if (index >= bounds)
1065 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1066 JSValueRef exception(NULL);
1067 JSValueRef arguments[2];
1068 arguments[0] = CYCastJSValue(context_, index);
1069 arguments[1] = CYCastJSValue(context_, 1);
1070 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1071 CYThrow(context_, exception);
1072 } CYObjectiveCatch }
1074 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1075 size_t bounds([self count]);
1076 if (index >= bounds)
1077 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1078 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1079 } CYObjectiveCatch }
1083 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1087 JSObjectRef object_;
1095 // XXX: delete object_? ;(
1098 static CYInternal *Get(id self) {
1099 CYInternal *internal(NULL);
1100 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1101 // XXX: do something epic? ;P
1107 static CYInternal *Set(id self) {
1108 CYInternal *internal(NULL);
1109 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1110 if (internal == NULL) {
1111 internal = new CYInternal();
1112 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1115 // XXX: do something epic? ;P
1121 bool HasProperty(JSContextRef context, JSStringRef name) {
1122 if (object_ == NULL)
1124 return JSObjectHasProperty(context, object_, name);
1127 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1128 if (object_ == NULL)
1130 return CYGetProperty(context, object_, name);
1133 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1134 if (object_ == NULL)
1135 object_ = JSObjectMake(context, NULL, NULL);
1136 CYSetProperty(context, object_, name, value);
1140 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1141 Selector_privateData *internal(new Selector_privateData(sel));
1142 return JSObjectMake(context, Selector_, internal);
1145 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1146 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1147 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1148 return reinterpret_cast<SEL>(internal->value_);
1150 return CYCastPointer<SEL>(context, value);
1153 void *CYObjectiveC_ExecuteStart() {
1154 return (void *) [[NSAutoreleasePool alloc] init];
1157 void CYObjectiveC_ExecuteEnd(void *handle) {
1158 return [(NSAutoreleasePool *) handle release];
1161 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) {
1163 return Instance::Make(context, nil);
1164 if (Class _class = objc_getClass(name.data))
1165 return CYMakeInstance(context, _class, true);
1169 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1170 switch (type->primitive) {
1172 case sig::typename_P:
1173 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1176 case sig::selector_P:
1177 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1187 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
1188 switch (type->primitive) {
1190 if (id object = *reinterpret_cast<id *>(data)) {
1191 JSValueRef value(CYCastJSValue(context, object));
1197 case sig::typename_P:
1198 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1200 case sig::selector_P:
1201 if (SEL sel = *reinterpret_cast<SEL *>(data))
1202 return CYMakeSelector(context, sel);
1206 return CYJSNull(context);
1212 CYHooks CYObjectiveCHooks = {
1213 &CYObjectiveC_ExecuteStart,
1214 &CYObjectiveC_ExecuteEnd,
1215 &CYObjectiveC_RuntimeProperty,
1216 &CYObjectiveC_PoolFFI,
1217 &CYObjectiveC_FromFFI,
1220 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1221 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1225 method_getReturnType(method, type, sizeof(type));
1230 // XXX: possibly use a more "awesome" check?
1234 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1236 return method_getTypeEncoding(method);
1238 const char *name(sel_getName(sel));
1240 sqlite3_stmt *statement;
1242 _sqlcall(sqlite3_prepare(Bridge_,
1244 "\"bridge\".\"value\" "
1247 " \"bridge\".\"mode\" = -1 and"
1248 " \"bridge\".\"name\" = ?"
1250 , -1, &statement, NULL));
1253 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
1256 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1261 value = sqlite3_column_pooled(pool, statement, 0);
1264 _sqlcall(sqlite3_finalize(statement));
1272 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1273 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1275 JSContextRef context(internal->context_);
1277 size_t count(internal->cif_.nargs);
1278 JSValueRef values[count];
1280 for (size_t index(0); index != count; ++index)
1281 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1283 JSObjectRef _this(CYCastJSObject(context, values[0]));
1285 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1286 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1289 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1290 Message_privateData *internal(new Message_privateData(sel, type, imp));
1291 return JSObjectMake(context, Message_, internal);
1294 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1295 JSObjectRef function(CYCastJSObject(context, value));
1296 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1297 return reinterpret_cast<IMP>(internal->GetValue());
1300 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1301 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1302 Class _class(internal->GetValue());
1305 const char *name(CYPoolCString(pool, context, property));
1307 if (SEL sel = sel_getUid(name))
1308 if (class_getInstanceMethod(_class, sel) != NULL)
1314 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1315 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1316 Class _class(internal->GetValue());
1319 const char *name(CYPoolCString(pool, context, property));
1321 if (SEL sel = sel_getUid(name))
1322 if (objc_method *method = class_getInstanceMethod(_class, sel))
1323 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1328 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1329 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1330 Class _class(internal->GetValue());
1333 const char *name(CYPoolCString(pool, context, property));
1335 SEL sel(sel_registerName(name));
1337 objc_method *method(class_getInstanceMethod(_class, sel));
1342 if (JSValueIsObjectOfClass(context, value, Message_)) {
1343 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1344 type = sig::Unparse(pool, &message->signature_);
1345 imp = reinterpret_cast<IMP>(message->GetValue());
1347 type = CYPoolTypeEncoding(pool, context, sel, method);
1348 imp = CYMakeMessage(context, value, type);
1352 method_setImplementation(method, imp);
1354 class_replaceMethod(_class, sel, imp, type);
1360 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1361 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1362 Class _class(internal->GetValue());
1365 const char *name(CYPoolCString(pool, property));
1367 if (SEL sel = sel_getUid(name))
1368 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1369 objc_method_list list = {NULL, 1, {method}};
1370 class_removeMethods(_class, &list);
1378 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1379 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1380 Class _class(internal->GetValue());
1383 objc_method **data(class_copyMethodList(_class, &size));
1384 for (size_t i(0); i != size; ++i)
1385 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1389 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1390 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1391 id self(internal->GetValue());
1393 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1397 NSString *name(CYCastNSString(pool, property));
1399 if (CYInternal *internal = CYInternal::Get(self))
1400 if (internal->HasProperty(context, property))
1403 Class _class(object_getClass(self));
1406 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1407 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1408 if ([self cy$hasProperty:name])
1410 } CYPoolCatch(false)
1412 const char *string(CYPoolCString(pool, context, name));
1414 if (class_getProperty(_class, string) != NULL)
1417 if (SEL sel = sel_getUid(string))
1418 if (CYImplements(self, _class, sel, true))
1424 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1425 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1426 id self(internal->GetValue());
1428 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1429 return Internal::Make(context, self, object);
1432 NSString *name(CYCastNSString(pool, property));
1434 if (CYInternal *internal = CYInternal::Get(self))
1435 if (JSValueRef value = internal->GetProperty(context, property))
1439 if (NSObject *data = [self cy$getProperty:name])
1440 return CYCastJSValue(context, data);
1443 const char *string(CYPoolCString(pool, context, name));
1444 Class _class(object_getClass(self));
1447 if (objc_property_t property = class_getProperty(_class, string)) {
1448 PropertyAttributes attributes(property);
1449 SEL sel(sel_registerName(attributes.Getter()));
1450 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1454 if (SEL sel = sel_getUid(string))
1455 if (CYImplements(self, _class, sel, true))
1456 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1461 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1462 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1463 id self(internal->GetValue());
1467 NSString *name(CYCastNSString(pool, property));
1468 NSObject *data(CYCastNSObject(pool, context, value));
1471 if ([self cy$setProperty:name to:data])
1475 const char *string(CYPoolCString(pool, context, name));
1476 Class _class(object_getClass(self));
1479 if (objc_property_t property = class_getProperty(_class, string)) {
1480 PropertyAttributes attributes(property);
1481 if (const char *setter = attributes.Setter()) {
1482 SEL sel(sel_registerName(setter));
1483 JSValueRef arguments[1] = {value};
1484 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1490 size_t length(strlen(string));
1492 char set[length + 5];
1498 if (string[0] != '\0') {
1499 set[3] = toupper(string[0]);
1500 memcpy(set + 4, string + 1, length - 1);
1503 set[length + 3] = ':';
1504 set[length + 4] = '\0';
1506 if (SEL sel = sel_getUid(set))
1507 if (CYImplements(self, _class, sel, false)) {
1508 JSValueRef arguments[1] = {value};
1509 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1512 if (CYInternal *internal = CYInternal::Set(self)) {
1513 internal->SetProperty(context, property, value);
1520 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1521 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1522 id self(internal->GetValue());
1525 NSString *name(CYCastNSString(NULL, property));
1526 return [self cy$deleteProperty:name];
1530 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1531 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1532 id self(internal->GetValue());
1535 Class _class(object_getClass(self));
1540 objc_property_t *data(class_copyPropertyList(_class, &size));
1541 for (size_t i(0); i != size; ++i)
1542 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1548 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1549 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1550 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1554 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1555 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1556 Class _class(internal->GetValue());
1557 if (!CYIsClass(_class))
1560 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1561 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1562 // XXX: this isn't always safe
1563 return [linternal->GetValue() isKindOfClass:_class];
1569 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1570 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1573 id self(internal->GetValue());
1574 const char *name(CYPoolCString(pool, context, property));
1576 if (object_getInstanceVariable(self, name, NULL) != NULL)
1582 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1583 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1586 id self(internal->GetValue());
1587 const char *name(CYPoolCString(pool, context, property));
1589 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
1590 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1591 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1597 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1598 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1601 id self(internal->GetValue());
1602 const char *name(CYPoolCString(pool, context, property));
1604 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
1605 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1606 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1613 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1614 if (Class super = class_getSuperclass(_class))
1615 Internal_getPropertyNames_(super, names);
1618 Ivar *data(class_copyIvarList(_class, &size));
1619 for (size_t i(0); i != size; ++i)
1620 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1624 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1625 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1628 id self(internal->GetValue());
1629 Class _class(object_getClass(self));
1631 Internal_getPropertyNames_(_class, names);
1634 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1635 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1636 return internal->GetOwner();
1639 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1641 NSString *name(CYCastNSString(pool, property));
1642 if (Class _class = NSClassFromString(name))
1643 return CYMakeInstance(context, _class, true);
1647 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1648 size_t size(objc_getClassList(NULL, 0));
1649 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1652 size_t writ(objc_getClassList(data, size));
1655 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1661 for (size_t i(0); i != writ; ++i)
1662 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1668 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1669 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1672 const char *name(CYPoolCString(pool, context, property));
1674 const char **data(objc_copyClassNamesForImage(internal, &size));
1676 for (size_t i(0); i != size; ++i)
1677 if (strcmp(name, data[i]) == 0) {
1678 if (Class _class = objc_getClass(name)) {
1679 value = CYMakeInstance(context, _class, true);
1690 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1691 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1693 const char **data(objc_copyClassNamesForImage(internal, &size));
1694 for (size_t i(0); i != size; ++i)
1695 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1699 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1701 const char *name(CYPoolCString(pool, context, property));
1703 const char **data(objc_copyImageNames(&size));
1704 for (size_t i(0); i != size; ++i)
1705 if (strcmp(name, data[i]) == 0) {
1714 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1715 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1719 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1721 const char **data(objc_copyImageNames(&size));
1722 for (size_t i(0); i != size; ++i)
1723 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1727 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1729 NSString *name(CYCastNSString(pool, property));
1730 if (Protocol *protocol = NSProtocolFromString(name))
1731 return CYMakeInstance(context, protocol, true);
1735 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1737 Protocol **data(objc_copyProtocolList(&size));
1738 for (size_t i(0); i != size; ++i)
1739 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1743 static bool stret(ffi_type *ffi_type) {
1744 return ffi_type->type == FFI_TYPE_STRUCT && (
1745 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1746 struct_forward_array[ffi_type->size] != 0
1750 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) { CYTry {
1754 _class = object_getClass(self);
1756 if (objc_method *method = class_getInstanceMethod(_class, _cmd))
1757 type = method_getTypeEncoding(method);
1760 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1762 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
1763 type = CYPoolCString(pool, context, [method _typeString]);
1767 objc_super super = {self, _class};
1768 void *arg0 = &super;
1774 sig::Signature signature;
1775 sig::Parse(pool, &signature, type, &Structor_);
1778 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1780 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSendSuper_stret) : reinterpret_cast<void (*)()>(&objc_msgSendSuper);
1781 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1784 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1786 throw CYJSError(context, "too few arguments to objc_msgSend");
1796 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
1797 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1798 self = internal->GetValue();
1799 _class = internal->class_;;
1800 uninitialized = false;
1801 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1802 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1803 self = internal->GetValue();
1805 uninitialized = internal->IsUninitialized();
1807 internal->value_ = nil;
1809 self = CYCastNSObject(pool, context, arguments[0]);
1811 uninitialized = false;
1815 return CYJSNull(context);
1817 _cmd = CYCastSEL(context, arguments[1]);
1819 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
1822 /* Hook: objc_registerClassPair {{{ */
1823 // XXX: replace this with associated objects
1825 MSHook(void, CYDealloc, id self, SEL sel) {
1826 CYInternal *internal;
1827 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
1828 if (internal != NULL)
1830 _CYDealloc(self, sel);
1833 MSHook(void, objc_registerClassPair, Class _class) {
1834 Class super(class_getSuperclass(_class));
1835 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
1836 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
1837 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
1840 _objc_registerClassPair(_class);
1843 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1845 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
1847 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
1848 if (value == NULL || !CYIsClass(value))
1849 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
1850 Class _class((Class) value);
1851 $objc_registerClassPair(_class);
1852 return CYJSUndefined(context);
1856 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1857 JSValueRef setup[count + 2];
1860 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1861 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1864 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1866 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
1868 // XXX: handle Instance::Uninitialized?
1869 id self(CYCastNSObject(pool, context, _this));
1873 setup[1] = &internal->sel_;
1875 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
1878 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1880 throw CYJSError(context, "incorrect number of arguments to Super constructor");
1882 id self(CYCastNSObject(pool, context, arguments[0]));
1883 Class _class(CYCastClass(pool, context, arguments[1]));
1884 return cy::Super::Make(context, self, _class);
1887 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1889 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
1891 const char *name(CYPoolCString(pool, context, arguments[0]));
1892 return CYMakeSelector(context, sel_registerName(name));
1895 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1897 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
1898 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
1899 return Instance::Make(context, self);
1902 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1903 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
1904 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1907 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1908 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1909 Type_privateData *typical(internal->GetType());
1914 if (typical == NULL) {
1918 type = typical->type_;
1919 ffi = typical->ffi_;
1922 return CYMakePointer(context, &internal->value_, type, ffi, object);
1925 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1926 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1927 return Instance::Make(context, object_getClass(internal->GetValue()));
1930 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1931 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1932 id self(internal->GetValue());
1933 if (!CYIsClass(self))
1934 return CYJSUndefined(context);
1935 return CYGetClassPrototype(context, self);
1938 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1939 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1940 id self(internal->GetValue());
1941 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
1942 return CYJSUndefined(context);
1943 return Messages::Make(context, self);
1946 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1947 if (!JSValueIsObjectOfClass(context, _this, Instance_))
1950 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1951 return CYCastJSValue(context, CYJSString(CYCastNSCYON(internal->GetValue())));
1954 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1955 if (!JSValueIsObjectOfClass(context, _this, Instance_))
1958 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1961 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1962 // XXX: check for support of cy$toJSON?
1963 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
1967 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1968 if (!JSValueIsObjectOfClass(context, _this, Instance_))
1971 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
1974 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
1975 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
1979 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1980 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1981 return CYCastJSValue(context, sel_getName(internal->GetValue()));
1984 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1985 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1988 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1989 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1990 const char *name(sel_getName(internal->GetValue()));
1993 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1997 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1999 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2002 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2003 SEL sel(internal->GetValue());
2005 objc_method *method;
2006 if (Class _class = CYCastClass(pool, context, arguments[0]))
2007 method = class_getInstanceMethod(_class, sel);
2011 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2012 return CYCastJSValue(context, CYJSString(type));
2014 return CYJSNull(context);
2017 static JSStaticValue Selector_staticValues[2] = {
2018 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2019 {NULL, NULL, NULL, 0}
2022 static JSStaticValue Instance_staticValues[5] = {
2023 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2024 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2025 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2026 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2027 {NULL, NULL, NULL, 0}
2030 static JSStaticFunction Instance_staticFunctions[5] = {
2031 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2032 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2033 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2034 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2038 static JSStaticFunction Internal_staticFunctions[2] = {
2039 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2043 static JSStaticFunction Selector_staticFunctions[5] = {
2044 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2045 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2046 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2047 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2051 void CYObjectiveC(JSContextRef context, JSObjectRef global) {
2052 apr_pool_t *pool(CYGetGlobalPool());
2054 hooks_ = &CYObjectiveCHooks;
2056 Object_type = new(pool) Type_privateData(pool, "@");
2057 Selector_type = new(pool) Type_privateData(pool, ":");
2060 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2061 NSCFType_ = objc_getClass("NSCFType");
2064 NSArray_ = objc_getClass("NSArray");
2065 NSDictionary_ = objc_getClass("NSDictonary");
2066 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2067 NSZombie_ = objc_getClass("_NSZombie_");
2068 Object_ = objc_getClass("Object");
2070 JSClassDefinition definition;
2072 definition = kJSClassDefinitionEmpty;
2073 definition.className = "Instance";
2074 definition.staticValues = Instance_staticValues;
2075 definition.staticFunctions = Instance_staticFunctions;
2076 definition.hasProperty = &Instance_hasProperty;
2077 definition.getProperty = &Instance_getProperty;
2078 definition.setProperty = &Instance_setProperty;
2079 definition.deleteProperty = &Instance_deleteProperty;
2080 definition.getPropertyNames = &Instance_getPropertyNames;
2081 definition.callAsConstructor = &Instance_callAsConstructor;
2082 definition.hasInstance = &Instance_hasInstance;
2083 definition.finalize = &CYFinalize;
2084 Instance_ = JSClassCreate(&definition);
2086 definition = kJSClassDefinitionEmpty;
2087 definition.className = "Internal";
2088 definition.staticFunctions = Internal_staticFunctions;
2089 definition.hasProperty = &Internal_hasProperty;
2090 definition.getProperty = &Internal_getProperty;
2091 definition.setProperty = &Internal_setProperty;
2092 definition.getPropertyNames = &Internal_getPropertyNames;
2093 definition.finalize = &CYFinalize;
2094 Internal_ = JSClassCreate(&definition);
2096 definition = kJSClassDefinitionEmpty;
2097 definition.className = "Message";
2098 definition.staticFunctions = cy::Functor::StaticFunctions;
2099 definition.callAsFunction = &Message_callAsFunction;
2100 definition.finalize = &CYFinalize;
2101 Message_ = JSClassCreate(&definition);
2103 definition = kJSClassDefinitionEmpty;
2104 definition.className = "Messages";
2105 definition.hasProperty = &Messages_hasProperty;
2106 definition.getProperty = &Messages_getProperty;
2107 definition.setProperty = &Messages_setProperty;
2109 definition.deleteProperty = &Messages_deleteProperty;
2111 definition.getPropertyNames = &Messages_getPropertyNames;
2112 definition.finalize = &CYFinalize;
2113 Messages_ = JSClassCreate(&definition);
2115 definition = kJSClassDefinitionEmpty;
2116 definition.className = "Selector";
2117 definition.staticValues = Selector_staticValues;
2118 definition.staticFunctions = Selector_staticFunctions;
2119 definition.callAsFunction = &Selector_callAsFunction;
2120 definition.finalize = &CYFinalize;
2121 Selector_ = JSClassCreate(&definition);
2123 definition = kJSClassDefinitionEmpty;
2124 definition.className = "Super";
2125 definition.staticFunctions = Internal_staticFunctions;
2126 definition.finalize = &CYFinalize;
2127 Super_ = JSClassCreate(&definition);
2129 definition = kJSClassDefinitionEmpty;
2130 definition.className = "ObjectiveC::Classes";
2131 definition.getProperty = &ObjectiveC_Classes_getProperty;
2132 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2133 ObjectiveC_Classes_ = JSClassCreate(&definition);
2135 definition = kJSClassDefinitionEmpty;
2136 definition.className = "ObjectiveC::Images";
2137 definition.getProperty = &ObjectiveC_Images_getProperty;
2138 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2139 ObjectiveC_Images_ = JSClassCreate(&definition);
2141 definition = kJSClassDefinitionEmpty;
2142 definition.className = "ObjectiveC::Image::Classes";
2143 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2144 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2145 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2147 definition = kJSClassDefinitionEmpty;
2148 definition.className = "ObjectiveC::Protocols";
2149 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2150 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2151 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2153 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2154 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
2156 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2157 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2158 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2160 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2161 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2162 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2163 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2165 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
2166 JSValueProtect(context, Instance_prototype_);
2168 CYSetProperty(context, global, CYJSString("Instance"), Instance);
2169 CYSetProperty(context, global, CYJSString("Selector"), Selector);
2170 CYSetProperty(context, global, CYJSString("Super"), Super);
2172 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2173 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2175 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), Function_prototype_);
2176 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), Function_prototype_);
2178 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2181 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");