1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2010 Jay Freeman (saurik)
5 /* GNU Lesser General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
26 #include <Foundation/Foundation.h>
28 #include "ObjectiveC/Internal.hpp"
30 #include <objc/objc-api.h>
32 #include "cycript.hpp"
34 #include "ObjectiveC/Internal.hpp"
37 #include <CoreFoundation/CoreFoundation.h>
38 #include <JavaScriptCore/JSStringRefCF.h>
39 #include <WebKit/WebScriptObject.h>
40 #include <objc/runtime.h>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
51 #define CYObjectiveTry_(context) { \
52 JSContextRef context_(context); \
54 #define CYObjectiveTry { \
56 #define CYObjectiveCatch \
57 catch (const CYException &error) { \
58 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
64 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
66 #define CYPoolCatch(value) \
67 @catch (NSException *error) { \
68 _saved = [error retain]; \
69 throw CYJSError(context, CYCastJSValue(context, error)); \
74 [_saved autorelease]; \
80 #define CYSadCatch(value) \
81 @catch (NSException *error ) { \
82 throw CYJSError(context, CYCastJSValue(context, error)); \
87 #define class_getSuperclass GSObjCSuper
88 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
89 #define class_getName GSNameFromClass
91 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
93 #define ivar_getName(ivar) ((ivar)->ivar_name)
94 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
95 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
97 #define method_getName(method) ((method)->method_name)
98 #define method_getImplementation(method) ((method)->method_imp)
99 #define method_getTypeEncoding(method) ((method)->method_types)
100 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
103 #define objc_getClass GSClassFromName
105 #define objc_getProtocol GSProtocolFromName
107 #define object_getClass GSObjCClass
109 #define object_getInstanceVariable(object, name, value) ({ \
110 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
111 _assert(value != NULL); \
113 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
117 #define object_setIvar(object, ivar, value) ({ \
118 void *data = (value); \
119 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
122 #define protocol_getName(protocol) [(protocol) name]
125 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
127 /* Objective-C Pool Release {{{ */
128 apr_status_t CYPoolRelease_(void *data) {
129 id object(reinterpret_cast<id>(data));
134 id CYPoolRelease_(apr_pool_t *pool, id object) {
137 else if (pool == NULL)
138 return [object autorelease];
140 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
145 template <typename Type_>
146 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
147 return (Type_) CYPoolRelease_(pool, (id) object);
150 /* Objective-C Strings {{{ */
151 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
153 return [value UTF8String];
155 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
156 char *string(new(pool) char[size]);
157 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
158 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
163 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
165 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
168 return CYCopyJSString(CYPoolCString(pool, context, value));
172 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
175 // XXX: this definition scares me; is anyone using this?!
176 NSString *string([value description]);
177 return CYCopyJSString(context, string);
180 NSString *CYCopyNSString(const CYUTF8String &value) {
182 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
184 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
188 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
190 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
193 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
197 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
198 return CYCopyNSString(context, CYJSString(context, value));
201 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
202 return CYPoolRelease(pool, CYCopyNSString(value));
205 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
206 const char *name(sel_getName(sel));
207 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
210 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
211 return CYPoolRelease(pool, CYCopyNSString(context, value));
214 CYUTF8String CYCastUTF8String(NSString *value) {
215 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
216 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
220 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
222 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
223 if (exception == NULL)
225 *exception = CYCastJSValue(context, error);
228 size_t CYGetIndex(NSString *value) {
229 return CYGetIndex(CYCastUTF8String(value));
232 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
233 return CYGetOffset(CYPoolCString(pool, context, value), index);
236 static JSClassRef Instance_;
237 static JSClassRef ArrayInstance_;
238 static JSClassRef ObjectInstance_;
239 static JSClassRef StringInstance_;
241 static JSClassRef Internal_;
242 static JSClassRef Message_;
243 static JSClassRef Messages_;
244 static JSClassRef Selector_;
245 static JSClassRef Super_;
247 static JSClassRef ObjectiveC_Classes_;
248 static JSClassRef ObjectiveC_Constants_;
249 static JSClassRef ObjectiveC_Protocols_;
252 static JSClassRef ObjectiveC_Image_Classes_;
253 static JSClassRef ObjectiveC_Images_;
257 static Class NSCFBoolean_;
258 static Class NSCFType_;
259 static Class NSGenericDeallocHandler_;
260 static Class NSMessageBuilder_;
261 static Class NSZombie_;
263 static Class NSBoolNumber_;
266 static Class NSArray_;
267 static Class NSDictionary_;
268 static Class NSString_;
269 static Class Object_;
271 static Type_privateData *Object_type;
272 static Type_privateData *Selector_type;
274 Type_privateData *Instance::GetType() const {
278 Type_privateData *Selector_privateData::GetType() const {
279 return Selector_type;
282 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
284 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
286 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
288 JSObjectRef global(CYGetGlobalObject(context));
289 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
292 sprintf(label, "i%p", self);
293 CYJSString name(label);
295 JSValueRef value(CYGetProperty(context, cy, name));
296 if (!JSValueIsUndefined(context, value))
299 JSClassRef _class(NULL);
300 JSValueRef prototype;
302 if (self == NSArray_)
303 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
304 else if (self == NSDictionary_)
305 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
306 else if (self == NSString_)
307 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
309 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
311 JSObjectRef object(JSObjectMake(context, _class, NULL));
312 JSObjectSetPrototype(context, object, prototype);
313 CYSetProperty(context, cy, name, object);
318 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
319 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
320 if (_class == NSArray_)
322 if (Class super = class_getSuperclass(_class))
323 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
325 JSObjectSetPrototype(context, value, Array_prototype_);*/
329 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
330 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
334 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
335 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
339 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
340 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
341 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
345 Instance::~Instance() {
346 if ((flags_ & Transient) == 0)
347 // XXX: does this handle background threads correctly?
348 // XXX: this simply does not work on the console because I'm stupid
349 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
352 struct Message_privateData :
357 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
358 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
364 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
365 Instance::Flags flags;
368 flags = Instance::Transient;
370 flags = Instance::None;
371 object = [object retain];
374 return Instance::Make(context, object, flags);
377 @interface NSMethodSignature (Cycript)
378 - (NSString *) _typeString;
381 @interface NSObject (Cycript)
383 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
384 - (JSType) cy$JSType;
386 - (NSObject *) cy$toJSON:(NSString *)key;
387 - (NSString *) cy$toCYON;
389 - (bool) cy$hasProperty:(NSString *)name;
390 - (NSObject *) cy$getProperty:(NSString *)name;
391 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
392 - (bool) cy$deleteProperty:(NSString *)name;
393 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
395 + (bool) cy$hasImplicitProperties;
401 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
404 NSString *CYCastNSCYON(id value) {
410 Class _class(object_getClass(value));
411 SEL sel(@selector(cy$toCYON));
413 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
414 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
415 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
416 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
417 string = [value cy$toCYON];
422 else if (value == NSZombie_)
423 string = @"_NSZombie_";
424 else if (_class == NSZombie_)
425 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
426 // XXX: frowny /in/ the pants
427 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
431 string = [NSString stringWithFormat:@"%@", value];
436 string = @"undefined";
443 struct PropertyAttributes {
448 const char *variable;
461 PropertyAttributes(objc_property_t property) :
473 name = property_getName(property);
474 const char *attributes(property_getAttributes(property));
476 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
478 case 'R': readonly = true; break;
479 case 'C': copy = true; break;
480 case '&': retain = true; break;
481 case 'N': nonatomic = true; break;
482 case 'G': getter_ = token + 1; break;
483 case 'S': setter_ = token + 1; break;
484 case 'V': variable = token + 1; break;
488 /*if (variable == NULL) {
489 variable = property_getName(property);
490 size_t size(strlen(variable));
491 char *name(new(pool_) char[size + 2]);
493 memcpy(name + 1, variable, size);
494 name[size + 1] = '\0';
499 const char *Getter() {
501 getter_ = apr_pstrdup(pool_, name);
505 const char *Setter() {
506 if (setter_ == NULL && !readonly) {
507 size_t length(strlen(name));
509 char *temp(new(pool_) char[length + 5]);
515 temp[3] = toupper(name[0]);
516 memcpy(temp + 4, name + 1, length - 1);
519 temp[length + 3] = ':';
520 temp[length + 4] = '\0';
531 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
532 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
537 @interface CYWebUndefined : NSObject {
540 + (CYWebUndefined *) undefined;
544 @implementation CYWebUndefined
546 + (CYWebUndefined *) undefined {
547 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
553 #define WebUndefined CYWebUndefined
556 /* Bridge: CYJSObject {{{ */
557 @interface CYJSObject : NSMutableDictionary {
559 JSContextRef context_;
562 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
564 - (NSObject *) cy$toJSON:(NSString *)key;
566 - (NSUInteger) count;
567 - (id) objectForKey:(id)key;
568 - (NSEnumerator *) keyEnumerator;
569 - (void) setObject:(id)object forKey:(id)key;
570 - (void) removeObjectForKey:(id)key;
574 /* Bridge: CYJSArray {{{ */
575 @interface CYJSArray : NSMutableArray {
577 JSContextRef context_;
580 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
582 - (NSUInteger) count;
583 - (id) objectAtIndex:(NSUInteger)index;
585 - (void) addObject:(id)anObject;
586 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
587 - (void) removeLastObject;
588 - (void) removeObjectAtIndex:(NSUInteger)index;
589 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
594 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
595 JSObjectRef Array(CYGetCachedObject(context, Array_s));
596 JSValueRef exception(NULL);
597 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
598 CYThrow(context, exception);
599 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
600 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
603 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
604 if (!JSValueIsObjectOfClass(context, object, Instance_))
605 return CYCastNSObject_(pool, context, object);
607 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
608 return internal->GetValue();
612 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
613 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
617 @interface NSBoolNumber : NSNumber {
622 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
626 switch (JSType type = JSValueGetType(context, value)) {
627 case kJSTypeUndefined:
628 object = [WebUndefined undefined];
638 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
641 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
647 object = CYCopyNSNumber(context, value);
652 object = CYCopyNSString(context, value);
657 // XXX: this might could be more efficient
658 object = CYCastNSObject(pool, context, (JSObjectRef) value);
663 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
670 return CYPoolRelease(pool, object);
672 return [object retain];
675 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
676 return CYNSObject(pool, context, value, true);
679 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
680 return CYNSObject(pool, context, value, false);
683 /* Bridge: NSArray {{{ */
684 @implementation NSArray (Cycript)
687 return [[self mutableCopy] autorelease];
690 - (NSString *) cy$toCYON {
691 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
692 [json appendString:@"@["];
696 for (id object in self) {
698 for (size_t index(0), count([self count]); index != count; ++index) {
699 id object([self objectAtIndex:index]);
702 [json appendString:@","];
705 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
706 [json appendString:CYCastNSCYON(object)];
708 [json appendString:@","];
713 [json appendString:@"]"];
717 - (bool) cy$hasProperty:(NSString *)name {
718 if ([name isEqualToString:@"length"])
721 size_t index(CYGetIndex(name));
722 if (index == _not(size_t) || index >= [self count])
723 return [super cy$hasProperty:name];
728 - (NSObject *) cy$getProperty:(NSString *)name {
729 if ([name isEqualToString:@"length"]) {
730 NSUInteger count([self count]);
732 return [NSNumber numberWithUnsignedInteger:count];
734 return [NSNumber numberWithUnsignedInt:count];
738 size_t index(CYGetIndex(name));
739 if (index == _not(size_t) || index >= [self count])
740 return [super cy$getProperty:name];
742 return [self objectAtIndex:index];
745 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
746 [super cy$getPropertyNames:names inContext:context];
748 for (size_t index(0), count([self count]); index != count; ++index) {
749 id object([self objectAtIndex:index]);
750 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
752 sprintf(name, "%zu", index);
753 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
758 + (bool) cy$hasImplicitProperties {
764 /* Bridge: NSBoolNumber {{{ */
766 @implementation NSBoolNumber (Cycript)
768 - (JSType) cy$JSType {
769 return kJSTypeBoolean;
772 - (NSObject *) cy$toJSON:(NSString *)key {
776 - (NSString *) cy$toCYON {
777 return [self boolValue] ? @"@true" : @"@false";
780 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
781 return CYCastJSValue(context, (bool) [self boolValue]);
787 /* Bridge: NSDictionary {{{ */
788 @implementation NSDictionary (Cycript)
791 return [[self mutableCopy] autorelease];
794 - (NSString *) cy$toCYON {
795 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
796 [json appendString:@"@{"];
800 for (NSObject *key in self) {
802 NSEnumerator *keys([self keyEnumerator]);
803 while (NSObject *key = [keys nextObject]) {
806 [json appendString:@","];
809 [json appendString:CYCastNSCYON(key)];
810 [json appendString:@":"];
811 NSObject *object([self objectForKey:key]);
812 [json appendString:CYCastNSCYON(object)];
815 [json appendString:@"}"];
819 - (bool) cy$hasProperty:(NSString *)name {
820 return [self objectForKey:name] != nil;
823 - (NSObject *) cy$getProperty:(NSString *)name {
824 return [self objectForKey:name];
827 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
828 [super cy$getPropertyNames:names inContext:context];
831 for (NSObject *key in self) {
833 NSEnumerator *keys([self keyEnumerator]);
834 while (NSObject *key = [keys nextObject]) {
836 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
840 + (bool) cy$hasImplicitProperties {
846 /* Bridge: NSMutableArray {{{ */
847 @implementation NSMutableArray (Cycript)
849 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
850 if ([name isEqualToString:@"length"]) {
851 // XXX: is this not intelligent?
852 NSNumber *number(reinterpret_cast<NSNumber *>(value));
854 NSUInteger size([number unsignedIntegerValue]);
856 NSUInteger size([number unsignedIntValue]);
858 NSUInteger count([self count]);
860 [self removeObjectsInRange:NSMakeRange(size, count - size)];
861 else if (size != count) {
862 WebUndefined *undefined([WebUndefined undefined]);
863 for (size_t i(count); i != size; ++i)
864 [self addObject:undefined];
869 size_t index(CYGetIndex(name));
870 if (index == _not(size_t))
871 return [super cy$setProperty:name to:value];
873 id object(value ?: [NSNull null]);
875 size_t count([self count]);
877 [self replaceObjectAtIndex:index withObject:object];
879 if (index != count) {
880 WebUndefined *undefined([WebUndefined undefined]);
881 for (size_t i(count); i != index; ++i)
882 [self addObject:undefined];
885 [self addObject:object];
891 - (bool) cy$deleteProperty:(NSString *)name {
892 size_t index(CYGetIndex(name));
893 if (index == _not(size_t) || index >= [self count])
894 return [super cy$deleteProperty:name];
895 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
901 /* Bridge: NSMutableDictionary {{{ */
902 @implementation NSMutableDictionary (Cycript)
904 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
905 [self setObject:(value ?: [NSNull null]) forKey:name];
909 - (bool) cy$deleteProperty:(NSString *)name {
910 if ([self objectForKey:name] == nil)
913 [self removeObjectForKey:name];
920 /* Bridge: NSNumber {{{ */
921 @implementation NSNumber (Cycript)
923 - (JSType) cy$JSType {
925 // XXX: this just seems stupid
926 if ([self class] == NSCFBoolean_)
927 return kJSTypeBoolean;
929 return kJSTypeNumber;
932 - (NSObject *) cy$toJSON:(NSString *)key {
936 - (NSString *) cy$toCYON {
937 return [self cy$JSType] != kJSTypeBoolean ? [NSString stringWithFormat:@"@%@", self] : [self boolValue] ? @"@true" : @"@false";
940 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
941 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
946 /* Bridge: NSNull {{{ */
947 @implementation NSNull (Cycript)
949 - (JSType) cy$JSType {
953 - (NSObject *) cy$toJSON:(NSString *)key {
957 - (NSString *) cy$toCYON {
963 /* Bridge: NSObject {{{ */
964 @implementation NSObject (Cycript)
970 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
974 - (JSType) cy$JSType {
975 return kJSTypeObject;
978 - (NSObject *) cy$toJSON:(NSString *)key {
979 return [self description];
982 - (NSString *) cy$toCYON {
983 return [[self cy$toJSON:@""] cy$toCYON];
986 - (bool) cy$hasProperty:(NSString *)name {
990 - (NSObject *) cy$getProperty:(NSString *)name {
994 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
998 - (bool) cy$deleteProperty:(NSString *)name {
1002 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1005 + (bool) cy$hasImplicitProperties {
1011 /* Bridge: NSProxy {{{ */
1012 @implementation NSProxy (Cycript)
1014 - (NSObject *) cy$toJSON:(NSString *)key {
1015 return [self description];
1018 - (NSString *) cy$toCYON {
1019 return [[self cy$toJSON:@""] cy$toCYON];
1024 /* Bridge: NSString {{{ */
1025 @implementation NSString (Cycript)
1028 return [[self copy] autorelease];
1031 - (JSType) cy$JSType {
1032 return kJSTypeString;
1035 - (NSObject *) cy$toJSON:(NSString *)key {
1039 - (NSString *) cy$toCYON {
1040 std::ostringstream str;
1042 CYUTF8String string(CYCastUTF8String(self));
1043 CYStringify(str, string.data, string.size);
1044 std::string value(str.str());
1045 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1048 - (bool) cy$hasProperty:(NSString *)name {
1049 if ([name isEqualToString:@"length"])
1052 size_t index(CYGetIndex(name));
1053 if (index == _not(size_t) || index >= [self length])
1054 return [super cy$hasProperty:name];
1059 - (NSObject *) cy$getProperty:(NSString *)name {
1060 if ([name isEqualToString:@"length"]) {
1061 NSUInteger count([self length]);
1063 return [NSNumber numberWithUnsignedInteger:count];
1065 return [NSNumber numberWithUnsignedInt:count];
1069 size_t index(CYGetIndex(name));
1070 if (index == _not(size_t) || index >= [self length])
1071 return [super cy$getProperty:name];
1073 return [self substringWithRange:NSMakeRange(index, 1)];
1076 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1077 [super cy$getPropertyNames:names inContext:context];
1079 for (size_t index(0), length([self length]); index != length; ++index) {
1081 sprintf(name, "%zu", index);
1082 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1086 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1087 + (bool) cy$hasImplicitProperties {
1091 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1092 return CYCastJSValue(context, CYJSString(context, self));
1093 } CYObjectiveCatch }
1097 /* Bridge: WebUndefined {{{ */
1098 @implementation WebUndefined (Cycript)
1100 - (JSType) cy$JSType {
1101 return kJSTypeUndefined;
1104 - (NSObject *) cy$toJSON:(NSString *)key {
1108 - (NSString *) cy$toCYON {
1109 return @"undefined";
1112 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1113 return CYJSUndefined(context);
1114 } CYObjectiveCatch }
1119 static bool CYIsClass(id self) {
1121 // XXX: this is a lame object_isClass
1122 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1124 return GSObjCIsClass(self);
1128 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1129 id self(CYCastNSObject(pool, context, value));
1130 if (CYIsClass(self))
1131 return (Class) self;
1132 throw CYJSError(context, "got something that is not a Class");
1136 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1138 size_t size(JSPropertyNameArrayGetCount(names));
1139 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1140 for (size_t index(0); index != size; ++index)
1141 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1145 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1147 return CYJSNull(context);
1149 return CYMakeInstance(context, value, false);
1150 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1152 @implementation CYJSObject
1154 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1155 if ((self = [super init]) != nil) {
1157 context_ = CYGetJSContext(context);
1158 //XXX:JSGlobalContextRetain(context_);
1159 JSValueProtect(context_, object_);
1161 } CYObjectiveCatch }
1163 - (void) dealloc { CYObjectiveTry {
1164 JSValueUnprotect(context_, object_);
1165 //XXX:JSGlobalContextRelease(context_);
1167 } CYObjectiveCatch }
1169 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1170 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1171 if (!CYIsCallable(context_, toJSON))
1172 return [super cy$toJSON:key];
1174 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1175 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1176 // XXX: do I really want an NSNull here?!
1177 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1179 } CYObjectiveCatch }
1181 - (NSString *) cy$toCYON { CYObjectiveTry {
1183 JSValueRef exception(NULL);
1184 const char *cyon(CYPoolCCYON(pool, context_, object_));
1185 CYThrow(context_, exception);
1187 return [super cy$toCYON];
1189 return [NSString stringWithUTF8String:cyon];
1190 } CYObjectiveCatch }
1192 - (NSUInteger) count { CYObjectiveTry {
1193 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1194 size_t size(JSPropertyNameArrayGetCount(names));
1195 JSPropertyNameArrayRelease(names);
1197 } CYObjectiveCatch }
1199 - (id) objectForKey:(id)key { CYObjectiveTry {
1200 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1201 if (JSValueIsUndefined(context_, value))
1203 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1204 } CYObjectiveCatch }
1206 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1207 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1208 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1209 JSPropertyNameArrayRelease(names);
1211 } CYObjectiveCatch }
1213 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1214 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1215 } CYObjectiveCatch }
1217 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1218 JSValueRef exception(NULL);
1219 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1220 CYThrow(context_, exception);
1221 } CYObjectiveCatch }
1225 @implementation CYJSArray
1227 - (NSString *) cy$toCYON {
1229 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1232 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1233 if ((self = [super init]) != nil) {
1235 context_ = CYGetJSContext(context);
1236 //XXX:JSGlobalContextRetain(context_);
1237 JSValueProtect(context_, object_);
1239 } CYObjectiveCatch }
1241 - (void) dealloc { CYObjectiveTry {
1242 JSValueUnprotect(context_, object_);
1243 //XXX:JSGlobalContextRelease(context_);
1245 } CYObjectiveCatch }
1247 - (NSUInteger) count { CYObjectiveTry {
1248 return CYArrayLength(context_, object_);
1249 } CYObjectiveCatch }
1251 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1252 size_t bounds([self count]);
1253 if (index >= bounds)
1254 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1255 JSValueRef exception(NULL);
1256 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1257 CYThrow(context_, exception);
1258 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1259 } CYObjectiveCatch }
1261 - (void) addObject:(id)object { CYObjectiveTry {
1262 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1263 } CYObjectiveCatch }
1265 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1266 size_t bounds([self count] + 1);
1267 if (index >= bounds)
1268 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1269 JSValueRef exception(NULL);
1270 JSValueRef arguments[3];
1271 arguments[0] = CYCastJSValue(context_, index);
1272 arguments[1] = CYCastJSValue(context_, 0);
1273 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1274 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1275 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1276 CYThrow(context_, exception);
1277 } CYObjectiveCatch }
1279 - (void) removeLastObject { CYObjectiveTry {
1280 JSValueRef exception(NULL);
1281 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1282 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1283 CYThrow(context_, exception);
1284 } CYObjectiveCatch }
1286 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1287 size_t bounds([self count]);
1288 if (index >= bounds)
1289 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1290 JSValueRef exception(NULL);
1291 JSValueRef arguments[2];
1292 arguments[0] = CYCastJSValue(context_, index);
1293 arguments[1] = CYCastJSValue(context_, 1);
1294 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1295 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1296 CYThrow(context_, exception);
1297 } CYObjectiveCatch }
1299 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1300 size_t bounds([self count]);
1301 if (index >= bounds)
1302 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1303 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1304 } CYObjectiveCatch }
1308 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1312 JSObjectRef object_;
1320 // XXX: delete object_? ;(
1323 static CYInternal *Get(id self) {
1324 CYInternal *internal(NULL);
1325 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1326 // XXX: do something epic? ;P
1332 static CYInternal *Set(id self) {
1333 CYInternal *internal(NULL);
1334 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1335 if (internal == NULL) {
1336 internal = new CYInternal();
1337 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1340 // XXX: do something epic? ;P
1346 bool HasProperty(JSContextRef context, JSStringRef name) {
1347 if (object_ == NULL)
1349 return JSObjectHasProperty(context, object_, name);
1352 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1353 if (object_ == NULL)
1355 return CYGetProperty(context, object_, name);
1358 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1359 if (object_ == NULL)
1360 object_ = JSObjectMake(context, NULL, NULL);
1361 CYSetProperty(context, object_, name, value);
1365 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1366 Selector_privateData *internal(new Selector_privateData(sel));
1367 return JSObjectMake(context, Selector_, internal);
1370 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1371 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1372 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1373 return reinterpret_cast<SEL>(internal->value_);
1375 return CYCastPointer<SEL>(context, value);
1378 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1379 return (void *) [[NSAutoreleasePool alloc] init];
1380 } CYSadCatch(NULL) }
1382 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1383 return [(NSAutoreleasePool *) handle release];
1386 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1388 return Instance::Make(context, nil);
1389 if (Class _class = objc_getClass(name.data))
1390 return CYMakeInstance(context, _class, true);
1391 if (Protocol *protocol = objc_getProtocol(name.data))
1392 return CYMakeInstance(context, protocol, true);
1394 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1396 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1397 ffi_call(cif, function, value, values);
1400 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1401 switch (type->primitive) {
1402 // XXX: do something epic about blocks
1405 case sig::typename_P:
1406 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1409 case sig::selector_P:
1410 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1418 } CYSadCatch(false) }
1420 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1421 switch (type->primitive) {
1422 // XXX: do something epic about blocks
1425 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1426 JSValueRef value(CYCastJSValue(context, object));
1432 case sig::typename_P:
1433 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1435 case sig::selector_P:
1436 if (SEL sel = *reinterpret_cast<SEL *>(data))
1437 return CYMakeSelector(context, sel);
1441 return CYJSNull(context);
1445 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1447 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1448 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1451 #if OBJC_API_VERSION >= 2
1453 method_getReturnType(method, type, sizeof(type));
1455 const char *type(method_getTypeEncoding(method));
1461 // XXX: possibly use a more "awesome" check?
1465 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1467 return method_getTypeEncoding(method);
1469 const char *name(sel_getName(sel));
1470 size_t length(strlen(name));
1472 char keyed[length + 2];
1474 keyed[length + 1] = '\0';
1475 memcpy(keyed + 1, name, length);
1477 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1478 return entry->value_;
1483 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1484 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1486 JSContextRef context(internal->context_);
1488 size_t count(internal->cif_.nargs);
1489 JSValueRef values[count];
1491 for (size_t index(0); index != count; ++index)
1492 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1494 JSObjectRef _this(CYCastJSObject(context, values[0]));
1496 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1497 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1500 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1501 Message_privateData *internal(new Message_privateData(sel, type, imp));
1502 return JSObjectMake(context, Message_, internal);
1505 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1506 JSObjectRef function(CYCastJSObject(context, value));
1507 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1508 // XXX: see notes in Library.cpp about needing to leak
1509 return reinterpret_cast<IMP>(internal->GetValue());
1512 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1513 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1514 Class _class(internal->GetValue());
1517 const char *name(CYPoolCString(pool, context, property));
1519 if (SEL sel = sel_getUid(name))
1520 if (class_getInstanceMethod(_class, sel) != NULL)
1526 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1527 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1528 Class _class(internal->GetValue());
1531 const char *name(CYPoolCString(pool, context, property));
1533 if (SEL sel = sel_getUid(name))
1534 if (objc_method *method = class_getInstanceMethod(_class, sel))
1535 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1540 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1541 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1542 Class _class(internal->GetValue());
1545 const char *name(CYPoolCString(pool, context, property));
1547 SEL sel(sel_registerName(name));
1549 objc_method *method(class_getInstanceMethod(_class, sel));
1554 if (JSValueIsObjectOfClass(context, value, Message_)) {
1555 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1556 type = sig::Unparse(pool, &message->signature_);
1557 imp = reinterpret_cast<IMP>(message->GetValue());
1559 type = CYPoolTypeEncoding(pool, context, sel, method);
1560 imp = CYMakeMessage(context, value, type);
1564 method_setImplementation(method, imp);
1567 GSMethodList list(GSAllocMethodList(1));
1568 GSAppendMethodToList(list, sel, type, imp, YES);
1569 GSAddMethodList(_class, list, YES);
1570 GSFlushMethodCacheForClass(_class);
1572 class_addMethod(_class, sel, imp, type);
1579 #if 0 && OBJC_API_VERSION < 2
1580 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1581 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1582 Class _class(internal->GetValue());
1585 const char *name(CYPoolCString(pool, context, property));
1587 if (SEL sel = sel_getUid(name))
1588 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1589 objc_method_list list = {NULL, 1, {method}};
1590 class_removeMethods(_class, &list);
1598 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1599 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1600 Class _class(internal->GetValue());
1602 #if OBJC_API_VERSION >= 2
1604 objc_method **data(class_copyMethodList(_class, &size));
1605 for (size_t i(0); i != size; ++i)
1606 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1609 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1610 for (int i(0); i != methods->method_count; ++i)
1611 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1615 static bool CYHasImplicitProperties(Class _class) {
1616 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1617 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1619 return [_class cy$hasImplicitProperties];
1622 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1623 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1624 id self(internal->GetValue());
1626 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1630 NSString *name(CYCastNSString(pool, context, property));
1632 if (CYInternal *internal = CYInternal::Get(self))
1633 if (internal->HasProperty(context, property))
1636 Class _class(object_getClass(self));
1639 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1640 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1641 if ([self cy$hasProperty:name])
1643 } CYPoolCatch(false)
1645 const char *string(CYPoolCString(pool, context, name));
1648 if (class_getProperty(_class, string) != NULL)
1652 if (CYHasImplicitProperties(_class))
1653 if (SEL sel = sel_getUid(string))
1654 if (CYImplements(self, _class, sel, true))
1660 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1661 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1662 id self(internal->GetValue());
1664 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1665 return Internal::Make(context, self, object);
1668 NSString *name(CYCastNSString(pool, context, property));
1670 if (CYInternal *internal = CYInternal::Get(self))
1671 if (JSValueRef value = internal->GetProperty(context, property))
1675 if (NSObject *data = [self cy$getProperty:name])
1676 return CYCastJSValue(context, data);
1679 const char *string(CYPoolCString(pool, context, name));
1680 Class _class(object_getClass(self));
1683 if (objc_property_t property = class_getProperty(_class, string)) {
1684 PropertyAttributes attributes(property);
1685 SEL sel(sel_registerName(attributes.Getter()));
1686 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1690 if (CYHasImplicitProperties(_class))
1691 if (SEL sel = sel_getUid(string))
1692 if (CYImplements(self, _class, sel, true))
1693 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1698 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1699 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1700 id self(internal->GetValue());
1704 NSString *name(CYCastNSString(pool, context, property));
1705 NSObject *data(CYCastNSObject(pool, context, value));
1708 if ([self cy$setProperty:name to:data])
1712 const char *string(CYPoolCString(pool, context, name));
1713 Class _class(object_getClass(self));
1716 if (objc_property_t property = class_getProperty(_class, string)) {
1717 PropertyAttributes attributes(property);
1718 if (const char *setter = attributes.Setter()) {
1719 SEL sel(sel_registerName(setter));
1720 JSValueRef arguments[1] = {value};
1721 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1727 size_t length(strlen(string));
1729 char set[length + 5];
1735 if (string[0] != '\0') {
1736 set[3] = toupper(string[0]);
1737 memcpy(set + 4, string + 1, length - 1);
1740 set[length + 3] = ':';
1741 set[length + 4] = '\0';
1743 if (SEL sel = sel_getUid(set))
1744 if (CYImplements(self, _class, sel, false)) {
1745 JSValueRef arguments[1] = {value};
1746 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1749 if (CYInternal *internal = CYInternal::Set(self)) {
1750 internal->SetProperty(context, property, value);
1757 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1758 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1759 id self(internal->GetValue());
1762 NSString *name(CYCastNSString(NULL, context, property));
1763 return [self cy$deleteProperty:name];
1765 } CYCatch return /*XXX*/ NULL; }
1767 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1768 const char *name(sel_getName(method_getName(method)));
1769 if (strchr(name, ':') != NULL)
1772 const char *type(method_getTypeEncoding(method));
1773 if (type == NULL || *type == '\0' || *type == 'v')
1776 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1779 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1780 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1781 id self(internal->GetValue());
1784 Class _class(object_getClass(self));
1789 objc_property_t *data(class_copyPropertyList(_class, &size));
1790 for (size_t i(0); i != size; ++i)
1791 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1796 if (CYHasImplicitProperties(_class))
1797 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1798 #if OBJC_API_VERSION >= 2
1800 objc_method **data(class_copyMethodList(current, &size));
1801 for (size_t i(0); i != size; ++i)
1802 Instance_getPropertyNames_message(names, data[i]);
1805 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1806 for (int i(0); i != methods->method_count; ++i)
1807 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1812 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1813 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1814 [self cy$getPropertyNames:names inContext:context];
1818 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1819 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1820 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1824 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1825 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1826 Class _class(internal->GetValue());
1827 if (!CYIsClass(_class))
1830 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1831 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1832 // XXX: this isn't always safe
1833 return [linternal->GetValue() isKindOfClass:_class];
1839 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1841 throw CYJSError(context, "incorrect number of arguments to Instance");
1843 id value(CYCastNSObject(pool, context, arguments[0]));
1845 value = [NSNull null];
1846 return CYCastJSValue(context, [value cy$box]);
1849 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1850 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1853 id self(internal->GetValue());
1854 const char *name(CYPoolCString(pool, context, property));
1856 if (object_getInstanceVariable(self, name, NULL) != NULL)
1862 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1863 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1866 id self(internal->GetValue());
1867 const char *name(CYPoolCString(pool, context, property));
1869 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1870 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1871 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1872 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1878 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1879 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1882 id self(internal->GetValue());
1883 const char *name(CYPoolCString(pool, context, property));
1885 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1886 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1887 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1894 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1895 if (Class super = class_getSuperclass(_class))
1896 Internal_getPropertyNames_(super, names);
1898 #if OBJC_API_VERSION >= 2
1900 objc_ivar **data(class_copyIvarList(_class, &size));
1901 for (size_t i(0); i != size; ++i)
1902 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1905 if (objc_ivar_list *ivars = _class->ivars)
1906 for (int i(0); i != ivars->ivar_count; ++i)
1907 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1911 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1912 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1915 id self(internal->GetValue());
1916 Class _class(object_getClass(self));
1918 Internal_getPropertyNames_(_class, names);
1921 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1922 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1923 return internal->GetOwner();
1926 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1928 NSString *name(CYCastNSString(pool, context, property));
1929 if (Class _class = NSClassFromString(name))
1930 return CYMakeInstance(context, _class, true);
1934 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1936 size_t size(objc_getClassList(NULL, 0));
1937 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1940 size_t writ(objc_getClassList(data, size));
1943 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1949 for (size_t i(0); i != writ; ++i)
1950 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1956 while (Class _class = objc_next_class(&state))
1957 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1961 #if OBJC_API_VERSION >= 2
1962 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1963 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1966 const char *name(CYPoolCString(pool, context, property));
1968 const char **data(objc_copyClassNamesForImage(internal, &size));
1970 for (size_t i(0); i != size; ++i)
1971 if (strcmp(name, data[i]) == 0) {
1972 if (Class _class = objc_getClass(name)) {
1973 value = CYMakeInstance(context, _class, true);
1984 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1985 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1987 const char **data(objc_copyClassNamesForImage(internal, &size));
1988 for (size_t i(0); i != size; ++i)
1989 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1993 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1995 const char *name(CYPoolCString(pool, context, property));
1997 const char **data(objc_copyImageNames(&size));
1998 for (size_t i(0); i != size; ++i)
1999 if (strcmp(name, data[i]) == 0) {
2008 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2009 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2013 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2015 const char **data(objc_copyImageNames(&size));
2016 for (size_t i(0); i != size; ++i)
2017 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2022 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2024 const char *name(CYPoolCString(pool, context, property));
2025 if (Protocol *protocol = objc_getProtocol(name))
2026 return CYMakeInstance(context, protocol, true);
2030 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2031 #if OBJC_API_VERSION >= 2
2033 Protocol **data(objc_copyProtocolList(&size));
2034 for (size_t i(0); i != size; ++i)
2035 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2042 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2044 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2046 return Instance::Make(context, nil);
2050 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2051 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2055 static bool stret(ffi_type *ffi_type) {
2056 return ffi_type->type == FFI_TYPE_STRUCT && (
2057 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2058 struct_forward_array[ffi_type->size] != 0
2063 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 {
2067 _class = object_getClass(self);
2071 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2072 imp = method_getImplementation(method);
2073 type = method_getTypeEncoding(method);
2078 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2080 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2081 type = CYPoolCString(pool, context, [method _typeString]);
2089 sig::Signature signature;
2090 sig::Parse(pool, &signature, type, &Structor_);
2092 size_t used(count + 3);
2093 if (used > signature.count) {
2094 sig::Element *elements(new (pool) sig::Element[used]);
2095 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2097 for (size_t index(signature.count); index != used; ++index) {
2098 sig::Element *element(&elements[index]);
2099 element->name = NULL;
2100 element->offset = _not(size_t);
2102 sig::Type *type(new (pool) sig::Type);
2103 memset(type, 0, sizeof(*type));
2104 type->primitive = sig::object_P;
2105 element->type = type;
2108 signature.elements = elements;
2109 signature.count = used;
2113 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2117 if (stret(cif.rtype))
2118 imp = class_getMethodImplementation_stret(_class, _cmd);
2120 imp = class_getMethodImplementation(_class, _cmd);
2122 objc_super super = {self, _class};
2123 imp = objc_msg_lookup_super(&super, _cmd);
2127 void (*function)() = reinterpret_cast<void (*)()>(imp);
2128 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2131 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2133 throw CYJSError(context, "too few arguments to objc_msgSend");
2143 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2144 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2145 self = internal->GetValue();
2146 _class = internal->class_;;
2147 uninitialized = false;
2148 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2149 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2150 self = internal->GetValue();
2152 uninitialized = internal->IsUninitialized();
2154 internal->value_ = nil;
2156 self = CYCastNSObject(pool, context, arguments[0]);
2158 uninitialized = false;
2162 return CYJSNull(context);
2164 _cmd = CYCastSEL(context, arguments[1]);
2166 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2169 /* Hook: objc_registerClassPair {{{ */
2170 #if defined(__APPLE__) && defined(__arm__) && 0
2171 // XXX: replace this with associated objects
2173 MSHook(void, CYDealloc, id self, SEL sel) {
2174 CYInternal *internal;
2175 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2176 if (internal != NULL)
2178 _CYDealloc(self, sel);
2181 MSHook(void, objc_registerClassPair, Class _class) {
2182 Class super(class_getSuperclass(_class));
2183 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2184 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2185 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2188 _objc_registerClassPair(_class);
2191 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2193 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2195 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2196 if (value == NULL || !CYIsClass(value))
2197 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2198 Class _class((Class) value);
2199 $objc_registerClassPair(_class);
2200 return CYJSUndefined(context);
2205 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2206 JSValueRef setup[count + 2];
2209 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2210 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2213 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2215 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2217 // XXX: handle Instance::Uninitialized?
2218 id self(CYCastNSObject(pool, context, _this));
2222 setup[1] = &internal->sel_;
2224 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2227 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2229 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2231 id self(CYCastNSObject(pool, context, arguments[0]));
2232 Class _class(CYCastClass(pool, context, arguments[1]));
2233 return cy::Super::Make(context, self, _class);
2236 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2238 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2240 const char *name(CYPoolCString(pool, context, arguments[0]));
2241 return CYMakeSelector(context, sel_registerName(name));
2244 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2246 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2247 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2248 return CYMakeInstance(context, self, false);
2251 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2252 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2253 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2256 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2257 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2258 Type_privateData *typical(internal->GetType());
2263 if (typical == NULL) {
2267 type = typical->type_;
2268 ffi = typical->ffi_;
2271 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2274 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2275 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2276 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2279 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2280 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2281 id self(internal->GetValue());
2282 if (!CYIsClass(self))
2283 return CYJSUndefined(context);
2284 return CYGetClassPrototype(context, self);
2287 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2288 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2289 id self(internal->GetValue());
2290 if (!CYIsClass(self))
2291 return CYJSUndefined(context);
2292 return Messages::Make(context, (Class) self);
2295 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2296 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2299 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2300 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2303 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2304 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2307 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2314 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2315 // XXX: check for support of cy$toJSON?
2316 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2318 } CYCatch return /*XXX*/ NULL; }
2320 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2321 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2324 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2325 id value(internal->GetValue());
2327 if (![value respondsToSelector:@selector(cy$JSValueInContext:)])
2330 if (JSValueRef result = [value cy$JSValueInContext:context])
2334 } CYCatch return /*XXX*/ NULL; }
2336 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2337 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2340 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2341 // XXX: but... but... THIS ISN'T A POINTER! :(
2342 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2343 } CYCatch return /*XXX*/ NULL; }
2345 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2346 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2349 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2350 id value(internal->GetValue());
2353 return CYCastJSValue(context, "nil");
2356 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2357 return CYCastJSValue(context, CYJSString(context, [value description]));
2359 } CYCatch return /*XXX*/ NULL; }
2361 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2362 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2363 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2366 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2367 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2370 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2371 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2372 const char *name(sel_getName(internal->GetValue()));
2375 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2376 return CYCastJSValue(context, CYJSString(context, string));
2378 } CYCatch return /*XXX*/ NULL; }
2380 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2382 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2385 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2386 SEL sel(internal->GetValue());
2388 objc_method *method;
2389 if (Class _class = CYCastClass(pool, context, arguments[0]))
2390 method = class_getInstanceMethod(_class, sel);
2394 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2395 return CYCastJSValue(context, CYJSString(type));
2397 return CYJSNull(context);
2400 static JSStaticValue Selector_staticValues[2] = {
2401 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2402 {NULL, NULL, NULL, 0}
2405 static JSStaticValue Instance_staticValues[5] = {
2406 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2407 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2408 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2409 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2410 {NULL, NULL, NULL, 0}
2413 static JSStaticFunction Instance_staticFunctions[7] = {
2414 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2415 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2416 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2417 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2418 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2419 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2423 static JSStaticFunction Internal_staticFunctions[2] = {
2424 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2428 static JSStaticFunction Selector_staticFunctions[5] = {
2429 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2430 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2431 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2432 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2436 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2437 apr_pool_t *pool(CYGetGlobalPool());
2439 Object_type = new(pool) Type_privateData("@");
2440 Selector_type = new(pool) Type_privateData(":");
2443 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2444 NSCFType_ = objc_getClass("NSCFType");
2445 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2446 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2447 NSZombie_ = objc_getClass("_NSZombie_");
2449 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2452 NSArray_ = objc_getClass("NSArray");
2453 NSDictionary_ = objc_getClass("NSDictionary");
2454 NSString_ = objc_getClass("NSString");
2455 Object_ = objc_getClass("Object");
2457 JSClassDefinition definition;
2459 definition = kJSClassDefinitionEmpty;
2460 definition.className = "Instance";
2461 definition.staticValues = Instance_staticValues;
2462 definition.staticFunctions = Instance_staticFunctions;
2463 definition.hasProperty = &Instance_hasProperty;
2464 definition.getProperty = &Instance_getProperty;
2465 definition.setProperty = &Instance_setProperty;
2466 definition.deleteProperty = &Instance_deleteProperty;
2467 definition.getPropertyNames = &Instance_getPropertyNames;
2468 definition.callAsConstructor = &Instance_callAsConstructor;
2469 definition.hasInstance = &Instance_hasInstance;
2470 definition.finalize = &CYFinalize;
2471 Instance_ = JSClassCreate(&definition);
2473 definition.className = "ArrayInstance";
2474 ArrayInstance_ = JSClassCreate(&definition);
2476 definition.className = "ObjectInstance";
2477 ObjectInstance_ = JSClassCreate(&definition);
2479 definition.className = "StringInstance";
2480 StringInstance_ = JSClassCreate(&definition);
2482 definition = kJSClassDefinitionEmpty;
2483 definition.className = "Internal";
2484 definition.staticFunctions = Internal_staticFunctions;
2485 definition.hasProperty = &Internal_hasProperty;
2486 definition.getProperty = &Internal_getProperty;
2487 definition.setProperty = &Internal_setProperty;
2488 definition.getPropertyNames = &Internal_getPropertyNames;
2489 definition.finalize = &CYFinalize;
2490 Internal_ = JSClassCreate(&definition);
2492 definition = kJSClassDefinitionEmpty;
2493 definition.className = "Message";
2494 definition.staticFunctions = cy::Functor::StaticFunctions;
2495 definition.callAsFunction = &Message_callAsFunction;
2496 definition.finalize = &CYFinalize;
2497 Message_ = JSClassCreate(&definition);
2499 definition = kJSClassDefinitionEmpty;
2500 definition.className = "Messages";
2501 definition.hasProperty = &Messages_hasProperty;
2502 definition.getProperty = &Messages_getProperty;
2503 definition.setProperty = &Messages_setProperty;
2504 #if 0 && OBJC_API_VERSION < 2
2505 definition.deleteProperty = &Messages_deleteProperty;
2507 definition.getPropertyNames = &Messages_getPropertyNames;
2508 definition.finalize = &CYFinalize;
2509 Messages_ = JSClassCreate(&definition);
2511 definition = kJSClassDefinitionEmpty;
2512 definition.className = "Selector";
2513 definition.staticValues = Selector_staticValues;
2514 definition.staticFunctions = Selector_staticFunctions;
2515 definition.callAsFunction = &Selector_callAsFunction;
2516 definition.finalize = &CYFinalize;
2517 Selector_ = JSClassCreate(&definition);
2519 definition = kJSClassDefinitionEmpty;
2520 definition.className = "Super";
2521 definition.staticFunctions = Internal_staticFunctions;
2522 definition.finalize = &CYFinalize;
2523 Super_ = JSClassCreate(&definition);
2525 definition = kJSClassDefinitionEmpty;
2526 definition.className = "ObjectiveC::Classes";
2527 definition.getProperty = &ObjectiveC_Classes_getProperty;
2528 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2529 ObjectiveC_Classes_ = JSClassCreate(&definition);
2531 definition = kJSClassDefinitionEmpty;
2532 definition.className = "ObjectiveC::Constants";
2533 definition.getProperty = &ObjectiveC_Constants_getProperty;
2534 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2535 ObjectiveC_Constants_ = JSClassCreate(&definition);
2537 #if OBJC_API_VERSION >= 2
2538 definition = kJSClassDefinitionEmpty;
2539 definition.className = "ObjectiveC::Images";
2540 definition.getProperty = &ObjectiveC_Images_getProperty;
2541 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2542 ObjectiveC_Images_ = JSClassCreate(&definition);
2544 definition = kJSClassDefinitionEmpty;
2545 definition.className = "ObjectiveC::Image::Classes";
2546 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2547 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2548 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2551 definition = kJSClassDefinitionEmpty;
2552 definition.className = "ObjectiveC::Protocols";
2553 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2554 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2555 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2557 #if defined(__APPLE__) && defined(__arm__) && 0
2558 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2562 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2566 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2567 JSObjectRef global(CYGetGlobalObject(context));
2568 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2569 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2570 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2571 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2573 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2574 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2576 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2577 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2578 CYArrayPush(context, alls, protocols);
2580 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2581 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2582 CYArrayPush(context, alls, classes);
2584 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2585 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2586 CYArrayPush(context, alls, constants);
2588 #if OBJC_API_VERSION >= 2
2589 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2592 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2593 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2594 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2595 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2597 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2598 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2600 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2601 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2602 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2603 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2604 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2606 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2607 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2608 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2609 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2610 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2612 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2613 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2614 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2615 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2616 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2618 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2619 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2620 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2622 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2623 CYSetProperty(context, Instance, CYJSString("box"), box);
2625 #if defined(__APPLE__) && defined(__arm__) && 0
2626 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2629 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2631 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2632 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2633 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2636 static CYHooks CYObjectiveCHooks = {
2637 &CYObjectiveC_ExecuteStart,
2638 &CYObjectiveC_ExecuteEnd,
2639 &CYObjectiveC_CallFunction,
2640 &CYObjectiveC_Initialize,
2641 &CYObjectiveC_SetupContext,
2642 &CYObjectiveC_PoolFFI,
2643 &CYObjectiveC_FromFFI,
2646 struct CYObjectiveC {
2648 hooks_ = &CYObjectiveCHooks;
2649 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2650 _assert(hooks_ != NULL);