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)); \
135 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
139 #define object_setIvar(object, ivar, value) ({ \
140 void *data = (value); \
141 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
144 #define protocol_getName(protocol) [(protocol) name]
147 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
149 /* Objective-C Pool Release {{{ */
150 apr_status_t CYPoolRelease_(void *data) {
151 id object(reinterpret_cast<id>(data));
156 id CYPoolRelease_(apr_pool_t *pool, id object) {
159 else if (pool == NULL)
160 return [object autorelease];
162 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
167 template <typename Type_>
168 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
169 return (Type_) CYPoolRelease_(pool, (id) object);
172 /* Objective-C Strings {{{ */
173 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
175 return [value UTF8String];
177 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
178 char *string(new(pool) char[size]);
179 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
180 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
185 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
187 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
190 return CYCopyJSString(CYPoolCString(pool, context, value));
194 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
197 // XXX: this definition scares me; is anyone using this?!
198 NSString *string([value description]);
199 return CYCopyJSString(context, string);
202 NSString *CYCopyNSString(const CYUTF8String &value) {
204 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
206 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
210 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
212 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
215 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
219 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
220 return CYCopyNSString(context, CYJSString(context, value));
223 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
224 return CYPoolRelease(pool, CYCopyNSString(value));
227 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
228 const char *name(sel_getName(sel));
229 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
232 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
233 return CYPoolRelease(pool, CYCopyNSString(context, value));
236 CYUTF8String CYCastUTF8String(NSString *value) {
237 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
238 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
242 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
244 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
245 if (exception == NULL)
247 *exception = CYCastJSValue(context, error);
250 size_t CYGetIndex(NSString *value) {
251 return CYGetIndex(CYCastUTF8String(value));
254 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
255 return CYGetOffset(CYPoolCString(pool, context, value), index);
258 static JSClassRef Instance_;
259 static JSClassRef Internal_;
260 static JSClassRef Message_;
261 static JSClassRef Messages_;
262 static JSClassRef Selector_;
263 static JSClassRef Super_;
265 static JSClassRef ObjectiveC_Classes_;
266 static JSClassRef ObjectiveC_Protocols_;
269 static JSClassRef ObjectiveC_Image_Classes_;
270 static JSClassRef ObjectiveC_Images_;
274 static Class NSCFBoolean_;
275 static Class NSCFType_;
276 static Class NSMessageBuilder_;
277 static Class NSZombie_;
279 static Class NSBoolNumber_;
282 static Class NSArray_;
283 static Class NSDictionary_;
284 static Class Object_;
286 static Type_privateData *Object_type;
287 static Type_privateData *Selector_type;
289 Type_privateData *Instance::GetType() const {
293 Type_privateData *Selector_privateData::GetType() const {
294 return Selector_type;
297 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
299 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
301 JSObjectRef global(CYGetGlobalObject(context));
302 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
305 sprintf(label, "i%p", self);
306 CYJSString name(label);
308 JSValueRef value(CYGetProperty(context, cy, name));
309 if (!JSValueIsUndefined(context, value))
312 JSClassRef _class(NULL);
313 JSValueRef prototype;
315 if (self == NSArray_)
316 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
317 else if (self == NSDictionary_)
318 prototype = CYGetCachedObject(context, CYJSString("Object_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);
328 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
329 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
330 if (_class == NSArray_)
332 if (Class super = class_getSuperclass(_class))
333 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
335 JSObjectSetPrototype(context, value, Array_prototype_);*/
339 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
340 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
344 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
345 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
349 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
350 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
351 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
355 Instance::~Instance() {
356 if ((flags_ & Transient) == 0)
357 // XXX: does this handle background threads correctly?
358 // XXX: this simply does not work on the console because I'm stupid
359 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
362 struct Message_privateData :
367 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
368 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
374 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
375 Instance::Flags flags;
378 flags = Instance::Transient;
380 flags = Instance::None;
381 object = [object retain];
384 return Instance::Make(context, object, flags);
387 @interface NSMethodSignature (Cycript)
388 - (NSString *) _typeString;
391 @interface NSObject (Cycript)
393 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
394 - (JSType) cy$JSType;
396 - (NSObject *) cy$toJSON:(NSString *)key;
397 - (NSString *) cy$toCYON;
398 - (NSString *) cy$toKey;
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;
411 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
414 NSString *CYCastNSCYON(id value) {
420 Class _class(object_getClass(value));
421 SEL sel(@selector(cy$toCYON));
423 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
424 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
425 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
426 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
427 string = [value cy$toCYON];
432 else if (value == NSZombie_)
433 string = @"_NSZombie_";
434 else if (_class == NSZombie_)
435 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
436 // XXX: frowny /in/ the pants
437 else if (value == NSMessageBuilder_ || value == Object_)
441 string = [NSString stringWithFormat:@"%@", value];
446 string = @"undefined";
453 struct PropertyAttributes {
458 const char *variable;
471 PropertyAttributes(objc_property_t property) :
483 name = property_getName(property);
484 const char *attributes(property_getAttributes(property));
486 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
488 case 'R': readonly = true; break;
489 case 'C': copy = true; break;
490 case '&': retain = true; break;
491 case 'N': nonatomic = true; break;
492 case 'G': getter_ = token + 1; break;
493 case 'S': setter_ = token + 1; break;
494 case 'V': variable = token + 1; break;
498 /*if (variable == NULL) {
499 variable = property_getName(property);
500 size_t size(strlen(variable));
501 char *name(new(pool_) char[size + 2]);
503 memcpy(name + 1, variable, size);
504 name[size + 1] = '\0';
509 const char *Getter() {
511 getter_ = apr_pstrdup(pool_, name);
515 const char *Setter() {
516 if (setter_ == NULL && !readonly) {
517 size_t length(strlen(name));
519 char *temp(new(pool_) char[length + 5]);
525 temp[3] = toupper(name[0]);
526 memcpy(temp + 4, name + 1, length - 1);
529 temp[length + 3] = ':';
530 temp[length + 4] = '\0';
541 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
542 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
547 @interface CYWebUndefined : NSObject {
550 + (CYWebUndefined *) undefined;
554 @implementation CYWebUndefined
556 + (CYWebUndefined *) undefined {
557 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
563 #define WebUndefined CYWebUndefined
566 /* Bridge: CYJSObject {{{ */
567 @interface CYJSObject : NSMutableDictionary {
569 JSContextRef context_;
572 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
574 - (NSObject *) cy$toJSON:(NSString *)key;
576 - (NSUInteger) count;
577 - (id) objectForKey:(id)key;
578 - (NSEnumerator *) keyEnumerator;
579 - (void) setObject:(id)object forKey:(id)key;
580 - (void) removeObjectForKey:(id)key;
584 /* Bridge: CYJSArray {{{ */
585 @interface CYJSArray : NSMutableArray {
587 JSContextRef context_;
590 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
592 - (NSUInteger) count;
593 - (id) objectAtIndex:(NSUInteger)index;
595 - (void) addObject:(id)anObject;
596 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
597 - (void) removeLastObject;
598 - (void) removeObjectAtIndex:(NSUInteger)index;
599 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
604 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
605 JSObjectRef Array(CYGetCachedObject(context, Array_s));
606 JSValueRef exception(NULL);
607 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
608 CYThrow(context, exception);
609 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
610 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
613 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
614 if (!JSValueIsObjectOfClass(context, object, Instance_))
615 return CYCastNSObject_(pool, context, object);
617 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
618 return internal->GetValue();
622 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
623 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
627 @interface NSBoolNumber : NSNumber {
632 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
636 switch (JSType type = JSValueGetType(context, value)) {
637 case kJSTypeUndefined:
638 object = [WebUndefined undefined];
648 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
651 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
657 object = CYCopyNSNumber(context, value);
662 object = CYCopyNSString(context, value);
667 // XXX: this might could be more efficient
668 object = CYCastNSObject(pool, context, (JSObjectRef) value);
673 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
680 return CYPoolRelease(pool, object);
682 return [object retain];
685 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
686 return CYNSObject(pool, context, value, true);
689 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
690 return CYNSObject(pool, context, value, false);
693 /* Bridge: NSArray {{{ */
694 @implementation NSArray (Cycript)
696 - (NSString *) cy$toCYON {
697 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
698 [json appendString:@"["];
702 for (id object in self) {
704 for (size_t index(0), count([self count]); index != count; ++index) {
705 id object([self objectAtIndex:index]);
708 [json appendString:@","];
711 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
712 [json appendString:CYCastNSCYON(object)];
714 [json appendString:@","];
719 [json appendString:@"]"];
723 - (bool) cy$hasProperty:(NSString *)name {
724 if ([name isEqualToString:@"length"])
727 size_t index(CYGetIndex(name));
728 if (index == _not(size_t) || index >= [self count])
729 return [super cy$hasProperty:name];
734 - (NSObject *) cy$getProperty:(NSString *)name {
735 if ([name isEqualToString:@"length"]) {
736 NSUInteger count([self count]);
738 return [NSNumber numberWithUnsignedInteger:count];
740 return [NSNumber numberWithUnsignedInt:count];
744 size_t index(CYGetIndex(name));
745 if (index == _not(size_t) || index >= [self count])
746 return [super cy$getProperty:name];
748 return [self objectAtIndex:index];
751 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
752 [super cy$getPropertyNames:names inContext:context];
754 for (size_t index(0), count([self count]); index != count; ++index) {
755 id object([self objectAtIndex:index]);
756 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
758 sprintf(name, "%zu", index);
759 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
764 + (bool) cy$hasImplicitProperties {
770 /* Bridge: NSBoolNumber {{{ */
772 @implementation NSBoolNumber (Cycript)
774 - (JSType) cy$JSType {
775 return kJSTypeBoolean;
778 - (NSObject *) cy$toJSON:(NSString *)key {
782 - (NSString *) cy$toCYON {
783 return [self boolValue] ? @"true" : @"false";
786 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
787 return CYCastJSValue(context, (bool) [self boolValue]);
793 /* Bridge: NSDictionary {{{ */
794 @implementation NSDictionary (Cycript)
796 - (NSString *) cy$toCYON {
797 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
798 [json appendString:@"{"];
802 for (NSObject *key in self) {
804 NSEnumerator *keys([self keyEnumerator]);
805 while (NSObject *key = [keys nextObject]) {
808 [json appendString:@","];
811 [json appendString:[key cy$toKey]];
812 [json appendString:@":"];
813 NSObject *object([self objectForKey:key]);
814 [json appendString:CYCastNSCYON(object)];
817 [json appendString:@"}"];
821 - (bool) cy$hasProperty:(NSString *)name {
822 return [self objectForKey:name] != nil;
825 - (NSObject *) cy$getProperty:(NSString *)name {
826 return [self objectForKey:name];
829 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
830 [super cy$getPropertyNames:names inContext:context];
833 for (NSObject *key in self) {
835 NSEnumerator *keys([self keyEnumerator]);
836 while (NSObject *key = [keys nextObject]) {
838 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
842 + (bool) cy$hasImplicitProperties {
848 /* Bridge: NSMutableArray {{{ */
849 @implementation NSMutableArray (Cycript)
851 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
852 if ([name isEqualToString:@"length"]) {
853 // XXX: is this not intelligent?
854 NSNumber *number(reinterpret_cast<NSNumber *>(value));
856 NSUInteger size([number unsignedIntegerValue]);
858 NSUInteger size([number unsignedIntValue]);
860 NSUInteger count([self count]);
862 [self removeObjectsInRange:NSMakeRange(size, count - size)];
863 else if (size != count) {
864 WebUndefined *undefined([WebUndefined undefined]);
865 for (size_t i(count); i != size; ++i)
866 [self addObject:undefined];
871 size_t index(CYGetIndex(name));
872 if (index == _not(size_t))
873 return [super cy$setProperty:name to:value];
875 id object(value ?: [NSNull null]);
877 size_t count([self count]);
879 [self replaceObjectAtIndex:index withObject:object];
881 if (index != count) {
882 WebUndefined *undefined([WebUndefined undefined]);
883 for (size_t i(count); i != index; ++i)
884 [self addObject:undefined];
887 [self addObject:object];
893 - (bool) cy$deleteProperty:(NSString *)name {
894 size_t index(CYGetIndex(name));
895 if (index == _not(size_t) || index >= [self count])
896 return [super cy$deleteProperty:name];
897 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
903 /* Bridge: NSMutableDictionary {{{ */
904 @implementation NSMutableDictionary (Cycript)
906 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
907 [self setObject:(value ?: [NSNull null]) forKey:name];
911 - (bool) cy$deleteProperty:(NSString *)name {
912 if ([self objectForKey:name] == nil)
915 [self removeObjectForKey:name];
922 /* Bridge: NSNumber {{{ */
923 @implementation NSNumber (Cycript)
925 - (JSType) cy$JSType {
927 // XXX: this just seems stupid
928 if ([self class] == NSCFBoolean_)
929 return kJSTypeBoolean;
931 return kJSTypeNumber;
934 - (NSObject *) cy$toJSON:(NSString *)key {
938 - (NSString *) cy$toCYON {
939 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
942 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
943 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
948 /* Bridge: NSNull {{{ */
949 @implementation NSNull (Cycript)
951 - (JSType) cy$JSType {
955 - (NSObject *) cy$toJSON:(NSString *)key {
959 - (NSString *) cy$toCYON {
965 /* Bridge: NSObject {{{ */
966 @implementation NSObject (Cycript)
968 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
969 return CYMakeInstance(context, self, false);
972 - (JSType) cy$JSType {
973 return kJSTypeObject;
976 - (NSObject *) cy$toJSON:(NSString *)key {
977 return [self description];
980 - (NSString *) cy$toCYON {
981 return [[self cy$toJSON:@""] cy$toCYON];
984 - (NSString *) cy$toKey {
985 return [self cy$toCYON];
988 - (bool) cy$hasProperty:(NSString *)name {
992 - (NSObject *) cy$getProperty:(NSString *)name {
996 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1000 - (bool) cy$deleteProperty:(NSString *)name {
1004 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1007 + (bool) cy$hasImplicitProperties {
1013 /* Bridge: NSProxy {{{ */
1014 @implementation NSProxy (Cycript)
1016 - (NSObject *) cy$toJSON:(NSString *)key {
1017 return [self description];
1020 - (NSString *) cy$toCYON {
1021 return [[self cy$toJSON:@""] cy$toCYON];
1026 /* Bridge: NSString {{{ */
1027 @implementation NSString (Cycript)
1029 - (JSType) cy$JSType {
1030 return kJSTypeString;
1033 - (NSObject *) cy$toJSON:(NSString *)key {
1037 - (NSString *) cy$toCYON {
1038 std::ostringstream str;
1039 CYUTF8String string(CYCastUTF8String(self));
1040 CYStringify(str, string.data, string.size);
1041 std::string value(str.str());
1042 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1045 - (NSString *) cy$toKey {
1046 if (CYIsKey(CYCastUTF8String(self)))
1048 return [self cy$toCYON];
1053 /* Bridge: WebUndefined {{{ */
1054 @implementation WebUndefined (Cycript)
1056 - (JSType) cy$JSType {
1057 return kJSTypeUndefined;
1060 - (NSObject *) cy$toJSON:(NSString *)key {
1064 - (NSString *) cy$toCYON {
1065 return @"undefined";
1068 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1069 return CYJSUndefined(context);
1070 } CYObjectiveCatch }
1075 static bool CYIsClass(id self) {
1077 // XXX: this is a lame object_isClass
1078 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1080 return GSObjCIsClass(self);
1084 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1085 id self(CYCastNSObject(pool, context, value));
1086 if (CYIsClass(self))
1087 return (Class) self;
1088 throw CYJSError(context, "got something that is not a Class");
1092 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1094 size_t size(JSPropertyNameArrayGetCount(names));
1095 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1096 for (size_t index(0); index != size; ++index)
1097 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1101 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1103 return CYJSNull(context);
1104 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1105 return [value cy$JSValueInContext:context];
1107 return CYMakeInstance(context, value, false);
1108 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1110 @implementation CYJSObject
1112 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1113 if ((self = [super init]) != nil) {
1115 context_ = CYGetJSContext(context);
1116 //XXX:JSGlobalContextRetain(context_);
1117 JSValueProtect(context_, object_);
1119 } CYObjectiveCatch }
1121 - (void) dealloc { CYObjectiveTry {
1122 JSValueUnprotect(context_, object_);
1123 //XXX:JSGlobalContextRelease(context_);
1125 } CYObjectiveCatch }
1127 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1128 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1129 if (!CYIsCallable(context_, toJSON))
1130 return [super cy$toJSON:key];
1132 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1133 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1134 // XXX: do I really want an NSNull here?!
1135 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1137 } CYObjectiveCatch }
1139 - (NSString *) cy$toCYON { CYObjectiveTry {
1141 JSValueRef exception(NULL);
1142 const char *cyon(CYPoolCCYON(pool, context_, object_));
1143 CYThrow(context_, exception);
1145 return [super cy$toCYON];
1147 return [NSString stringWithUTF8String:cyon];
1148 } CYObjectiveCatch }
1150 - (NSUInteger) count { CYObjectiveTry {
1151 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1152 size_t size(JSPropertyNameArrayGetCount(names));
1153 JSPropertyNameArrayRelease(names);
1155 } CYObjectiveCatch }
1157 - (id) objectForKey:(id)key { CYObjectiveTry {
1158 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1159 if (JSValueIsUndefined(context_, value))
1161 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1162 } CYObjectiveCatch }
1164 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1165 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1166 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1167 JSPropertyNameArrayRelease(names);
1169 } CYObjectiveCatch }
1171 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1172 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1173 } CYObjectiveCatch }
1175 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1176 JSValueRef exception(NULL);
1177 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1178 CYThrow(context_, exception);
1179 } CYObjectiveCatch }
1183 @implementation CYJSArray
1185 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1186 if ((self = [super init]) != nil) {
1188 context_ = CYGetJSContext(context);
1189 //XXX:JSGlobalContextRetain(context_);
1190 JSValueProtect(context_, object_);
1192 } CYObjectiveCatch }
1194 - (void) dealloc { CYObjectiveTry {
1195 JSValueUnprotect(context_, object_);
1196 //XXX:JSGlobalContextRelease(context_);
1198 } CYObjectiveCatch }
1200 - (NSUInteger) count { CYObjectiveTry {
1201 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1202 } CYObjectiveCatch }
1204 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1205 size_t bounds([self count]);
1206 if (index >= bounds)
1207 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1208 JSValueRef exception(NULL);
1209 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1210 CYThrow(context_, exception);
1211 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1212 } CYObjectiveCatch }
1214 - (void) addObject:(id)object { CYObjectiveTry {
1215 JSValueRef exception(NULL);
1216 JSValueRef arguments[1];
1217 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1218 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1219 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1220 CYThrow(context_, exception);
1221 } CYObjectiveCatch }
1223 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1224 size_t bounds([self count] + 1);
1225 if (index >= bounds)
1226 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1227 JSValueRef exception(NULL);
1228 JSValueRef arguments[3];
1229 arguments[0] = CYCastJSValue(context_, index);
1230 arguments[1] = CYCastJSValue(context_, 0);
1231 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1232 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1233 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1234 CYThrow(context_, exception);
1235 } CYObjectiveCatch }
1237 - (void) removeLastObject { CYObjectiveTry {
1238 JSValueRef exception(NULL);
1239 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1240 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1241 CYThrow(context_, exception);
1242 } CYObjectiveCatch }
1244 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1245 size_t bounds([self count]);
1246 if (index >= bounds)
1247 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1248 JSValueRef exception(NULL);
1249 JSValueRef arguments[2];
1250 arguments[0] = CYCastJSValue(context_, index);
1251 arguments[1] = CYCastJSValue(context_, 1);
1252 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1253 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1254 CYThrow(context_, exception);
1255 } CYObjectiveCatch }
1257 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1258 size_t bounds([self count]);
1259 if (index >= bounds)
1260 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1261 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1262 } CYObjectiveCatch }
1266 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1270 JSObjectRef object_;
1278 // XXX: delete object_? ;(
1281 static CYInternal *Get(id self) {
1282 CYInternal *internal(NULL);
1283 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1284 // XXX: do something epic? ;P
1290 static CYInternal *Set(id self) {
1291 CYInternal *internal(NULL);
1292 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1293 if (internal == NULL) {
1294 internal = new CYInternal();
1295 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1298 // XXX: do something epic? ;P
1304 bool HasProperty(JSContextRef context, JSStringRef name) {
1305 if (object_ == NULL)
1307 return JSObjectHasProperty(context, object_, name);
1310 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1311 if (object_ == NULL)
1313 return CYGetProperty(context, object_, name);
1316 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1317 if (object_ == NULL)
1318 object_ = JSObjectMake(context, NULL, NULL);
1319 CYSetProperty(context, object_, name, value);
1323 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1324 Selector_privateData *internal(new Selector_privateData(sel));
1325 return JSObjectMake(context, Selector_, internal);
1328 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1329 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1330 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1331 return reinterpret_cast<SEL>(internal->value_);
1333 return CYCastPointer<SEL>(context, value);
1336 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1337 return (void *) [[NSAutoreleasePool alloc] init];
1338 } CYSadCatch(NULL) }
1340 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1341 return [(NSAutoreleasePool *) handle release];
1344 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1346 return Instance::Make(context, nil);
1347 if (Class _class = objc_getClass(name.data))
1348 return CYMakeInstance(context, _class, true);
1349 if (Protocol *protocol = objc_getProtocol(name.data))
1350 return CYMakeInstance(context, protocol, true);
1352 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1354 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1355 ffi_call(cif, function, value, values);
1358 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1359 switch (type->primitive) {
1360 // XXX: do something epic about blocks
1363 case sig::typename_P:
1364 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1367 case sig::selector_P:
1368 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1376 } CYSadCatch(false) }
1378 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1379 switch (type->primitive) {
1380 // XXX: do something epic about blocks
1383 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1384 JSValueRef value(CYCastJSValue(context, object));
1390 case sig::typename_P:
1391 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1393 case sig::selector_P:
1394 if (SEL sel = *reinterpret_cast<SEL *>(data))
1395 return CYMakeSelector(context, sel);
1399 return CYJSNull(context);
1403 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1405 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1406 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1409 #if OBJC_API_VERSION >= 2
1411 method_getReturnType(method, type, sizeof(type));
1413 const char *type(method_getTypeEncoding(method));
1419 // XXX: possibly use a more "awesome" check?
1423 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1425 return method_getTypeEncoding(method);
1427 const char *name(sel_getName(sel));
1428 size_t length(strlen(name));
1430 char keyed[length + 2];
1432 keyed[length + 1] = '\0';
1433 memcpy(keyed + 1, name, length);
1435 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1436 return entry->value_;
1441 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1442 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1444 JSContextRef context(internal->context_);
1446 size_t count(internal->cif_.nargs);
1447 JSValueRef values[count];
1449 for (size_t index(0); index != count; ++index)
1450 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1452 JSObjectRef _this(CYCastJSObject(context, values[0]));
1454 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1455 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1458 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1459 Message_privateData *internal(new Message_privateData(sel, type, imp));
1460 return JSObjectMake(context, Message_, internal);
1463 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1464 JSObjectRef function(CYCastJSObject(context, value));
1465 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1466 // XXX: see notes in Library.cpp about needing to leak
1467 return reinterpret_cast<IMP>(internal->GetValue());
1470 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1471 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1472 Class _class(internal->GetValue());
1475 const char *name(CYPoolCString(pool, context, property));
1477 if (SEL sel = sel_getUid(name))
1478 if (class_getInstanceMethod(_class, sel) != NULL)
1484 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1485 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1486 Class _class(internal->GetValue());
1489 const char *name(CYPoolCString(pool, context, property));
1491 if (SEL sel = sel_getUid(name))
1492 if (objc_method *method = class_getInstanceMethod(_class, sel))
1493 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1498 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1499 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1500 Class _class(internal->GetValue());
1503 const char *name(CYPoolCString(pool, context, property));
1505 SEL sel(sel_registerName(name));
1507 objc_method *method(class_getInstanceMethod(_class, sel));
1512 if (JSValueIsObjectOfClass(context, value, Message_)) {
1513 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1514 type = sig::Unparse(pool, &message->signature_);
1515 imp = reinterpret_cast<IMP>(message->GetValue());
1517 type = CYPoolTypeEncoding(pool, context, sel, method);
1518 imp = CYMakeMessage(context, value, type);
1522 method_setImplementation(method, imp);
1525 GSMethodList list(GSAllocMethodList(1));
1526 GSAppendMethodToList(list, sel, type, imp, YES);
1527 GSAddMethodList(_class, list, YES);
1528 GSFlushMethodCacheForClass(_class);
1530 class_addMethod(_class, sel, imp, type);
1537 #if 0 && OBJC_API_VERSION < 2
1538 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1539 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1540 Class _class(internal->GetValue());
1543 const char *name(CYPoolCString(pool, context, property));
1545 if (SEL sel = sel_getUid(name))
1546 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1547 objc_method_list list = {NULL, 1, {method}};
1548 class_removeMethods(_class, &list);
1556 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1557 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1558 Class _class(internal->GetValue());
1560 #if OBJC_API_VERSION >= 2
1562 objc_method **data(class_copyMethodList(_class, &size));
1563 for (size_t i(0); i != size; ++i)
1564 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1567 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1568 for (int i(0); i != methods->method_count; ++i)
1569 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1573 static bool CYHasImplicitProperties(Class _class) {
1574 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1575 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1577 return [_class cy$hasImplicitProperties];
1580 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1581 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1582 id self(internal->GetValue());
1584 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1588 NSString *name(CYCastNSString(pool, context, property));
1590 if (CYInternal *internal = CYInternal::Get(self))
1591 if (internal->HasProperty(context, property))
1594 Class _class(object_getClass(self));
1597 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1598 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1599 if ([self cy$hasProperty:name])
1601 } CYPoolCatch(false)
1603 const char *string(CYPoolCString(pool, context, name));
1606 if (class_getProperty(_class, string) != NULL)
1610 if (CYHasImplicitProperties(_class))
1611 if (SEL sel = sel_getUid(string))
1612 if (CYImplements(self, _class, sel, true))
1618 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1619 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1620 id self(internal->GetValue());
1622 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1623 return Internal::Make(context, self, object);
1626 NSString *name(CYCastNSString(pool, context, property));
1628 if (CYInternal *internal = CYInternal::Get(self))
1629 if (JSValueRef value = internal->GetProperty(context, property))
1633 if (NSObject *data = [self cy$getProperty:name])
1634 return CYCastJSValue(context, data);
1637 const char *string(CYPoolCString(pool, context, name));
1638 Class _class(object_getClass(self));
1641 if (objc_property_t property = class_getProperty(_class, string)) {
1642 PropertyAttributes attributes(property);
1643 SEL sel(sel_registerName(attributes.Getter()));
1644 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1648 if (CYHasImplicitProperties(_class))
1649 if (SEL sel = sel_getUid(string))
1650 if (CYImplements(self, _class, sel, true))
1651 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1656 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1657 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1658 id self(internal->GetValue());
1662 NSString *name(CYCastNSString(pool, context, property));
1663 NSObject *data(CYCastNSObject(pool, context, value));
1666 if ([self cy$setProperty:name to:data])
1670 const char *string(CYPoolCString(pool, context, name));
1671 Class _class(object_getClass(self));
1674 if (objc_property_t property = class_getProperty(_class, string)) {
1675 PropertyAttributes attributes(property);
1676 if (const char *setter = attributes.Setter()) {
1677 SEL sel(sel_registerName(setter));
1678 JSValueRef arguments[1] = {value};
1679 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1685 size_t length(strlen(string));
1687 char set[length + 5];
1693 if (string[0] != '\0') {
1694 set[3] = toupper(string[0]);
1695 memcpy(set + 4, string + 1, length - 1);
1698 set[length + 3] = ':';
1699 set[length + 4] = '\0';
1701 if (SEL sel = sel_getUid(set))
1702 if (CYImplements(self, _class, sel, false)) {
1703 JSValueRef arguments[1] = {value};
1704 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1707 if (CYInternal *internal = CYInternal::Set(self)) {
1708 internal->SetProperty(context, property, value);
1715 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1716 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1717 id self(internal->GetValue());
1720 NSString *name(CYCastNSString(NULL, context, property));
1721 return [self cy$deleteProperty:name];
1723 } CYCatch return /*XXX*/ NULL; }
1725 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1726 const char *name(sel_getName(method_getName(method)));
1727 if (strchr(name, ':') != NULL)
1730 const char *type(method_getTypeEncoding(method));
1731 if (type == NULL || *type == '\0' || *type == 'v')
1734 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1737 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1738 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1739 id self(internal->GetValue());
1742 Class _class(object_getClass(self));
1747 objc_property_t *data(class_copyPropertyList(_class, &size));
1748 for (size_t i(0); i != size; ++i)
1749 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1754 if (CYHasImplicitProperties(_class))
1755 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1756 #if OBJC_API_VERSION >= 2
1758 objc_method **data(class_copyMethodList(current, &size));
1759 for (size_t i(0); i != size; ++i)
1760 Instance_getPropertyNames_message(names, data[i]);
1763 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1764 for (int i(0); i != methods->method_count; ++i)
1765 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1770 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1771 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1772 [self cy$getPropertyNames:names inContext:context];
1776 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1777 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1778 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1782 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1783 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1784 Class _class(internal->GetValue());
1785 if (!CYIsClass(_class))
1788 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1789 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1790 // XXX: this isn't always safe
1791 return [linternal->GetValue() isKindOfClass:_class];
1797 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1798 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1801 id self(internal->GetValue());
1802 const char *name(CYPoolCString(pool, context, property));
1804 if (object_getInstanceVariable(self, name, NULL) != NULL)
1810 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1811 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1814 id self(internal->GetValue());
1815 const char *name(CYPoolCString(pool, context, property));
1817 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1818 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1819 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1820 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1826 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1827 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1830 id self(internal->GetValue());
1831 const char *name(CYPoolCString(pool, context, property));
1833 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1834 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1835 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1842 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1843 if (Class super = class_getSuperclass(_class))
1844 Internal_getPropertyNames_(super, names);
1846 #if OBJC_API_VERSION >= 2
1848 objc_ivar **data(class_copyIvarList(_class, &size));
1849 for (size_t i(0); i != size; ++i)
1850 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1853 if (objc_ivar_list *ivars = _class->ivars)
1854 for (int i(0); i != ivars->ivar_count; ++i)
1855 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1859 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1860 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1863 id self(internal->GetValue());
1864 Class _class(object_getClass(self));
1866 Internal_getPropertyNames_(_class, names);
1869 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1870 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1871 return internal->GetOwner();
1874 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1876 NSString *name(CYCastNSString(pool, context, property));
1877 if (Class _class = NSClassFromString(name))
1878 return CYMakeInstance(context, _class, true);
1882 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1884 size_t size(objc_getClassList(NULL, 0));
1885 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1888 size_t writ(objc_getClassList(data, size));
1891 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1897 for (size_t i(0); i != writ; ++i)
1898 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1904 while (Class _class = objc_next_class(&state))
1905 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1909 #if OBJC_API_VERSION >= 2
1910 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1911 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1914 const char *name(CYPoolCString(pool, context, property));
1916 const char **data(objc_copyClassNamesForImage(internal, &size));
1918 for (size_t i(0); i != size; ++i)
1919 if (strcmp(name, data[i]) == 0) {
1920 if (Class _class = objc_getClass(name)) {
1921 value = CYMakeInstance(context, _class, true);
1932 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1933 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1935 const char **data(objc_copyClassNamesForImage(internal, &size));
1936 for (size_t i(0); i != size; ++i)
1937 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1941 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1943 const char *name(CYPoolCString(pool, context, property));
1945 const char **data(objc_copyImageNames(&size));
1946 for (size_t i(0); i != size; ++i)
1947 if (strcmp(name, data[i]) == 0) {
1956 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1957 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1961 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1963 const char **data(objc_copyImageNames(&size));
1964 for (size_t i(0); i != size; ++i)
1965 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1970 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1972 const char *name(CYPoolCString(pool, context, property));
1973 if (Protocol *protocol = objc_getProtocol(name))
1974 return CYMakeInstance(context, protocol, true);
1978 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1979 #if OBJC_API_VERSION >= 2
1981 Protocol **data(objc_copyProtocolList(&size));
1982 for (size_t i(0); i != size; ++i)
1983 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1991 static bool stret(ffi_type *ffi_type) {
1992 return ffi_type->type == FFI_TYPE_STRUCT && (
1993 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1994 struct_forward_array[ffi_type->size] != 0
1999 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 {
2003 _class = object_getClass(self);
2007 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2008 imp = method_getImplementation(method);
2009 type = method_getTypeEncoding(method);
2014 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2016 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2017 type = CYPoolCString(pool, context, [method _typeString]);
2025 sig::Signature signature;
2026 sig::Parse(pool, &signature, type, &Structor_);
2029 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2033 if (stret(cif.rtype))
2034 imp = class_getMethodImplementation_stret(_class, _cmd);
2036 imp = class_getMethodImplementation(_class, _cmd);
2038 objc_super super = {self, _class};
2039 imp = objc_msg_lookup_super(&super, _cmd);
2043 void (*function)() = reinterpret_cast<void (*)()>(imp);
2044 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2047 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2049 throw CYJSError(context, "too few arguments to objc_msgSend");
2059 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2060 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2061 self = internal->GetValue();
2062 _class = internal->class_;;
2063 uninitialized = false;
2064 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2065 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2066 self = internal->GetValue();
2068 uninitialized = internal->IsUninitialized();
2070 internal->value_ = nil;
2072 self = CYCastNSObject(pool, context, arguments[0]);
2074 uninitialized = false;
2078 return CYJSNull(context);
2080 _cmd = CYCastSEL(context, arguments[1]);
2082 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2085 /* Hook: objc_registerClassPair {{{ */
2086 #if defined(__APPLE__) && defined(__arm__)
2087 // XXX: replace this with associated objects
2089 MSHook(void, CYDealloc, id self, SEL sel) {
2090 CYInternal *internal;
2091 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2092 if (internal != NULL)
2094 _CYDealloc(self, sel);
2097 MSHook(void, objc_registerClassPair, Class _class) {
2098 Class super(class_getSuperclass(_class));
2099 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2100 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2101 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2104 _objc_registerClassPair(_class);
2107 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2109 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2111 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2112 if (value == NULL || !CYIsClass(value))
2113 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2114 Class _class((Class) value);
2115 $objc_registerClassPair(_class);
2116 return CYJSUndefined(context);
2121 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2122 JSValueRef setup[count + 2];
2125 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2126 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2129 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2131 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2133 // XXX: handle Instance::Uninitialized?
2134 id self(CYCastNSObject(pool, context, _this));
2138 setup[1] = &internal->sel_;
2140 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2143 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2145 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2147 id self(CYCastNSObject(pool, context, arguments[0]));
2148 Class _class(CYCastClass(pool, context, arguments[1]));
2149 return cy::Super::Make(context, self, _class);
2152 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2154 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2156 const char *name(CYPoolCString(pool, context, arguments[0]));
2157 return CYMakeSelector(context, sel_registerName(name));
2160 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2162 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2163 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2164 return CYMakeInstance(context, self, false);
2167 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2168 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2169 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2172 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2173 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2174 Type_privateData *typical(internal->GetType());
2179 if (typical == NULL) {
2183 type = typical->type_;
2184 ffi = typical->ffi_;
2187 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2190 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2191 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2192 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2195 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2196 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2197 id self(internal->GetValue());
2198 if (!CYIsClass(self))
2199 return CYJSUndefined(context);
2200 return CYGetClassPrototype(context, self);
2203 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2204 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2205 id self(internal->GetValue());
2206 if (!CYIsClass(self))
2207 return CYJSUndefined(context);
2208 return Messages::Make(context, (Class) self);
2211 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2212 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2215 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2216 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2219 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2220 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2223 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2230 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2231 // XXX: check for support of cy$toJSON?
2232 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2234 } CYCatch return /*XXX*/ NULL; }
2237 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2238 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2241 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2242 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2243 } CYCatch return /*XXX*/ NULL; }
2246 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2247 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2250 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2251 // XXX: but... but... THIS ISN'T A POINTER! :(
2252 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2253 } CYCatch return /*XXX*/ NULL; }
2255 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2256 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2259 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2261 id value(internal->GetValue());
2263 return CYCastJSValue(context, "nil");
2266 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2267 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2269 } CYCatch return /*XXX*/ NULL; }
2271 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2272 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2273 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2276 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2277 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2280 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2281 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2282 const char *name(sel_getName(internal->GetValue()));
2285 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2286 return CYCastJSValue(context, CYJSString(context, string));
2288 } CYCatch return /*XXX*/ NULL; }
2290 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2292 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2295 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2296 SEL sel(internal->GetValue());
2298 objc_method *method;
2299 if (Class _class = CYCastClass(pool, context, arguments[0]))
2300 method = class_getInstanceMethod(_class, sel);
2304 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2305 return CYCastJSValue(context, CYJSString(type));
2307 return CYJSNull(context);
2310 static JSStaticValue Selector_staticValues[2] = {
2311 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2312 {NULL, NULL, NULL, 0}
2315 static JSStaticValue Instance_staticValues[5] = {
2316 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2317 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2318 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2319 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2320 {NULL, NULL, NULL, 0}
2323 static JSStaticFunction Instance_staticFunctions[6] = {
2324 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2325 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2326 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2327 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2328 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2329 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2333 static JSStaticFunction Internal_staticFunctions[2] = {
2334 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2338 static JSStaticFunction Selector_staticFunctions[5] = {
2339 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2340 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2341 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2342 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2346 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2347 apr_pool_t *pool(CYGetGlobalPool());
2349 Object_type = new(pool) Type_privateData("@");
2350 Selector_type = new(pool) Type_privateData(":");
2353 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2354 NSCFType_ = objc_getClass("NSCFType");
2355 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2356 NSZombie_ = objc_getClass("_NSZombie_");
2358 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2361 NSArray_ = objc_getClass("NSArray");
2362 NSDictionary_ = objc_getClass("NSDictionary");
2363 Object_ = objc_getClass("Object");
2365 JSClassDefinition definition;
2367 definition = kJSClassDefinitionEmpty;
2368 definition.className = "Instance";
2369 definition.staticValues = Instance_staticValues;
2370 definition.staticFunctions = Instance_staticFunctions;
2371 definition.hasProperty = &Instance_hasProperty;
2372 definition.getProperty = &Instance_getProperty;
2373 definition.setProperty = &Instance_setProperty;
2374 definition.deleteProperty = &Instance_deleteProperty;
2375 definition.getPropertyNames = &Instance_getPropertyNames;
2376 definition.callAsConstructor = &Instance_callAsConstructor;
2377 definition.hasInstance = &Instance_hasInstance;
2378 definition.finalize = &CYFinalize;
2379 Instance_ = JSClassCreate(&definition);
2381 definition = kJSClassDefinitionEmpty;
2382 definition.className = "Internal";
2383 definition.staticFunctions = Internal_staticFunctions;
2384 definition.hasProperty = &Internal_hasProperty;
2385 definition.getProperty = &Internal_getProperty;
2386 definition.setProperty = &Internal_setProperty;
2387 definition.getPropertyNames = &Internal_getPropertyNames;
2388 definition.finalize = &CYFinalize;
2389 Internal_ = JSClassCreate(&definition);
2391 definition = kJSClassDefinitionEmpty;
2392 definition.className = "Message";
2393 definition.staticFunctions = cy::Functor::StaticFunctions;
2394 definition.callAsFunction = &Message_callAsFunction;
2395 definition.finalize = &CYFinalize;
2396 Message_ = JSClassCreate(&definition);
2398 definition = kJSClassDefinitionEmpty;
2399 definition.className = "Messages";
2400 definition.hasProperty = &Messages_hasProperty;
2401 definition.getProperty = &Messages_getProperty;
2402 definition.setProperty = &Messages_setProperty;
2403 #if 0 && OBJC_API_VERSION < 2
2404 definition.deleteProperty = &Messages_deleteProperty;
2406 definition.getPropertyNames = &Messages_getPropertyNames;
2407 definition.finalize = &CYFinalize;
2408 Messages_ = JSClassCreate(&definition);
2410 definition = kJSClassDefinitionEmpty;
2411 definition.className = "Selector";
2412 definition.staticValues = Selector_staticValues;
2413 definition.staticFunctions = Selector_staticFunctions;
2414 definition.callAsFunction = &Selector_callAsFunction;
2415 definition.finalize = &CYFinalize;
2416 Selector_ = JSClassCreate(&definition);
2418 definition = kJSClassDefinitionEmpty;
2419 definition.className = "Super";
2420 definition.staticFunctions = Internal_staticFunctions;
2421 definition.finalize = &CYFinalize;
2422 Super_ = JSClassCreate(&definition);
2424 definition = kJSClassDefinitionEmpty;
2425 definition.className = "ObjectiveC::Classes";
2426 definition.getProperty = &ObjectiveC_Classes_getProperty;
2427 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2428 ObjectiveC_Classes_ = JSClassCreate(&definition);
2430 #if OBJC_API_VERSION >= 2
2431 definition = kJSClassDefinitionEmpty;
2432 definition.className = "ObjectiveC::Images";
2433 definition.getProperty = &ObjectiveC_Images_getProperty;
2434 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2435 ObjectiveC_Images_ = JSClassCreate(&definition);
2437 definition = kJSClassDefinitionEmpty;
2438 definition.className = "ObjectiveC::Image::Classes";
2439 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2440 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2441 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2444 definition = kJSClassDefinitionEmpty;
2445 definition.className = "ObjectiveC::Protocols";
2446 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2447 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2448 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2450 #if defined(__APPLE__) && defined(__arm__)
2451 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2455 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2459 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2460 JSObjectRef global(CYGetGlobalObject(context));
2461 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2462 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2463 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2465 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2466 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2468 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2469 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2471 #if OBJC_API_VERSION >= 2
2472 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2475 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2476 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2477 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2478 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2480 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2481 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2483 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2484 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2485 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2487 #if defined(__APPLE__) && defined(__arm__)
2488 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2491 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2493 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2494 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2495 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2498 static CYHooks CYObjectiveCHooks = {
2499 &CYObjectiveC_ExecuteStart,
2500 &CYObjectiveC_ExecuteEnd,
2501 &CYObjectiveC_RuntimeProperty,
2502 &CYObjectiveC_CallFunction,
2503 &CYObjectiveC_Initialize,
2504 &CYObjectiveC_SetupContext,
2505 &CYObjectiveC_PoolFFI,
2506 &CYObjectiveC_FromFFI,
2509 struct CYObjectiveC {
2511 hooks_ = &CYObjectiveCHooks;
2512 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2513 _assert(hooks_ != NULL);