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 struct BlockDescriptor1 {
132 unsigned long int reserved;
133 unsigned long int size;
136 struct BlockDescriptor2 {
137 void (*copy_helper)(void *dst, void *src);
138 void (*dispose_helper)(void *src);
141 struct BlockDescriptor3 {
142 const char *signature;
146 struct BlockLiteral {
150 void (*invoke)(void *, ...);
155 BLOCK_DEALLOCATING = 0x0001,
156 BLOCK_REFCOUNT_MASK = 0xfffe,
157 BLOCK_NEEDS_FREE = 1 << 24,
158 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
159 BLOCK_HAS_CTOR = 1 << 26,
160 BLOCK_IS_GC = 1 << 27,
161 BLOCK_IS_GLOBAL = 1 << 28,
162 BLOCK_HAS_STRET = 1 << 29,
163 BLOCK_HAS_SIGNATURE = 1 << 30,
166 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
168 /* Objective-C Pool Release {{{ */
169 apr_status_t CYPoolRelease_(void *data) {
170 id object(reinterpret_cast<id>(data));
175 id CYPoolRelease_(apr_pool_t *pool, id object) {
178 else if (pool == NULL)
179 return [object autorelease];
181 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
186 template <typename Type_>
187 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
188 return (Type_) CYPoolRelease_(pool, (id) object);
191 /* Objective-C Strings {{{ */
192 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
194 return [value UTF8String];
196 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
197 char *string(new(pool) char[size]);
198 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
199 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
204 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
206 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
209 return CYCopyJSString(CYPoolCString(pool, context, value));
213 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
216 // XXX: this definition scares me; is anyone using this?!
217 NSString *string([value description]);
218 return CYCopyJSString(context, string);
221 NSString *CYCopyNSString(const CYUTF8String &value) {
223 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
225 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
229 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
231 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
234 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
238 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
239 return CYCopyNSString(context, CYJSString(context, value));
242 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
243 return CYPoolRelease(pool, CYCopyNSString(value));
246 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
247 const char *name(sel_getName(sel));
248 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
251 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
252 return CYPoolRelease(pool, CYCopyNSString(context, value));
255 CYUTF8String CYCastUTF8String(NSString *value) {
256 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
257 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
261 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
263 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
264 if (exception == NULL)
266 *exception = CYCastJSValue(context, error);
269 size_t CYGetIndex(NSString *value) {
270 return CYGetIndex(CYCastUTF8String(value));
273 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
274 return CYGetOffset(CYPoolCString(pool, context, value), index);
277 static JSClassRef Instance_;
279 static JSClassRef ArrayInstance_;
280 static JSClassRef FunctionInstance_;
281 static JSClassRef ObjectInstance_;
282 static JSClassRef StringInstance_;
284 static JSClassRef Class_;
285 static JSClassRef Internal_;
286 static JSClassRef Message_;
287 static JSClassRef Messages_;
288 static JSClassRef Selector_;
289 static JSClassRef Super_;
291 static JSClassRef ObjectiveC_Classes_;
292 static JSClassRef ObjectiveC_Constants_;
293 static JSClassRef ObjectiveC_Protocols_;
296 static JSClassRef ObjectiveC_Image_Classes_;
297 static JSClassRef ObjectiveC_Images_;
301 static Class NSCFBoolean_;
302 static Class NSCFType_;
303 static Class NSGenericDeallocHandler_;
304 static Class NSMessageBuilder_;
305 static Class NSZombie_;
307 static Class NSBoolNumber_;
310 static Class NSArray_;
311 static Class NSBlock_;
312 static Class NSDictionary_;
313 static Class NSString_;
314 static Class Object_;
316 static Type_privateData *Object_type;
317 static Type_privateData *Selector_type;
319 Type_privateData *Instance::GetType() const {
323 Type_privateData *Selector_privateData::GetType() const {
324 return Selector_type;
327 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
329 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
331 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
332 else if (meta && !class_isMetaClass(self))
333 return CYGetCachedObject(context, CYJSString("Class_prototype"));
335 JSObjectRef global(CYGetGlobalObject(context));
336 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
339 sprintf(label, "i%p", self);
340 CYJSString name(label);
342 JSValueRef value(CYGetProperty(context, cy, name));
343 if (!JSValueIsUndefined(context, value))
346 JSClassRef _class(NULL);
347 JSValueRef prototype;
349 if (self == NSArray_)
350 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
351 else if (self == NSBlock_)
352 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
353 else if (self == NSDictionary_)
354 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
355 else if (self == NSString_)
356 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
358 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
360 JSObjectRef object(JSObjectMake(context, _class, NULL));
361 JSObjectSetPrototype(context, object, prototype);
362 CYSetProperty(context, cy, name, object);
367 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
368 return CYGetClassPrototype(context, self, class_isMetaClass(self));
371 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
372 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
373 if (Class super = class_getSuperclass(_class))
374 JSObjectSetPrototype(context, value, Messages::Make(context, super));
378 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
379 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
383 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
384 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
388 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
389 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
390 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
394 Instance::~Instance() {
395 if ((flags_ & Transient) == 0)
396 // XXX: does this handle background threads correctly?
397 // XXX: this simply does not work on the console because I'm stupid
398 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
401 struct Message_privateData :
406 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
407 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
413 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
414 Instance::Flags flags;
417 flags = Instance::Transient;
419 flags = Instance::None;
420 object = [object retain];
423 return Instance::Make(context, object, flags);
426 @interface NSMethodSignature (Cycript)
427 - (NSString *) _typeString;
430 @interface NSObject (Cycript)
432 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
433 - (JSType) cy$JSType;
435 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
436 - (NSString *) cy$toCYON:(bool)objective;
438 - (bool) cy$hasProperty:(NSString *)name;
439 - (NSObject *) cy$getProperty:(NSString *)name;
440 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
441 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
442 - (bool) cy$deleteProperty:(NSString *)name;
443 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
445 + (bool) cy$hasImplicitProperties;
451 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
454 NSString *CYCastNSCYON(id value, bool objective) {
460 Class _class(object_getClass(value));
461 SEL sel(@selector(cy$toCYON:));
463 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
464 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
465 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
466 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
467 string = [value cy$toCYON:objective];
472 else if (value == NSZombie_)
473 string = @"_NSZombie_";
474 else if (_class == NSZombie_)
475 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
476 // XXX: frowny /in/ the pants
477 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
481 string = [NSString stringWithFormat:@"%@", value];
486 string = @"undefined";
493 struct PropertyAttributes {
498 const char *variable;
511 PropertyAttributes(objc_property_t property) :
523 name = property_getName(property);
524 const char *attributes(property_getAttributes(property));
526 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
528 case 'R': readonly = true; break;
529 case 'C': copy = true; break;
530 case '&': retain = true; break;
531 case 'N': nonatomic = true; break;
532 case 'G': getter_ = token + 1; break;
533 case 'S': setter_ = token + 1; break;
534 case 'V': variable = token + 1; break;
538 /*if (variable == NULL) {
539 variable = property_getName(property);
540 size_t size(strlen(variable));
541 char *name(new(pool_) char[size + 2]);
543 memcpy(name + 1, variable, size);
544 name[size + 1] = '\0';
549 const char *Getter() {
551 getter_ = apr_pstrdup(pool_, name);
555 const char *Setter() {
556 if (setter_ == NULL && !readonly) {
557 size_t length(strlen(name));
559 char *temp(new(pool_) char[length + 5]);
565 temp[3] = toupper(name[0]);
566 memcpy(temp + 4, name + 1, length - 1);
569 temp[length + 3] = ':';
570 temp[length + 4] = '\0';
581 @interface CYWebUndefined : NSObject {
584 + (CYWebUndefined *) undefined;
588 @implementation CYWebUndefined
590 + (CYWebUndefined *) undefined {
591 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
597 #define WebUndefined CYWebUndefined
600 /* Bridge: CYJSObject {{{ */
601 @interface CYJSObject : NSMutableDictionary {
603 JSGlobalContextRef context_;
606 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
608 - (NSUInteger) count;
609 - (id) objectForKey:(id)key;
610 - (NSEnumerator *) keyEnumerator;
611 - (void) setObject:(id)object forKey:(id)key;
612 - (void) removeObjectForKey:(id)key;
616 /* Bridge: CYJSArray {{{ */
617 @interface CYJSArray : NSMutableArray {
619 JSGlobalContextRef context_;
622 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
624 - (NSUInteger) count;
625 - (id) objectAtIndex:(NSUInteger)index;
627 - (void) addObject:(id)anObject;
628 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
629 - (void) removeLastObject;
630 - (void) removeObjectAtIndex:(NSUInteger)index;
631 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
636 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
637 return JSValueIsObjectOfClass(context, value, Instance_);
640 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
641 JSValueRef exception(NULL);
642 JSObjectRef constructor(CYGetCachedObject(context, cache));
643 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
644 CYThrow(context, exception);
648 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
649 if (CYJSValueIsNSObject(context, object)) {
650 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
651 return internal->GetValue();
654 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
655 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
656 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
659 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
660 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
664 @interface NSBoolNumber : NSNumber {
669 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
673 switch (JSType type = JSValueGetType(context, value)) {
674 case kJSTypeUndefined:
675 object = [WebUndefined undefined];
685 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
688 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
694 object = CYCopyNSNumber(context, value);
699 object = CYCopyNSString(context, value);
704 // XXX: this might could be more efficient
705 object = CYCastNSObject(pool, context, (JSObjectRef) value);
710 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
717 return CYPoolRelease(pool, object);
719 return [object retain];
722 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
723 return CYNSObject(pool, context, value, true);
726 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
727 return CYNSObject(pool, context, value, false);
730 /* Bridge: NSArray {{{ */
731 @implementation NSArray (Cycript)
734 return [[self mutableCopy] autorelease];
737 - (NSString *) cy$toCYON:(bool)objective {
738 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
739 [json appendString:@"@["];
743 for (id object in self) {
745 for (size_t index(0), count([self count]); index != count; ++index) {
746 id object([self objectAtIndex:index]);
749 [json appendString:@","];
752 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
753 [json appendString:CYCastNSCYON(object, true)];
755 [json appendString:@","];
760 [json appendString:@"]"];
764 - (bool) cy$hasProperty:(NSString *)name {
765 if ([name isEqualToString:@"length"])
768 size_t index(CYGetIndex(name));
769 if (index == _not(size_t) || index >= [self count])
770 return [super cy$hasProperty:name];
775 - (NSObject *) cy$getProperty:(NSString *)name {
776 size_t index(CYGetIndex(name));
777 if (index == _not(size_t) || index >= [self count])
778 return [super cy$getProperty:name];
780 return [self objectAtIndex:index];
783 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
784 CYObjectiveTry_(context) {
785 if ([name isEqualToString:@"length"])
786 return CYCastJSValue(context, [self count]);
789 return [super cy$getProperty:name inContext:context];
792 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
793 [super cy$getPropertyNames:names inContext:context];
795 for (size_t index(0), count([self count]); index != count; ++index) {
796 id object([self objectAtIndex:index]);
797 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
799 sprintf(name, "%zu", index);
800 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
805 + (bool) cy$hasImplicitProperties {
811 /* Bridge: NSBlock {{{ */
818 /* Bridge: NSBoolNumber {{{ */
820 @implementation NSBoolNumber (Cycript)
822 - (JSType) cy$JSType {
823 return kJSTypeBoolean;
826 - (NSString *) cy$toCYON:(bool)objective {
827 NSString *value([self boolValue] ? @"true" : @"false");
828 return objective ? value : [NSString stringWithFormat:@"@%@", value];
831 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
832 return CYCastJSValue(context, (bool) [self boolValue]);
838 /* Bridge: NSDictionary {{{ */
839 @implementation NSDictionary (Cycript)
842 return [[self mutableCopy] autorelease];
845 - (NSString *) cy$toCYON:(bool)objective {
846 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
847 [json appendString:@"@{"];
851 for (NSObject *key in self) {
853 NSEnumerator *keys([self keyEnumerator]);
854 while (NSObject *key = [keys nextObject]) {
857 [json appendString:@","];
860 [json appendString:CYCastNSCYON(key, true)];
861 [json appendString:@":"];
862 NSObject *object([self objectForKey:key]);
863 [json appendString:CYCastNSCYON(object, true)];
866 [json appendString:@"}"];
870 - (bool) cy$hasProperty:(NSString *)name {
871 return [self objectForKey:name] != nil;
874 - (NSObject *) cy$getProperty:(NSString *)name {
875 return [self objectForKey:name];
878 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
879 [super cy$getPropertyNames:names inContext:context];
882 for (NSObject *key in self) {
884 NSEnumerator *keys([self keyEnumerator]);
885 while (NSObject *key = [keys nextObject]) {
887 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
891 + (bool) cy$hasImplicitProperties {
897 /* Bridge: NSMutableArray {{{ */
898 @implementation NSMutableArray (Cycript)
900 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
901 if ([name isEqualToString:@"length"]) {
902 // XXX: is this not intelligent?
903 NSNumber *number(reinterpret_cast<NSNumber *>(value));
905 NSUInteger size([number unsignedIntegerValue]);
907 NSUInteger size([number unsignedIntValue]);
909 NSUInteger count([self count]);
911 [self removeObjectsInRange:NSMakeRange(size, count - size)];
912 else if (size != count) {
913 WebUndefined *undefined([WebUndefined undefined]);
914 for (size_t i(count); i != size; ++i)
915 [self addObject:undefined];
920 size_t index(CYGetIndex(name));
921 if (index == _not(size_t))
922 return [super cy$setProperty:name to:value];
924 id object(value ?: [NSNull null]);
926 size_t count([self count]);
928 [self replaceObjectAtIndex:index withObject:object];
930 if (index != count) {
931 WebUndefined *undefined([WebUndefined undefined]);
932 for (size_t i(count); i != index; ++i)
933 [self addObject:undefined];
936 [self addObject:object];
942 - (bool) cy$deleteProperty:(NSString *)name {
943 size_t index(CYGetIndex(name));
944 if (index == _not(size_t) || index >= [self count])
945 return [super cy$deleteProperty:name];
946 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
952 /* Bridge: NSMutableDictionary {{{ */
953 @implementation NSMutableDictionary (Cycript)
955 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
956 [self setObject:(value ?: [NSNull null]) forKey:name];
960 - (bool) cy$deleteProperty:(NSString *)name {
961 if ([self objectForKey:name] == nil)
964 [self removeObjectForKey:name];
971 /* Bridge: NSNumber {{{ */
972 @implementation NSNumber (Cycript)
974 - (JSType) cy$JSType {
976 // XXX: this just seems stupid
977 if ([self class] == NSCFBoolean_)
978 return kJSTypeBoolean;
980 return kJSTypeNumber;
983 - (NSString *) cy$toCYON:(bool)objective {
984 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
985 return objective ? value : [NSString stringWithFormat:@"@%@", value];
988 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
989 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
994 /* Bridge: NSNull {{{ */
995 @implementation NSNull (Cycript)
997 - (JSType) cy$JSType {
1001 - (NSString *) cy$toCYON:(bool)objective {
1002 NSString *value(@"null");
1003 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1006 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1007 return CYJSNull(context);
1008 } CYObjectiveCatch }
1012 /* Bridge: NSObject {{{ */
1013 @implementation NSObject (Cycript)
1019 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1020 return [self cy$valueOfInContext:context];
1023 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1025 } CYObjectiveCatch }
1027 - (JSType) cy$JSType {
1028 return kJSTypeObject;
1031 - (NSString *) cy$toCYON:(bool)objective {
1032 return [[self description] cy$toCYON:objective];
1035 - (bool) cy$hasProperty:(NSString *)name {
1039 - (NSObject *) cy$getProperty:(NSString *)name {
1043 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_(context) {
1044 if (NSObject *value = [self cy$getProperty:name])
1045 return CYCastJSValue(context, value);
1047 } CYObjectiveCatch }
1049 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1053 - (bool) cy$deleteProperty:(NSString *)name {
1057 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1060 + (bool) cy$hasImplicitProperties {
1066 /* Bridge: NSProxy {{{ */
1067 @implementation NSProxy (Cycript)
1069 - (NSString *) cy$toCYON:(bool)objective {
1070 return [[self description] cy$toCYON:objective];
1075 /* Bridge: NSString {{{ */
1076 @implementation NSString (Cycript)
1079 return [[self copy] autorelease];
1082 - (JSType) cy$JSType {
1083 return kJSTypeString;
1086 - (NSString *) cy$toCYON:(bool)objective {
1087 std::ostringstream str;
1090 CYUTF8String string(CYCastUTF8String(self));
1091 CYStringify(str, string.data, string.size);
1092 std::string value(str.str());
1093 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1096 - (bool) cy$hasProperty:(NSString *)name {
1097 size_t index(CYGetIndex(name));
1098 if (index == _not(size_t) || index >= [self length])
1099 return [super cy$hasProperty:name];
1104 - (NSObject *) cy$getProperty:(NSString *)name {
1105 size_t index(CYGetIndex(name));
1106 if (index == _not(size_t) || index >= [self length])
1107 return [super cy$getProperty:name];
1109 return [self substringWithRange:NSMakeRange(index, 1)];
1112 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1113 [super cy$getPropertyNames:names inContext:context];
1115 for (size_t index(0), length([self length]); index != length; ++index) {
1117 sprintf(name, "%zu", index);
1118 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1122 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1123 return CYCastJSValue(context, CYJSString(context, self));
1124 } CYObjectiveCatch }
1128 /* Bridge: WebUndefined {{{ */
1129 @implementation WebUndefined (Cycript)
1131 - (JSType) cy$JSType {
1132 return kJSTypeUndefined;
1135 - (NSString *) cy$toCYON:(bool)objective {
1136 NSString *value(@"undefined");
1137 return value; // XXX: maybe use the below code, adding @undefined?
1138 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1141 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1142 return CYJSUndefined(context);
1143 } CYObjectiveCatch }
1148 static bool CYIsClass(id self) {
1150 return class_isMetaClass(object_getClass(self));
1152 return GSObjCIsClass(self);
1156 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1157 id self(CYCastNSObject(pool, context, value));
1158 if (CYIsClass(self))
1159 return (Class) self;
1160 throw CYJSError(context, "got something that is not a Class");
1164 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1166 size_t size(JSPropertyNameArrayGetCount(names));
1167 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1168 for (size_t index(0); index != size; ++index)
1169 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1173 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1175 return CYJSNull(context);
1177 return CYMakeInstance(context, value, false);
1178 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1180 @implementation CYJSObject
1182 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1183 if ((self = [super init]) != nil) {
1185 context_ = CYGetJSContext(context);
1186 JSGlobalContextRetain(context_);
1187 JSValueProtect(context_, object_);
1189 } CYObjectiveCatch }
1191 - (void) dealloc { CYObjectiveTry {
1192 JSValueUnprotect(context_, object_);
1193 JSGlobalContextRelease(context_);
1195 } CYObjectiveCatch }
1197 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1199 JSValueRef exception(NULL);
1200 const char *cyon(CYPoolCCYON(pool, context_, object_));
1201 CYThrow(context_, exception);
1203 return [super cy$toCYON:objective];
1205 return [NSString stringWithUTF8String:cyon];
1206 } CYObjectiveCatch }
1208 - (NSUInteger) count { CYObjectiveTry {
1209 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1210 size_t size(JSPropertyNameArrayGetCount(names));
1211 JSPropertyNameArrayRelease(names);
1213 } CYObjectiveCatch }
1215 - (id) objectForKey:(id)key { CYObjectiveTry {
1216 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1217 if (JSValueIsUndefined(context_, value))
1219 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1220 } CYObjectiveCatch }
1222 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1223 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1224 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1225 JSPropertyNameArrayRelease(names);
1227 } CYObjectiveCatch }
1229 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1230 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1231 } CYObjectiveCatch }
1233 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1234 JSValueRef exception(NULL);
1235 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1236 CYThrow(context_, exception);
1237 } CYObjectiveCatch }
1241 @implementation CYJSArray
1243 - (NSString *) cy$toCYON:(bool)objective {
1245 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1248 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1249 if ((self = [super init]) != nil) {
1251 context_ = CYGetJSContext(context);
1252 JSGlobalContextRetain(context_);
1253 JSValueProtect(context_, object_);
1255 } CYObjectiveCatch }
1257 - (void) dealloc { CYObjectiveTry {
1258 JSValueUnprotect(context_, object_);
1259 JSGlobalContextRelease(context_);
1261 } CYObjectiveCatch }
1263 - (NSUInteger) count { CYObjectiveTry {
1264 return CYArrayLength(context_, object_);
1265 } CYObjectiveCatch }
1267 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1268 size_t bounds([self count]);
1269 if (index >= bounds)
1270 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1271 JSValueRef exception(NULL);
1272 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1273 CYThrow(context_, exception);
1274 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1275 } CYObjectiveCatch }
1277 - (void) addObject:(id)object { CYObjectiveTry {
1278 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1279 } CYObjectiveCatch }
1281 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1282 size_t bounds([self count] + 1);
1283 if (index >= bounds)
1284 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1285 JSValueRef exception(NULL);
1286 JSValueRef arguments[3];
1287 arguments[0] = CYCastJSValue(context_, index);
1288 arguments[1] = CYCastJSValue(context_, 0);
1289 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1290 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1291 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1292 CYThrow(context_, exception);
1293 } CYObjectiveCatch }
1295 - (void) removeLastObject { CYObjectiveTry {
1296 JSValueRef exception(NULL);
1297 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1298 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1299 CYThrow(context_, exception);
1300 } CYObjectiveCatch }
1302 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1303 size_t bounds([self count]);
1304 if (index >= bounds)
1305 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1306 JSValueRef exception(NULL);
1307 JSValueRef arguments[2];
1308 arguments[0] = CYCastJSValue(context_, index);
1309 arguments[1] = CYCastJSValue(context_, 1);
1310 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1311 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1312 CYThrow(context_, exception);
1313 } CYObjectiveCatch }
1315 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1316 size_t bounds([self count]);
1317 if (index >= bounds)
1318 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1319 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1320 } CYObjectiveCatch }
1324 // XXX: inherit from or replace with CYJSObject
1325 @interface CYInternal : NSObject {
1326 JSGlobalContextRef context_;
1327 JSObjectRef object_;
1332 @implementation CYInternal
1335 JSValueUnprotect(context_, object_);
1336 JSGlobalContextRelease(context_);
1340 - (id) initInContext:(JSContextRef)context {
1341 if ((self = [super init]) != nil) {
1342 context_ = CYGetJSContext(context);
1343 JSGlobalContextRetain(context_);
1347 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1348 if (object_ == NULL)
1351 return JSObjectHasProperty(context, object_, name);
1354 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1355 if (object_ == NULL)
1358 return CYGetProperty(context, object_, name);
1361 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1362 @synchronized (self) {
1363 if (object_ == NULL) {
1364 object_ = JSObjectMake(context, NULL, NULL);
1365 JSValueProtect(context, object_);
1369 CYSetProperty(context, object_, name, value);
1372 + (CYInternal *) get:(id)object {
1373 if ($objc_getAssociatedObject == NULL)
1376 @synchronized (object) {
1377 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1384 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1385 if ($objc_getAssociatedObject == NULL)
1388 @synchronized (object) {
1389 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1392 if ($objc_setAssociatedObject == NULL)
1395 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1396 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1405 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1406 Selector_privateData *internal(new Selector_privateData(sel));
1407 return JSObjectMake(context, Selector_, internal);
1410 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1411 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1412 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1413 return reinterpret_cast<SEL>(internal->value_);
1415 return CYCastPointer<SEL>(context, value);
1418 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1419 return (void *) [[NSAutoreleasePool alloc] init];
1420 } CYSadCatch(NULL) }
1422 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1423 return [(NSAutoreleasePool *) handle release];
1426 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1428 return Instance::Make(context, nil);
1429 if (Class _class = objc_getClass(name.data))
1430 return CYMakeInstance(context, _class, true);
1431 if (Protocol *protocol = objc_getProtocol(name.data))
1432 return CYMakeInstance(context, protocol, true);
1434 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1436 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1437 ffi_call(cif, function, value, values);
1440 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1441 switch (type->primitive) {
1442 // XXX: do something epic about blocks
1445 case sig::typename_P:
1446 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1449 case sig::selector_P:
1450 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1458 } CYSadCatch(false) }
1460 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1461 switch (type->primitive) {
1462 // XXX: do something epic about blocks
1465 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1466 JSValueRef value(CYCastJSValue(context, object));
1472 case sig::typename_P:
1473 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1475 case sig::selector_P:
1476 if (SEL sel = *reinterpret_cast<SEL *>(data))
1477 return CYMakeSelector(context, sel);
1481 return CYJSNull(context);
1485 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1487 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1488 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1491 #if OBJC_API_VERSION >= 2
1493 method_getReturnType(method, type, sizeof(type));
1495 const char *type(method_getTypeEncoding(method));
1501 // XXX: possibly use a more "awesome" check?
1505 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1507 return method_getTypeEncoding(method);
1509 const char *name(sel_getName(sel));
1510 size_t length(strlen(name));
1512 char keyed[length + 2];
1514 keyed[length + 1] = '\0';
1515 memcpy(keyed + 1, name, length);
1517 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1518 return entry->value_;
1523 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1524 JSObjectRef _this(CYCastJSObject(context, values[0]));
1525 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1528 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1529 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1532 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1533 Message_privateData *internal(new Message_privateData(sel, type, imp));
1534 return JSObjectMake(context, Message_, internal);
1537 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1538 JSObjectRef function(CYCastJSObject(context, value));
1539 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1540 // XXX: see notes in Library.cpp about needing to leak
1541 return reinterpret_cast<IMP>(internal->GetValue());
1544 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1545 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1546 Class _class(internal->GetValue());
1549 const char *name(CYPoolCString(pool, context, property));
1551 if (SEL sel = sel_getUid(name))
1552 if (class_getInstanceMethod(_class, sel) != NULL)
1558 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1559 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1560 Class _class(internal->GetValue());
1563 const char *name(CYPoolCString(pool, context, property));
1565 if (SEL sel = sel_getUid(name))
1566 if (objc_method *method = class_getInstanceMethod(_class, sel))
1567 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1572 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1573 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1574 Class _class(internal->GetValue());
1577 const char *name(CYPoolCString(pool, context, property));
1579 SEL sel(sel_registerName(name));
1581 objc_method *method(class_getInstanceMethod(_class, sel));
1586 if (JSValueIsObjectOfClass(context, value, Message_)) {
1587 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1588 type = sig::Unparse(pool, &message->signature_);
1589 imp = reinterpret_cast<IMP>(message->GetValue());
1591 type = CYPoolTypeEncoding(pool, context, sel, method);
1592 imp = CYMakeMessage(context, value, type);
1596 method_setImplementation(method, imp);
1599 GSMethodList list(GSAllocMethodList(1));
1600 GSAppendMethodToList(list, sel, type, imp, YES);
1601 GSAddMethodList(_class, list, YES);
1602 GSFlushMethodCacheForClass(_class);
1604 class_addMethod(_class, sel, imp, type);
1611 #if 0 && OBJC_API_VERSION < 2
1612 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1613 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1614 Class _class(internal->GetValue());
1617 const char *name(CYPoolCString(pool, context, property));
1619 if (SEL sel = sel_getUid(name))
1620 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1621 objc_method_list list = {NULL, 1, {method}};
1622 class_removeMethods(_class, &list);
1630 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1631 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1632 Class _class(internal->GetValue());
1634 #if OBJC_API_VERSION >= 2
1636 objc_method **data(class_copyMethodList(_class, &size));
1637 for (size_t i(0); i != size; ++i)
1638 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1641 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1642 for (int i(0); i != methods->method_count; ++i)
1643 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1647 static bool CYHasImplicitProperties(Class _class) {
1648 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1649 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1651 return [_class cy$hasImplicitProperties];
1654 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1655 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1656 id self(internal->GetValue());
1658 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1662 NSString *name(CYCastNSString(pool, context, property));
1664 if (CYInternal *internal = [CYInternal get:self])
1665 if ([internal hasProperty:property inContext:context])
1668 Class _class(object_getClass(self));
1671 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1672 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1673 if ([self cy$hasProperty:name])
1675 } CYPoolCatch(false)
1677 const char *string(CYPoolCString(pool, context, name));
1680 if (class_getProperty(_class, string) != NULL)
1684 if (CYHasImplicitProperties(_class))
1685 if (SEL sel = sel_getUid(string))
1686 if (CYImplements(self, _class, sel, true))
1692 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1693 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1694 id self(internal->GetValue());
1696 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1697 return Internal::Make(context, self, object);
1700 NSString *name(CYCastNSString(pool, context, property));
1702 if (CYInternal *internal = [CYInternal get:self])
1703 if (JSValueRef value = [internal getProperty:property inContext:context])
1707 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1711 const char *string(CYPoolCString(pool, context, name));
1712 Class _class(object_getClass(self));
1715 if (objc_property_t property = class_getProperty(_class, string)) {
1716 PropertyAttributes attributes(property);
1717 SEL sel(sel_registerName(attributes.Getter()));
1718 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1722 if (CYHasImplicitProperties(_class))
1723 if (SEL sel = sel_getUid(string))
1724 if (CYImplements(self, _class, sel, true))
1725 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1730 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1731 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1732 id self(internal->GetValue());
1736 NSString *name(CYCastNSString(pool, context, property));
1737 NSObject *data(CYCastNSObject(pool, context, value));
1740 if ([self cy$setProperty:name to:data])
1744 const char *string(CYPoolCString(pool, context, name));
1745 Class _class(object_getClass(self));
1748 if (objc_property_t property = class_getProperty(_class, string)) {
1749 PropertyAttributes attributes(property);
1750 if (const char *setter = attributes.Setter()) {
1751 SEL sel(sel_registerName(setter));
1752 JSValueRef arguments[1] = {value};
1753 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1759 size_t length(strlen(string));
1761 char set[length + 5];
1767 if (string[0] != '\0') {
1768 set[3] = toupper(string[0]);
1769 memcpy(set + 4, string + 1, length - 1);
1772 set[length + 3] = ':';
1773 set[length + 4] = '\0';
1775 if (SEL sel = sel_getUid(set))
1776 if (CYImplements(self, _class, sel)) {
1777 JSValueRef arguments[1] = {value};
1778 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1782 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1783 [internal setProperty:property toValue:value inContext:context];
1790 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1791 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1792 id self(internal->GetValue());
1795 NSString *name(CYCastNSString(NULL, context, property));
1796 return [self cy$deleteProperty:name];
1798 } CYCatch return /*XXX*/ NULL; }
1800 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1801 const char *name(sel_getName(method_getName(method)));
1802 if (strchr(name, ':') != NULL)
1805 const char *type(method_getTypeEncoding(method));
1806 if (type == NULL || *type == '\0' || *type == 'v')
1809 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1812 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1813 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1814 id self(internal->GetValue());
1817 Class _class(object_getClass(self));
1822 objc_property_t *data(class_copyPropertyList(_class, &size));
1823 for (size_t i(0); i != size; ++i)
1824 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1829 if (CYHasImplicitProperties(_class))
1830 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1831 #if OBJC_API_VERSION >= 2
1833 objc_method **data(class_copyMethodList(current, &size));
1834 for (size_t i(0); i != size; ++i)
1835 Instance_getPropertyNames_message(names, data[i]);
1838 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1839 for (int i(0); i != methods->method_count; ++i)
1840 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1845 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1846 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1847 [self cy$getPropertyNames:names inContext:context];
1851 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1852 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1853 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1857 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1858 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1859 id self(internal->GetValue());
1861 if (![self isKindOfClass:NSBlock_])
1862 CYThrow("non-NSBlock object is not a function");
1863 // XXX: replace above logic with the following assertion
1864 //_assert([self isKindOfClass:NSBlock_]);
1865 // to do this, make it so FunctionInstance_ is the class of blocks
1866 // to do /that/, generalize the various "is exactly Instance_" checks
1867 // then, move Instance_callAsFunction to only be on FunctionInstance
1869 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1871 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1872 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1873 descriptor += sizeof(BlockDescriptor1);
1874 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1875 descriptor += sizeof(BlockDescriptor2);
1876 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1878 if (const char *type = descriptor3->signature) {
1884 sig::Signature signature;
1885 sig::Parse(pool, &signature, type, &Structor_);
1888 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1890 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1891 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1896 CYThrow("NSBlock without signature field passed arguments");
1900 } CYPoolCatch(NULL);
1905 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1906 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1907 Class _class(internal->GetValue());
1908 if (!CYIsClass(_class))
1911 if (CYJSValueIsNSObject(context, instance)) {
1912 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1913 // XXX: this isn't always safe
1914 return [linternal->GetValue() isKindOfClass:_class];
1920 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1922 throw CYJSError(context, "incorrect number of arguments to Instance");
1924 id value(CYCastNSObject(pool, context, arguments[0]));
1926 value = [NSNull null];
1927 return CYCastJSValue(context, [value cy$box]);
1930 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1931 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1934 id self(internal->GetValue());
1935 const char *name(CYPoolCString(pool, context, property));
1937 if (object_getInstanceVariable(self, name, NULL) != NULL)
1943 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1944 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1947 id self(internal->GetValue());
1948 const char *name(CYPoolCString(pool, context, property));
1950 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1951 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1952 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1953 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1959 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1960 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1963 id self(internal->GetValue());
1964 const char *name(CYPoolCString(pool, context, property));
1966 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1967 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1968 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1975 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1976 if (Class super = class_getSuperclass(_class))
1977 Internal_getPropertyNames_(super, names);
1979 #if OBJC_API_VERSION >= 2
1981 objc_ivar **data(class_copyIvarList(_class, &size));
1982 for (size_t i(0); i != size; ++i)
1983 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1986 if (objc_ivar_list *ivars = _class->ivars)
1987 for (int i(0); i != ivars->ivar_count; ++i)
1988 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1992 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1993 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1996 id self(internal->GetValue());
1997 Class _class(object_getClass(self));
1999 Internal_getPropertyNames_(_class, names);
2002 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2003 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2004 return internal->GetOwner();
2007 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2009 NSString *name(CYCastNSString(pool, context, property));
2010 if (Class _class = NSClassFromString(name))
2011 return CYMakeInstance(context, _class, true);
2015 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2017 size_t size(objc_getClassList(NULL, 0));
2018 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2021 size_t writ(objc_getClassList(data, size));
2024 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2030 for (size_t i(0); i != writ; ++i)
2031 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2037 while (Class _class = objc_next_class(&state))
2038 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2042 #if OBJC_API_VERSION >= 2
2043 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2044 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2047 const char *name(CYPoolCString(pool, context, property));
2049 const char **data(objc_copyClassNamesForImage(internal, &size));
2051 for (size_t i(0); i != size; ++i)
2052 if (strcmp(name, data[i]) == 0) {
2053 if (Class _class = objc_getClass(name)) {
2054 value = CYMakeInstance(context, _class, true);
2065 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2066 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2068 const char **data(objc_copyClassNamesForImage(internal, &size));
2069 for (size_t i(0); i != size; ++i)
2070 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2074 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2076 const char *name(CYPoolCString(pool, context, property));
2078 const char **data(objc_copyImageNames(&size));
2079 for (size_t i(0); i != size; ++i)
2080 if (strcmp(name, data[i]) == 0) {
2089 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2090 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2094 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2096 const char **data(objc_copyImageNames(&size));
2097 for (size_t i(0); i != size; ++i)
2098 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2103 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2105 const char *name(CYPoolCString(pool, context, property));
2106 if (Protocol *protocol = objc_getProtocol(name))
2107 return CYMakeInstance(context, protocol, true);
2111 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2112 #if OBJC_API_VERSION >= 2
2114 Protocol **data(objc_copyProtocolList(&size));
2115 for (size_t i(0); i != size; ++i)
2116 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2123 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2125 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2127 return Instance::Make(context, nil);
2131 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2132 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2136 static bool stret(ffi_type *ffi_type) {
2137 return ffi_type->type == FFI_TYPE_STRUCT && (
2138 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2139 struct_forward_array[ffi_type->size] != 0
2144 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 {
2148 _class = object_getClass(self);
2152 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2153 imp = method_getImplementation(method);
2154 type = method_getTypeEncoding(method);
2159 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2161 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2162 type = CYPoolCString(pool, context, [method _typeString]);
2170 sig::Signature signature;
2171 sig::Parse(pool, &signature, type, &Structor_);
2173 size_t used(count + 3);
2174 if (used > signature.count) {
2175 sig::Element *elements(new (pool) sig::Element[used]);
2176 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2178 for (size_t index(signature.count); index != used; ++index) {
2179 sig::Element *element(&elements[index]);
2180 element->name = NULL;
2181 element->offset = _not(size_t);
2183 sig::Type *type(new (pool) sig::Type);
2184 memset(type, 0, sizeof(*type));
2185 type->primitive = sig::object_P;
2186 element->type = type;
2189 signature.elements = elements;
2190 signature.count = used;
2194 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2198 if (stret(cif.rtype))
2199 imp = class_getMethodImplementation_stret(_class, _cmd);
2201 imp = class_getMethodImplementation(_class, _cmd);
2203 objc_super super = {self, _class};
2204 imp = objc_msg_lookup_super(&super, _cmd);
2208 void (*function)() = reinterpret_cast<void (*)()>(imp);
2209 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2212 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2214 throw CYJSError(context, "too few arguments to objc_msgSend");
2224 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2225 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2226 self = internal->GetValue();
2227 _class = internal->class_;;
2228 uninitialized = false;
2229 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2230 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2231 self = internal->GetValue();
2233 uninitialized = internal->IsUninitialized();
2235 internal->value_ = nil;
2237 self = CYCastNSObject(pool, context, arguments[0]);
2239 uninitialized = false;
2243 return CYJSNull(context);
2245 _cmd = CYCastSEL(context, arguments[1]);
2247 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2250 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2251 JSValueRef setup[count + 2];
2254 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2255 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2258 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2260 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2262 // XXX: handle Instance::Uninitialized?
2263 id self(CYCastNSObject(pool, context, _this));
2267 setup[1] = &internal->sel_;
2269 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2272 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2274 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2276 id self(CYCastNSObject(pool, context, arguments[0]));
2277 Class _class(CYCastClass(pool, context, arguments[1]));
2278 return cy::Super::Make(context, self, _class);
2281 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2283 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2285 const char *name(CYPoolCString(pool, context, arguments[0]));
2286 return CYMakeSelector(context, sel_registerName(name));
2289 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2291 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2292 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2293 return CYMakeInstance(context, self, false);
2296 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2297 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2298 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2301 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2302 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2303 Type_privateData *typical(internal->GetType());
2308 if (typical == NULL) {
2312 type = typical->type_;
2313 ffi = typical->ffi_;
2316 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2319 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2320 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2321 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2324 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2325 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2326 id self(internal->GetValue());
2327 if (!CYIsClass(self))
2328 return CYJSUndefined(context);
2329 return CYGetClassPrototype(context, self);
2332 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2333 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2334 id self(internal->GetValue());
2335 if (!CYIsClass(self))
2336 return CYJSUndefined(context);
2337 return Messages::Make(context, (Class) self);
2340 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2341 if (!CYJSValueIsNSObject(context, _this))
2344 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2345 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2348 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2349 if (!CYJSValueIsNSObject(context, _this))
2352 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2353 id value(internal->GetValue());
2360 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2362 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2363 return CYJSUndefined(context);
2364 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2367 return CYCastJSValue(context, CYJSString(context, [value description]));
2369 } CYCatch return /*XXX*/ NULL; }
2371 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2372 if (!CYJSValueIsNSObject(context, _this))
2375 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2376 id value(internal->GetValue());
2378 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2381 if (JSValueRef result = [value cy$valueOfInContext:context])
2385 } CYCatch return /*XXX*/ NULL; }
2387 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2388 if (!CYJSValueIsNSObject(context, _this))
2391 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2392 // XXX: but... but... THIS ISN'T A POINTER! :(
2393 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2394 } CYCatch return /*XXX*/ NULL; }
2396 static JSValueRef Instance_callAsFunction_toString(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 id value(internal->GetValue());
2404 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2405 return CYCastJSValue(context, CYJSString(context, [value description]));
2407 } CYCatch return /*XXX*/ NULL; }
2409 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2410 if (!CYJSValueIsNSObject(context, _this))
2413 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2414 id value(internal->GetValue());
2416 if (!CYIsClass(value))
2417 CYThrow("non-Class object cannot be used as Type");
2419 // XXX: this is a very silly implementation
2421 std::ostringstream type;
2423 type << class_getName(value);
2427 return CYMakeType(context, type.str().c_str());
2429 } CYCatch return /*XXX*/ NULL; }
2431 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2432 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2433 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2436 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2437 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2440 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2441 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2442 const char *name(sel_getName(internal->GetValue()));
2445 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2446 return CYCastJSValue(context, CYJSString(context, string));
2448 } CYCatch return /*XXX*/ NULL; }
2450 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2452 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2455 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2456 SEL sel(internal->GetValue());
2458 objc_method *method;
2459 if (Class _class = CYCastClass(pool, context, arguments[0]))
2460 method = class_getInstanceMethod(_class, sel);
2464 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2465 return CYCastJSValue(context, CYJSString(type));
2467 return CYJSNull(context);
2470 static JSStaticValue Selector_staticValues[2] = {
2471 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2472 {NULL, NULL, NULL, 0}
2475 static JSStaticValue Instance_staticValues[5] = {
2476 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2477 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2478 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2479 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2480 {NULL, NULL, NULL, 0}
2483 static JSStaticFunction Instance_staticFunctions[7] = {
2484 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2485 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2486 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2487 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2488 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2489 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2493 static JSStaticFunction Class_staticFunctions[2] = {
2494 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2498 static JSStaticFunction Internal_staticFunctions[2] = {
2499 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2503 static JSStaticFunction Selector_staticFunctions[5] = {
2504 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2505 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2506 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2507 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2512 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_(context) {
2513 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2514 } CYObjectiveCatch }
2517 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2518 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2519 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2520 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2522 apr_pool_t *pool(CYGetGlobalPool());
2524 Object_type = new(pool) Type_privateData("@");
2525 Selector_type = new(pool) Type_privateData(":");
2528 // XXX: apparently, iOS now has both of these
2529 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2530 if (NSCFBoolean_ == nil)
2531 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2533 NSCFType_ = objc_getClass("NSCFType");
2534 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2535 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2536 NSZombie_ = objc_getClass("_NSZombie_");
2538 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2541 NSArray_ = objc_getClass("NSArray");
2542 NSBlock_ = objc_getClass("NSBlock");
2543 NSDictionary_ = objc_getClass("NSDictionary");
2544 NSString_ = objc_getClass("NSString");
2545 Object_ = objc_getClass("Object");
2547 JSClassDefinition definition;
2549 definition = kJSClassDefinitionEmpty;
2550 definition.className = "Instance";
2551 definition.staticValues = Instance_staticValues;
2552 definition.staticFunctions = Instance_staticFunctions;
2553 definition.hasProperty = &Instance_hasProperty;
2554 definition.getProperty = &Instance_getProperty;
2555 definition.setProperty = &Instance_setProperty;
2556 definition.deleteProperty = &Instance_deleteProperty;
2557 definition.getPropertyNames = &Instance_getPropertyNames;
2558 definition.callAsConstructor = &Instance_callAsConstructor;
2559 definition.callAsFunction = &Instance_callAsFunction;
2560 definition.hasInstance = &Instance_hasInstance;
2561 definition.finalize = &CYFinalize;
2562 Instance_ = JSClassCreate(&definition);
2564 definition.className = "ArrayInstance";
2565 ArrayInstance_ = JSClassCreate(&definition);
2567 definition.className = "FunctionInstance";
2568 FunctionInstance_ = JSClassCreate(&definition);
2570 definition.className = "ObjectInstance";
2571 ObjectInstance_ = JSClassCreate(&definition);
2573 definition.className = "StringInstance";
2574 StringInstance_ = JSClassCreate(&definition);
2576 definition = kJSClassDefinitionEmpty;
2577 definition.className = "Class";
2578 definition.staticFunctions = Class_staticFunctions;
2579 Class_ = JSClassCreate(&definition);
2581 definition = kJSClassDefinitionEmpty;
2582 definition.className = "Internal";
2583 definition.staticFunctions = Internal_staticFunctions;
2584 definition.hasProperty = &Internal_hasProperty;
2585 definition.getProperty = &Internal_getProperty;
2586 definition.setProperty = &Internal_setProperty;
2587 definition.getPropertyNames = &Internal_getPropertyNames;
2588 definition.finalize = &CYFinalize;
2589 Internal_ = JSClassCreate(&definition);
2591 definition = kJSClassDefinitionEmpty;
2592 definition.className = "Message";
2593 definition.staticFunctions = cy::Functor::StaticFunctions;
2594 definition.callAsFunction = &Message_callAsFunction;
2595 definition.finalize = &CYFinalize;
2596 Message_ = JSClassCreate(&definition);
2598 definition = kJSClassDefinitionEmpty;
2599 definition.className = "Messages";
2600 definition.hasProperty = &Messages_hasProperty;
2601 definition.getProperty = &Messages_getProperty;
2602 definition.setProperty = &Messages_setProperty;
2603 #if 0 && OBJC_API_VERSION < 2
2604 definition.deleteProperty = &Messages_deleteProperty;
2606 definition.getPropertyNames = &Messages_getPropertyNames;
2607 definition.finalize = &CYFinalize;
2608 Messages_ = JSClassCreate(&definition);
2610 definition = kJSClassDefinitionEmpty;
2611 definition.className = "Selector";
2612 definition.staticValues = Selector_staticValues;
2613 definition.staticFunctions = Selector_staticFunctions;
2614 definition.callAsFunction = &Selector_callAsFunction;
2615 definition.finalize = &CYFinalize;
2616 Selector_ = JSClassCreate(&definition);
2618 definition = kJSClassDefinitionEmpty;
2619 definition.className = "Super";
2620 definition.staticFunctions = Internal_staticFunctions;
2621 definition.finalize = &CYFinalize;
2622 Super_ = JSClassCreate(&definition);
2624 definition = kJSClassDefinitionEmpty;
2625 definition.className = "ObjectiveC::Classes";
2626 definition.getProperty = &ObjectiveC_Classes_getProperty;
2627 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2628 ObjectiveC_Classes_ = JSClassCreate(&definition);
2630 definition = kJSClassDefinitionEmpty;
2631 definition.className = "ObjectiveC::Constants";
2632 definition.getProperty = &ObjectiveC_Constants_getProperty;
2633 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2634 ObjectiveC_Constants_ = JSClassCreate(&definition);
2636 #if OBJC_API_VERSION >= 2
2637 definition = kJSClassDefinitionEmpty;
2638 definition.className = "ObjectiveC::Images";
2639 definition.getProperty = &ObjectiveC_Images_getProperty;
2640 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2641 ObjectiveC_Images_ = JSClassCreate(&definition);
2643 definition = kJSClassDefinitionEmpty;
2644 definition.className = "ObjectiveC::Image::Classes";
2645 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2646 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2647 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2650 definition = kJSClassDefinitionEmpty;
2651 definition.className = "ObjectiveC::Protocols";
2652 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2653 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2654 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2657 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2661 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2662 JSObjectRef global(CYGetGlobalObject(context));
2663 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2664 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2665 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2666 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2668 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2669 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2671 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2672 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2673 CYArrayPush(context, alls, protocols);
2675 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2676 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2677 CYArrayPush(context, alls, classes);
2679 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2680 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2681 CYArrayPush(context, alls, constants);
2683 #if OBJC_API_VERSION >= 2
2684 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2687 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2688 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2689 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2690 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2691 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2693 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2694 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2696 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2697 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2698 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2699 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2700 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2702 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2703 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2704 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2705 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2706 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2708 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2709 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2710 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2711 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2712 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2714 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2715 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2716 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2717 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2718 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2720 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2721 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2722 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2724 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2725 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2726 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2728 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2729 CYSetProperty(context, Instance, CYJSString("box"), box);
2731 #if defined(__APPLE__) && defined(__arm__) && 0
2732 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2735 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2737 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2738 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2741 static CYHooks CYObjectiveCHooks = {
2742 &CYObjectiveC_ExecuteStart,
2743 &CYObjectiveC_ExecuteEnd,
2744 &CYObjectiveC_CallFunction,
2745 &CYObjectiveC_Initialize,
2746 &CYObjectiveC_SetupContext,
2747 &CYObjectiveC_PoolFFI,
2748 &CYObjectiveC_FromFFI,
2751 struct CYObjectiveC {
2753 hooks_ = &CYObjectiveCHooks;
2754 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2755 _assert(hooks_ != NULL);