1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2012 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"
53 #define CYObjectiveTry_(context) { \
54 JSContextRef context_(context); \
56 #define CYObjectiveTry { \
58 #define CYObjectiveCatch \
59 catch (const CYException &error) { \
60 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
66 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
68 #define CYPoolCatch(value) \
69 @catch (NSException *error) { \
70 _saved = [error retain]; \
71 throw CYJSError(context, CYCastJSValue(context, error)); \
76 [_saved autorelease]; \
82 #define CYSadCatch(value) \
83 @catch (NSException *error ) { \
84 throw CYJSError(context, CYCastJSValue(context, error)); \
89 #define class_getSuperclass GSObjCSuper
90 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
91 #define class_getName GSNameFromClass
93 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
95 #define ivar_getName(ivar) ((ivar)->ivar_name)
96 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
97 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
99 #define method_getName(method) ((method)->method_name)
100 #define method_getImplementation(method) ((method)->method_imp)
101 #define method_getTypeEncoding(method) ((method)->method_types)
102 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
105 #define objc_getClass GSClassFromName
107 #define objc_getProtocol GSProtocolFromName
109 #define object_getClass GSObjCClass
111 #define object_getInstanceVariable(object, name, value) ({ \
112 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
113 _assert(value != NULL); \
115 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
119 #define object_setIvar(object, ivar, value) ({ \
120 void *data = (value); \
121 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
124 #define protocol_getName(protocol) [(protocol) name]
127 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
128 static id (*$objc_getAssociatedObject)(id object, void *key);
129 static void (*$objc_removeAssociatedObjects)(id object);
131 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
133 /* Objective-C Pool Release {{{ */
134 apr_status_t CYPoolRelease_(void *data) {
135 id object(reinterpret_cast<id>(data));
140 id CYPoolRelease_(apr_pool_t *pool, id object) {
143 else if (pool == NULL)
144 return [object autorelease];
146 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
151 template <typename Type_>
152 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
153 return (Type_) CYPoolRelease_(pool, (id) object);
156 /* Objective-C Strings {{{ */
157 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
159 return [value UTF8String];
161 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
162 char *string(new(pool) char[size]);
163 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
164 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
169 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
171 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
174 return CYCopyJSString(CYPoolCString(pool, context, value));
178 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
181 // XXX: this definition scares me; is anyone using this?!
182 NSString *string([value description]);
183 return CYCopyJSString(context, string);
186 NSString *CYCopyNSString(const CYUTF8String &value) {
188 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
190 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
194 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
196 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
199 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
203 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
204 return CYCopyNSString(context, CYJSString(context, value));
207 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
208 return CYPoolRelease(pool, CYCopyNSString(value));
211 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
212 const char *name(sel_getName(sel));
213 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
216 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
217 return CYPoolRelease(pool, CYCopyNSString(context, value));
220 CYUTF8String CYCastUTF8String(NSString *value) {
221 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
222 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
226 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
228 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
229 if (exception == NULL)
231 *exception = CYCastJSValue(context, error);
234 size_t CYGetIndex(NSString *value) {
235 return CYGetIndex(CYCastUTF8String(value));
238 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
239 return CYGetOffset(CYPoolCString(pool, context, value), index);
242 static JSClassRef Instance_;
244 static JSClassRef ArrayInstance_;
245 static JSClassRef FunctionInstance_;
246 static JSClassRef ObjectInstance_;
247 static JSClassRef StringInstance_;
249 static JSClassRef Internal_;
250 static JSClassRef Message_;
251 static JSClassRef Messages_;
252 static JSClassRef Selector_;
253 static JSClassRef Super_;
255 static JSClassRef ObjectiveC_Classes_;
256 static JSClassRef ObjectiveC_Constants_;
257 static JSClassRef ObjectiveC_Protocols_;
260 static JSClassRef ObjectiveC_Image_Classes_;
261 static JSClassRef ObjectiveC_Images_;
265 static Class NSCFBoolean_;
266 static Class NSCFType_;
267 static Class NSGenericDeallocHandler_;
268 static Class NSMessageBuilder_;
269 static Class NSZombie_;
271 static Class NSBoolNumber_;
274 static Class NSArray_;
275 static Class NSBlock_;
276 static Class NSDictionary_;
277 static Class NSString_;
278 static Class Object_;
280 static Type_privateData *Object_type;
281 static Type_privateData *Selector_type;
283 Type_privateData *Instance::GetType() const {
287 Type_privateData *Selector_privateData::GetType() const {
288 return Selector_type;
291 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
293 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
295 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
297 JSObjectRef global(CYGetGlobalObject(context));
298 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
301 sprintf(label, "i%p", self);
302 CYJSString name(label);
304 JSValueRef value(CYGetProperty(context, cy, name));
305 if (!JSValueIsUndefined(context, value))
308 JSClassRef _class(NULL);
309 JSValueRef prototype;
311 if (self == NSArray_)
312 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
313 else if (self == NSBlock_)
314 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
315 else if (self == NSDictionary_)
316 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
317 else if (self == NSString_)
318 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
320 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
322 JSObjectRef object(JSObjectMake(context, _class, NULL));
323 JSObjectSetPrototype(context, object, prototype);
324 CYSetProperty(context, cy, name, object);
329 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
330 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
331 if (Class super = class_getSuperclass(_class))
332 JSObjectSetPrototype(context, value, Messages::Make(context, super));
336 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
337 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
341 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
342 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
346 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
347 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
348 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
352 Instance::~Instance() {
353 if ((flags_ & Transient) == 0)
354 // XXX: does this handle background threads correctly?
355 // XXX: this simply does not work on the console because I'm stupid
356 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
359 struct Message_privateData :
364 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
365 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
371 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
372 Instance::Flags flags;
375 flags = Instance::Transient;
377 flags = Instance::None;
378 object = [object retain];
381 return Instance::Make(context, object, flags);
384 @interface NSMethodSignature (Cycript)
385 - (NSString *) _typeString;
388 @interface NSObject (Cycript)
390 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
391 - (JSType) cy$JSType;
393 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
394 - (NSString *) cy$toCYON:(bool)objective;
396 - (bool) cy$hasProperty:(NSString *)name;
397 - (NSObject *) cy$getProperty:(NSString *)name;
398 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
399 - (bool) cy$deleteProperty:(NSString *)name;
400 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
402 + (bool) cy$hasImplicitProperties;
408 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
411 NSString *CYCastNSCYON(id value, bool objective) {
417 Class _class(object_getClass(value));
418 SEL sel(@selector(cy$toCYON:));
420 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
421 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
422 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
423 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
424 string = [value cy$toCYON:objective];
429 else if (value == NSZombie_)
430 string = @"_NSZombie_";
431 else if (_class == NSZombie_)
432 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
433 // XXX: frowny /in/ the pants
434 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
438 string = [NSString stringWithFormat:@"%@", value];
443 string = @"undefined";
450 struct PropertyAttributes {
455 const char *variable;
468 PropertyAttributes(objc_property_t property) :
480 name = property_getName(property);
481 const char *attributes(property_getAttributes(property));
483 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
485 case 'R': readonly = true; break;
486 case 'C': copy = true; break;
487 case '&': retain = true; break;
488 case 'N': nonatomic = true; break;
489 case 'G': getter_ = token + 1; break;
490 case 'S': setter_ = token + 1; break;
491 case 'V': variable = token + 1; break;
495 /*if (variable == NULL) {
496 variable = property_getName(property);
497 size_t size(strlen(variable));
498 char *name(new(pool_) char[size + 2]);
500 memcpy(name + 1, variable, size);
501 name[size + 1] = '\0';
506 const char *Getter() {
508 getter_ = apr_pstrdup(pool_, name);
512 const char *Setter() {
513 if (setter_ == NULL && !readonly) {
514 size_t length(strlen(name));
516 char *temp(new(pool_) char[length + 5]);
522 temp[3] = toupper(name[0]);
523 memcpy(temp + 4, name + 1, length - 1);
526 temp[length + 3] = ':';
527 temp[length + 4] = '\0';
538 @interface CYWebUndefined : NSObject {
541 + (CYWebUndefined *) undefined;
545 @implementation CYWebUndefined
547 + (CYWebUndefined *) undefined {
548 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
554 #define WebUndefined CYWebUndefined
557 /* Bridge: CYJSObject {{{ */
558 @interface CYJSObject : NSMutableDictionary {
560 JSGlobalContextRef context_;
563 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
565 - (NSUInteger) count;
566 - (id) objectForKey:(id)key;
567 - (NSEnumerator *) keyEnumerator;
568 - (void) setObject:(id)object forKey:(id)key;
569 - (void) removeObjectForKey:(id)key;
573 /* Bridge: CYJSArray {{{ */
574 @interface CYJSArray : NSMutableArray {
576 JSGlobalContextRef context_;
579 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
581 - (NSUInteger) count;
582 - (id) objectAtIndex:(NSUInteger)index;
584 - (void) addObject:(id)anObject;
585 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
586 - (void) removeLastObject;
587 - (void) removeObjectAtIndex:(NSUInteger)index;
588 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
593 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
594 return JSValueIsObjectOfClass(context, value, Instance_);
597 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
598 JSValueRef exception(NULL);
599 JSObjectRef constructor(CYGetCachedObject(context, cache));
600 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
601 CYThrow(context, exception);
605 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
606 if (CYJSValueIsNSObject(context, object)) {
607 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
608 return internal->GetValue();
611 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
612 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
613 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
616 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
617 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
621 @interface NSBoolNumber : NSNumber {
626 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
630 switch (JSType type = JSValueGetType(context, value)) {
631 case kJSTypeUndefined:
632 object = [WebUndefined undefined];
642 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
645 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
651 object = CYCopyNSNumber(context, value);
656 object = CYCopyNSString(context, value);
661 // XXX: this might could be more efficient
662 object = CYCastNSObject(pool, context, (JSObjectRef) value);
667 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
674 return CYPoolRelease(pool, object);
676 return [object retain];
679 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
680 return CYNSObject(pool, context, value, true);
683 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
684 return CYNSObject(pool, context, value, false);
687 /* Bridge: NSArray {{{ */
688 @implementation NSArray (Cycript)
691 return [[self mutableCopy] autorelease];
694 - (NSString *) cy$toCYON:(bool)objective {
695 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
696 [json appendString:@"@["];
700 for (id object in self) {
702 for (size_t index(0), count([self count]); index != count; ++index) {
703 id object([self objectAtIndex:index]);
706 [json appendString:@","];
709 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
710 [json appendString:CYCastNSCYON(object, true)];
712 [json appendString:@","];
717 [json appendString:@"]"];
721 - (bool) cy$hasProperty:(NSString *)name {
722 if ([name isEqualToString:@"length"])
725 size_t index(CYGetIndex(name));
726 if (index == _not(size_t) || index >= [self count])
727 return [super cy$hasProperty:name];
732 - (NSObject *) cy$getProperty:(NSString *)name {
733 if ([name isEqualToString:@"length"]) {
734 NSUInteger count([self count]);
736 return [NSNumber numberWithUnsignedInteger:count];
738 return [NSNumber numberWithUnsignedInt:count];
742 size_t index(CYGetIndex(name));
743 if (index == _not(size_t) || index >= [self count])
744 return [super cy$getProperty:name];
746 return [self objectAtIndex:index];
749 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
750 [super cy$getPropertyNames:names inContext:context];
752 for (size_t index(0), count([self count]); index != count; ++index) {
753 id object([self objectAtIndex:index]);
754 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
756 sprintf(name, "%zu", index);
757 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
762 + (bool) cy$hasImplicitProperties {
768 /* Bridge: NSBlock {{{ */
775 /* Bridge: NSBoolNumber {{{ */
777 @implementation NSBoolNumber (Cycript)
779 - (JSType) cy$JSType {
780 return kJSTypeBoolean;
783 - (NSString *) cy$toCYON:(bool)objective {
784 NSString *value([self boolValue] ? @"true" : @"false");
785 return objective ? value : [NSString stringWithFormat:@"@%@", value];
788 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
789 return CYCastJSValue(context, (bool) [self boolValue]);
795 /* Bridge: NSDictionary {{{ */
796 @implementation NSDictionary (Cycript)
799 return [[self mutableCopy] autorelease];
802 - (NSString *) cy$toCYON:(bool)objective {
803 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
804 [json appendString:@"@{"];
808 for (NSObject *key in self) {
810 NSEnumerator *keys([self keyEnumerator]);
811 while (NSObject *key = [keys nextObject]) {
814 [json appendString:@","];
817 [json appendString:CYCastNSCYON(key, true)];
818 [json appendString:@":"];
819 NSObject *object([self objectForKey:key]);
820 [json appendString:CYCastNSCYON(object, true)];
823 [json appendString:@"}"];
827 - (bool) cy$hasProperty:(NSString *)name {
828 return [self objectForKey:name] != nil;
831 - (NSObject *) cy$getProperty:(NSString *)name {
832 return [self objectForKey:name];
835 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
836 [super cy$getPropertyNames:names inContext:context];
839 for (NSObject *key in self) {
841 NSEnumerator *keys([self keyEnumerator]);
842 while (NSObject *key = [keys nextObject]) {
844 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
848 + (bool) cy$hasImplicitProperties {
854 /* Bridge: NSMutableArray {{{ */
855 @implementation NSMutableArray (Cycript)
857 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
858 if ([name isEqualToString:@"length"]) {
859 // XXX: is this not intelligent?
860 NSNumber *number(reinterpret_cast<NSNumber *>(value));
862 NSUInteger size([number unsignedIntegerValue]);
864 NSUInteger size([number unsignedIntValue]);
866 NSUInteger count([self count]);
868 [self removeObjectsInRange:NSMakeRange(size, count - size)];
869 else if (size != count) {
870 WebUndefined *undefined([WebUndefined undefined]);
871 for (size_t i(count); i != size; ++i)
872 [self addObject:undefined];
877 size_t index(CYGetIndex(name));
878 if (index == _not(size_t))
879 return [super cy$setProperty:name to:value];
881 id object(value ?: [NSNull null]);
883 size_t count([self count]);
885 [self replaceObjectAtIndex:index withObject:object];
887 if (index != count) {
888 WebUndefined *undefined([WebUndefined undefined]);
889 for (size_t i(count); i != index; ++i)
890 [self addObject:undefined];
893 [self addObject:object];
899 - (bool) cy$deleteProperty:(NSString *)name {
900 size_t index(CYGetIndex(name));
901 if (index == _not(size_t) || index >= [self count])
902 return [super cy$deleteProperty:name];
903 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
909 /* Bridge: NSMutableDictionary {{{ */
910 @implementation NSMutableDictionary (Cycript)
912 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
913 [self setObject:(value ?: [NSNull null]) forKey:name];
917 - (bool) cy$deleteProperty:(NSString *)name {
918 if ([self objectForKey:name] == nil)
921 [self removeObjectForKey:name];
928 /* Bridge: NSNumber {{{ */
929 @implementation NSNumber (Cycript)
931 - (JSType) cy$JSType {
933 // XXX: this just seems stupid
934 if ([self class] == NSCFBoolean_)
935 return kJSTypeBoolean;
937 return kJSTypeNumber;
940 - (NSString *) cy$toCYON:(bool)objective {
941 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
942 return objective ? value : [NSString stringWithFormat:@"@%@", value];
945 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
946 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
951 /* Bridge: NSNull {{{ */
952 @implementation NSNull (Cycript)
954 - (JSType) cy$JSType {
958 - (NSString *) cy$toCYON:(bool)objective {
959 NSString *value(@"null");
960 return objective ? value : [NSString stringWithFormat:@"@%@", value];
963 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
964 return CYJSNull(context);
969 /* Bridge: NSObject {{{ */
970 @implementation NSObject (Cycript)
976 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
977 return [self cy$valueOfInContext:context];
980 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
984 - (JSType) cy$JSType {
985 return kJSTypeObject;
988 - (NSString *) cy$toCYON:(bool)objective {
989 return [[self description] cy$toCYON:objective];
992 - (bool) cy$hasProperty:(NSString *)name {
996 - (NSObject *) cy$getProperty:(NSString *)name {
1000 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1004 - (bool) cy$deleteProperty:(NSString *)name {
1008 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1011 + (bool) cy$hasImplicitProperties {
1017 /* Bridge: NSProxy {{{ */
1018 @implementation NSProxy (Cycript)
1020 - (NSString *) cy$toCYON:(bool)objective {
1021 return [[self description] cy$toCYON:objective];
1026 /* Bridge: NSString {{{ */
1027 @implementation NSString (Cycript)
1030 return [[self copy] autorelease];
1033 - (JSType) cy$JSType {
1034 return kJSTypeString;
1037 - (NSString *) cy$toCYON:(bool)objective {
1038 std::ostringstream str;
1041 CYUTF8String string(CYCastUTF8String(self));
1042 CYStringify(str, string.data, string.size);
1043 std::string value(str.str());
1044 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1047 - (bool) cy$hasProperty:(NSString *)name {
1048 if ([name isEqualToString:@"length"])
1051 size_t index(CYGetIndex(name));
1052 if (index == _not(size_t) || index >= [self length])
1053 return [super cy$hasProperty:name];
1058 - (NSObject *) cy$getProperty:(NSString *)name {
1059 if ([name isEqualToString:@"length"]) {
1060 NSUInteger count([self length]);
1062 return [NSNumber numberWithUnsignedInteger:count];
1064 return [NSNumber numberWithUnsignedInt:count];
1068 size_t index(CYGetIndex(name));
1069 if (index == _not(size_t) || index >= [self length])
1070 return [super cy$getProperty:name];
1072 return [self substringWithRange:NSMakeRange(index, 1)];
1075 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1076 [super cy$getPropertyNames:names inContext:context];
1078 for (size_t index(0), length([self length]); index != length; ++index) {
1080 sprintf(name, "%zu", index);
1081 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1085 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1086 + (bool) cy$hasImplicitProperties {
1090 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1091 return CYCastJSValue(context, CYJSString(context, self));
1092 } CYObjectiveCatch }
1096 /* Bridge: WebUndefined {{{ */
1097 @implementation WebUndefined (Cycript)
1099 - (JSType) cy$JSType {
1100 return kJSTypeUndefined;
1103 - (NSString *) cy$toCYON {
1104 NSString *value(@"undefined");
1105 return value; // XXX: maybe use the below code, adding @undefined?
1106 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1109 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1110 return CYJSUndefined(context);
1111 } CYObjectiveCatch }
1116 static bool CYIsClass(id self) {
1118 return class_isMetaClass(object_getClass(self));
1120 return GSObjCIsClass(self);
1124 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1125 id self(CYCastNSObject(pool, context, value));
1126 if (CYIsClass(self))
1127 return (Class) self;
1128 throw CYJSError(context, "got something that is not a Class");
1132 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1134 size_t size(JSPropertyNameArrayGetCount(names));
1135 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1136 for (size_t index(0); index != size; ++index)
1137 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1141 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1143 return CYJSNull(context);
1145 return CYMakeInstance(context, value, false);
1146 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1148 @implementation CYJSObject
1150 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1151 if ((self = [super init]) != nil) {
1153 context_ = CYGetJSContext(context);
1154 JSGlobalContextRetain(context_);
1155 JSValueProtect(context_, object_);
1157 } CYObjectiveCatch }
1159 - (void) dealloc { CYObjectiveTry {
1160 JSValueUnprotect(context_, object_);
1161 JSGlobalContextRelease(context_);
1163 } CYObjectiveCatch }
1165 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1167 JSValueRef exception(NULL);
1168 const char *cyon(CYPoolCCYON(pool, context_, object_));
1169 CYThrow(context_, exception);
1171 return [super cy$toCYON:objective];
1173 return [NSString stringWithUTF8String:cyon];
1174 } CYObjectiveCatch }
1176 - (NSUInteger) count { CYObjectiveTry {
1177 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1178 size_t size(JSPropertyNameArrayGetCount(names));
1179 JSPropertyNameArrayRelease(names);
1181 } CYObjectiveCatch }
1183 - (id) objectForKey:(id)key { CYObjectiveTry {
1184 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1185 if (JSValueIsUndefined(context_, value))
1187 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1188 } CYObjectiveCatch }
1190 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1191 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1192 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1193 JSPropertyNameArrayRelease(names);
1195 } CYObjectiveCatch }
1197 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1198 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1199 } CYObjectiveCatch }
1201 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1202 JSValueRef exception(NULL);
1203 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1204 CYThrow(context_, exception);
1205 } CYObjectiveCatch }
1209 @implementation CYJSArray
1211 - (NSString *) cy$toCYON:(bool)objective {
1213 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1216 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1217 if ((self = [super init]) != nil) {
1219 context_ = CYGetJSContext(context);
1220 JSGlobalContextRetain(context_);
1221 JSValueProtect(context_, object_);
1223 } CYObjectiveCatch }
1225 - (void) dealloc { CYObjectiveTry {
1226 JSValueUnprotect(context_, object_);
1227 JSGlobalContextRelease(context_);
1229 } CYObjectiveCatch }
1231 - (NSUInteger) count { CYObjectiveTry {
1232 return CYArrayLength(context_, object_);
1233 } CYObjectiveCatch }
1235 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1236 size_t bounds([self count]);
1237 if (index >= bounds)
1238 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1239 JSValueRef exception(NULL);
1240 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1241 CYThrow(context_, exception);
1242 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1243 } CYObjectiveCatch }
1245 - (void) addObject:(id)object { CYObjectiveTry {
1246 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1247 } CYObjectiveCatch }
1249 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1250 size_t bounds([self count] + 1);
1251 if (index >= bounds)
1252 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1253 JSValueRef exception(NULL);
1254 JSValueRef arguments[3];
1255 arguments[0] = CYCastJSValue(context_, index);
1256 arguments[1] = CYCastJSValue(context_, 0);
1257 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1258 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1259 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1260 CYThrow(context_, exception);
1261 } CYObjectiveCatch }
1263 - (void) removeLastObject { CYObjectiveTry {
1264 JSValueRef exception(NULL);
1265 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1266 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1267 CYThrow(context_, exception);
1268 } CYObjectiveCatch }
1270 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1271 size_t bounds([self count]);
1272 if (index >= bounds)
1273 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1274 JSValueRef exception(NULL);
1275 JSValueRef arguments[2];
1276 arguments[0] = CYCastJSValue(context_, index);
1277 arguments[1] = CYCastJSValue(context_, 1);
1278 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1279 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1280 CYThrow(context_, exception);
1281 } CYObjectiveCatch }
1283 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1284 size_t bounds([self count]);
1285 if (index >= bounds)
1286 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1287 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1288 } CYObjectiveCatch }
1292 // XXX: inherit from or replace with CYJSObject
1293 @interface CYInternal : NSObject {
1294 JSGlobalContextRef context_;
1295 JSObjectRef object_;
1300 @implementation CYInternal
1303 JSValueUnprotect(context_, object_);
1304 JSGlobalContextRelease(context_);
1308 - (id) initInContext:(JSContextRef)context {
1309 if ((self = [super init]) != nil) {
1310 context_ = CYGetJSContext(context);
1311 JSGlobalContextRetain(context_);
1315 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1316 if (object_ == NULL)
1319 return JSObjectHasProperty(context, object_, name);
1322 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1323 if (object_ == NULL)
1326 return CYGetProperty(context, object_, name);
1329 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1330 @synchronized (self) {
1331 if (object_ == NULL) {
1332 object_ = JSObjectMake(context, NULL, NULL);
1333 JSValueProtect(context, object_);
1337 CYSetProperty(context, object_, name, value);
1340 + (CYInternal *) get:(id)object {
1341 if ($objc_getAssociatedObject == NULL)
1344 @synchronized (object) {
1345 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1352 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1353 if ($objc_getAssociatedObject == NULL)
1356 @synchronized (object) {
1357 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1360 if ($objc_setAssociatedObject == NULL)
1363 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1364 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1373 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1374 Selector_privateData *internal(new Selector_privateData(sel));
1375 return JSObjectMake(context, Selector_, internal);
1378 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1379 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1380 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1381 return reinterpret_cast<SEL>(internal->value_);
1383 return CYCastPointer<SEL>(context, value);
1386 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1387 return (void *) [[NSAutoreleasePool alloc] init];
1388 } CYSadCatch(NULL) }
1390 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1391 return [(NSAutoreleasePool *) handle release];
1394 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1396 return Instance::Make(context, nil);
1397 if (Class _class = objc_getClass(name.data))
1398 return CYMakeInstance(context, _class, true);
1399 if (Protocol *protocol = objc_getProtocol(name.data))
1400 return CYMakeInstance(context, protocol, true);
1402 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1404 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1405 ffi_call(cif, function, value, values);
1408 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1409 switch (type->primitive) {
1410 // XXX: do something epic about blocks
1413 case sig::typename_P:
1414 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1417 case sig::selector_P:
1418 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1426 } CYSadCatch(false) }
1428 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1429 switch (type->primitive) {
1430 // XXX: do something epic about blocks
1433 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1434 JSValueRef value(CYCastJSValue(context, object));
1440 case sig::typename_P:
1441 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1443 case sig::selector_P:
1444 if (SEL sel = *reinterpret_cast<SEL *>(data))
1445 return CYMakeSelector(context, sel);
1449 return CYJSNull(context);
1453 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1455 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1456 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1459 #if OBJC_API_VERSION >= 2
1461 method_getReturnType(method, type, sizeof(type));
1463 const char *type(method_getTypeEncoding(method));
1469 // XXX: possibly use a more "awesome" check?
1473 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1475 return method_getTypeEncoding(method);
1477 const char *name(sel_getName(sel));
1478 size_t length(strlen(name));
1480 char keyed[length + 2];
1482 keyed[length + 1] = '\0';
1483 memcpy(keyed + 1, name, length);
1485 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1486 return entry->value_;
1491 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1492 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1494 JSContextRef context(internal->context_);
1496 size_t count(internal->cif_.nargs);
1497 JSValueRef values[count];
1499 for (size_t index(0); index != count; ++index)
1500 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1502 JSObjectRef _this(CYCastJSObject(context, values[0]));
1504 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1505 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1508 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1509 Message_privateData *internal(new Message_privateData(sel, type, imp));
1510 return JSObjectMake(context, Message_, internal);
1513 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1514 JSObjectRef function(CYCastJSObject(context, value));
1515 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1516 // XXX: see notes in Library.cpp about needing to leak
1517 return reinterpret_cast<IMP>(internal->GetValue());
1520 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1521 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1522 Class _class(internal->GetValue());
1525 const char *name(CYPoolCString(pool, context, property));
1527 if (SEL sel = sel_getUid(name))
1528 if (class_getInstanceMethod(_class, sel) != NULL)
1534 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1535 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1536 Class _class(internal->GetValue());
1539 const char *name(CYPoolCString(pool, context, property));
1541 if (SEL sel = sel_getUid(name))
1542 if (objc_method *method = class_getInstanceMethod(_class, sel))
1543 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1548 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1549 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1550 Class _class(internal->GetValue());
1553 const char *name(CYPoolCString(pool, context, property));
1555 SEL sel(sel_registerName(name));
1557 objc_method *method(class_getInstanceMethod(_class, sel));
1562 if (JSValueIsObjectOfClass(context, value, Message_)) {
1563 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1564 type = sig::Unparse(pool, &message->signature_);
1565 imp = reinterpret_cast<IMP>(message->GetValue());
1567 type = CYPoolTypeEncoding(pool, context, sel, method);
1568 imp = CYMakeMessage(context, value, type);
1572 method_setImplementation(method, imp);
1575 GSMethodList list(GSAllocMethodList(1));
1576 GSAppendMethodToList(list, sel, type, imp, YES);
1577 GSAddMethodList(_class, list, YES);
1578 GSFlushMethodCacheForClass(_class);
1580 class_addMethod(_class, sel, imp, type);
1587 #if 0 && OBJC_API_VERSION < 2
1588 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1589 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1590 Class _class(internal->GetValue());
1593 const char *name(CYPoolCString(pool, context, property));
1595 if (SEL sel = sel_getUid(name))
1596 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1597 objc_method_list list = {NULL, 1, {method}};
1598 class_removeMethods(_class, &list);
1606 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1607 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1608 Class _class(internal->GetValue());
1610 #if OBJC_API_VERSION >= 2
1612 objc_method **data(class_copyMethodList(_class, &size));
1613 for (size_t i(0); i != size; ++i)
1614 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1617 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1618 for (int i(0); i != methods->method_count; ++i)
1619 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1623 static bool CYHasImplicitProperties(Class _class) {
1624 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1625 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1627 return [_class cy$hasImplicitProperties];
1630 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1631 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1632 id self(internal->GetValue());
1634 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1638 NSString *name(CYCastNSString(pool, context, property));
1640 if (CYInternal *internal = [CYInternal get:self])
1641 if ([internal hasProperty:property inContext:context])
1644 Class _class(object_getClass(self));
1647 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1648 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1649 if ([self cy$hasProperty:name])
1651 } CYPoolCatch(false)
1653 const char *string(CYPoolCString(pool, context, name));
1656 if (class_getProperty(_class, string) != NULL)
1660 if (CYHasImplicitProperties(_class))
1661 if (SEL sel = sel_getUid(string))
1662 if (CYImplements(self, _class, sel, true))
1668 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1669 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1670 id self(internal->GetValue());
1672 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1673 return Internal::Make(context, self, object);
1676 NSString *name(CYCastNSString(pool, context, property));
1678 if (CYInternal *internal = [CYInternal get:self])
1679 if (JSValueRef value = [internal getProperty:property inContext:context])
1683 if (NSObject *data = [self cy$getProperty:name])
1684 return CYCastJSValue(context, data);
1687 const char *string(CYPoolCString(pool, context, name));
1688 Class _class(object_getClass(self));
1691 if (objc_property_t property = class_getProperty(_class, string)) {
1692 PropertyAttributes attributes(property);
1693 SEL sel(sel_registerName(attributes.Getter()));
1694 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1698 if (CYHasImplicitProperties(_class))
1699 if (SEL sel = sel_getUid(string))
1700 if (CYImplements(self, _class, sel, true))
1701 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1706 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1707 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1708 id self(internal->GetValue());
1712 NSString *name(CYCastNSString(pool, context, property));
1713 NSObject *data(CYCastNSObject(pool, context, value));
1716 if ([self cy$setProperty:name to:data])
1720 const char *string(CYPoolCString(pool, context, name));
1721 Class _class(object_getClass(self));
1724 if (objc_property_t property = class_getProperty(_class, string)) {
1725 PropertyAttributes attributes(property);
1726 if (const char *setter = attributes.Setter()) {
1727 SEL sel(sel_registerName(setter));
1728 JSValueRef arguments[1] = {value};
1729 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1735 size_t length(strlen(string));
1737 char set[length + 5];
1743 if (string[0] != '\0') {
1744 set[3] = toupper(string[0]);
1745 memcpy(set + 4, string + 1, length - 1);
1748 set[length + 3] = ':';
1749 set[length + 4] = '\0';
1751 if (SEL sel = sel_getUid(set))
1752 if (CYImplements(self, _class, sel)) {
1753 JSValueRef arguments[1] = {value};
1754 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1758 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1759 [internal setProperty:property toValue:value inContext:context];
1766 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1767 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1768 id self(internal->GetValue());
1771 NSString *name(CYCastNSString(NULL, context, property));
1772 return [self cy$deleteProperty:name];
1774 } CYCatch return /*XXX*/ NULL; }
1776 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1777 const char *name(sel_getName(method_getName(method)));
1778 if (strchr(name, ':') != NULL)
1781 const char *type(method_getTypeEncoding(method));
1782 if (type == NULL || *type == '\0' || *type == 'v')
1785 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1788 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1789 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1790 id self(internal->GetValue());
1793 Class _class(object_getClass(self));
1798 objc_property_t *data(class_copyPropertyList(_class, &size));
1799 for (size_t i(0); i != size; ++i)
1800 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1805 if (CYHasImplicitProperties(_class))
1806 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1807 #if OBJC_API_VERSION >= 2
1809 objc_method **data(class_copyMethodList(current, &size));
1810 for (size_t i(0); i != size; ++i)
1811 Instance_getPropertyNames_message(names, data[i]);
1814 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1815 for (int i(0); i != methods->method_count; ++i)
1816 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1821 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1822 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1823 [self cy$getPropertyNames:names inContext:context];
1827 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1828 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1829 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1833 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1834 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1835 id self(internal->GetValue());
1837 if (![self isKindOfClass:NSBlock_])
1838 CYThrow("non-NSBlock object is not a function");
1839 // XXX: replace above logic with the following assertion
1840 //_assert([self isKindOfClass:NSBlock_]);
1841 // to do this, make it so FunctionInstance_ is the class of blocks
1842 // to do /that/, generalize the various "is exactly Instance_" checks
1843 // then, move Instance_callAsFunction to only be on FunctionInstance
1845 struct BlockDescriptor1 {
1846 unsigned long int reserved;
1847 unsigned long int size;
1850 struct BlockDescriptor2 {
1851 void (*copy_helper)(void *dst, void *src);
1852 void (*dispose_helper)(void *src);
1855 struct BlockDescriptor3 {
1856 const char *signature;
1860 struct BlockLiteral {
1864 void (*invoke)(void *, ...);
1866 } *literal = reinterpret_cast<BlockLiteral *>(self);
1869 BLOCK_DEALLOCATING = 0x0001,
1870 BLOCK_REFCOUNT_MASK = 0xfffe,
1871 BLOCK_NEEDS_FREE = 1 << 24,
1872 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1873 BLOCK_HAS_CTOR = 1 << 26,
1874 BLOCK_IS_GC = 1 << 27,
1875 BLOCK_IS_GLOBAL = 1 << 28,
1876 BLOCK_HAS_STRET = 1 << 29,
1877 BLOCK_HAS_SIGNATURE = 1 << 30,
1880 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1881 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1882 descriptor += sizeof(BlockDescriptor1);
1883 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1884 descriptor += sizeof(BlockDescriptor2);
1885 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1887 if (const char *type = descriptor3->signature) {
1893 sig::Signature signature;
1894 sig::Parse(pool, &signature, type, &Structor_);
1897 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1899 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1900 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1905 CYThrow("NSBlock without signature field passed arguments");
1909 } CYPoolCatch(NULL);
1914 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1915 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1916 Class _class(internal->GetValue());
1917 if (!CYIsClass(_class))
1920 if (CYJSValueIsNSObject(context, instance)) {
1921 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1922 // XXX: this isn't always safe
1923 return [linternal->GetValue() isKindOfClass:_class];
1929 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1931 throw CYJSError(context, "incorrect number of arguments to Instance");
1933 id value(CYCastNSObject(pool, context, arguments[0]));
1935 value = [NSNull null];
1936 return CYCastJSValue(context, [value cy$box]);
1939 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1940 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1943 id self(internal->GetValue());
1944 const char *name(CYPoolCString(pool, context, property));
1946 if (object_getInstanceVariable(self, name, NULL) != NULL)
1952 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1953 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1956 id self(internal->GetValue());
1957 const char *name(CYPoolCString(pool, context, property));
1959 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1960 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1961 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1962 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1968 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1969 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1972 id self(internal->GetValue());
1973 const char *name(CYPoolCString(pool, context, property));
1975 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1976 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1977 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1984 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1985 if (Class super = class_getSuperclass(_class))
1986 Internal_getPropertyNames_(super, names);
1988 #if OBJC_API_VERSION >= 2
1990 objc_ivar **data(class_copyIvarList(_class, &size));
1991 for (size_t i(0); i != size; ++i)
1992 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1995 if (objc_ivar_list *ivars = _class->ivars)
1996 for (int i(0); i != ivars->ivar_count; ++i)
1997 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2001 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2002 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2005 id self(internal->GetValue());
2006 Class _class(object_getClass(self));
2008 Internal_getPropertyNames_(_class, names);
2011 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2012 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2013 return internal->GetOwner();
2016 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2018 NSString *name(CYCastNSString(pool, context, property));
2019 if (Class _class = NSClassFromString(name))
2020 return CYMakeInstance(context, _class, true);
2024 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2026 size_t size(objc_getClassList(NULL, 0));
2027 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2030 size_t writ(objc_getClassList(data, size));
2033 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2039 for (size_t i(0); i != writ; ++i)
2040 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2046 while (Class _class = objc_next_class(&state))
2047 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2051 #if OBJC_API_VERSION >= 2
2052 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2053 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2056 const char *name(CYPoolCString(pool, context, property));
2058 const char **data(objc_copyClassNamesForImage(internal, &size));
2060 for (size_t i(0); i != size; ++i)
2061 if (strcmp(name, data[i]) == 0) {
2062 if (Class _class = objc_getClass(name)) {
2063 value = CYMakeInstance(context, _class, true);
2074 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2075 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2077 const char **data(objc_copyClassNamesForImage(internal, &size));
2078 for (size_t i(0); i != size; ++i)
2079 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2083 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2085 const char *name(CYPoolCString(pool, context, property));
2087 const char **data(objc_copyImageNames(&size));
2088 for (size_t i(0); i != size; ++i)
2089 if (strcmp(name, data[i]) == 0) {
2098 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2099 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2103 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2105 const char **data(objc_copyImageNames(&size));
2106 for (size_t i(0); i != size; ++i)
2107 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2112 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2114 const char *name(CYPoolCString(pool, context, property));
2115 if (Protocol *protocol = objc_getProtocol(name))
2116 return CYMakeInstance(context, protocol, true);
2120 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2121 #if OBJC_API_VERSION >= 2
2123 Protocol **data(objc_copyProtocolList(&size));
2124 for (size_t i(0); i != size; ++i)
2125 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2132 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2134 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2136 return Instance::Make(context, nil);
2140 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2141 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2145 static bool stret(ffi_type *ffi_type) {
2146 return ffi_type->type == FFI_TYPE_STRUCT && (
2147 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2148 struct_forward_array[ffi_type->size] != 0
2153 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 {
2157 _class = object_getClass(self);
2161 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2162 imp = method_getImplementation(method);
2163 type = method_getTypeEncoding(method);
2168 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2170 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2171 type = CYPoolCString(pool, context, [method _typeString]);
2179 sig::Signature signature;
2180 sig::Parse(pool, &signature, type, &Structor_);
2182 size_t used(count + 3);
2183 if (used > signature.count) {
2184 sig::Element *elements(new (pool) sig::Element[used]);
2185 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2187 for (size_t index(signature.count); index != used; ++index) {
2188 sig::Element *element(&elements[index]);
2189 element->name = NULL;
2190 element->offset = _not(size_t);
2192 sig::Type *type(new (pool) sig::Type);
2193 memset(type, 0, sizeof(*type));
2194 type->primitive = sig::object_P;
2195 element->type = type;
2198 signature.elements = elements;
2199 signature.count = used;
2203 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2207 if (stret(cif.rtype))
2208 imp = class_getMethodImplementation_stret(_class, _cmd);
2210 imp = class_getMethodImplementation(_class, _cmd);
2212 objc_super super = {self, _class};
2213 imp = objc_msg_lookup_super(&super, _cmd);
2217 void (*function)() = reinterpret_cast<void (*)()>(imp);
2218 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2221 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2223 throw CYJSError(context, "too few arguments to objc_msgSend");
2233 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2234 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2235 self = internal->GetValue();
2236 _class = internal->class_;;
2237 uninitialized = false;
2238 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2239 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2240 self = internal->GetValue();
2242 uninitialized = internal->IsUninitialized();
2244 internal->value_ = nil;
2246 self = CYCastNSObject(pool, context, arguments[0]);
2248 uninitialized = false;
2252 return CYJSNull(context);
2254 _cmd = CYCastSEL(context, arguments[1]);
2256 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2259 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2260 JSValueRef setup[count + 2];
2263 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2264 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2267 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2269 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2271 // XXX: handle Instance::Uninitialized?
2272 id self(CYCastNSObject(pool, context, _this));
2276 setup[1] = &internal->sel_;
2278 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2281 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2283 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2285 id self(CYCastNSObject(pool, context, arguments[0]));
2286 Class _class(CYCastClass(pool, context, arguments[1]));
2287 return cy::Super::Make(context, self, _class);
2290 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2292 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2294 const char *name(CYPoolCString(pool, context, arguments[0]));
2295 return CYMakeSelector(context, sel_registerName(name));
2298 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2300 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2301 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2302 return CYMakeInstance(context, self, false);
2305 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2306 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2307 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2310 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2311 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2312 Type_privateData *typical(internal->GetType());
2317 if (typical == NULL) {
2321 type = typical->type_;
2322 ffi = typical->ffi_;
2325 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2328 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2329 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2330 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2333 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2334 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2335 id self(internal->GetValue());
2336 if (!CYIsClass(self))
2337 return CYJSUndefined(context);
2338 return CYGetClassPrototype(context, self);
2341 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2342 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2343 id self(internal->GetValue());
2344 if (!CYIsClass(self))
2345 return CYJSUndefined(context);
2346 return Messages::Make(context, (Class) self);
2349 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2350 if (!CYJSValueIsNSObject(context, _this))
2353 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2354 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2357 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2358 if (!CYJSValueIsNSObject(context, _this))
2361 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2362 id value(internal->GetValue());
2369 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2371 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2372 return CYJSUndefined(context);
2373 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2376 return CYCastJSValue(context, CYJSString(context, [value description]));
2378 } CYCatch return /*XXX*/ NULL; }
2380 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2381 if (!CYJSValueIsNSObject(context, _this))
2384 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2385 id value(internal->GetValue());
2387 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2390 if (JSValueRef result = [value cy$valueOfInContext:context])
2394 } CYCatch return /*XXX*/ NULL; }
2396 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2397 if (!CYJSValueIsNSObject(context, _this))
2400 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2401 // XXX: but... but... THIS ISN'T A POINTER! :(
2402 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2403 } CYCatch return /*XXX*/ NULL; }
2405 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2406 if (!CYJSValueIsNSObject(context, _this))
2409 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2410 id value(internal->GetValue());
2413 return CYCastJSValue(context, "nil");
2416 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2417 return CYCastJSValue(context, CYJSString(context, [value description]));
2419 } CYCatch return /*XXX*/ NULL; }
2421 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2422 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2423 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2426 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2427 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2430 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2431 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2432 const char *name(sel_getName(internal->GetValue()));
2435 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2436 return CYCastJSValue(context, CYJSString(context, string));
2438 } CYCatch return /*XXX*/ NULL; }
2440 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2442 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2445 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2446 SEL sel(internal->GetValue());
2448 objc_method *method;
2449 if (Class _class = CYCastClass(pool, context, arguments[0]))
2450 method = class_getInstanceMethod(_class, sel);
2454 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2455 return CYCastJSValue(context, CYJSString(type));
2457 return CYJSNull(context);
2460 static JSStaticValue Selector_staticValues[2] = {
2461 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2462 {NULL, NULL, NULL, 0}
2465 static JSStaticValue Instance_staticValues[5] = {
2466 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2467 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2468 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2469 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2470 {NULL, NULL, NULL, 0}
2473 static JSStaticFunction Instance_staticFunctions[7] = {
2474 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2475 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2476 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2477 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2478 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2479 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2483 static JSStaticFunction Internal_staticFunctions[2] = {
2484 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2488 static JSStaticFunction Selector_staticFunctions[5] = {
2489 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2490 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2491 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2492 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2497 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_(context) {
2498 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2499 } CYObjectiveCatch }
2502 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2503 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2504 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2505 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2507 apr_pool_t *pool(CYGetGlobalPool());
2509 Object_type = new(pool) Type_privateData("@");
2510 Selector_type = new(pool) Type_privateData(":");
2513 // XXX: apparently, iOS now has both of these
2514 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2515 if (NSCFBoolean_ == nil)
2516 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2518 NSCFType_ = objc_getClass("NSCFType");
2519 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2520 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2521 NSZombie_ = objc_getClass("_NSZombie_");
2523 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2526 NSArray_ = objc_getClass("NSArray");
2527 NSBlock_ = objc_getClass("NSBlock");
2528 NSDictionary_ = objc_getClass("NSDictionary");
2529 NSString_ = objc_getClass("NSString");
2530 Object_ = objc_getClass("Object");
2532 JSClassDefinition definition;
2534 definition = kJSClassDefinitionEmpty;
2535 definition.className = "Instance";
2536 definition.staticValues = Instance_staticValues;
2537 definition.staticFunctions = Instance_staticFunctions;
2538 definition.hasProperty = &Instance_hasProperty;
2539 definition.getProperty = &Instance_getProperty;
2540 definition.setProperty = &Instance_setProperty;
2541 definition.deleteProperty = &Instance_deleteProperty;
2542 definition.getPropertyNames = &Instance_getPropertyNames;
2543 definition.callAsConstructor = &Instance_callAsConstructor;
2544 definition.callAsFunction = &Instance_callAsFunction;
2545 definition.hasInstance = &Instance_hasInstance;
2546 definition.finalize = &CYFinalize;
2547 Instance_ = JSClassCreate(&definition);
2549 definition.className = "ArrayInstance";
2550 ArrayInstance_ = JSClassCreate(&definition);
2552 definition.className = "ObjectInstance";
2553 ObjectInstance_ = JSClassCreate(&definition);
2555 definition.className = "StringInstance";
2556 StringInstance_ = JSClassCreate(&definition);
2558 definition.className = "FunctionInstance";
2559 FunctionInstance_ = JSClassCreate(&definition);
2561 definition = kJSClassDefinitionEmpty;
2562 definition.className = "Internal";
2563 definition.staticFunctions = Internal_staticFunctions;
2564 definition.hasProperty = &Internal_hasProperty;
2565 definition.getProperty = &Internal_getProperty;
2566 definition.setProperty = &Internal_setProperty;
2567 definition.getPropertyNames = &Internal_getPropertyNames;
2568 definition.finalize = &CYFinalize;
2569 Internal_ = JSClassCreate(&definition);
2571 definition = kJSClassDefinitionEmpty;
2572 definition.className = "Message";
2573 definition.staticFunctions = cy::Functor::StaticFunctions;
2574 definition.callAsFunction = &Message_callAsFunction;
2575 definition.finalize = &CYFinalize;
2576 Message_ = JSClassCreate(&definition);
2578 definition = kJSClassDefinitionEmpty;
2579 definition.className = "Messages";
2580 definition.hasProperty = &Messages_hasProperty;
2581 definition.getProperty = &Messages_getProperty;
2582 definition.setProperty = &Messages_setProperty;
2583 #if 0 && OBJC_API_VERSION < 2
2584 definition.deleteProperty = &Messages_deleteProperty;
2586 definition.getPropertyNames = &Messages_getPropertyNames;
2587 definition.finalize = &CYFinalize;
2588 Messages_ = JSClassCreate(&definition);
2590 definition = kJSClassDefinitionEmpty;
2591 definition.className = "Selector";
2592 definition.staticValues = Selector_staticValues;
2593 definition.staticFunctions = Selector_staticFunctions;
2594 definition.callAsFunction = &Selector_callAsFunction;
2595 definition.finalize = &CYFinalize;
2596 Selector_ = JSClassCreate(&definition);
2598 definition = kJSClassDefinitionEmpty;
2599 definition.className = "Super";
2600 definition.staticFunctions = Internal_staticFunctions;
2601 definition.finalize = &CYFinalize;
2602 Super_ = JSClassCreate(&definition);
2604 definition = kJSClassDefinitionEmpty;
2605 definition.className = "ObjectiveC::Classes";
2606 definition.getProperty = &ObjectiveC_Classes_getProperty;
2607 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2608 ObjectiveC_Classes_ = JSClassCreate(&definition);
2610 definition = kJSClassDefinitionEmpty;
2611 definition.className = "ObjectiveC::Constants";
2612 definition.getProperty = &ObjectiveC_Constants_getProperty;
2613 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2614 ObjectiveC_Constants_ = JSClassCreate(&definition);
2616 #if OBJC_API_VERSION >= 2
2617 definition = kJSClassDefinitionEmpty;
2618 definition.className = "ObjectiveC::Images";
2619 definition.getProperty = &ObjectiveC_Images_getProperty;
2620 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2621 ObjectiveC_Images_ = JSClassCreate(&definition);
2623 definition = kJSClassDefinitionEmpty;
2624 definition.className = "ObjectiveC::Image::Classes";
2625 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2626 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2627 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2630 definition = kJSClassDefinitionEmpty;
2631 definition.className = "ObjectiveC::Protocols";
2632 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2633 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2634 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2637 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2641 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2642 JSObjectRef global(CYGetGlobalObject(context));
2643 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2644 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2645 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2646 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2648 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2649 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2651 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2652 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2653 CYArrayPush(context, alls, protocols);
2655 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2656 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2657 CYArrayPush(context, alls, classes);
2659 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2660 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2661 CYArrayPush(context, alls, constants);
2663 #if OBJC_API_VERSION >= 2
2664 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2667 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2668 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2669 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2670 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2672 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2673 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2675 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2676 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2677 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2678 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2679 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2681 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2682 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2683 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2684 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2685 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2687 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2688 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2689 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2690 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2691 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2693 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2694 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2695 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2696 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2697 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2699 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2700 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2701 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2703 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2704 CYSetProperty(context, Instance, CYJSString("box"), box);
2706 #if defined(__APPLE__) && defined(__arm__) && 0
2707 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2710 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2712 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2713 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2716 static CYHooks CYObjectiveCHooks = {
2717 &CYObjectiveC_ExecuteStart,
2718 &CYObjectiveC_ExecuteEnd,
2719 &CYObjectiveC_CallFunction,
2720 &CYObjectiveC_Initialize,
2721 &CYObjectiveC_SetupContext,
2722 &CYObjectiveC_PoolFFI,
2723 &CYObjectiveC_FromFFI,
2726 struct CYObjectiveC {
2728 hooks_ = &CYObjectiveCHooks;
2729 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2730 _assert(hooks_ != NULL);