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, bool array) {
330 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
331 if (_class == NSArray_)
333 if (Class super = class_getSuperclass(_class))
334 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
336 JSObjectSetPrototype(context, value, Array_prototype_);*/
340 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
341 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
345 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
346 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
350 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
351 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
352 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
356 Instance::~Instance() {
357 if ((flags_ & Transient) == 0)
358 // XXX: does this handle background threads correctly?
359 // XXX: this simply does not work on the console because I'm stupid
360 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
363 struct Message_privateData :
368 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
369 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
375 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
376 Instance::Flags flags;
379 flags = Instance::Transient;
381 flags = Instance::None;
382 object = [object retain];
385 return Instance::Make(context, object, flags);
388 @interface NSMethodSignature (Cycript)
389 - (NSString *) _typeString;
392 @interface NSObject (Cycript)
394 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
395 - (JSType) cy$JSType;
397 - (NSObject *) cy$toJSON:(NSString *)key;
398 - (NSString *) cy$toCYON;
400 - (bool) cy$hasProperty:(NSString *)name;
401 - (NSObject *) cy$getProperty:(NSString *)name;
402 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
403 - (bool) cy$deleteProperty:(NSString *)name;
404 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
406 + (bool) cy$hasImplicitProperties;
412 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
415 NSString *CYCastNSCYON(id value) {
421 Class _class(object_getClass(value));
422 SEL sel(@selector(cy$toCYON));
424 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
425 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
426 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
427 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
428 string = [value cy$toCYON];
433 else if (value == NSZombie_)
434 string = @"_NSZombie_";
435 else if (_class == NSZombie_)
436 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
437 // XXX: frowny /in/ the pants
438 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
442 string = [NSString stringWithFormat:@"%@", value];
447 string = @"undefined";
454 struct PropertyAttributes {
459 const char *variable;
472 PropertyAttributes(objc_property_t property) :
484 name = property_getName(property);
485 const char *attributes(property_getAttributes(property));
487 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
489 case 'R': readonly = true; break;
490 case 'C': copy = true; break;
491 case '&': retain = true; break;
492 case 'N': nonatomic = true; break;
493 case 'G': getter_ = token + 1; break;
494 case 'S': setter_ = token + 1; break;
495 case 'V': variable = token + 1; break;
499 /*if (variable == NULL) {
500 variable = property_getName(property);
501 size_t size(strlen(variable));
502 char *name(new(pool_) char[size + 2]);
504 memcpy(name + 1, variable, size);
505 name[size + 1] = '\0';
510 const char *Getter() {
512 getter_ = apr_pstrdup(pool_, name);
516 const char *Setter() {
517 if (setter_ == NULL && !readonly) {
518 size_t length(strlen(name));
520 char *temp(new(pool_) char[length + 5]);
526 temp[3] = toupper(name[0]);
527 memcpy(temp + 4, name + 1, length - 1);
530 temp[length + 3] = ':';
531 temp[length + 4] = '\0';
542 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
543 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
548 @interface CYWebUndefined : NSObject {
551 + (CYWebUndefined *) undefined;
555 @implementation CYWebUndefined
557 + (CYWebUndefined *) undefined {
558 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
564 #define WebUndefined CYWebUndefined
567 /* Bridge: CYJSObject {{{ */
568 @interface CYJSObject : NSMutableDictionary {
570 JSGlobalContextRef context_;
573 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
575 - (NSObject *) cy$toJSON:(NSString *)key;
577 - (NSUInteger) count;
578 - (id) objectForKey:(id)key;
579 - (NSEnumerator *) keyEnumerator;
580 - (void) setObject:(id)object forKey:(id)key;
581 - (void) removeObjectForKey:(id)key;
585 /* Bridge: CYJSArray {{{ */
586 @interface CYJSArray : NSMutableArray {
588 JSGlobalContextRef context_;
591 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
593 - (NSUInteger) count;
594 - (id) objectAtIndex:(NSUInteger)index;
596 - (void) addObject:(id)anObject;
597 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
598 - (void) removeLastObject;
599 - (void) removeObjectAtIndex:(NSUInteger)index;
600 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
605 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
606 JSValueRef exception(NULL);
607 JSObjectRef constructor(CYGetCachedObject(context, cache));
608 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
609 CYThrow(context, exception);
613 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
614 if (JSValueIsObjectOfClass(context, object, Instance_)) {
615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
616 return internal->GetValue();
619 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
620 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
621 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
624 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
625 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
629 @interface NSBoolNumber : NSNumber {
634 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
638 switch (JSType type = JSValueGetType(context, value)) {
639 case kJSTypeUndefined:
640 object = [WebUndefined undefined];
650 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
653 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
659 object = CYCopyNSNumber(context, value);
664 object = CYCopyNSString(context, value);
669 // XXX: this might could be more efficient
670 object = CYCastNSObject(pool, context, (JSObjectRef) value);
675 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
682 return CYPoolRelease(pool, object);
684 return [object retain];
687 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
688 return CYNSObject(pool, context, value, true);
691 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
692 return CYNSObject(pool, context, value, false);
695 /* Bridge: NSArray {{{ */
696 @implementation NSArray (Cycript)
699 return [[self mutableCopy] autorelease];
702 - (NSString *) cy$toCYON {
703 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
704 [json appendString:@"@["];
708 for (id object in self) {
710 for (size_t index(0), count([self count]); index != count; ++index) {
711 id object([self objectAtIndex:index]);
714 [json appendString:@","];
717 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
718 [json appendString:CYCastNSCYON(object)];
720 [json appendString:@","];
725 [json appendString:@"]"];
729 - (bool) cy$hasProperty:(NSString *)name {
730 if ([name isEqualToString:@"length"])
733 size_t index(CYGetIndex(name));
734 if (index == _not(size_t) || index >= [self count])
735 return [super cy$hasProperty:name];
740 - (NSObject *) cy$getProperty:(NSString *)name {
741 if ([name isEqualToString:@"length"]) {
742 NSUInteger count([self count]);
744 return [NSNumber numberWithUnsignedInteger:count];
746 return [NSNumber numberWithUnsignedInt:count];
750 size_t index(CYGetIndex(name));
751 if (index == _not(size_t) || index >= [self count])
752 return [super cy$getProperty:name];
754 return [self objectAtIndex:index];
757 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
758 [super cy$getPropertyNames:names inContext:context];
760 for (size_t index(0), count([self count]); index != count; ++index) {
761 id object([self objectAtIndex:index]);
762 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
764 sprintf(name, "%zu", index);
765 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
770 + (bool) cy$hasImplicitProperties {
776 /* Bridge: NSBlock {{{ */
783 /* Bridge: NSBoolNumber {{{ */
785 @implementation NSBoolNumber (Cycript)
787 - (JSType) cy$JSType {
788 return kJSTypeBoolean;
791 - (NSObject *) cy$toJSON:(NSString *)key {
795 - (NSString *) cy$toCYON {
796 return [self boolValue] ? @"@true" : @"@false";
799 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
800 return CYCastJSValue(context, (bool) [self boolValue]);
806 /* Bridge: NSDictionary {{{ */
807 @implementation NSDictionary (Cycript)
810 return [[self mutableCopy] autorelease];
813 - (NSString *) cy$toCYON {
814 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
815 [json appendString:@"@{"];
819 for (NSObject *key in self) {
821 NSEnumerator *keys([self keyEnumerator]);
822 while (NSObject *key = [keys nextObject]) {
825 [json appendString:@","];
828 [json appendString:CYCastNSCYON(key)];
829 [json appendString:@":"];
830 NSObject *object([self objectForKey:key]);
831 [json appendString:CYCastNSCYON(object)];
834 [json appendString:@"}"];
838 - (bool) cy$hasProperty:(NSString *)name {
839 return [self objectForKey:name] != nil;
842 - (NSObject *) cy$getProperty:(NSString *)name {
843 return [self objectForKey:name];
846 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
847 [super cy$getPropertyNames:names inContext:context];
850 for (NSObject *key in self) {
852 NSEnumerator *keys([self keyEnumerator]);
853 while (NSObject *key = [keys nextObject]) {
855 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
859 + (bool) cy$hasImplicitProperties {
865 /* Bridge: NSMutableArray {{{ */
866 @implementation NSMutableArray (Cycript)
868 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
869 if ([name isEqualToString:@"length"]) {
870 // XXX: is this not intelligent?
871 NSNumber *number(reinterpret_cast<NSNumber *>(value));
873 NSUInteger size([number unsignedIntegerValue]);
875 NSUInteger size([number unsignedIntValue]);
877 NSUInteger count([self count]);
879 [self removeObjectsInRange:NSMakeRange(size, count - size)];
880 else if (size != count) {
881 WebUndefined *undefined([WebUndefined undefined]);
882 for (size_t i(count); i != size; ++i)
883 [self addObject:undefined];
888 size_t index(CYGetIndex(name));
889 if (index == _not(size_t))
890 return [super cy$setProperty:name to:value];
892 id object(value ?: [NSNull null]);
894 size_t count([self count]);
896 [self replaceObjectAtIndex:index withObject:object];
898 if (index != count) {
899 WebUndefined *undefined([WebUndefined undefined]);
900 for (size_t i(count); i != index; ++i)
901 [self addObject:undefined];
904 [self addObject:object];
910 - (bool) cy$deleteProperty:(NSString *)name {
911 size_t index(CYGetIndex(name));
912 if (index == _not(size_t) || index >= [self count])
913 return [super cy$deleteProperty:name];
914 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
920 /* Bridge: NSMutableDictionary {{{ */
921 @implementation NSMutableDictionary (Cycript)
923 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
924 [self setObject:(value ?: [NSNull null]) forKey:name];
928 - (bool) cy$deleteProperty:(NSString *)name {
929 if ([self objectForKey:name] == nil)
932 [self removeObjectForKey:name];
939 /* Bridge: NSNumber {{{ */
940 @implementation NSNumber (Cycript)
942 - (JSType) cy$JSType {
944 // XXX: this just seems stupid
945 if ([self class] == NSCFBoolean_)
946 return kJSTypeBoolean;
948 return kJSTypeNumber;
951 - (NSObject *) cy$toJSON:(NSString *)key {
955 - (NSString *) cy$toCYON {
956 return [self cy$JSType] != kJSTypeBoolean ? [NSString stringWithFormat:@"@%@", self] : [self boolValue] ? @"@true" : @"@false";
959 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
960 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
965 /* Bridge: NSNull {{{ */
966 @implementation NSNull (Cycript)
968 - (JSType) cy$JSType {
972 - (NSObject *) cy$toJSON:(NSString *)key {
976 - (NSString *) cy$toCYON {
982 /* Bridge: NSObject {{{ */
983 @implementation NSObject (Cycript)
989 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
993 - (JSType) cy$JSType {
994 return kJSTypeObject;
997 - (NSObject *) cy$toJSON:(NSString *)key {
998 return [self description];
1001 - (NSString *) cy$toCYON {
1002 return [[self cy$toJSON:@""] cy$toCYON];
1005 - (bool) cy$hasProperty:(NSString *)name {
1009 - (NSObject *) cy$getProperty:(NSString *)name {
1013 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1017 - (bool) cy$deleteProperty:(NSString *)name {
1021 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1024 + (bool) cy$hasImplicitProperties {
1030 /* Bridge: NSProxy {{{ */
1031 @implementation NSProxy (Cycript)
1033 - (NSObject *) cy$toJSON:(NSString *)key {
1034 return [self description];
1037 - (NSString *) cy$toCYON {
1038 return [[self cy$toJSON:@""] cy$toCYON];
1043 /* Bridge: NSString {{{ */
1044 @implementation NSString (Cycript)
1047 return [[self copy] autorelease];
1050 - (JSType) cy$JSType {
1051 return kJSTypeString;
1054 - (NSObject *) cy$toJSON:(NSString *)key {
1058 - (NSString *) cy$toCYON {
1059 std::ostringstream str;
1061 CYUTF8String string(CYCastUTF8String(self));
1062 CYStringify(str, string.data, string.size);
1063 std::string value(str.str());
1064 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1067 - (bool) cy$hasProperty:(NSString *)name {
1068 if ([name isEqualToString:@"length"])
1071 size_t index(CYGetIndex(name));
1072 if (index == _not(size_t) || index >= [self length])
1073 return [super cy$hasProperty:name];
1078 - (NSObject *) cy$getProperty:(NSString *)name {
1079 if ([name isEqualToString:@"length"]) {
1080 NSUInteger count([self length]);
1082 return [NSNumber numberWithUnsignedInteger:count];
1084 return [NSNumber numberWithUnsignedInt:count];
1088 size_t index(CYGetIndex(name));
1089 if (index == _not(size_t) || index >= [self length])
1090 return [super cy$getProperty:name];
1092 return [self substringWithRange:NSMakeRange(index, 1)];
1095 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1096 [super cy$getPropertyNames:names inContext:context];
1098 for (size_t index(0), length([self length]); index != length; ++index) {
1100 sprintf(name, "%zu", index);
1101 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1105 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1106 + (bool) cy$hasImplicitProperties {
1110 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1111 return CYCastJSValue(context, CYJSString(context, self));
1112 } CYObjectiveCatch }
1116 /* Bridge: WebUndefined {{{ */
1117 @implementation WebUndefined (Cycript)
1119 - (JSType) cy$JSType {
1120 return kJSTypeUndefined;
1123 - (NSObject *) cy$toJSON:(NSString *)key {
1127 - (NSString *) cy$toCYON {
1128 return @"undefined";
1131 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1132 return CYJSUndefined(context);
1133 } CYObjectiveCatch }
1138 static bool CYIsClass(id self) {
1140 // XXX: this is a lame object_isClass
1141 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1143 return GSObjCIsClass(self);
1147 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1148 id self(CYCastNSObject(pool, context, value));
1149 if (CYIsClass(self))
1150 return (Class) self;
1151 throw CYJSError(context, "got something that is not a Class");
1155 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1157 size_t size(JSPropertyNameArrayGetCount(names));
1158 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1159 for (size_t index(0); index != size; ++index)
1160 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1164 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1166 return CYJSNull(context);
1168 return CYMakeInstance(context, value, false);
1169 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1171 @implementation CYJSObject
1173 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1174 if ((self = [super init]) != nil) {
1176 context_ = CYGetJSContext(context);
1177 JSGlobalContextRetain(context_);
1178 JSValueProtect(context_, object_);
1180 } CYObjectiveCatch }
1182 - (void) dealloc { CYObjectiveTry {
1183 JSValueUnprotect(context_, object_);
1184 JSGlobalContextRelease(context_);
1186 } CYObjectiveCatch }
1188 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1189 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1190 if (!CYIsCallable(context_, toJSON))
1191 return [super cy$toJSON:key];
1193 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1194 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1195 // XXX: do I really want an NSNull here?!
1196 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1198 } CYObjectiveCatch }
1200 - (NSString *) cy$toCYON { CYObjectiveTry {
1202 JSValueRef exception(NULL);
1203 const char *cyon(CYPoolCCYON(pool, context_, object_));
1204 CYThrow(context_, exception);
1206 return [super cy$toCYON];
1208 return [NSString stringWithUTF8String:cyon];
1209 } CYObjectiveCatch }
1211 - (NSUInteger) count { CYObjectiveTry {
1212 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1213 size_t size(JSPropertyNameArrayGetCount(names));
1214 JSPropertyNameArrayRelease(names);
1216 } CYObjectiveCatch }
1218 - (id) objectForKey:(id)key { CYObjectiveTry {
1219 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1220 if (JSValueIsUndefined(context_, value))
1222 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1223 } CYObjectiveCatch }
1225 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1226 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1227 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1228 JSPropertyNameArrayRelease(names);
1230 } CYObjectiveCatch }
1232 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1233 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1234 } CYObjectiveCatch }
1236 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1237 JSValueRef exception(NULL);
1238 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1239 CYThrow(context_, exception);
1240 } CYObjectiveCatch }
1244 @implementation CYJSArray
1246 - (NSString *) cy$toCYON {
1248 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1251 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1252 if ((self = [super init]) != nil) {
1254 context_ = CYGetJSContext(context);
1255 JSGlobalContextRetain(context_);
1256 JSValueProtect(context_, object_);
1258 } CYObjectiveCatch }
1260 - (void) dealloc { CYObjectiveTry {
1261 JSValueUnprotect(context_, object_);
1262 JSGlobalContextRelease(context_);
1264 } CYObjectiveCatch }
1266 - (NSUInteger) count { CYObjectiveTry {
1267 return CYArrayLength(context_, object_);
1268 } CYObjectiveCatch }
1270 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1271 size_t bounds([self count]);
1272 if (index >= bounds)
1273 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1274 JSValueRef exception(NULL);
1275 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1276 CYThrow(context_, exception);
1277 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1278 } CYObjectiveCatch }
1280 - (void) addObject:(id)object { CYObjectiveTry {
1281 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1282 } CYObjectiveCatch }
1284 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1285 size_t bounds([self count] + 1);
1286 if (index >= bounds)
1287 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1288 JSValueRef exception(NULL);
1289 JSValueRef arguments[3];
1290 arguments[0] = CYCastJSValue(context_, index);
1291 arguments[1] = CYCastJSValue(context_, 0);
1292 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1293 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1294 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1295 CYThrow(context_, exception);
1296 } CYObjectiveCatch }
1298 - (void) removeLastObject { CYObjectiveTry {
1299 JSValueRef exception(NULL);
1300 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1301 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1302 CYThrow(context_, exception);
1303 } CYObjectiveCatch }
1305 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1306 size_t bounds([self count]);
1307 if (index >= bounds)
1308 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1309 JSValueRef exception(NULL);
1310 JSValueRef arguments[2];
1311 arguments[0] = CYCastJSValue(context_, index);
1312 arguments[1] = CYCastJSValue(context_, 1);
1313 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1314 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1315 CYThrow(context_, exception);
1316 } CYObjectiveCatch }
1318 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1319 size_t bounds([self count]);
1320 if (index >= bounds)
1321 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1322 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1323 } CYObjectiveCatch }
1327 // XXX: inherit from or replace with CYJSObject
1328 @interface CYInternal : NSObject {
1329 JSGlobalContextRef context_;
1330 JSObjectRef object_;
1335 @implementation CYInternal
1338 JSValueUnprotect(context_, object_);
1339 JSGlobalContextRelease(context_);
1343 - (id) initInContext:(JSContextRef)context {
1344 if ((self = [super init]) != nil) {
1345 context_ = CYGetJSContext(context);
1346 JSGlobalContextRetain(context_);
1350 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1351 if (object_ == NULL)
1354 return JSObjectHasProperty(context, object_, name);
1357 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1358 if (object_ == NULL)
1361 return CYGetProperty(context, object_, name);
1364 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1365 @synchronized (self) {
1366 if (object_ == NULL) {
1367 object_ = JSObjectMake(context, NULL, NULL);
1368 JSValueProtect(context, object_);
1372 CYSetProperty(context, object_, name, value);
1375 + (CYInternal *) get:(id)object {
1376 if ($objc_getAssociatedObject == NULL)
1379 @synchronized (object) {
1380 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1387 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1388 if ($objc_getAssociatedObject == NULL)
1391 @synchronized (object) {
1392 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1395 if ($objc_setAssociatedObject == NULL)
1398 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1399 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1408 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1409 Selector_privateData *internal(new Selector_privateData(sel));
1410 return JSObjectMake(context, Selector_, internal);
1413 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1414 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1415 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1416 return reinterpret_cast<SEL>(internal->value_);
1418 return CYCastPointer<SEL>(context, value);
1421 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1422 return (void *) [[NSAutoreleasePool alloc] init];
1423 } CYSadCatch(NULL) }
1425 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1426 return [(NSAutoreleasePool *) handle release];
1429 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1431 return Instance::Make(context, nil);
1432 if (Class _class = objc_getClass(name.data))
1433 return CYMakeInstance(context, _class, true);
1434 if (Protocol *protocol = objc_getProtocol(name.data))
1435 return CYMakeInstance(context, protocol, true);
1437 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1439 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1440 ffi_call(cif, function, value, values);
1443 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1444 switch (type->primitive) {
1445 // XXX: do something epic about blocks
1448 case sig::typename_P:
1449 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1452 case sig::selector_P:
1453 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1461 } CYSadCatch(false) }
1463 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1464 switch (type->primitive) {
1465 // XXX: do something epic about blocks
1468 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1469 JSValueRef value(CYCastJSValue(context, object));
1475 case sig::typename_P:
1476 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1478 case sig::selector_P:
1479 if (SEL sel = *reinterpret_cast<SEL *>(data))
1480 return CYMakeSelector(context, sel);
1484 return CYJSNull(context);
1488 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1490 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1491 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1494 #if OBJC_API_VERSION >= 2
1496 method_getReturnType(method, type, sizeof(type));
1498 const char *type(method_getTypeEncoding(method));
1504 // XXX: possibly use a more "awesome" check?
1508 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1510 return method_getTypeEncoding(method);
1512 const char *name(sel_getName(sel));
1513 size_t length(strlen(name));
1515 char keyed[length + 2];
1517 keyed[length + 1] = '\0';
1518 memcpy(keyed + 1, name, length);
1520 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1521 return entry->value_;
1526 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1527 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1529 JSContextRef context(internal->context_);
1531 size_t count(internal->cif_.nargs);
1532 JSValueRef values[count];
1534 for (size_t index(0); index != count; ++index)
1535 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1537 JSObjectRef _this(CYCastJSObject(context, values[0]));
1539 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1540 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1543 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1544 Message_privateData *internal(new Message_privateData(sel, type, imp));
1545 return JSObjectMake(context, Message_, internal);
1548 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1549 JSObjectRef function(CYCastJSObject(context, value));
1550 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1551 // XXX: see notes in Library.cpp about needing to leak
1552 return reinterpret_cast<IMP>(internal->GetValue());
1555 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1556 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1557 Class _class(internal->GetValue());
1560 const char *name(CYPoolCString(pool, context, property));
1562 if (SEL sel = sel_getUid(name))
1563 if (class_getInstanceMethod(_class, sel) != NULL)
1569 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1570 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1571 Class _class(internal->GetValue());
1574 const char *name(CYPoolCString(pool, context, property));
1576 if (SEL sel = sel_getUid(name))
1577 if (objc_method *method = class_getInstanceMethod(_class, sel))
1578 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1583 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1584 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1585 Class _class(internal->GetValue());
1588 const char *name(CYPoolCString(pool, context, property));
1590 SEL sel(sel_registerName(name));
1592 objc_method *method(class_getInstanceMethod(_class, sel));
1597 if (JSValueIsObjectOfClass(context, value, Message_)) {
1598 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1599 type = sig::Unparse(pool, &message->signature_);
1600 imp = reinterpret_cast<IMP>(message->GetValue());
1602 type = CYPoolTypeEncoding(pool, context, sel, method);
1603 imp = CYMakeMessage(context, value, type);
1607 method_setImplementation(method, imp);
1610 GSMethodList list(GSAllocMethodList(1));
1611 GSAppendMethodToList(list, sel, type, imp, YES);
1612 GSAddMethodList(_class, list, YES);
1613 GSFlushMethodCacheForClass(_class);
1615 class_addMethod(_class, sel, imp, type);
1622 #if 0 && OBJC_API_VERSION < 2
1623 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1624 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1625 Class _class(internal->GetValue());
1628 const char *name(CYPoolCString(pool, context, property));
1630 if (SEL sel = sel_getUid(name))
1631 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1632 objc_method_list list = {NULL, 1, {method}};
1633 class_removeMethods(_class, &list);
1641 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1642 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1643 Class _class(internal->GetValue());
1645 #if OBJC_API_VERSION >= 2
1647 objc_method **data(class_copyMethodList(_class, &size));
1648 for (size_t i(0); i != size; ++i)
1649 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1652 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1653 for (int i(0); i != methods->method_count; ++i)
1654 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1658 static bool CYHasImplicitProperties(Class _class) {
1659 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1660 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1662 return [_class cy$hasImplicitProperties];
1665 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1666 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1667 id self(internal->GetValue());
1669 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1673 NSString *name(CYCastNSString(pool, context, property));
1675 if (CYInternal *internal = [CYInternal get:self])
1676 if ([internal hasProperty:property inContext:context])
1679 Class _class(object_getClass(self));
1682 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1683 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1684 if ([self cy$hasProperty:name])
1686 } CYPoolCatch(false)
1688 const char *string(CYPoolCString(pool, context, name));
1691 if (class_getProperty(_class, string) != NULL)
1695 if (CYHasImplicitProperties(_class))
1696 if (SEL sel = sel_getUid(string))
1697 if (CYImplements(self, _class, sel, true))
1703 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1707 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1708 return Internal::Make(context, self, object);
1711 NSString *name(CYCastNSString(pool, context, property));
1713 if (CYInternal *internal = [CYInternal get:self])
1714 if (JSValueRef value = [internal getProperty:property inContext:context])
1718 if (NSObject *data = [self cy$getProperty:name])
1719 return CYCastJSValue(context, data);
1722 const char *string(CYPoolCString(pool, context, name));
1723 Class _class(object_getClass(self));
1726 if (objc_property_t property = class_getProperty(_class, string)) {
1727 PropertyAttributes attributes(property);
1728 SEL sel(sel_registerName(attributes.Getter()));
1729 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1733 if (CYHasImplicitProperties(_class))
1734 if (SEL sel = sel_getUid(string))
1735 if (CYImplements(self, _class, sel, true))
1736 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1741 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1742 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1743 id self(internal->GetValue());
1747 NSString *name(CYCastNSString(pool, context, property));
1748 NSObject *data(CYCastNSObject(pool, context, value));
1751 if ([self cy$setProperty:name to:data])
1755 const char *string(CYPoolCString(pool, context, name));
1756 Class _class(object_getClass(self));
1759 if (objc_property_t property = class_getProperty(_class, string)) {
1760 PropertyAttributes attributes(property);
1761 if (const char *setter = attributes.Setter()) {
1762 SEL sel(sel_registerName(setter));
1763 JSValueRef arguments[1] = {value};
1764 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1770 size_t length(strlen(string));
1772 char set[length + 5];
1778 if (string[0] != '\0') {
1779 set[3] = toupper(string[0]);
1780 memcpy(set + 4, string + 1, length - 1);
1783 set[length + 3] = ':';
1784 set[length + 4] = '\0';
1786 if (SEL sel = sel_getUid(set))
1787 if (CYImplements(self, _class, sel, false)) {
1788 JSValueRef arguments[1] = {value};
1789 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1793 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1794 [internal setProperty:property toValue:value inContext:context];
1801 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1802 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1803 id self(internal->GetValue());
1806 NSString *name(CYCastNSString(NULL, context, property));
1807 return [self cy$deleteProperty:name];
1809 } CYCatch return /*XXX*/ NULL; }
1811 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1812 const char *name(sel_getName(method_getName(method)));
1813 if (strchr(name, ':') != NULL)
1816 const char *type(method_getTypeEncoding(method));
1817 if (type == NULL || *type == '\0' || *type == 'v')
1820 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1823 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1824 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1825 id self(internal->GetValue());
1828 Class _class(object_getClass(self));
1833 objc_property_t *data(class_copyPropertyList(_class, &size));
1834 for (size_t i(0); i != size; ++i)
1835 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1840 if (CYHasImplicitProperties(_class))
1841 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1842 #if OBJC_API_VERSION >= 2
1844 objc_method **data(class_copyMethodList(current, &size));
1845 for (size_t i(0); i != size; ++i)
1846 Instance_getPropertyNames_message(names, data[i]);
1849 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1850 for (int i(0); i != methods->method_count; ++i)
1851 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1856 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1857 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1858 [self cy$getPropertyNames:names inContext:context];
1862 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1863 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1864 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1868 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1869 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1870 id self(internal->GetValue());
1872 if (![self isKindOfClass:NSBlock_])
1873 CYThrow("non-NSBlock object is not a function");
1875 struct BlockDescriptor1 {
1876 unsigned long int reserved;
1877 unsigned long int size;
1880 struct BlockDescriptor2 {
1881 void (*copy_helper)(void *dst, void *src);
1882 void (*dispose_helper)(void *src);
1885 struct BlockDescriptor3 {
1886 const char *signature;
1890 struct BlockLiteral {
1894 void (*invoke)(void *, ...);
1896 } *literal = reinterpret_cast<BlockLiteral *>(self);
1899 BLOCK_DEALLOCATING = 0x0001,
1900 BLOCK_REFCOUNT_MASK = 0xfffe,
1901 BLOCK_NEEDS_FREE = 1 << 24,
1902 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1903 BLOCK_HAS_CTOR = 1 << 26,
1904 BLOCK_IS_GC = 1 << 27,
1905 BLOCK_IS_GLOBAL = 1 << 28,
1906 BLOCK_HAS_STRET = 1 << 29,
1907 BLOCK_HAS_SIGNATURE = 1 << 30,
1910 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1911 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1912 descriptor += sizeof(BlockDescriptor1);
1913 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1914 descriptor += sizeof(BlockDescriptor2);
1915 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1917 if (const char *type = descriptor3->signature) {
1923 sig::Signature signature;
1924 sig::Parse(pool, &signature, type, &Structor_);
1927 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1929 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1930 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1935 CYThrow("NSBlock without signature field passed arguments");
1939 } CYPoolCatch(NULL);
1944 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1945 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1946 Class _class(internal->GetValue());
1947 if (!CYIsClass(_class))
1950 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1951 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1952 // XXX: this isn't always safe
1953 return [linternal->GetValue() isKindOfClass:_class];
1959 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1961 throw CYJSError(context, "incorrect number of arguments to Instance");
1963 id value(CYCastNSObject(pool, context, arguments[0]));
1965 value = [NSNull null];
1966 return CYCastJSValue(context, [value cy$box]);
1969 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1970 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1973 id self(internal->GetValue());
1974 const char *name(CYPoolCString(pool, context, property));
1976 if (object_getInstanceVariable(self, name, NULL) != NULL)
1982 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1983 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1986 id self(internal->GetValue());
1987 const char *name(CYPoolCString(pool, context, property));
1989 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1990 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1991 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1992 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1998 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1999 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2002 id self(internal->GetValue());
2003 const char *name(CYPoolCString(pool, context, property));
2005 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2006 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2007 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2014 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2015 if (Class super = class_getSuperclass(_class))
2016 Internal_getPropertyNames_(super, names);
2018 #if OBJC_API_VERSION >= 2
2020 objc_ivar **data(class_copyIvarList(_class, &size));
2021 for (size_t i(0); i != size; ++i)
2022 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2025 if (objc_ivar_list *ivars = _class->ivars)
2026 for (int i(0); i != ivars->ivar_count; ++i)
2027 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2031 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2032 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2035 id self(internal->GetValue());
2036 Class _class(object_getClass(self));
2038 Internal_getPropertyNames_(_class, names);
2041 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2042 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2043 return internal->GetOwner();
2046 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2048 NSString *name(CYCastNSString(pool, context, property));
2049 if (Class _class = NSClassFromString(name))
2050 return CYMakeInstance(context, _class, true);
2054 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2056 size_t size(objc_getClassList(NULL, 0));
2057 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2060 size_t writ(objc_getClassList(data, size));
2063 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2069 for (size_t i(0); i != writ; ++i)
2070 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2076 while (Class _class = objc_next_class(&state))
2077 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2081 #if OBJC_API_VERSION >= 2
2082 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2083 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2086 const char *name(CYPoolCString(pool, context, property));
2088 const char **data(objc_copyClassNamesForImage(internal, &size));
2090 for (size_t i(0); i != size; ++i)
2091 if (strcmp(name, data[i]) == 0) {
2092 if (Class _class = objc_getClass(name)) {
2093 value = CYMakeInstance(context, _class, true);
2104 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2105 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2107 const char **data(objc_copyClassNamesForImage(internal, &size));
2108 for (size_t i(0); i != size; ++i)
2109 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2113 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2115 const char *name(CYPoolCString(pool, context, property));
2117 const char **data(objc_copyImageNames(&size));
2118 for (size_t i(0); i != size; ++i)
2119 if (strcmp(name, data[i]) == 0) {
2128 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2129 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2133 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2135 const char **data(objc_copyImageNames(&size));
2136 for (size_t i(0); i != size; ++i)
2137 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2142 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2144 const char *name(CYPoolCString(pool, context, property));
2145 if (Protocol *protocol = objc_getProtocol(name))
2146 return CYMakeInstance(context, protocol, true);
2150 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2151 #if OBJC_API_VERSION >= 2
2153 Protocol **data(objc_copyProtocolList(&size));
2154 for (size_t i(0); i != size; ++i)
2155 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2162 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2164 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2166 return Instance::Make(context, nil);
2170 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2171 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2175 static bool stret(ffi_type *ffi_type) {
2176 return ffi_type->type == FFI_TYPE_STRUCT && (
2177 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2178 struct_forward_array[ffi_type->size] != 0
2183 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 {
2187 _class = object_getClass(self);
2191 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2192 imp = method_getImplementation(method);
2193 type = method_getTypeEncoding(method);
2198 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2200 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2201 type = CYPoolCString(pool, context, [method _typeString]);
2209 sig::Signature signature;
2210 sig::Parse(pool, &signature, type, &Structor_);
2212 size_t used(count + 3);
2213 if (used > signature.count) {
2214 sig::Element *elements(new (pool) sig::Element[used]);
2215 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2217 for (size_t index(signature.count); index != used; ++index) {
2218 sig::Element *element(&elements[index]);
2219 element->name = NULL;
2220 element->offset = _not(size_t);
2222 sig::Type *type(new (pool) sig::Type);
2223 memset(type, 0, sizeof(*type));
2224 type->primitive = sig::object_P;
2225 element->type = type;
2228 signature.elements = elements;
2229 signature.count = used;
2233 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2237 if (stret(cif.rtype))
2238 imp = class_getMethodImplementation_stret(_class, _cmd);
2240 imp = class_getMethodImplementation(_class, _cmd);
2242 objc_super super = {self, _class};
2243 imp = objc_msg_lookup_super(&super, _cmd);
2247 void (*function)() = reinterpret_cast<void (*)()>(imp);
2248 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2251 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2253 throw CYJSError(context, "too few arguments to objc_msgSend");
2263 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2264 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2265 self = internal->GetValue();
2266 _class = internal->class_;;
2267 uninitialized = false;
2268 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2269 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2270 self = internal->GetValue();
2272 uninitialized = internal->IsUninitialized();
2274 internal->value_ = nil;
2276 self = CYCastNSObject(pool, context, arguments[0]);
2278 uninitialized = false;
2282 return CYJSNull(context);
2284 _cmd = CYCastSEL(context, arguments[1]);
2286 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2289 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2290 JSValueRef setup[count + 2];
2293 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2294 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2297 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2299 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2301 // XXX: handle Instance::Uninitialized?
2302 id self(CYCastNSObject(pool, context, _this));
2306 setup[1] = &internal->sel_;
2308 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2311 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2313 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2315 id self(CYCastNSObject(pool, context, arguments[0]));
2316 Class _class(CYCastClass(pool, context, arguments[1]));
2317 return cy::Super::Make(context, self, _class);
2320 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2322 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2324 const char *name(CYPoolCString(pool, context, arguments[0]));
2325 return CYMakeSelector(context, sel_registerName(name));
2328 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2330 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2331 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2332 return CYMakeInstance(context, self, false);
2335 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2336 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2337 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2340 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2341 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2342 Type_privateData *typical(internal->GetType());
2347 if (typical == NULL) {
2351 type = typical->type_;
2352 ffi = typical->ffi_;
2355 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2358 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2359 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2360 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2363 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2364 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2365 id self(internal->GetValue());
2366 if (!CYIsClass(self))
2367 return CYJSUndefined(context);
2368 return CYGetClassPrototype(context, self);
2371 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2372 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2373 id self(internal->GetValue());
2374 if (!CYIsClass(self))
2375 return CYJSUndefined(context);
2376 return Messages::Make(context, (Class) self);
2379 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2380 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2383 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2384 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2387 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2388 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2391 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2398 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2399 // XXX: check for support of cy$toJSON?
2400 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2402 } CYCatch return /*XXX*/ NULL; }
2404 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2405 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2408 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2409 id value(internal->GetValue());
2411 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2414 if (JSValueRef result = [value cy$valueOfInContext:context])
2418 } CYCatch return /*XXX*/ NULL; }
2420 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2421 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2424 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2425 // XXX: but... but... THIS ISN'T A POINTER! :(
2426 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2427 } CYCatch return /*XXX*/ NULL; }
2429 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2430 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2433 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2434 id value(internal->GetValue());
2437 return CYCastJSValue(context, "nil");
2440 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2441 return CYCastJSValue(context, CYJSString(context, [value description]));
2443 } CYCatch return /*XXX*/ NULL; }
2445 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2446 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2447 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2450 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2451 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2454 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2455 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2456 const char *name(sel_getName(internal->GetValue()));
2459 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2460 return CYCastJSValue(context, CYJSString(context, string));
2462 } CYCatch return /*XXX*/ NULL; }
2464 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2466 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2469 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2470 SEL sel(internal->GetValue());
2472 objc_method *method;
2473 if (Class _class = CYCastClass(pool, context, arguments[0]))
2474 method = class_getInstanceMethod(_class, sel);
2478 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2479 return CYCastJSValue(context, CYJSString(type));
2481 return CYJSNull(context);
2484 static JSStaticValue Selector_staticValues[2] = {
2485 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2486 {NULL, NULL, NULL, 0}
2489 static JSStaticValue Instance_staticValues[5] = {
2490 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2491 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2492 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2493 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2494 {NULL, NULL, NULL, 0}
2497 static JSStaticFunction Instance_staticFunctions[7] = {
2498 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2499 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2500 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2501 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2502 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2503 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2507 static JSStaticFunction Internal_staticFunctions[2] = {
2508 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2512 static JSStaticFunction Selector_staticFunctions[5] = {
2513 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2514 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2515 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2516 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2520 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2521 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2522 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2523 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2525 apr_pool_t *pool(CYGetGlobalPool());
2527 Object_type = new(pool) Type_privateData("@");
2528 Selector_type = new(pool) Type_privateData(":");
2531 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2532 if (NSCFBoolean_ == nil)
2533 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2535 NSCFType_ = objc_getClass("NSCFType");
2536 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2537 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2538 NSZombie_ = objc_getClass("_NSZombie_");
2540 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2543 NSArray_ = objc_getClass("NSArray");
2544 NSBlock_ = objc_getClass("NSBlock");
2545 NSDictionary_ = objc_getClass("NSDictionary");
2546 NSString_ = objc_getClass("NSString");
2547 Object_ = objc_getClass("Object");
2549 JSClassDefinition definition;
2551 definition = kJSClassDefinitionEmpty;
2552 definition.className = "Instance";
2553 definition.staticValues = Instance_staticValues;
2554 definition.staticFunctions = Instance_staticFunctions;
2555 definition.hasProperty = &Instance_hasProperty;
2556 definition.getProperty = &Instance_getProperty;
2557 definition.setProperty = &Instance_setProperty;
2558 definition.deleteProperty = &Instance_deleteProperty;
2559 definition.getPropertyNames = &Instance_getPropertyNames;
2560 definition.callAsConstructor = &Instance_callAsConstructor;
2561 definition.callAsFunction = &Instance_callAsFunction;
2562 definition.hasInstance = &Instance_hasInstance;
2563 definition.finalize = &CYFinalize;
2564 Instance_ = JSClassCreate(&definition);
2566 definition.className = "ArrayInstance";
2567 ArrayInstance_ = JSClassCreate(&definition);
2569 definition.className = "FunctionInstance";
2570 FunctionInstance_ = JSClassCreate(&definition);
2572 definition.className = "ObjectInstance";
2573 ObjectInstance_ = JSClassCreate(&definition);
2575 definition.className = "StringInstance";
2576 StringInstance_ = JSClassCreate(&definition);
2578 definition = kJSClassDefinitionEmpty;
2579 definition.className = "Internal";
2580 definition.staticFunctions = Internal_staticFunctions;
2581 definition.hasProperty = &Internal_hasProperty;
2582 definition.getProperty = &Internal_getProperty;
2583 definition.setProperty = &Internal_setProperty;
2584 definition.getPropertyNames = &Internal_getPropertyNames;
2585 definition.finalize = &CYFinalize;
2586 Internal_ = JSClassCreate(&definition);
2588 definition = kJSClassDefinitionEmpty;
2589 definition.className = "Message";
2590 definition.staticFunctions = cy::Functor::StaticFunctions;
2591 definition.callAsFunction = &Message_callAsFunction;
2592 definition.finalize = &CYFinalize;
2593 Message_ = JSClassCreate(&definition);
2595 definition = kJSClassDefinitionEmpty;
2596 definition.className = "Messages";
2597 definition.hasProperty = &Messages_hasProperty;
2598 definition.getProperty = &Messages_getProperty;
2599 definition.setProperty = &Messages_setProperty;
2600 #if 0 && OBJC_API_VERSION < 2
2601 definition.deleteProperty = &Messages_deleteProperty;
2603 definition.getPropertyNames = &Messages_getPropertyNames;
2604 definition.finalize = &CYFinalize;
2605 Messages_ = JSClassCreate(&definition);
2607 definition = kJSClassDefinitionEmpty;
2608 definition.className = "Selector";
2609 definition.staticValues = Selector_staticValues;
2610 definition.staticFunctions = Selector_staticFunctions;
2611 definition.callAsFunction = &Selector_callAsFunction;
2612 definition.finalize = &CYFinalize;
2613 Selector_ = JSClassCreate(&definition);
2615 definition = kJSClassDefinitionEmpty;
2616 definition.className = "Super";
2617 definition.staticFunctions = Internal_staticFunctions;
2618 definition.finalize = &CYFinalize;
2619 Super_ = JSClassCreate(&definition);
2621 definition = kJSClassDefinitionEmpty;
2622 definition.className = "ObjectiveC::Classes";
2623 definition.getProperty = &ObjectiveC_Classes_getProperty;
2624 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2625 ObjectiveC_Classes_ = JSClassCreate(&definition);
2627 definition = kJSClassDefinitionEmpty;
2628 definition.className = "ObjectiveC::Constants";
2629 definition.getProperty = &ObjectiveC_Constants_getProperty;
2630 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2631 ObjectiveC_Constants_ = JSClassCreate(&definition);
2633 #if OBJC_API_VERSION >= 2
2634 definition = kJSClassDefinitionEmpty;
2635 definition.className = "ObjectiveC::Images";
2636 definition.getProperty = &ObjectiveC_Images_getProperty;
2637 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2638 ObjectiveC_Images_ = JSClassCreate(&definition);
2640 definition = kJSClassDefinitionEmpty;
2641 definition.className = "ObjectiveC::Image::Classes";
2642 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2643 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2644 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2647 definition = kJSClassDefinitionEmpty;
2648 definition.className = "ObjectiveC::Protocols";
2649 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2650 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2651 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2654 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2658 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2659 JSObjectRef global(CYGetGlobalObject(context));
2660 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2661 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2662 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2663 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2665 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2666 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2668 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2669 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2670 CYArrayPush(context, alls, protocols);
2672 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2673 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2674 CYArrayPush(context, alls, classes);
2676 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2677 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2678 CYArrayPush(context, alls, constants);
2680 #if OBJC_API_VERSION >= 2
2681 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2684 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2685 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2686 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2687 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2689 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2690 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2692 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2693 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2694 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2695 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2696 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2698 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2699 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2700 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2701 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2702 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2704 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2705 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2706 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2707 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2708 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2710 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2711 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2712 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2713 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2714 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2716 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2717 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2718 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2720 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2721 CYSetProperty(context, Instance, CYJSString("box"), box);
2723 #if defined(__APPLE__) && defined(__arm__) && 0
2724 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2727 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2729 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2730 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2733 static CYHooks CYObjectiveCHooks = {
2734 &CYObjectiveC_ExecuteStart,
2735 &CYObjectiveC_ExecuteEnd,
2736 &CYObjectiveC_CallFunction,
2737 &CYObjectiveC_Initialize,
2738 &CYObjectiveC_SetupContext,
2739 &CYObjectiveC_PoolFFI,
2740 &CYObjectiveC_FromFFI,
2743 struct CYObjectiveC {
2745 hooks_ = &CYObjectiveCHooks;
2746 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2747 _assert(hooks_ != NULL);