1 /* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #if defined(__APPLE__) && defined(__arm__)
41 #include <substrate.h>
43 #include <objc/objc-api.h>
50 #include <Foundation/Foundation.h>
52 #include "ObjectiveC/Internal.hpp"
54 #include <objc/Protocol.h>
56 #include "cycript.hpp"
58 #include "ObjectiveC/Internal.hpp"
61 #include <CoreFoundation/CoreFoundation.h>
62 #include <JavaScriptCore/JSStringRefCF.h>
63 #include <WebKit/WebScriptObject.h>
67 #include "JavaScript.hpp"
69 #include "Execute.hpp"
74 #define CYObjectiveTry_(context) { \
75 JSContextRef context_(context); \
77 #define CYObjectiveTry { \
79 #define CYObjectiveCatch \
80 catch (const CYException &error) { \
81 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
92 throw CYJSError(context, CYCastJSValue(context, error)); \
97 [_saved autorelease]; \
103 #define CYSadCatch(value) \
104 @catch (NSException *error ) { \
105 throw CYJSError(context, CYCastJSValue(context, error)); \
110 #define class_getSuperclass GSObjCSuper
111 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
112 #define class_getName GSNameFromClass
114 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
116 #define ivar_getName(ivar) ((ivar)->ivar_name)
117 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
118 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
120 #define method_getName(method) ((method)->method_name)
121 #define method_getImplementation(method) ((method)->method_imp)
122 #define method_getTypeEncoding(method) ((method)->method_types)
123 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
126 #define objc_getClass GSClassFromName
128 #define objc_getProtocol GSProtocolFromName
130 #define object_getClass GSObjCClass
132 #define object_getInstanceVariable(object, name, value) ({ \
133 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
134 _assert(value != NULL); \
136 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
140 #define object_setIvar(object, ivar, value) ({ \
141 void *data = (value); \
142 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
145 #define protocol_getName(protocol) [(protocol) name]
148 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
150 /* Objective-C Pool Release {{{ */
151 apr_status_t CYPoolRelease_(void *data) {
152 id object(reinterpret_cast<id>(data));
157 id CYPoolRelease_(apr_pool_t *pool, id object) {
160 else if (pool == NULL)
161 return [object autorelease];
163 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
168 template <typename Type_>
169 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
170 return (Type_) CYPoolRelease_(pool, (id) object);
173 /* Objective-C Strings {{{ */
174 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
176 return [value UTF8String];
178 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
179 char *string(new(pool) char[size]);
180 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
181 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
186 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
188 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
191 return CYCopyJSString(CYPoolCString(pool, context, value));
195 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
198 // XXX: this definition scares me; is anyone using this?!
199 NSString *string([value description]);
200 return CYCopyJSString(context, string);
203 NSString *CYCopyNSString(const CYUTF8String &value) {
205 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
207 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
211 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
213 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
216 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
220 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
221 return CYCopyNSString(context, CYJSString(context, value));
224 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
225 return CYPoolRelease(pool, CYCopyNSString(value));
228 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
229 const char *name(sel_getName(sel));
230 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
233 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
234 return CYPoolRelease(pool, CYCopyNSString(context, value));
237 CYUTF8String CYCastUTF8String(NSString *value) {
238 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
239 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
243 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
245 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
246 if (exception == NULL)
248 *exception = CYCastJSValue(context, error);
251 size_t CYGetIndex(NSString *value) {
252 return CYGetIndex(CYCastUTF8String(value));
255 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
256 return CYGetOffset(CYPoolCString(pool, context, value), index);
259 static JSClassRef Instance_;
260 static JSClassRef Internal_;
261 static JSClassRef Message_;
262 static JSClassRef Messages_;
263 static JSClassRef Selector_;
264 static JSClassRef StringInstance_;
265 static JSClassRef Super_;
267 static JSClassRef ObjectiveC_Classes_;
268 static JSClassRef ObjectiveC_Protocols_;
271 static JSClassRef ObjectiveC_Image_Classes_;
272 static JSClassRef ObjectiveC_Images_;
276 static Class NSCFBoolean_;
277 static Class NSCFType_;
278 static Class NSMessageBuilder_;
279 static Class NSZombie_;
281 static Class NSBoolNumber_;
284 static Class NSArray_;
285 static Class NSDictionary_;
286 static Class NSString_;
287 static Class Object_;
289 static Type_privateData *Object_type;
290 static Type_privateData *Selector_type;
292 Type_privateData *Instance::GetType() const {
296 Type_privateData *Selector_privateData::GetType() const {
297 return Selector_type;
300 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
302 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
304 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
306 JSObjectRef global(CYGetGlobalObject(context));
307 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
310 sprintf(label, "i%p", self);
311 CYJSString name(label);
313 JSValueRef value(CYGetProperty(context, cy, name));
314 if (!JSValueIsUndefined(context, value))
317 JSClassRef _class(NULL);
318 JSValueRef prototype;
320 if (self == NSArray_)
321 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
322 else if (self == NSDictionary_)
323 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
324 else if (self == NSString_)
325 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
327 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
329 JSObjectRef object(JSObjectMake(context, _class, NULL));
330 JSObjectSetPrototype(context, object, prototype);
331 CYSetProperty(context, cy, name, object);
336 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
337 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
338 if (_class == NSArray_)
340 if (Class super = class_getSuperclass(_class))
341 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
343 JSObjectSetPrototype(context, value, Array_prototype_);*/
347 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
348 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
352 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
353 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
357 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
358 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
359 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
363 Instance::~Instance() {
364 if ((flags_ & Transient) == 0)
365 // XXX: does this handle background threads correctly?
366 // XXX: this simply does not work on the console because I'm stupid
367 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
370 struct Message_privateData :
375 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
376 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
382 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
383 Instance::Flags flags;
386 flags = Instance::Transient;
388 flags = Instance::None;
389 object = [object retain];
392 return Instance::Make(context, object, flags);
395 @interface NSMethodSignature (Cycript)
396 - (NSString *) _typeString;
399 @interface NSObject (Cycript)
401 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
402 - (JSType) cy$JSType;
404 - (NSObject *) cy$toJSON:(NSString *)key;
405 - (NSString *) cy$toCYON;
406 - (NSString *) cy$toKey;
408 - (bool) cy$hasProperty:(NSString *)name;
409 - (NSObject *) cy$getProperty:(NSString *)name;
410 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
411 - (bool) cy$deleteProperty:(NSString *)name;
412 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
414 + (bool) cy$hasImplicitProperties;
419 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
422 NSString *CYCastNSCYON(id value) {
428 Class _class(object_getClass(value));
429 SEL sel(@selector(cy$toCYON));
431 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
432 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
433 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
434 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
435 string = [value cy$toCYON];
440 else if (value == NSZombie_)
441 string = @"_NSZombie_";
442 else if (_class == NSZombie_)
443 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
444 // XXX: frowny /in/ the pants
445 else if (value == NSMessageBuilder_ || value == Object_)
449 string = [NSString stringWithFormat:@"%@", value];
454 string = @"undefined";
461 struct PropertyAttributes {
466 const char *variable;
479 PropertyAttributes(objc_property_t property) :
491 name = property_getName(property);
492 const char *attributes(property_getAttributes(property));
494 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
496 case 'R': readonly = true; break;
497 case 'C': copy = true; break;
498 case '&': retain = true; break;
499 case 'N': nonatomic = true; break;
500 case 'G': getter_ = token + 1; break;
501 case 'S': setter_ = token + 1; break;
502 case 'V': variable = token + 1; break;
506 /*if (variable == NULL) {
507 variable = property_getName(property);
508 size_t size(strlen(variable));
509 char *name(new(pool_) char[size + 2]);
511 memcpy(name + 1, variable, size);
512 name[size + 1] = '\0';
517 const char *Getter() {
519 getter_ = apr_pstrdup(pool_, name);
523 const char *Setter() {
524 if (setter_ == NULL && !readonly) {
525 size_t length(strlen(name));
527 char *temp(new(pool_) char[length + 5]);
533 temp[3] = toupper(name[0]);
534 memcpy(temp + 4, name + 1, length - 1);
537 temp[length + 3] = ':';
538 temp[length + 4] = '\0';
549 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
550 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
555 @interface CYWebUndefined : NSObject {
558 + (CYWebUndefined *) undefined;
562 @implementation CYWebUndefined
564 + (CYWebUndefined *) undefined {
565 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
571 #define WebUndefined CYWebUndefined
574 /* Bridge: CYJSObject {{{ */
575 @interface CYJSObject : NSMutableDictionary {
577 JSContextRef context_;
580 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
582 - (NSObject *) cy$toJSON:(NSString *)key;
584 - (NSUInteger) count;
585 - (id) objectForKey:(id)key;
586 - (NSEnumerator *) keyEnumerator;
587 - (void) setObject:(id)object forKey:(id)key;
588 - (void) removeObjectForKey:(id)key;
592 /* Bridge: CYJSArray {{{ */
593 @interface CYJSArray : NSMutableArray {
595 JSContextRef context_;
598 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
600 - (NSUInteger) count;
601 - (id) objectAtIndex:(NSUInteger)index;
603 - (void) addObject:(id)anObject;
604 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
605 - (void) removeLastObject;
606 - (void) removeObjectAtIndex:(NSUInteger)index;
607 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
612 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
613 JSObjectRef Array(CYGetCachedObject(context, Array_s));
614 JSValueRef exception(NULL);
615 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
616 CYThrow(context, exception);
617 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
618 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
621 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
622 if (!JSValueIsObjectOfClass(context, object, Instance_))
623 return CYCastNSObject_(pool, context, object);
625 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
626 return internal->GetValue();
630 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
631 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
635 @interface NSBoolNumber : NSNumber {
640 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
644 switch (JSType type = JSValueGetType(context, value)) {
645 case kJSTypeUndefined:
646 object = [WebUndefined undefined];
656 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
659 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
665 object = CYCopyNSNumber(context, value);
670 object = CYCopyNSString(context, value);
675 // XXX: this might could be more efficient
676 object = CYCastNSObject(pool, context, (JSObjectRef) value);
681 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
688 return CYPoolRelease(pool, object);
690 return [object retain];
693 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
694 return CYNSObject(pool, context, value, true);
697 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
698 return CYNSObject(pool, context, value, false);
701 /* Bridge: NSArray {{{ */
702 @implementation NSArray (Cycript)
704 - (NSString *) cy$toCYON {
705 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
706 [json appendString:@"["];
710 for (id object in self) {
712 for (size_t index(0), count([self count]); index != count; ++index) {
713 id object([self objectAtIndex:index]);
716 [json appendString:@","];
719 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
720 [json appendString:CYCastNSCYON(object)];
722 [json appendString:@","];
727 [json appendString:@"]"];
731 - (bool) cy$hasProperty:(NSString *)name {
732 if ([name isEqualToString:@"length"])
735 size_t index(CYGetIndex(name));
736 if (index == _not(size_t) || index >= [self count])
737 return [super cy$hasProperty:name];
742 - (NSObject *) cy$getProperty:(NSString *)name {
743 if ([name isEqualToString:@"length"]) {
744 NSUInteger count([self count]);
746 return [NSNumber numberWithUnsignedInteger:count];
748 return [NSNumber numberWithUnsignedInt:count];
752 size_t index(CYGetIndex(name));
753 if (index == _not(size_t) || index >= [self count])
754 return [super cy$getProperty:name];
756 return [self objectAtIndex:index];
759 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
760 [super cy$getPropertyNames:names inContext:context];
762 for (size_t index(0), count([self count]); index != count; ++index) {
763 id object([self objectAtIndex:index]);
764 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
766 sprintf(name, "%zu", index);
767 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
772 + (bool) cy$hasImplicitProperties {
778 /* Bridge: NSBoolNumber {{{ */
780 @implementation NSBoolNumber (Cycript)
782 - (JSType) cy$JSType {
783 return kJSTypeBoolean;
786 - (NSObject *) cy$toJSON:(NSString *)key {
790 - (NSString *) cy$toCYON {
791 return [self boolValue] ? @"true" : @"false";
794 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
795 return CYCastJSValue(context, (bool) [self boolValue]);
801 /* Bridge: NSDictionary {{{ */
802 @implementation NSDictionary (Cycript)
804 - (NSString *) cy$toCYON {
805 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
806 [json appendString:@"{"];
810 for (NSObject *key in self) {
812 NSEnumerator *keys([self keyEnumerator]);
813 while (NSObject *key = [keys nextObject]) {
816 [json appendString:@","];
819 [json appendString:[key cy$toKey]];
820 [json appendString:@":"];
821 NSObject *object([self objectForKey:key]);
822 [json appendString:CYCastNSCYON(object)];
825 [json appendString:@"}"];
829 - (bool) cy$hasProperty:(NSString *)name {
830 return [self objectForKey:name] != nil;
833 - (NSObject *) cy$getProperty:(NSString *)name {
834 return [self objectForKey:name];
837 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
838 [super cy$getPropertyNames:names inContext:context];
841 for (NSObject *key in self) {
843 NSEnumerator *keys([self keyEnumerator]);
844 while (NSObject *key = [keys nextObject]) {
846 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
850 + (bool) cy$hasImplicitProperties {
856 /* Bridge: NSMutableArray {{{ */
857 @implementation NSMutableArray (Cycript)
859 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
860 if ([name isEqualToString:@"length"]) {
861 // XXX: is this not intelligent?
862 NSNumber *number(reinterpret_cast<NSNumber *>(value));
864 NSUInteger size([number unsignedIntegerValue]);
866 NSUInteger size([number unsignedIntValue]);
868 NSUInteger count([self count]);
870 [self removeObjectsInRange:NSMakeRange(size, count - size)];
871 else if (size != count) {
872 WebUndefined *undefined([WebUndefined undefined]);
873 for (size_t i(count); i != size; ++i)
874 [self addObject:undefined];
879 size_t index(CYGetIndex(name));
880 if (index == _not(size_t))
881 return [super cy$setProperty:name to:value];
883 id object(value ?: [NSNull null]);
885 size_t count([self count]);
887 [self replaceObjectAtIndex:index withObject:object];
889 if (index != count) {
890 WebUndefined *undefined([WebUndefined undefined]);
891 for (size_t i(count); i != index; ++i)
892 [self addObject:undefined];
895 [self addObject:object];
901 - (bool) cy$deleteProperty:(NSString *)name {
902 size_t index(CYGetIndex(name));
903 if (index == _not(size_t) || index >= [self count])
904 return [super cy$deleteProperty:name];
905 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
911 /* Bridge: NSMutableDictionary {{{ */
912 @implementation NSMutableDictionary (Cycript)
914 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
915 [self setObject:(value ?: [NSNull null]) forKey:name];
919 - (bool) cy$deleteProperty:(NSString *)name {
920 if ([self objectForKey:name] == nil)
923 [self removeObjectForKey:name];
930 /* Bridge: NSNumber {{{ */
931 @implementation NSNumber (Cycript)
933 - (JSType) cy$JSType {
935 // XXX: this just seems stupid
936 if ([self class] == NSCFBoolean_)
937 return kJSTypeBoolean;
939 return kJSTypeNumber;
942 - (NSObject *) cy$toJSON:(NSString *)key {
946 - (NSString *) cy$toCYON {
947 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
950 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
951 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
956 /* Bridge: NSNull {{{ */
957 @implementation NSNull (Cycript)
959 - (JSType) cy$JSType {
963 - (NSObject *) cy$toJSON:(NSString *)key {
967 - (NSString *) cy$toCYON {
973 /* Bridge: NSObject {{{ */
974 @implementation NSObject (Cycript)
976 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
977 return CYMakeInstance(context, self, false);
980 - (JSType) cy$JSType {
981 return kJSTypeObject;
984 - (NSObject *) cy$toJSON:(NSString *)key {
985 return [self description];
988 - (NSString *) cy$toCYON {
989 return [[self cy$toJSON:@""] cy$toCYON];
992 - (NSString *) cy$toKey {
993 return [self cy$toCYON];
996 - (bool) cy$hasProperty:(NSString *)name {
1000 - (NSObject *) cy$getProperty:(NSString *)name {
1004 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1008 - (bool) cy$deleteProperty:(NSString *)name {
1012 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1015 + (bool) cy$hasImplicitProperties {
1021 /* Bridge: NSProxy {{{ */
1022 @implementation NSProxy (Cycript)
1024 - (NSObject *) cy$toJSON:(NSString *)key {
1025 return [self description];
1028 - (NSString *) cy$toCYON {
1029 return [[self cy$toJSON:@""] cy$toCYON];
1034 /* Bridge: NSString {{{ */
1035 @implementation NSString (Cycript)
1037 - (JSType) cy$JSType {
1038 return kJSTypeString;
1041 - (NSObject *) cy$toJSON:(NSString *)key {
1045 - (NSString *) cy$toCYON {
1046 std::ostringstream str;
1047 CYUTF8String string(CYCastUTF8String(self));
1048 CYStringify(str, string.data, string.size);
1049 std::string value(str.str());
1050 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1053 - (NSString *) cy$toKey {
1054 if (CYIsKey(CYCastUTF8String(self)))
1056 return [self cy$toCYON];
1059 - (bool) cy$hasProperty:(NSString *)name {
1060 if ([name isEqualToString:@"length"])
1063 size_t index(CYGetIndex(name));
1064 if (index == _not(size_t) || index >= [self length])
1065 return [super cy$hasProperty:name];
1070 - (NSObject *) cy$getProperty:(NSString *)name {
1071 if ([name isEqualToString:@"length"]) {
1072 NSUInteger count([self length]);
1074 return [NSNumber numberWithUnsignedInteger:count];
1076 return [NSNumber numberWithUnsignedInt:count];
1080 size_t index(CYGetIndex(name));
1081 if (index == _not(size_t) || index >= [self length])
1082 return [super cy$getProperty:name];
1084 return [self substringWithRange:NSMakeRange(index, 1)];
1087 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1088 [super cy$getPropertyNames:names inContext:context];
1090 for (size_t index(0), length([self length]); index != length; ++index) {
1092 sprintf(name, "%zu", index);
1093 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1097 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1098 + (bool) cy$hasImplicitProperties {
1104 /* Bridge: WebUndefined {{{ */
1105 @implementation WebUndefined (Cycript)
1107 - (JSType) cy$JSType {
1108 return kJSTypeUndefined;
1111 - (NSObject *) cy$toJSON:(NSString *)key {
1115 - (NSString *) cy$toCYON {
1116 return @"undefined";
1119 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1120 return CYJSUndefined(context);
1121 } CYObjectiveCatch }
1126 static bool CYIsClass(id self) {
1128 // XXX: this is a lame object_isClass
1129 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1131 return GSObjCIsClass(self);
1135 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1136 id self(CYCastNSObject(pool, context, value));
1137 if (CYIsClass(self))
1138 return (Class) self;
1139 throw CYJSError(context, "got something that is not a Class");
1143 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1145 size_t size(JSPropertyNameArrayGetCount(names));
1146 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1147 for (size_t index(0); index != size; ++index)
1148 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1152 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1154 return CYJSNull(context);
1155 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1156 return [value cy$JSValueInContext:context];
1158 return CYMakeInstance(context, value, false);
1159 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1161 @implementation CYJSObject
1163 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1164 if ((self = [super init]) != nil) {
1166 context_ = CYGetJSContext(context);
1167 //XXX:JSGlobalContextRetain(context_);
1168 JSValueProtect(context_, object_);
1170 } CYObjectiveCatch }
1172 - (void) dealloc { CYObjectiveTry {
1173 JSValueUnprotect(context_, object_);
1174 //XXX:JSGlobalContextRelease(context_);
1176 } CYObjectiveCatch }
1178 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1179 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1180 if (!CYIsCallable(context_, toJSON))
1181 return [super cy$toJSON:key];
1183 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1184 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1185 // XXX: do I really want an NSNull here?!
1186 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1188 } CYObjectiveCatch }
1190 - (NSString *) cy$toCYON { CYObjectiveTry {
1192 JSValueRef exception(NULL);
1193 const char *cyon(CYPoolCCYON(pool, context_, object_));
1194 CYThrow(context_, exception);
1196 return [super cy$toCYON];
1198 return [NSString stringWithUTF8String:cyon];
1199 } CYObjectiveCatch }
1201 - (NSUInteger) count { CYObjectiveTry {
1202 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1203 size_t size(JSPropertyNameArrayGetCount(names));
1204 JSPropertyNameArrayRelease(names);
1206 } CYObjectiveCatch }
1208 - (id) objectForKey:(id)key { CYObjectiveTry {
1209 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1210 if (JSValueIsUndefined(context_, value))
1212 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1213 } CYObjectiveCatch }
1215 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1216 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1217 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1218 JSPropertyNameArrayRelease(names);
1220 } CYObjectiveCatch }
1222 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1223 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1224 } CYObjectiveCatch }
1226 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1227 JSValueRef exception(NULL);
1228 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1229 CYThrow(context_, exception);
1230 } CYObjectiveCatch }
1234 @implementation CYJSArray
1236 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1237 if ((self = [super init]) != nil) {
1239 context_ = CYGetJSContext(context);
1240 //XXX:JSGlobalContextRetain(context_);
1241 JSValueProtect(context_, object_);
1243 } CYObjectiveCatch }
1245 - (void) dealloc { CYObjectiveTry {
1246 JSValueUnprotect(context_, object_);
1247 //XXX:JSGlobalContextRelease(context_);
1249 } CYObjectiveCatch }
1251 - (NSUInteger) count { CYObjectiveTry {
1252 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1253 } CYObjectiveCatch }
1255 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1256 size_t bounds([self count]);
1257 if (index >= bounds)
1258 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1259 JSValueRef exception(NULL);
1260 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1261 CYThrow(context_, exception);
1262 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1263 } CYObjectiveCatch }
1265 - (void) addObject:(id)object { CYObjectiveTry {
1266 JSValueRef exception(NULL);
1267 JSValueRef arguments[1];
1268 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1269 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1270 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1271 CYThrow(context_, exception);
1272 } CYObjectiveCatch }
1274 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1275 size_t bounds([self count] + 1);
1276 if (index >= bounds)
1277 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1278 JSValueRef exception(NULL);
1279 JSValueRef arguments[3];
1280 arguments[0] = CYCastJSValue(context_, index);
1281 arguments[1] = CYCastJSValue(context_, 0);
1282 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1283 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1284 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1285 CYThrow(context_, exception);
1286 } CYObjectiveCatch }
1288 - (void) removeLastObject { CYObjectiveTry {
1289 JSValueRef exception(NULL);
1290 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1291 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1292 CYThrow(context_, exception);
1293 } CYObjectiveCatch }
1295 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1296 size_t bounds([self count]);
1297 if (index >= bounds)
1298 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1299 JSValueRef exception(NULL);
1300 JSValueRef arguments[2];
1301 arguments[0] = CYCastJSValue(context_, index);
1302 arguments[1] = CYCastJSValue(context_, 1);
1303 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1304 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1305 CYThrow(context_, exception);
1306 } CYObjectiveCatch }
1308 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1309 size_t bounds([self count]);
1310 if (index >= bounds)
1311 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1312 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1313 } CYObjectiveCatch }
1317 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1321 JSObjectRef object_;
1329 // XXX: delete object_? ;(
1332 static CYInternal *Get(id self) {
1333 CYInternal *internal(NULL);
1334 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1335 // XXX: do something epic? ;P
1341 static CYInternal *Set(id self) {
1342 CYInternal *internal(NULL);
1343 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1344 if (internal == NULL) {
1345 internal = new CYInternal();
1346 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1349 // XXX: do something epic? ;P
1355 bool HasProperty(JSContextRef context, JSStringRef name) {
1356 if (object_ == NULL)
1358 return JSObjectHasProperty(context, object_, name);
1361 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1362 if (object_ == NULL)
1364 return CYGetProperty(context, object_, name);
1367 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1368 if (object_ == NULL)
1369 object_ = JSObjectMake(context, NULL, NULL);
1370 CYSetProperty(context, object_, name, value);
1374 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1375 Selector_privateData *internal(new Selector_privateData(sel));
1376 return JSObjectMake(context, Selector_, internal);
1379 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1380 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1381 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1382 return reinterpret_cast<SEL>(internal->value_);
1384 return CYCastPointer<SEL>(context, value);
1387 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1388 return (void *) [[NSAutoreleasePool alloc] init];
1389 } CYSadCatch(NULL) }
1391 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1392 return [(NSAutoreleasePool *) handle release];
1395 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1397 return Instance::Make(context, nil);
1398 if (Class _class = objc_getClass(name.data))
1399 return CYMakeInstance(context, _class, true);
1400 if (Protocol *protocol = objc_getProtocol(name.data))
1401 return CYMakeInstance(context, protocol, true);
1403 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1405 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1406 ffi_call(cif, function, value, values);
1409 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1410 switch (type->primitive) {
1411 // XXX: do something epic about blocks
1414 case sig::typename_P:
1415 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1418 case sig::selector_P:
1419 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1427 } CYSadCatch(false) }
1429 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1430 switch (type->primitive) {
1431 // XXX: do something epic about blocks
1434 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1435 JSValueRef value(CYCastJSValue(context, object));
1441 case sig::typename_P:
1442 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1444 case sig::selector_P:
1445 if (SEL sel = *reinterpret_cast<SEL *>(data))
1446 return CYMakeSelector(context, sel);
1450 return CYJSNull(context);
1454 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1456 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1457 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1460 #if OBJC_API_VERSION >= 2
1462 method_getReturnType(method, type, sizeof(type));
1464 const char *type(method_getTypeEncoding(method));
1470 // XXX: possibly use a more "awesome" check?
1474 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1476 return method_getTypeEncoding(method);
1478 const char *name(sel_getName(sel));
1479 size_t length(strlen(name));
1481 char keyed[length + 2];
1483 keyed[length + 1] = '\0';
1484 memcpy(keyed + 1, name, length);
1486 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1487 return entry->value_;
1492 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1493 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1495 JSContextRef context(internal->context_);
1497 size_t count(internal->cif_.nargs);
1498 JSValueRef values[count];
1500 for (size_t index(0); index != count; ++index)
1501 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1503 JSObjectRef _this(CYCastJSObject(context, values[0]));
1505 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1506 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1509 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1510 Message_privateData *internal(new Message_privateData(sel, type, imp));
1511 return JSObjectMake(context, Message_, internal);
1514 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1515 JSObjectRef function(CYCastJSObject(context, value));
1516 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1517 // XXX: see notes in Library.cpp about needing to leak
1518 return reinterpret_cast<IMP>(internal->GetValue());
1521 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1522 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1523 Class _class(internal->GetValue());
1526 const char *name(CYPoolCString(pool, context, property));
1528 if (SEL sel = sel_getUid(name))
1529 if (class_getInstanceMethod(_class, sel) != NULL)
1535 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1536 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1537 Class _class(internal->GetValue());
1540 const char *name(CYPoolCString(pool, context, property));
1542 if (SEL sel = sel_getUid(name))
1543 if (objc_method *method = class_getInstanceMethod(_class, sel))
1544 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1549 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1550 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1551 Class _class(internal->GetValue());
1554 const char *name(CYPoolCString(pool, context, property));
1556 SEL sel(sel_registerName(name));
1558 objc_method *method(class_getInstanceMethod(_class, sel));
1563 if (JSValueIsObjectOfClass(context, value, Message_)) {
1564 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1565 type = sig::Unparse(pool, &message->signature_);
1566 imp = reinterpret_cast<IMP>(message->GetValue());
1568 type = CYPoolTypeEncoding(pool, context, sel, method);
1569 imp = CYMakeMessage(context, value, type);
1573 method_setImplementation(method, imp);
1576 GSMethodList list(GSAllocMethodList(1));
1577 GSAppendMethodToList(list, sel, type, imp, YES);
1578 GSAddMethodList(_class, list, YES);
1579 GSFlushMethodCacheForClass(_class);
1581 class_addMethod(_class, sel, imp, type);
1588 #if 0 && OBJC_API_VERSION < 2
1589 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1590 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1591 Class _class(internal->GetValue());
1594 const char *name(CYPoolCString(pool, context, property));
1596 if (SEL sel = sel_getUid(name))
1597 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1598 objc_method_list list = {NULL, 1, {method}};
1599 class_removeMethods(_class, &list);
1607 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1608 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1609 Class _class(internal->GetValue());
1611 #if OBJC_API_VERSION >= 2
1613 objc_method **data(class_copyMethodList(_class, &size));
1614 for (size_t i(0); i != size; ++i)
1615 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1618 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1619 for (int i(0); i != methods->method_count; ++i)
1620 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1624 static bool CYHasImplicitProperties(Class _class) {
1625 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1626 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1628 return [_class cy$hasImplicitProperties];
1631 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1632 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1633 id self(internal->GetValue());
1635 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1639 NSString *name(CYCastNSString(pool, context, property));
1641 if (CYInternal *internal = CYInternal::Get(self))
1642 if (internal->HasProperty(context, property))
1645 Class _class(object_getClass(self));
1648 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1649 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1650 if ([self cy$hasProperty:name])
1652 } CYPoolCatch(false)
1654 const char *string(CYPoolCString(pool, context, name));
1657 if (class_getProperty(_class, string) != NULL)
1661 if (CYHasImplicitProperties(_class))
1662 if (SEL sel = sel_getUid(string))
1663 if (CYImplements(self, _class, sel, true))
1669 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1670 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1671 id self(internal->GetValue());
1673 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1674 return Internal::Make(context, self, object);
1677 NSString *name(CYCastNSString(pool, context, property));
1679 if (CYInternal *internal = CYInternal::Get(self))
1680 if (JSValueRef value = internal->GetProperty(context, property))
1684 if (NSObject *data = [self cy$getProperty:name])
1685 return CYCastJSValue(context, data);
1688 const char *string(CYPoolCString(pool, context, name));
1689 Class _class(object_getClass(self));
1692 if (objc_property_t property = class_getProperty(_class, string)) {
1693 PropertyAttributes attributes(property);
1694 SEL sel(sel_registerName(attributes.Getter()));
1695 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1699 if (CYHasImplicitProperties(_class))
1700 if (SEL sel = sel_getUid(string))
1701 if (CYImplements(self, _class, sel, true))
1702 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1707 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1709 id self(internal->GetValue());
1713 NSString *name(CYCastNSString(pool, context, property));
1714 NSObject *data(CYCastNSObject(pool, context, value));
1717 if ([self cy$setProperty:name to:data])
1721 const char *string(CYPoolCString(pool, context, name));
1722 Class _class(object_getClass(self));
1725 if (objc_property_t property = class_getProperty(_class, string)) {
1726 PropertyAttributes attributes(property);
1727 if (const char *setter = attributes.Setter()) {
1728 SEL sel(sel_registerName(setter));
1729 JSValueRef arguments[1] = {value};
1730 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1736 size_t length(strlen(string));
1738 char set[length + 5];
1744 if (string[0] != '\0') {
1745 set[3] = toupper(string[0]);
1746 memcpy(set + 4, string + 1, length - 1);
1749 set[length + 3] = ':';
1750 set[length + 4] = '\0';
1752 if (SEL sel = sel_getUid(set))
1753 if (CYImplements(self, _class, sel, false)) {
1754 JSValueRef arguments[1] = {value};
1755 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1758 if (CYInternal *internal = CYInternal::Set(self)) {
1759 internal->SetProperty(context, property, value);
1766 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1767 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1768 id self(internal->GetValue());
1771 NSString *name(CYCastNSString(NULL, context, property));
1772 return [self cy$deleteProperty:name];
1774 } CYCatch return /*XXX*/ NULL; }
1776 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1777 const char *name(sel_getName(method_getName(method)));
1778 if (strchr(name, ':') != NULL)
1781 const char *type(method_getTypeEncoding(method));
1782 if (type == NULL || *type == '\0' || *type == 'v')
1785 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1788 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1789 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1790 id self(internal->GetValue());
1793 Class _class(object_getClass(self));
1798 objc_property_t *data(class_copyPropertyList(_class, &size));
1799 for (size_t i(0); i != size; ++i)
1800 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1805 if (CYHasImplicitProperties(_class))
1806 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1807 #if OBJC_API_VERSION >= 2
1809 objc_method **data(class_copyMethodList(current, &size));
1810 for (size_t i(0); i != size; ++i)
1811 Instance_getPropertyNames_message(names, data[i]);
1814 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1815 for (int i(0); i != methods->method_count; ++i)
1816 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1821 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1822 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1823 [self cy$getPropertyNames:names inContext:context];
1827 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1828 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1829 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1833 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1834 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1835 Class _class(internal->GetValue());
1836 if (!CYIsClass(_class))
1839 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1840 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1841 // XXX: this isn't always safe
1842 return [linternal->GetValue() isKindOfClass:_class];
1848 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1849 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1852 id self(internal->GetValue());
1853 const char *name(CYPoolCString(pool, context, property));
1855 if (object_getInstanceVariable(self, name, NULL) != NULL)
1861 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1862 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1865 id self(internal->GetValue());
1866 const char *name(CYPoolCString(pool, context, property));
1868 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1869 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1870 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1871 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1877 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1878 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1881 id self(internal->GetValue());
1882 const char *name(CYPoolCString(pool, context, property));
1884 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1885 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1886 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1893 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1894 if (Class super = class_getSuperclass(_class))
1895 Internal_getPropertyNames_(super, names);
1897 #if OBJC_API_VERSION >= 2
1899 objc_ivar **data(class_copyIvarList(_class, &size));
1900 for (size_t i(0); i != size; ++i)
1901 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1904 if (objc_ivar_list *ivars = _class->ivars)
1905 for (int i(0); i != ivars->ivar_count; ++i)
1906 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1910 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1911 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1914 id self(internal->GetValue());
1915 Class _class(object_getClass(self));
1917 Internal_getPropertyNames_(_class, names);
1920 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1921 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1922 return internal->GetOwner();
1925 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1927 NSString *name(CYCastNSString(pool, context, property));
1928 if (Class _class = NSClassFromString(name))
1929 return CYMakeInstance(context, _class, true);
1933 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1935 size_t size(objc_getClassList(NULL, 0));
1936 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1939 size_t writ(objc_getClassList(data, size));
1942 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1948 for (size_t i(0); i != writ; ++i)
1949 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1955 while (Class _class = objc_next_class(&state))
1956 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1960 #if OBJC_API_VERSION >= 2
1961 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1962 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1965 const char *name(CYPoolCString(pool, context, property));
1967 const char **data(objc_copyClassNamesForImage(internal, &size));
1969 for (size_t i(0); i != size; ++i)
1970 if (strcmp(name, data[i]) == 0) {
1971 if (Class _class = objc_getClass(name)) {
1972 value = CYMakeInstance(context, _class, true);
1983 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1984 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1986 const char **data(objc_copyClassNamesForImage(internal, &size));
1987 for (size_t i(0); i != size; ++i)
1988 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1992 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1994 const char *name(CYPoolCString(pool, context, property));
1996 const char **data(objc_copyImageNames(&size));
1997 for (size_t i(0); i != size; ++i)
1998 if (strcmp(name, data[i]) == 0) {
2007 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2008 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2012 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2014 const char **data(objc_copyImageNames(&size));
2015 for (size_t i(0); i != size; ++i)
2016 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2021 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2023 const char *name(CYPoolCString(pool, context, property));
2024 if (Protocol *protocol = objc_getProtocol(name))
2025 return CYMakeInstance(context, protocol, true);
2029 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2030 #if OBJC_API_VERSION >= 2
2032 Protocol **data(objc_copyProtocolList(&size));
2033 for (size_t i(0); i != size; ++i)
2034 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2042 static bool stret(ffi_type *ffi_type) {
2043 return ffi_type->type == FFI_TYPE_STRUCT && (
2044 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2045 struct_forward_array[ffi_type->size] != 0
2050 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 {
2054 _class = object_getClass(self);
2058 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2059 imp = method_getImplementation(method);
2060 type = method_getTypeEncoding(method);
2065 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2067 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2068 type = CYPoolCString(pool, context, [method _typeString]);
2076 sig::Signature signature;
2077 sig::Parse(pool, &signature, type, &Structor_);
2080 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2084 if (stret(cif.rtype))
2085 imp = class_getMethodImplementation_stret(_class, _cmd);
2087 imp = class_getMethodImplementation(_class, _cmd);
2089 objc_super super = {self, _class};
2090 imp = objc_msg_lookup_super(&super, _cmd);
2094 void (*function)() = reinterpret_cast<void (*)()>(imp);
2095 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2098 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2100 throw CYJSError(context, "too few arguments to objc_msgSend");
2110 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2111 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2112 self = internal->GetValue();
2113 _class = internal->class_;;
2114 uninitialized = false;
2115 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2116 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2117 self = internal->GetValue();
2119 uninitialized = internal->IsUninitialized();
2121 internal->value_ = nil;
2123 self = CYCastNSObject(pool, context, arguments[0]);
2125 uninitialized = false;
2129 return CYJSNull(context);
2131 _cmd = CYCastSEL(context, arguments[1]);
2133 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2136 /* Hook: objc_registerClassPair {{{ */
2137 #if defined(__APPLE__) && defined(__arm__)
2138 // XXX: replace this with associated objects
2140 MSHook(void, CYDealloc, id self, SEL sel) {
2141 CYInternal *internal;
2142 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2143 if (internal != NULL)
2145 _CYDealloc(self, sel);
2148 MSHook(void, objc_registerClassPair, Class _class) {
2149 Class super(class_getSuperclass(_class));
2150 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2151 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2152 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2155 _objc_registerClassPair(_class);
2158 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2160 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2162 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2163 if (value == NULL || !CYIsClass(value))
2164 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2165 Class _class((Class) value);
2166 $objc_registerClassPair(_class);
2167 return CYJSUndefined(context);
2172 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2173 JSValueRef setup[count + 2];
2176 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2177 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2180 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2182 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2184 // XXX: handle Instance::Uninitialized?
2185 id self(CYCastNSObject(pool, context, _this));
2189 setup[1] = &internal->sel_;
2191 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2194 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2196 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2198 id self(CYCastNSObject(pool, context, arguments[0]));
2199 Class _class(CYCastClass(pool, context, arguments[1]));
2200 return cy::Super::Make(context, self, _class);
2203 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2205 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2207 const char *name(CYPoolCString(pool, context, arguments[0]));
2208 return CYMakeSelector(context, sel_registerName(name));
2211 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2213 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2214 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2215 return CYMakeInstance(context, self, false);
2218 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2219 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2220 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2223 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2224 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2225 Type_privateData *typical(internal->GetType());
2230 if (typical == NULL) {
2234 type = typical->type_;
2235 ffi = typical->ffi_;
2238 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2241 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2242 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2243 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2246 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2247 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2248 id self(internal->GetValue());
2249 if (!CYIsClass(self))
2250 return CYJSUndefined(context);
2251 return CYGetClassPrototype(context, self);
2254 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2255 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2256 id self(internal->GetValue());
2257 if (!CYIsClass(self))
2258 return CYJSUndefined(context);
2259 return Messages::Make(context, (Class) self);
2262 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2263 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2266 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2267 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2270 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2271 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2274 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2281 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2282 // XXX: check for support of cy$toJSON?
2283 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2285 } CYCatch return /*XXX*/ NULL; }
2288 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2289 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2292 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2293 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2294 } CYCatch return /*XXX*/ NULL; }
2297 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2298 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2301 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2302 // XXX: but... but... THIS ISN'T A POINTER! :(
2303 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2304 } CYCatch return /*XXX*/ NULL; }
2306 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2307 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2310 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2312 id value(internal->GetValue());
2314 return CYCastJSValue(context, "nil");
2317 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2318 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2320 } CYCatch return /*XXX*/ NULL; }
2322 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2323 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2324 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2327 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2328 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2331 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2332 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2333 const char *name(sel_getName(internal->GetValue()));
2336 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2337 return CYCastJSValue(context, CYJSString(context, string));
2339 } CYCatch return /*XXX*/ NULL; }
2341 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2343 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2346 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2347 SEL sel(internal->GetValue());
2349 objc_method *method;
2350 if (Class _class = CYCastClass(pool, context, arguments[0]))
2351 method = class_getInstanceMethod(_class, sel);
2355 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2356 return CYCastJSValue(context, CYJSString(type));
2358 return CYJSNull(context);
2361 static JSStaticValue Selector_staticValues[2] = {
2362 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2363 {NULL, NULL, NULL, 0}
2366 static JSStaticValue Instance_staticValues[5] = {
2367 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2368 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2369 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2370 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2371 {NULL, NULL, NULL, 0}
2374 static JSStaticFunction Instance_staticFunctions[6] = {
2375 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2376 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2377 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2378 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2379 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2380 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2384 static JSStaticFunction Internal_staticFunctions[2] = {
2385 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2389 static JSStaticFunction Selector_staticFunctions[5] = {
2390 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2391 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2392 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2393 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2397 static JSStaticFunction StringInstance_staticFunctions[2] = {
2398 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2399 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2403 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2404 apr_pool_t *pool(CYGetGlobalPool());
2406 Object_type = new(pool) Type_privateData("@");
2407 Selector_type = new(pool) Type_privateData(":");
2410 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2411 NSCFType_ = objc_getClass("NSCFType");
2412 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2413 NSZombie_ = objc_getClass("_NSZombie_");
2415 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2418 NSArray_ = objc_getClass("NSArray");
2419 NSDictionary_ = objc_getClass("NSDictionary");
2420 NSString_ = objc_getClass("NSString");
2421 Object_ = objc_getClass("Object");
2423 JSClassDefinition definition;
2425 definition = kJSClassDefinitionEmpty;
2426 definition.className = "Instance";
2427 definition.staticValues = Instance_staticValues;
2428 definition.staticFunctions = Instance_staticFunctions;
2429 definition.hasProperty = &Instance_hasProperty;
2430 definition.getProperty = &Instance_getProperty;
2431 definition.setProperty = &Instance_setProperty;
2432 definition.deleteProperty = &Instance_deleteProperty;
2433 definition.getPropertyNames = &Instance_getPropertyNames;
2434 definition.callAsConstructor = &Instance_callAsConstructor;
2435 definition.hasInstance = &Instance_hasInstance;
2436 definition.finalize = &CYFinalize;
2437 Instance_ = JSClassCreate(&definition);
2439 definition = kJSClassDefinitionEmpty;
2440 definition.className = "Internal";
2441 definition.staticFunctions = Internal_staticFunctions;
2442 definition.hasProperty = &Internal_hasProperty;
2443 definition.getProperty = &Internal_getProperty;
2444 definition.setProperty = &Internal_setProperty;
2445 definition.getPropertyNames = &Internal_getPropertyNames;
2446 definition.finalize = &CYFinalize;
2447 Internal_ = JSClassCreate(&definition);
2449 definition = kJSClassDefinitionEmpty;
2450 definition.className = "Message";
2451 definition.staticFunctions = cy::Functor::StaticFunctions;
2452 definition.callAsFunction = &Message_callAsFunction;
2453 definition.finalize = &CYFinalize;
2454 Message_ = JSClassCreate(&definition);
2456 definition = kJSClassDefinitionEmpty;
2457 definition.className = "Messages";
2458 definition.hasProperty = &Messages_hasProperty;
2459 definition.getProperty = &Messages_getProperty;
2460 definition.setProperty = &Messages_setProperty;
2461 #if 0 && OBJC_API_VERSION < 2
2462 definition.deleteProperty = &Messages_deleteProperty;
2464 definition.getPropertyNames = &Messages_getPropertyNames;
2465 definition.finalize = &CYFinalize;
2466 Messages_ = JSClassCreate(&definition);
2468 definition = kJSClassDefinitionEmpty;
2469 definition.className = "Selector";
2470 definition.staticValues = Selector_staticValues;
2471 definition.staticFunctions = Selector_staticFunctions;
2472 definition.callAsFunction = &Selector_callAsFunction;
2473 definition.finalize = &CYFinalize;
2474 Selector_ = JSClassCreate(&definition);
2476 definition = kJSClassDefinitionEmpty;
2477 definition.className = "StringInstance";
2478 definition.staticFunctions = StringInstance_staticFunctions;
2479 StringInstance_ = JSClassCreate(&definition);
2481 definition = kJSClassDefinitionEmpty;
2482 definition.className = "Super";
2483 definition.staticFunctions = Internal_staticFunctions;
2484 definition.finalize = &CYFinalize;
2485 Super_ = JSClassCreate(&definition);
2487 definition = kJSClassDefinitionEmpty;
2488 definition.className = "ObjectiveC::Classes";
2489 definition.getProperty = &ObjectiveC_Classes_getProperty;
2490 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2491 ObjectiveC_Classes_ = JSClassCreate(&definition);
2493 #if OBJC_API_VERSION >= 2
2494 definition = kJSClassDefinitionEmpty;
2495 definition.className = "ObjectiveC::Images";
2496 definition.getProperty = &ObjectiveC_Images_getProperty;
2497 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2498 ObjectiveC_Images_ = JSClassCreate(&definition);
2500 definition = kJSClassDefinitionEmpty;
2501 definition.className = "ObjectiveC::Image::Classes";
2502 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2503 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2504 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2507 definition = kJSClassDefinitionEmpty;
2508 definition.className = "ObjectiveC::Protocols";
2509 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2510 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2511 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2513 #if defined(__APPLE__) && defined(__arm__)
2514 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2518 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2522 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2523 JSObjectRef global(CYGetGlobalObject(context));
2524 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2525 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2526 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2528 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2529 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2531 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2532 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2534 #if OBJC_API_VERSION >= 2
2535 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2538 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2539 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2540 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2541 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2542 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2544 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2545 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2547 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2548 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2550 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2551 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2553 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2554 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2555 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2557 #if defined(__APPLE__) && defined(__arm__)
2558 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2561 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2563 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2564 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2565 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2568 static CYHooks CYObjectiveCHooks = {
2569 &CYObjectiveC_ExecuteStart,
2570 &CYObjectiveC_ExecuteEnd,
2571 &CYObjectiveC_RuntimeProperty,
2572 &CYObjectiveC_CallFunction,
2573 &CYObjectiveC_Initialize,
2574 &CYObjectiveC_SetupContext,
2575 &CYObjectiveC_PoolFFI,
2576 &CYObjectiveC_FromFFI,
2579 struct CYObjectiveC {
2581 hooks_ = &CYObjectiveCHooks;
2582 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2583 _assert(hooks_ != NULL);