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 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
399 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
400 - (bool) cy$deleteProperty:(NSString *)name;
401 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
403 + (bool) cy$hasImplicitProperties;
409 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
412 NSString *CYCastNSCYON(id value, bool objective) {
418 Class _class(object_getClass(value));
419 SEL sel(@selector(cy$toCYON:));
421 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
422 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
423 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
424 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
425 string = [value cy$toCYON:objective];
430 else if (value == NSZombie_)
431 string = @"_NSZombie_";
432 else if (_class == NSZombie_)
433 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
434 // XXX: frowny /in/ the pants
435 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
439 string = [NSString stringWithFormat:@"%@", value];
444 string = @"undefined";
451 struct PropertyAttributes {
456 const char *variable;
469 PropertyAttributes(objc_property_t property) :
481 name = property_getName(property);
482 const char *attributes(property_getAttributes(property));
484 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
486 case 'R': readonly = true; break;
487 case 'C': copy = true; break;
488 case '&': retain = true; break;
489 case 'N': nonatomic = true; break;
490 case 'G': getter_ = token + 1; break;
491 case 'S': setter_ = token + 1; break;
492 case 'V': variable = token + 1; break;
496 /*if (variable == NULL) {
497 variable = property_getName(property);
498 size_t size(strlen(variable));
499 char *name(new(pool_) char[size + 2]);
501 memcpy(name + 1, variable, size);
502 name[size + 1] = '\0';
507 const char *Getter() {
509 getter_ = apr_pstrdup(pool_, name);
513 const char *Setter() {
514 if (setter_ == NULL && !readonly) {
515 size_t length(strlen(name));
517 char *temp(new(pool_) char[length + 5]);
523 temp[3] = toupper(name[0]);
524 memcpy(temp + 4, name + 1, length - 1);
527 temp[length + 3] = ':';
528 temp[length + 4] = '\0';
539 @interface CYWebUndefined : NSObject {
542 + (CYWebUndefined *) undefined;
546 @implementation CYWebUndefined
548 + (CYWebUndefined *) undefined {
549 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
555 #define WebUndefined CYWebUndefined
558 /* Bridge: CYJSObject {{{ */
559 @interface CYJSObject : NSMutableDictionary {
561 JSGlobalContextRef context_;
564 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
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 JSGlobalContextRef 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 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
595 return JSValueIsObjectOfClass(context, value, Instance_);
598 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
599 JSValueRef exception(NULL);
600 JSObjectRef constructor(CYGetCachedObject(context, cache));
601 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
602 CYThrow(context, exception);
606 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
607 if (CYJSValueIsNSObject(context, object)) {
608 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
609 return internal->GetValue();
612 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
613 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
614 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
617 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
618 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
622 @interface NSBoolNumber : NSNumber {
627 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
631 switch (JSType type = JSValueGetType(context, value)) {
632 case kJSTypeUndefined:
633 object = [WebUndefined undefined];
643 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
646 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
652 object = CYCopyNSNumber(context, value);
657 object = CYCopyNSString(context, value);
662 // XXX: this might could be more efficient
663 object = CYCastNSObject(pool, context, (JSObjectRef) value);
668 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
675 return CYPoolRelease(pool, object);
677 return [object retain];
680 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
681 return CYNSObject(pool, context, value, true);
684 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
685 return CYNSObject(pool, context, value, false);
688 /* Bridge: NSArray {{{ */
689 @implementation NSArray (Cycript)
692 return [[self mutableCopy] autorelease];
695 - (NSString *) cy$toCYON:(bool)objective {
696 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
697 [json appendString:@"@["];
701 for (id object in self) {
703 for (size_t index(0), count([self count]); index != count; ++index) {
704 id object([self objectAtIndex:index]);
707 [json appendString:@","];
710 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
711 [json appendString:CYCastNSCYON(object, true)];
713 [json appendString:@","];
718 [json appendString:@"]"];
722 - (bool) cy$hasProperty:(NSString *)name {
723 if ([name isEqualToString:@"length"])
726 size_t index(CYGetIndex(name));
727 if (index == _not(size_t) || index >= [self count])
728 return [super cy$hasProperty:name];
733 - (NSObject *) cy$getProperty:(NSString *)name {
734 size_t index(CYGetIndex(name));
735 if (index == _not(size_t) || index >= [self count])
736 return [super cy$getProperty:name];
738 return [self objectAtIndex:index];
741 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
742 CYObjectiveTry_(context) {
743 if ([name isEqualToString:@"length"])
744 return CYCastJSValue(context, [self count]);
747 return [super cy$getProperty:name inContext:context];
750 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
751 [super cy$getPropertyNames:names inContext:context];
753 for (size_t index(0), count([self count]); index != count; ++index) {
754 id object([self objectAtIndex:index]);
755 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
757 sprintf(name, "%zu", index);
758 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
763 + (bool) cy$hasImplicitProperties {
769 /* Bridge: NSBlock {{{ */
776 /* Bridge: NSBoolNumber {{{ */
778 @implementation NSBoolNumber (Cycript)
780 - (JSType) cy$JSType {
781 return kJSTypeBoolean;
784 - (NSString *) cy$toCYON:(bool)objective {
785 NSString *value([self boolValue] ? @"true" : @"false");
786 return objective ? value : [NSString stringWithFormat:@"@%@", value];
789 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
790 return CYCastJSValue(context, (bool) [self boolValue]);
796 /* Bridge: NSDictionary {{{ */
797 @implementation NSDictionary (Cycript)
800 return [[self mutableCopy] autorelease];
803 - (NSString *) cy$toCYON:(bool)objective {
804 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
805 [json appendString:@"@{"];
809 for (NSObject *key in self) {
811 NSEnumerator *keys([self keyEnumerator]);
812 while (NSObject *key = [keys nextObject]) {
815 [json appendString:@","];
818 [json appendString:CYCastNSCYON(key, true)];
819 [json appendString:@":"];
820 NSObject *object([self objectForKey:key]);
821 [json appendString:CYCastNSCYON(object, true)];
824 [json appendString:@"}"];
828 - (bool) cy$hasProperty:(NSString *)name {
829 return [self objectForKey:name] != nil;
832 - (NSObject *) cy$getProperty:(NSString *)name {
833 return [self objectForKey:name];
836 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
837 [super cy$getPropertyNames:names inContext:context];
840 for (NSObject *key in self) {
842 NSEnumerator *keys([self keyEnumerator]);
843 while (NSObject *key = [keys nextObject]) {
845 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
849 + (bool) cy$hasImplicitProperties {
855 /* Bridge: NSMutableArray {{{ */
856 @implementation NSMutableArray (Cycript)
858 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
859 if ([name isEqualToString:@"length"]) {
860 // XXX: is this not intelligent?
861 NSNumber *number(reinterpret_cast<NSNumber *>(value));
863 NSUInteger size([number unsignedIntegerValue]);
865 NSUInteger size([number unsignedIntValue]);
867 NSUInteger count([self count]);
869 [self removeObjectsInRange:NSMakeRange(size, count - size)];
870 else if (size != count) {
871 WebUndefined *undefined([WebUndefined undefined]);
872 for (size_t i(count); i != size; ++i)
873 [self addObject:undefined];
878 size_t index(CYGetIndex(name));
879 if (index == _not(size_t))
880 return [super cy$setProperty:name to:value];
882 id object(value ?: [NSNull null]);
884 size_t count([self count]);
886 [self replaceObjectAtIndex:index withObject:object];
888 if (index != count) {
889 WebUndefined *undefined([WebUndefined undefined]);
890 for (size_t i(count); i != index; ++i)
891 [self addObject:undefined];
894 [self addObject:object];
900 - (bool) cy$deleteProperty:(NSString *)name {
901 size_t index(CYGetIndex(name));
902 if (index == _not(size_t) || index >= [self count])
903 return [super cy$deleteProperty:name];
904 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
910 /* Bridge: NSMutableDictionary {{{ */
911 @implementation NSMutableDictionary (Cycript)
913 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
914 [self setObject:(value ?: [NSNull null]) forKey:name];
918 - (bool) cy$deleteProperty:(NSString *)name {
919 if ([self objectForKey:name] == nil)
922 [self removeObjectForKey:name];
929 /* Bridge: NSNumber {{{ */
930 @implementation NSNumber (Cycript)
932 - (JSType) cy$JSType {
934 // XXX: this just seems stupid
935 if ([self class] == NSCFBoolean_)
936 return kJSTypeBoolean;
938 return kJSTypeNumber;
941 - (NSString *) cy$toCYON:(bool)objective {
942 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
943 return objective ? value : [NSString stringWithFormat:@"@%@", value];
946 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
947 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
952 /* Bridge: NSNull {{{ */
953 @implementation NSNull (Cycript)
955 - (JSType) cy$JSType {
959 - (NSString *) cy$toCYON:(bool)objective {
960 NSString *value(@"null");
961 return objective ? value : [NSString stringWithFormat:@"@%@", value];
964 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
965 return CYJSNull(context);
970 /* Bridge: NSObject {{{ */
971 @implementation NSObject (Cycript)
977 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
978 return [self cy$valueOfInContext:context];
981 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
985 - (JSType) cy$JSType {
986 return kJSTypeObject;
989 - (NSString *) cy$toCYON:(bool)objective {
990 return [[self description] cy$toCYON:objective];
993 - (bool) cy$hasProperty:(NSString *)name {
997 - (NSObject *) cy$getProperty:(NSString *)name {
1001 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_(context) {
1002 if (NSObject *value = [self cy$getProperty:name])
1003 return CYCastJSValue(context, value);
1005 } CYObjectiveCatch }
1007 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1011 - (bool) cy$deleteProperty:(NSString *)name {
1015 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1018 + (bool) cy$hasImplicitProperties {
1024 /* Bridge: NSProxy {{{ */
1025 @implementation NSProxy (Cycript)
1027 - (NSString *) cy$toCYON:(bool)objective {
1028 return [[self description] cy$toCYON:objective];
1033 /* Bridge: NSString {{{ */
1034 @implementation NSString (Cycript)
1037 return [[self copy] autorelease];
1040 - (JSType) cy$JSType {
1041 return kJSTypeString;
1044 - (NSString *) cy$toCYON:(bool)objective {
1045 std::ostringstream str;
1048 CYUTF8String string(CYCastUTF8String(self));
1049 CYStringify(str, string.data, string.size);
1050 std::string value(str.str());
1051 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1054 - (bool) cy$hasProperty:(NSString *)name {
1055 size_t index(CYGetIndex(name));
1056 if (index == _not(size_t) || index >= [self length])
1057 return [super cy$hasProperty:name];
1062 - (NSObject *) cy$getProperty:(NSString *)name {
1063 size_t index(CYGetIndex(name));
1064 if (index == _not(size_t) || index >= [self length])
1065 return [super cy$getProperty:name];
1067 return [self substringWithRange:NSMakeRange(index, 1)];
1070 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1071 [super cy$getPropertyNames:names inContext:context];
1073 for (size_t index(0), length([self length]); index != length; ++index) {
1075 sprintf(name, "%zu", index);
1076 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1080 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1081 return CYCastJSValue(context, CYJSString(context, self));
1082 } CYObjectiveCatch }
1086 /* Bridge: WebUndefined {{{ */
1087 @implementation WebUndefined (Cycript)
1089 - (JSType) cy$JSType {
1090 return kJSTypeUndefined;
1093 - (NSString *) cy$toCYON:(bool)objective {
1094 NSString *value(@"undefined");
1095 return value; // XXX: maybe use the below code, adding @undefined?
1096 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1099 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1100 return CYJSUndefined(context);
1101 } CYObjectiveCatch }
1106 static bool CYIsClass(id self) {
1108 return class_isMetaClass(object_getClass(self));
1110 return GSObjCIsClass(self);
1114 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1115 id self(CYCastNSObject(pool, context, value));
1116 if (CYIsClass(self))
1117 return (Class) self;
1118 throw CYJSError(context, "got something that is not a Class");
1122 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1124 size_t size(JSPropertyNameArrayGetCount(names));
1125 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1126 for (size_t index(0); index != size; ++index)
1127 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1131 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1133 return CYJSNull(context);
1135 return CYMakeInstance(context, value, false);
1136 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1138 @implementation CYJSObject
1140 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1141 if ((self = [super init]) != nil) {
1143 context_ = CYGetJSContext(context);
1144 JSGlobalContextRetain(context_);
1145 JSValueProtect(context_, object_);
1147 } CYObjectiveCatch }
1149 - (void) dealloc { CYObjectiveTry {
1150 JSValueUnprotect(context_, object_);
1151 JSGlobalContextRelease(context_);
1153 } CYObjectiveCatch }
1155 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1157 JSValueRef exception(NULL);
1158 const char *cyon(CYPoolCCYON(pool, context_, object_));
1159 CYThrow(context_, exception);
1161 return [super cy$toCYON:objective];
1163 return [NSString stringWithUTF8String:cyon];
1164 } CYObjectiveCatch }
1166 - (NSUInteger) count { CYObjectiveTry {
1167 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1168 size_t size(JSPropertyNameArrayGetCount(names));
1169 JSPropertyNameArrayRelease(names);
1171 } CYObjectiveCatch }
1173 - (id) objectForKey:(id)key { CYObjectiveTry {
1174 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1175 if (JSValueIsUndefined(context_, value))
1177 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1178 } CYObjectiveCatch }
1180 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1181 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1182 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1183 JSPropertyNameArrayRelease(names);
1185 } CYObjectiveCatch }
1187 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1188 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1189 } CYObjectiveCatch }
1191 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1192 JSValueRef exception(NULL);
1193 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1194 CYThrow(context_, exception);
1195 } CYObjectiveCatch }
1199 @implementation CYJSArray
1201 - (NSString *) cy$toCYON:(bool)objective {
1203 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1206 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1207 if ((self = [super init]) != nil) {
1209 context_ = CYGetJSContext(context);
1210 JSGlobalContextRetain(context_);
1211 JSValueProtect(context_, object_);
1213 } CYObjectiveCatch }
1215 - (void) dealloc { CYObjectiveTry {
1216 JSValueUnprotect(context_, object_);
1217 JSGlobalContextRelease(context_);
1219 } CYObjectiveCatch }
1221 - (NSUInteger) count { CYObjectiveTry {
1222 return CYArrayLength(context_, object_);
1223 } CYObjectiveCatch }
1225 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1226 size_t bounds([self count]);
1227 if (index >= bounds)
1228 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1229 JSValueRef exception(NULL);
1230 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1231 CYThrow(context_, exception);
1232 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1233 } CYObjectiveCatch }
1235 - (void) addObject:(id)object { CYObjectiveTry {
1236 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1237 } CYObjectiveCatch }
1239 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1240 size_t bounds([self count] + 1);
1241 if (index >= bounds)
1242 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1243 JSValueRef exception(NULL);
1244 JSValueRef arguments[3];
1245 arguments[0] = CYCastJSValue(context_, index);
1246 arguments[1] = CYCastJSValue(context_, 0);
1247 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1248 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1249 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1250 CYThrow(context_, exception);
1251 } CYObjectiveCatch }
1253 - (void) removeLastObject { CYObjectiveTry {
1254 JSValueRef exception(NULL);
1255 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1256 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1257 CYThrow(context_, exception);
1258 } CYObjectiveCatch }
1260 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1261 size_t bounds([self count]);
1262 if (index >= bounds)
1263 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1264 JSValueRef exception(NULL);
1265 JSValueRef arguments[2];
1266 arguments[0] = CYCastJSValue(context_, index);
1267 arguments[1] = CYCastJSValue(context_, 1);
1268 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1269 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1270 CYThrow(context_, exception);
1271 } CYObjectiveCatch }
1273 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1274 size_t bounds([self count]);
1275 if (index >= bounds)
1276 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1277 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1278 } CYObjectiveCatch }
1282 // XXX: inherit from or replace with CYJSObject
1283 @interface CYInternal : NSObject {
1284 JSGlobalContextRef context_;
1285 JSObjectRef object_;
1290 @implementation CYInternal
1293 JSValueUnprotect(context_, object_);
1294 JSGlobalContextRelease(context_);
1298 - (id) initInContext:(JSContextRef)context {
1299 if ((self = [super init]) != nil) {
1300 context_ = CYGetJSContext(context);
1301 JSGlobalContextRetain(context_);
1305 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1306 if (object_ == NULL)
1309 return JSObjectHasProperty(context, object_, name);
1312 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1313 if (object_ == NULL)
1316 return CYGetProperty(context, object_, name);
1319 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1320 @synchronized (self) {
1321 if (object_ == NULL) {
1322 object_ = JSObjectMake(context, NULL, NULL);
1323 JSValueProtect(context, object_);
1327 CYSetProperty(context, object_, name, value);
1330 + (CYInternal *) get:(id)object {
1331 if ($objc_getAssociatedObject == NULL)
1334 @synchronized (object) {
1335 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1342 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1343 if ($objc_getAssociatedObject == NULL)
1346 @synchronized (object) {
1347 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1350 if ($objc_setAssociatedObject == NULL)
1353 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1354 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1363 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1364 Selector_privateData *internal(new Selector_privateData(sel));
1365 return JSObjectMake(context, Selector_, internal);
1368 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1369 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1370 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1371 return reinterpret_cast<SEL>(internal->value_);
1373 return CYCastPointer<SEL>(context, value);
1376 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1377 return (void *) [[NSAutoreleasePool alloc] init];
1378 } CYSadCatch(NULL) }
1380 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1381 return [(NSAutoreleasePool *) handle release];
1384 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1386 return Instance::Make(context, nil);
1387 if (Class _class = objc_getClass(name.data))
1388 return CYMakeInstance(context, _class, true);
1389 if (Protocol *protocol = objc_getProtocol(name.data))
1390 return CYMakeInstance(context, protocol, true);
1392 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1394 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1395 ffi_call(cif, function, value, values);
1398 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1399 switch (type->primitive) {
1400 // XXX: do something epic about blocks
1403 case sig::typename_P:
1404 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1407 case sig::selector_P:
1408 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1416 } CYSadCatch(false) }
1418 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1419 switch (type->primitive) {
1420 // XXX: do something epic about blocks
1423 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1424 JSValueRef value(CYCastJSValue(context, object));
1430 case sig::typename_P:
1431 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1433 case sig::selector_P:
1434 if (SEL sel = *reinterpret_cast<SEL *>(data))
1435 return CYMakeSelector(context, sel);
1439 return CYJSNull(context);
1443 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1445 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1446 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1449 #if OBJC_API_VERSION >= 2
1451 method_getReturnType(method, type, sizeof(type));
1453 const char *type(method_getTypeEncoding(method));
1459 // XXX: possibly use a more "awesome" check?
1463 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1465 return method_getTypeEncoding(method);
1467 const char *name(sel_getName(sel));
1468 size_t length(strlen(name));
1470 char keyed[length + 2];
1472 keyed[length + 1] = '\0';
1473 memcpy(keyed + 1, name, length);
1475 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1476 return entry->value_;
1481 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1482 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1484 JSContextRef context(internal->context_);
1486 size_t count(internal->cif_.nargs);
1487 JSValueRef values[count];
1489 for (size_t index(0); index != count; ++index)
1490 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1492 JSObjectRef _this(CYCastJSObject(context, values[0]));
1494 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1495 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1498 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1499 Message_privateData *internal(new Message_privateData(sel, type, imp));
1500 return JSObjectMake(context, Message_, internal);
1503 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1504 JSObjectRef function(CYCastJSObject(context, value));
1505 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1506 // XXX: see notes in Library.cpp about needing to leak
1507 return reinterpret_cast<IMP>(internal->GetValue());
1510 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1511 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1512 Class _class(internal->GetValue());
1515 const char *name(CYPoolCString(pool, context, property));
1517 if (SEL sel = sel_getUid(name))
1518 if (class_getInstanceMethod(_class, sel) != NULL)
1524 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1525 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1526 Class _class(internal->GetValue());
1529 const char *name(CYPoolCString(pool, context, property));
1531 if (SEL sel = sel_getUid(name))
1532 if (objc_method *method = class_getInstanceMethod(_class, sel))
1533 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1538 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1539 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1540 Class _class(internal->GetValue());
1543 const char *name(CYPoolCString(pool, context, property));
1545 SEL sel(sel_registerName(name));
1547 objc_method *method(class_getInstanceMethod(_class, sel));
1552 if (JSValueIsObjectOfClass(context, value, Message_)) {
1553 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1554 type = sig::Unparse(pool, &message->signature_);
1555 imp = reinterpret_cast<IMP>(message->GetValue());
1557 type = CYPoolTypeEncoding(pool, context, sel, method);
1558 imp = CYMakeMessage(context, value, type);
1562 method_setImplementation(method, imp);
1565 GSMethodList list(GSAllocMethodList(1));
1566 GSAppendMethodToList(list, sel, type, imp, YES);
1567 GSAddMethodList(_class, list, YES);
1568 GSFlushMethodCacheForClass(_class);
1570 class_addMethod(_class, sel, imp, type);
1577 #if 0 && OBJC_API_VERSION < 2
1578 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1579 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1580 Class _class(internal->GetValue());
1583 const char *name(CYPoolCString(pool, context, property));
1585 if (SEL sel = sel_getUid(name))
1586 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1587 objc_method_list list = {NULL, 1, {method}};
1588 class_removeMethods(_class, &list);
1596 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1597 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1598 Class _class(internal->GetValue());
1600 #if OBJC_API_VERSION >= 2
1602 objc_method **data(class_copyMethodList(_class, &size));
1603 for (size_t i(0); i != size; ++i)
1604 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1607 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1608 for (int i(0); i != methods->method_count; ++i)
1609 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1613 static bool CYHasImplicitProperties(Class _class) {
1614 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1615 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1617 return [_class cy$hasImplicitProperties];
1620 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1621 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1622 id self(internal->GetValue());
1624 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1628 NSString *name(CYCastNSString(pool, context, property));
1630 if (CYInternal *internal = [CYInternal get:self])
1631 if ([internal hasProperty:property inContext:context])
1634 Class _class(object_getClass(self));
1637 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1638 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1639 if ([self cy$hasProperty:name])
1641 } CYPoolCatch(false)
1643 const char *string(CYPoolCString(pool, context, name));
1646 if (class_getProperty(_class, string) != NULL)
1650 if (CYHasImplicitProperties(_class))
1651 if (SEL sel = sel_getUid(string))
1652 if (CYImplements(self, _class, sel, true))
1658 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1659 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1660 id self(internal->GetValue());
1662 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1663 return Internal::Make(context, self, object);
1666 NSString *name(CYCastNSString(pool, context, property));
1668 if (CYInternal *internal = [CYInternal get:self])
1669 if (JSValueRef value = [internal getProperty:property inContext:context])
1673 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1677 const char *string(CYPoolCString(pool, context, name));
1678 Class _class(object_getClass(self));
1681 if (objc_property_t property = class_getProperty(_class, string)) {
1682 PropertyAttributes attributes(property);
1683 SEL sel(sel_registerName(attributes.Getter()));
1684 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1688 if (CYHasImplicitProperties(_class))
1689 if (SEL sel = sel_getUid(string))
1690 if (CYImplements(self, _class, sel, true))
1691 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1696 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1697 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1698 id self(internal->GetValue());
1702 NSString *name(CYCastNSString(pool, context, property));
1703 NSObject *data(CYCastNSObject(pool, context, value));
1706 if ([self cy$setProperty:name to:data])
1710 const char *string(CYPoolCString(pool, context, name));
1711 Class _class(object_getClass(self));
1714 if (objc_property_t property = class_getProperty(_class, string)) {
1715 PropertyAttributes attributes(property);
1716 if (const char *setter = attributes.Setter()) {
1717 SEL sel(sel_registerName(setter));
1718 JSValueRef arguments[1] = {value};
1719 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1725 size_t length(strlen(string));
1727 char set[length + 5];
1733 if (string[0] != '\0') {
1734 set[3] = toupper(string[0]);
1735 memcpy(set + 4, string + 1, length - 1);
1738 set[length + 3] = ':';
1739 set[length + 4] = '\0';
1741 if (SEL sel = sel_getUid(set))
1742 if (CYImplements(self, _class, sel)) {
1743 JSValueRef arguments[1] = {value};
1744 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1748 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1749 [internal setProperty:property toValue:value inContext:context];
1756 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1757 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1758 id self(internal->GetValue());
1761 NSString *name(CYCastNSString(NULL, context, property));
1762 return [self cy$deleteProperty:name];
1764 } CYCatch return /*XXX*/ NULL; }
1766 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1767 const char *name(sel_getName(method_getName(method)));
1768 if (strchr(name, ':') != NULL)
1771 const char *type(method_getTypeEncoding(method));
1772 if (type == NULL || *type == '\0' || *type == 'v')
1775 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1778 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1779 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1780 id self(internal->GetValue());
1783 Class _class(object_getClass(self));
1788 objc_property_t *data(class_copyPropertyList(_class, &size));
1789 for (size_t i(0); i != size; ++i)
1790 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1795 if (CYHasImplicitProperties(_class))
1796 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1797 #if OBJC_API_VERSION >= 2
1799 objc_method **data(class_copyMethodList(current, &size));
1800 for (size_t i(0); i != size; ++i)
1801 Instance_getPropertyNames_message(names, data[i]);
1804 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1805 for (int i(0); i != methods->method_count; ++i)
1806 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1811 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1812 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1813 [self cy$getPropertyNames:names inContext:context];
1817 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1818 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1819 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1823 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1824 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1825 id self(internal->GetValue());
1827 if (![self isKindOfClass:NSBlock_])
1828 CYThrow("non-NSBlock object is not a function");
1829 // XXX: replace above logic with the following assertion
1830 //_assert([self isKindOfClass:NSBlock_]);
1831 // to do this, make it so FunctionInstance_ is the class of blocks
1832 // to do /that/, generalize the various "is exactly Instance_" checks
1833 // then, move Instance_callAsFunction to only be on FunctionInstance
1835 struct BlockDescriptor1 {
1836 unsigned long int reserved;
1837 unsigned long int size;
1840 struct BlockDescriptor2 {
1841 void (*copy_helper)(void *dst, void *src);
1842 void (*dispose_helper)(void *src);
1845 struct BlockDescriptor3 {
1846 const char *signature;
1850 struct BlockLiteral {
1854 void (*invoke)(void *, ...);
1856 } *literal = reinterpret_cast<BlockLiteral *>(self);
1859 BLOCK_DEALLOCATING = 0x0001,
1860 BLOCK_REFCOUNT_MASK = 0xfffe,
1861 BLOCK_NEEDS_FREE = 1 << 24,
1862 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1863 BLOCK_HAS_CTOR = 1 << 26,
1864 BLOCK_IS_GC = 1 << 27,
1865 BLOCK_IS_GLOBAL = 1 << 28,
1866 BLOCK_HAS_STRET = 1 << 29,
1867 BLOCK_HAS_SIGNATURE = 1 << 30,
1870 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1871 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1872 descriptor += sizeof(BlockDescriptor1);
1873 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1874 descriptor += sizeof(BlockDescriptor2);
1875 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1877 if (const char *type = descriptor3->signature) {
1883 sig::Signature signature;
1884 sig::Parse(pool, &signature, type, &Structor_);
1887 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1889 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1890 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1895 CYThrow("NSBlock without signature field passed arguments");
1899 } CYPoolCatch(NULL);
1904 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1905 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1906 Class _class(internal->GetValue());
1907 if (!CYIsClass(_class))
1910 if (CYJSValueIsNSObject(context, instance)) {
1911 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1912 // XXX: this isn't always safe
1913 return [linternal->GetValue() isKindOfClass:_class];
1919 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1921 throw CYJSError(context, "incorrect number of arguments to Instance");
1923 id value(CYCastNSObject(pool, context, arguments[0]));
1925 value = [NSNull null];
1926 return CYCastJSValue(context, [value cy$box]);
1929 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1930 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1933 id self(internal->GetValue());
1934 const char *name(CYPoolCString(pool, context, property));
1936 if (object_getInstanceVariable(self, name, NULL) != NULL)
1942 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1943 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1946 id self(internal->GetValue());
1947 const char *name(CYPoolCString(pool, context, property));
1949 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1950 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1951 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1952 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1958 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1959 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1962 id self(internal->GetValue());
1963 const char *name(CYPoolCString(pool, context, property));
1965 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1966 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1967 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1974 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1975 if (Class super = class_getSuperclass(_class))
1976 Internal_getPropertyNames_(super, names);
1978 #if OBJC_API_VERSION >= 2
1980 objc_ivar **data(class_copyIvarList(_class, &size));
1981 for (size_t i(0); i != size; ++i)
1982 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1985 if (objc_ivar_list *ivars = _class->ivars)
1986 for (int i(0); i != ivars->ivar_count; ++i)
1987 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1991 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1992 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1995 id self(internal->GetValue());
1996 Class _class(object_getClass(self));
1998 Internal_getPropertyNames_(_class, names);
2001 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2002 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2003 return internal->GetOwner();
2006 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2008 NSString *name(CYCastNSString(pool, context, property));
2009 if (Class _class = NSClassFromString(name))
2010 return CYMakeInstance(context, _class, true);
2014 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2016 size_t size(objc_getClassList(NULL, 0));
2017 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2020 size_t writ(objc_getClassList(data, size));
2023 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2029 for (size_t i(0); i != writ; ++i)
2030 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2036 while (Class _class = objc_next_class(&state))
2037 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2041 #if OBJC_API_VERSION >= 2
2042 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2043 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2046 const char *name(CYPoolCString(pool, context, property));
2048 const char **data(objc_copyClassNamesForImage(internal, &size));
2050 for (size_t i(0); i != size; ++i)
2051 if (strcmp(name, data[i]) == 0) {
2052 if (Class _class = objc_getClass(name)) {
2053 value = CYMakeInstance(context, _class, true);
2064 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2065 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2067 const char **data(objc_copyClassNamesForImage(internal, &size));
2068 for (size_t i(0); i != size; ++i)
2069 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2073 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2075 const char *name(CYPoolCString(pool, context, property));
2077 const char **data(objc_copyImageNames(&size));
2078 for (size_t i(0); i != size; ++i)
2079 if (strcmp(name, data[i]) == 0) {
2088 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2089 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2093 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2095 const char **data(objc_copyImageNames(&size));
2096 for (size_t i(0); i != size; ++i)
2097 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2102 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2104 const char *name(CYPoolCString(pool, context, property));
2105 if (Protocol *protocol = objc_getProtocol(name))
2106 return CYMakeInstance(context, protocol, true);
2110 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2111 #if OBJC_API_VERSION >= 2
2113 Protocol **data(objc_copyProtocolList(&size));
2114 for (size_t i(0); i != size; ++i)
2115 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2122 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2124 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2126 return Instance::Make(context, nil);
2130 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2131 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2135 static bool stret(ffi_type *ffi_type) {
2136 return ffi_type->type == FFI_TYPE_STRUCT && (
2137 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2138 struct_forward_array[ffi_type->size] != 0
2143 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 {
2147 _class = object_getClass(self);
2151 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2152 imp = method_getImplementation(method);
2153 type = method_getTypeEncoding(method);
2158 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2160 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2161 type = CYPoolCString(pool, context, [method _typeString]);
2169 sig::Signature signature;
2170 sig::Parse(pool, &signature, type, &Structor_);
2172 size_t used(count + 3);
2173 if (used > signature.count) {
2174 sig::Element *elements(new (pool) sig::Element[used]);
2175 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2177 for (size_t index(signature.count); index != used; ++index) {
2178 sig::Element *element(&elements[index]);
2179 element->name = NULL;
2180 element->offset = _not(size_t);
2182 sig::Type *type(new (pool) sig::Type);
2183 memset(type, 0, sizeof(*type));
2184 type->primitive = sig::object_P;
2185 element->type = type;
2188 signature.elements = elements;
2189 signature.count = used;
2193 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2197 if (stret(cif.rtype))
2198 imp = class_getMethodImplementation_stret(_class, _cmd);
2200 imp = class_getMethodImplementation(_class, _cmd);
2202 objc_super super = {self, _class};
2203 imp = objc_msg_lookup_super(&super, _cmd);
2207 void (*function)() = reinterpret_cast<void (*)()>(imp);
2208 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2211 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2213 throw CYJSError(context, "too few arguments to objc_msgSend");
2223 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2224 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2225 self = internal->GetValue();
2226 _class = internal->class_;;
2227 uninitialized = false;
2228 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2229 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2230 self = internal->GetValue();
2232 uninitialized = internal->IsUninitialized();
2234 internal->value_ = nil;
2236 self = CYCastNSObject(pool, context, arguments[0]);
2238 uninitialized = false;
2242 return CYJSNull(context);
2244 _cmd = CYCastSEL(context, arguments[1]);
2246 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2249 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2250 JSValueRef setup[count + 2];
2253 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2254 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2257 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2259 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2261 // XXX: handle Instance::Uninitialized?
2262 id self(CYCastNSObject(pool, context, _this));
2266 setup[1] = &internal->sel_;
2268 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2271 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2273 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2275 id self(CYCastNSObject(pool, context, arguments[0]));
2276 Class _class(CYCastClass(pool, context, arguments[1]));
2277 return cy::Super::Make(context, self, _class);
2280 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2282 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2284 const char *name(CYPoolCString(pool, context, arguments[0]));
2285 return CYMakeSelector(context, sel_registerName(name));
2288 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2290 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2291 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2292 return CYMakeInstance(context, self, false);
2295 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2296 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2297 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2300 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2301 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2302 Type_privateData *typical(internal->GetType());
2307 if (typical == NULL) {
2311 type = typical->type_;
2312 ffi = typical->ffi_;
2315 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2318 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2319 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2320 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2323 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2324 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2325 id self(internal->GetValue());
2326 if (!CYIsClass(self))
2327 return CYJSUndefined(context);
2328 return CYGetClassPrototype(context, self);
2331 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2332 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2333 id self(internal->GetValue());
2334 if (!CYIsClass(self))
2335 return CYJSUndefined(context);
2336 return Messages::Make(context, (Class) self);
2339 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2340 if (!CYJSValueIsNSObject(context, _this))
2343 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2344 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2347 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2348 if (!CYJSValueIsNSObject(context, _this))
2351 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2352 id value(internal->GetValue());
2359 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2361 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2362 return CYJSUndefined(context);
2363 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2366 return CYCastJSValue(context, CYJSString(context, [value description]));
2368 } CYCatch return /*XXX*/ NULL; }
2370 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2371 if (!CYJSValueIsNSObject(context, _this))
2374 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2375 id value(internal->GetValue());
2377 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2380 if (JSValueRef result = [value cy$valueOfInContext:context])
2384 } CYCatch return /*XXX*/ NULL; }
2386 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2387 if (!CYJSValueIsNSObject(context, _this))
2390 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2391 // XXX: but... but... THIS ISN'T A POINTER! :(
2392 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2393 } CYCatch return /*XXX*/ NULL; }
2395 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2396 if (!CYJSValueIsNSObject(context, _this))
2399 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2400 id value(internal->GetValue());
2403 return CYCastJSValue(context, "nil");
2406 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2407 return CYCastJSValue(context, CYJSString(context, [value description]));
2409 } CYCatch return /*XXX*/ NULL; }
2411 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2412 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2413 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2416 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2417 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2420 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2421 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2422 const char *name(sel_getName(internal->GetValue()));
2425 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2426 return CYCastJSValue(context, CYJSString(context, string));
2428 } CYCatch return /*XXX*/ NULL; }
2430 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2432 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2435 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2436 SEL sel(internal->GetValue());
2438 objc_method *method;
2439 if (Class _class = CYCastClass(pool, context, arguments[0]))
2440 method = class_getInstanceMethod(_class, sel);
2444 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2445 return CYCastJSValue(context, CYJSString(type));
2447 return CYJSNull(context);
2450 static JSStaticValue Selector_staticValues[2] = {
2451 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2452 {NULL, NULL, NULL, 0}
2455 static JSStaticValue Instance_staticValues[5] = {
2456 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2457 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2458 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2459 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2460 {NULL, NULL, NULL, 0}
2463 static JSStaticFunction Instance_staticFunctions[7] = {
2464 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2465 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2466 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2467 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2468 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2469 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2473 static JSStaticFunction Internal_staticFunctions[2] = {
2474 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2478 static JSStaticFunction Selector_staticFunctions[5] = {
2479 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2480 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2481 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2482 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2487 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_(context) {
2488 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2489 } CYObjectiveCatch }
2492 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2493 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2494 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2495 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2497 apr_pool_t *pool(CYGetGlobalPool());
2499 Object_type = new(pool) Type_privateData("@");
2500 Selector_type = new(pool) Type_privateData(":");
2503 // XXX: apparently, iOS now has both of these
2504 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2505 if (NSCFBoolean_ == nil)
2506 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2508 NSCFType_ = objc_getClass("NSCFType");
2509 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2510 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2511 NSZombie_ = objc_getClass("_NSZombie_");
2513 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2516 NSArray_ = objc_getClass("NSArray");
2517 NSBlock_ = objc_getClass("NSBlock");
2518 NSDictionary_ = objc_getClass("NSDictionary");
2519 NSString_ = objc_getClass("NSString");
2520 Object_ = objc_getClass("Object");
2522 JSClassDefinition definition;
2524 definition = kJSClassDefinitionEmpty;
2525 definition.className = "Instance";
2526 definition.staticValues = Instance_staticValues;
2527 definition.staticFunctions = Instance_staticFunctions;
2528 definition.hasProperty = &Instance_hasProperty;
2529 definition.getProperty = &Instance_getProperty;
2530 definition.setProperty = &Instance_setProperty;
2531 definition.deleteProperty = &Instance_deleteProperty;
2532 definition.getPropertyNames = &Instance_getPropertyNames;
2533 definition.callAsConstructor = &Instance_callAsConstructor;
2534 definition.callAsFunction = &Instance_callAsFunction;
2535 definition.hasInstance = &Instance_hasInstance;
2536 definition.finalize = &CYFinalize;
2537 Instance_ = JSClassCreate(&definition);
2539 definition.className = "ArrayInstance";
2540 ArrayInstance_ = JSClassCreate(&definition);
2542 definition.className = "ObjectInstance";
2543 ObjectInstance_ = JSClassCreate(&definition);
2545 definition.className = "StringInstance";
2546 StringInstance_ = JSClassCreate(&definition);
2548 definition.className = "FunctionInstance";
2549 FunctionInstance_ = JSClassCreate(&definition);
2551 definition = kJSClassDefinitionEmpty;
2552 definition.className = "Internal";
2553 definition.staticFunctions = Internal_staticFunctions;
2554 definition.hasProperty = &Internal_hasProperty;
2555 definition.getProperty = &Internal_getProperty;
2556 definition.setProperty = &Internal_setProperty;
2557 definition.getPropertyNames = &Internal_getPropertyNames;
2558 definition.finalize = &CYFinalize;
2559 Internal_ = JSClassCreate(&definition);
2561 definition = kJSClassDefinitionEmpty;
2562 definition.className = "Message";
2563 definition.staticFunctions = cy::Functor::StaticFunctions;
2564 definition.callAsFunction = &Message_callAsFunction;
2565 definition.finalize = &CYFinalize;
2566 Message_ = JSClassCreate(&definition);
2568 definition = kJSClassDefinitionEmpty;
2569 definition.className = "Messages";
2570 definition.hasProperty = &Messages_hasProperty;
2571 definition.getProperty = &Messages_getProperty;
2572 definition.setProperty = &Messages_setProperty;
2573 #if 0 && OBJC_API_VERSION < 2
2574 definition.deleteProperty = &Messages_deleteProperty;
2576 definition.getPropertyNames = &Messages_getPropertyNames;
2577 definition.finalize = &CYFinalize;
2578 Messages_ = JSClassCreate(&definition);
2580 definition = kJSClassDefinitionEmpty;
2581 definition.className = "Selector";
2582 definition.staticValues = Selector_staticValues;
2583 definition.staticFunctions = Selector_staticFunctions;
2584 definition.callAsFunction = &Selector_callAsFunction;
2585 definition.finalize = &CYFinalize;
2586 Selector_ = JSClassCreate(&definition);
2588 definition = kJSClassDefinitionEmpty;
2589 definition.className = "Super";
2590 definition.staticFunctions = Internal_staticFunctions;
2591 definition.finalize = &CYFinalize;
2592 Super_ = JSClassCreate(&definition);
2594 definition = kJSClassDefinitionEmpty;
2595 definition.className = "ObjectiveC::Classes";
2596 definition.getProperty = &ObjectiveC_Classes_getProperty;
2597 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2598 ObjectiveC_Classes_ = JSClassCreate(&definition);
2600 definition = kJSClassDefinitionEmpty;
2601 definition.className = "ObjectiveC::Constants";
2602 definition.getProperty = &ObjectiveC_Constants_getProperty;
2603 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2604 ObjectiveC_Constants_ = JSClassCreate(&definition);
2606 #if OBJC_API_VERSION >= 2
2607 definition = kJSClassDefinitionEmpty;
2608 definition.className = "ObjectiveC::Images";
2609 definition.getProperty = &ObjectiveC_Images_getProperty;
2610 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2611 ObjectiveC_Images_ = JSClassCreate(&definition);
2613 definition = kJSClassDefinitionEmpty;
2614 definition.className = "ObjectiveC::Image::Classes";
2615 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2616 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2617 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2620 definition = kJSClassDefinitionEmpty;
2621 definition.className = "ObjectiveC::Protocols";
2622 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2623 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2624 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2627 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2631 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2632 JSObjectRef global(CYGetGlobalObject(context));
2633 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2634 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2635 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2636 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2638 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2639 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2641 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2642 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2643 CYArrayPush(context, alls, protocols);
2645 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2646 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2647 CYArrayPush(context, alls, classes);
2649 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2650 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2651 CYArrayPush(context, alls, constants);
2653 #if OBJC_API_VERSION >= 2
2654 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2657 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2658 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2659 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2660 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2662 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2663 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2665 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2666 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2667 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2668 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2669 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2671 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2672 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2673 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2674 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2675 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2677 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2678 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2679 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2680 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2681 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2683 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2684 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2685 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2686 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2687 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2689 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2690 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2691 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2693 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2694 CYSetProperty(context, Instance, CYJSString("box"), box);
2696 #if defined(__APPLE__) && defined(__arm__) && 0
2697 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2700 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2702 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2703 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2706 static CYHooks CYObjectiveCHooks = {
2707 &CYObjectiveC_ExecuteStart,
2708 &CYObjectiveC_ExecuteEnd,
2709 &CYObjectiveC_CallFunction,
2710 &CYObjectiveC_Initialize,
2711 &CYObjectiveC_SetupContext,
2712 &CYObjectiveC_PoolFFI,
2713 &CYObjectiveC_FromFFI,
2716 struct CYObjectiveC {
2718 hooks_ = &CYObjectiveCHooks;
2719 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2720 _assert(hooks_ != NULL);