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];
1051 - (bool) cy$hasProperty:(NSString *)name {
1052 if ([name isEqualToString:@"length"])
1055 size_t index(CYGetIndex(name));
1056 if (index == _not(size_t) || index >= [self length])
1057 return [super cy$hasProperty:name];
1062 - (NSObject *) cy$getProperty:(NSString *)name {
1063 if ([name isEqualToString:@"length"]) {
1064 NSUInteger count([self length]);
1066 return [NSNumber numberWithUnsignedInteger:count];
1068 return [NSNumber numberWithUnsignedInt:count];
1072 size_t index(CYGetIndex(name));
1073 if (index == _not(size_t) || index >= [self length])
1074 return [super cy$getProperty:name];
1076 return [self substringWithRange:NSMakeRange(index, 1)];
1079 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1080 [super cy$getPropertyNames:names inContext:context];
1082 for (size_t index(0), length([self length]); index != length; ++index) {
1084 sprintf(name, "%zu", index);
1085 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1089 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1090 + (bool) cy$hasImplicitProperties {
1096 /* Bridge: WebUndefined {{{ */
1097 @implementation WebUndefined (Cycript)
1099 - (JSType) cy$JSType {
1100 return kJSTypeUndefined;
1103 - (NSObject *) cy$toJSON:(NSString *)key {
1107 - (NSString *) cy$toCYON {
1108 return @"undefined";
1111 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1112 return CYJSUndefined(context);
1113 } CYObjectiveCatch }
1118 static bool CYIsClass(id self) {
1120 // XXX: this is a lame object_isClass
1121 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1123 return GSObjCIsClass(self);
1127 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1128 id self(CYCastNSObject(pool, context, value));
1129 if (CYIsClass(self))
1130 return (Class) self;
1131 throw CYJSError(context, "got something that is not a Class");
1135 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1137 size_t size(JSPropertyNameArrayGetCount(names));
1138 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1139 for (size_t index(0); index != size; ++index)
1140 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1144 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1146 return CYJSNull(context);
1147 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1148 return [value cy$JSValueInContext:context];
1150 return CYMakeInstance(context, value, false);
1151 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1153 @implementation CYJSObject
1155 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1156 if ((self = [super init]) != nil) {
1158 context_ = CYGetJSContext(context);
1159 //XXX:JSGlobalContextRetain(context_);
1160 JSValueProtect(context_, object_);
1162 } CYObjectiveCatch }
1164 - (void) dealloc { CYObjectiveTry {
1165 JSValueUnprotect(context_, object_);
1166 //XXX:JSGlobalContextRelease(context_);
1168 } CYObjectiveCatch }
1170 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1171 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1172 if (!CYIsCallable(context_, toJSON))
1173 return [super cy$toJSON:key];
1175 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1176 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1177 // XXX: do I really want an NSNull here?!
1178 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1180 } CYObjectiveCatch }
1182 - (NSString *) cy$toCYON { CYObjectiveTry {
1184 JSValueRef exception(NULL);
1185 const char *cyon(CYPoolCCYON(pool, context_, object_));
1186 CYThrow(context_, exception);
1188 return [super cy$toCYON];
1190 return [NSString stringWithUTF8String:cyon];
1191 } CYObjectiveCatch }
1193 - (NSUInteger) count { CYObjectiveTry {
1194 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1195 size_t size(JSPropertyNameArrayGetCount(names));
1196 JSPropertyNameArrayRelease(names);
1198 } CYObjectiveCatch }
1200 - (id) objectForKey:(id)key { CYObjectiveTry {
1201 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1202 if (JSValueIsUndefined(context_, value))
1204 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1205 } CYObjectiveCatch }
1207 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1208 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1209 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1210 JSPropertyNameArrayRelease(names);
1212 } CYObjectiveCatch }
1214 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1215 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1216 } CYObjectiveCatch }
1218 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1219 JSValueRef exception(NULL);
1220 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1221 CYThrow(context_, exception);
1222 } CYObjectiveCatch }
1226 @implementation CYJSArray
1228 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1229 if ((self = [super init]) != nil) {
1231 context_ = CYGetJSContext(context);
1232 //XXX:JSGlobalContextRetain(context_);
1233 JSValueProtect(context_, object_);
1235 } CYObjectiveCatch }
1237 - (void) dealloc { CYObjectiveTry {
1238 JSValueUnprotect(context_, object_);
1239 //XXX:JSGlobalContextRelease(context_);
1241 } CYObjectiveCatch }
1243 - (NSUInteger) count { CYObjectiveTry {
1244 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1245 } CYObjectiveCatch }
1247 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1248 size_t bounds([self count]);
1249 if (index >= bounds)
1250 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1251 JSValueRef exception(NULL);
1252 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1253 CYThrow(context_, exception);
1254 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1255 } CYObjectiveCatch }
1257 - (void) addObject:(id)object { CYObjectiveTry {
1258 JSValueRef exception(NULL);
1259 JSValueRef arguments[1];
1260 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1261 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1262 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1263 CYThrow(context_, exception);
1264 } CYObjectiveCatch }
1266 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1267 size_t bounds([self count] + 1);
1268 if (index >= bounds)
1269 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1270 JSValueRef exception(NULL);
1271 JSValueRef arguments[3];
1272 arguments[0] = CYCastJSValue(context_, index);
1273 arguments[1] = CYCastJSValue(context_, 0);
1274 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1275 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1276 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1277 CYThrow(context_, exception);
1278 } CYObjectiveCatch }
1280 - (void) removeLastObject { CYObjectiveTry {
1281 JSValueRef exception(NULL);
1282 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1283 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1284 CYThrow(context_, exception);
1285 } CYObjectiveCatch }
1287 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1288 size_t bounds([self count]);
1289 if (index >= bounds)
1290 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1291 JSValueRef exception(NULL);
1292 JSValueRef arguments[2];
1293 arguments[0] = CYCastJSValue(context_, index);
1294 arguments[1] = CYCastJSValue(context_, 1);
1295 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1296 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1297 CYThrow(context_, exception);
1298 } CYObjectiveCatch }
1300 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1301 size_t bounds([self count]);
1302 if (index >= bounds)
1303 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1304 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1305 } CYObjectiveCatch }
1309 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1313 JSObjectRef object_;
1321 // XXX: delete object_? ;(
1324 static CYInternal *Get(id self) {
1325 CYInternal *internal(NULL);
1326 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1327 // XXX: do something epic? ;P
1333 static CYInternal *Set(id self) {
1334 CYInternal *internal(NULL);
1335 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1336 if (internal == NULL) {
1337 internal = new CYInternal();
1338 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1341 // XXX: do something epic? ;P
1347 bool HasProperty(JSContextRef context, JSStringRef name) {
1348 if (object_ == NULL)
1350 return JSObjectHasProperty(context, object_, name);
1353 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1354 if (object_ == NULL)
1356 return CYGetProperty(context, object_, name);
1359 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1360 if (object_ == NULL)
1361 object_ = JSObjectMake(context, NULL, NULL);
1362 CYSetProperty(context, object_, name, value);
1366 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1367 Selector_privateData *internal(new Selector_privateData(sel));
1368 return JSObjectMake(context, Selector_, internal);
1371 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1372 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1373 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1374 return reinterpret_cast<SEL>(internal->value_);
1376 return CYCastPointer<SEL>(context, value);
1379 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1380 return (void *) [[NSAutoreleasePool alloc] init];
1381 } CYSadCatch(NULL) }
1383 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1384 return [(NSAutoreleasePool *) handle release];
1387 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1389 return Instance::Make(context, nil);
1390 if (Class _class = objc_getClass(name.data))
1391 return CYMakeInstance(context, _class, true);
1392 if (Protocol *protocol = objc_getProtocol(name.data))
1393 return CYMakeInstance(context, protocol, true);
1395 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1397 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1398 ffi_call(cif, function, value, values);
1401 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1402 switch (type->primitive) {
1403 // XXX: do something epic about blocks
1406 case sig::typename_P:
1407 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1410 case sig::selector_P:
1411 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1419 } CYSadCatch(false) }
1421 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1422 switch (type->primitive) {
1423 // XXX: do something epic about blocks
1426 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1427 JSValueRef value(CYCastJSValue(context, object));
1433 case sig::typename_P:
1434 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1436 case sig::selector_P:
1437 if (SEL sel = *reinterpret_cast<SEL *>(data))
1438 return CYMakeSelector(context, sel);
1442 return CYJSNull(context);
1446 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1448 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1449 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1452 #if OBJC_API_VERSION >= 2
1454 method_getReturnType(method, type, sizeof(type));
1456 const char *type(method_getTypeEncoding(method));
1462 // XXX: possibly use a more "awesome" check?
1466 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1468 return method_getTypeEncoding(method);
1470 const char *name(sel_getName(sel));
1471 size_t length(strlen(name));
1473 char keyed[length + 2];
1475 keyed[length + 1] = '\0';
1476 memcpy(keyed + 1, name, length);
1478 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1479 return entry->value_;
1484 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1485 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1487 JSContextRef context(internal->context_);
1489 size_t count(internal->cif_.nargs);
1490 JSValueRef values[count];
1492 for (size_t index(0); index != count; ++index)
1493 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1495 JSObjectRef _this(CYCastJSObject(context, values[0]));
1497 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1498 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1501 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1502 Message_privateData *internal(new Message_privateData(sel, type, imp));
1503 return JSObjectMake(context, Message_, internal);
1506 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1507 JSObjectRef function(CYCastJSObject(context, value));
1508 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1509 // XXX: see notes in Library.cpp about needing to leak
1510 return reinterpret_cast<IMP>(internal->GetValue());
1513 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1514 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1515 Class _class(internal->GetValue());
1518 const char *name(CYPoolCString(pool, context, property));
1520 if (SEL sel = sel_getUid(name))
1521 if (class_getInstanceMethod(_class, sel) != NULL)
1527 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1528 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1529 Class _class(internal->GetValue());
1532 const char *name(CYPoolCString(pool, context, property));
1534 if (SEL sel = sel_getUid(name))
1535 if (objc_method *method = class_getInstanceMethod(_class, sel))
1536 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1541 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1542 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1543 Class _class(internal->GetValue());
1546 const char *name(CYPoolCString(pool, context, property));
1548 SEL sel(sel_registerName(name));
1550 objc_method *method(class_getInstanceMethod(_class, sel));
1555 if (JSValueIsObjectOfClass(context, value, Message_)) {
1556 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1557 type = sig::Unparse(pool, &message->signature_);
1558 imp = reinterpret_cast<IMP>(message->GetValue());
1560 type = CYPoolTypeEncoding(pool, context, sel, method);
1561 imp = CYMakeMessage(context, value, type);
1565 method_setImplementation(method, imp);
1568 GSMethodList list(GSAllocMethodList(1));
1569 GSAppendMethodToList(list, sel, type, imp, YES);
1570 GSAddMethodList(_class, list, YES);
1571 GSFlushMethodCacheForClass(_class);
1573 class_addMethod(_class, sel, imp, type);
1580 #if 0 && OBJC_API_VERSION < 2
1581 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1582 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1583 Class _class(internal->GetValue());
1586 const char *name(CYPoolCString(pool, context, property));
1588 if (SEL sel = sel_getUid(name))
1589 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1590 objc_method_list list = {NULL, 1, {method}};
1591 class_removeMethods(_class, &list);
1599 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1600 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1601 Class _class(internal->GetValue());
1603 #if OBJC_API_VERSION >= 2
1605 objc_method **data(class_copyMethodList(_class, &size));
1606 for (size_t i(0); i != size; ++i)
1607 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1610 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1611 for (int i(0); i != methods->method_count; ++i)
1612 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1616 static bool CYHasImplicitProperties(Class _class) {
1617 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1618 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1620 return [_class cy$hasImplicitProperties];
1623 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1624 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1625 id self(internal->GetValue());
1627 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1631 NSString *name(CYCastNSString(pool, context, property));
1633 if (CYInternal *internal = CYInternal::Get(self))
1634 if (internal->HasProperty(context, property))
1637 Class _class(object_getClass(self));
1640 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1641 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1642 if ([self cy$hasProperty:name])
1644 } CYPoolCatch(false)
1646 const char *string(CYPoolCString(pool, context, name));
1649 if (class_getProperty(_class, string) != NULL)
1653 if (CYHasImplicitProperties(_class))
1654 if (SEL sel = sel_getUid(string))
1655 if (CYImplements(self, _class, sel, true))
1661 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1662 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1663 id self(internal->GetValue());
1665 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1666 return Internal::Make(context, self, object);
1669 NSString *name(CYCastNSString(pool, context, property));
1671 if (CYInternal *internal = CYInternal::Get(self))
1672 if (JSValueRef value = internal->GetProperty(context, property))
1676 if (NSObject *data = [self cy$getProperty:name])
1677 return CYCastJSValue(context, data);
1680 const char *string(CYPoolCString(pool, context, name));
1681 Class _class(object_getClass(self));
1684 if (objc_property_t property = class_getProperty(_class, string)) {
1685 PropertyAttributes attributes(property);
1686 SEL sel(sel_registerName(attributes.Getter()));
1687 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1691 if (CYHasImplicitProperties(_class))
1692 if (SEL sel = sel_getUid(string))
1693 if (CYImplements(self, _class, sel, true))
1694 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1699 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1700 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1701 id self(internal->GetValue());
1705 NSString *name(CYCastNSString(pool, context, property));
1706 NSObject *data(CYCastNSObject(pool, context, value));
1709 if ([self cy$setProperty:name to:data])
1713 const char *string(CYPoolCString(pool, context, name));
1714 Class _class(object_getClass(self));
1717 if (objc_property_t property = class_getProperty(_class, string)) {
1718 PropertyAttributes attributes(property);
1719 if (const char *setter = attributes.Setter()) {
1720 SEL sel(sel_registerName(setter));
1721 JSValueRef arguments[1] = {value};
1722 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1728 size_t length(strlen(string));
1730 char set[length + 5];
1736 if (string[0] != '\0') {
1737 set[3] = toupper(string[0]);
1738 memcpy(set + 4, string + 1, length - 1);
1741 set[length + 3] = ':';
1742 set[length + 4] = '\0';
1744 if (SEL sel = sel_getUid(set))
1745 if (CYImplements(self, _class, sel, false)) {
1746 JSValueRef arguments[1] = {value};
1747 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1750 if (CYInternal *internal = CYInternal::Set(self)) {
1751 internal->SetProperty(context, property, value);
1758 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1759 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1760 id self(internal->GetValue());
1763 NSString *name(CYCastNSString(NULL, context, property));
1764 return [self cy$deleteProperty:name];
1766 } CYCatch return /*XXX*/ NULL; }
1768 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1769 const char *name(sel_getName(method_getName(method)));
1770 if (strchr(name, ':') != NULL)
1773 const char *type(method_getTypeEncoding(method));
1774 if (type == NULL || *type == '\0' || *type == 'v')
1777 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1780 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1781 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1782 id self(internal->GetValue());
1785 Class _class(object_getClass(self));
1790 objc_property_t *data(class_copyPropertyList(_class, &size));
1791 for (size_t i(0); i != size; ++i)
1792 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1797 if (CYHasImplicitProperties(_class))
1798 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1799 #if OBJC_API_VERSION >= 2
1801 objc_method **data(class_copyMethodList(current, &size));
1802 for (size_t i(0); i != size; ++i)
1803 Instance_getPropertyNames_message(names, data[i]);
1806 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1807 for (int i(0); i != methods->method_count; ++i)
1808 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1813 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1814 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1815 [self cy$getPropertyNames:names inContext:context];
1819 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1820 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1821 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1825 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1826 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1827 Class _class(internal->GetValue());
1828 if (!CYIsClass(_class))
1831 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1832 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1833 // XXX: this isn't always safe
1834 return [linternal->GetValue() isKindOfClass:_class];
1840 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1841 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1844 id self(internal->GetValue());
1845 const char *name(CYPoolCString(pool, context, property));
1847 if (object_getInstanceVariable(self, name, NULL) != NULL)
1853 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1854 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1857 id self(internal->GetValue());
1858 const char *name(CYPoolCString(pool, context, property));
1860 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1861 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1862 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1863 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1869 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1870 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1873 id self(internal->GetValue());
1874 const char *name(CYPoolCString(pool, context, property));
1876 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1877 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1878 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1885 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1886 if (Class super = class_getSuperclass(_class))
1887 Internal_getPropertyNames_(super, names);
1889 #if OBJC_API_VERSION >= 2
1891 objc_ivar **data(class_copyIvarList(_class, &size));
1892 for (size_t i(0); i != size; ++i)
1893 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1896 if (objc_ivar_list *ivars = _class->ivars)
1897 for (int i(0); i != ivars->ivar_count; ++i)
1898 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1902 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1903 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1906 id self(internal->GetValue());
1907 Class _class(object_getClass(self));
1909 Internal_getPropertyNames_(_class, names);
1912 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1913 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1914 return internal->GetOwner();
1917 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1919 NSString *name(CYCastNSString(pool, context, property));
1920 if (Class _class = NSClassFromString(name))
1921 return CYMakeInstance(context, _class, true);
1925 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1927 size_t size(objc_getClassList(NULL, 0));
1928 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1931 size_t writ(objc_getClassList(data, size));
1934 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1940 for (size_t i(0); i != writ; ++i)
1941 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1947 while (Class _class = objc_next_class(&state))
1948 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1952 #if OBJC_API_VERSION >= 2
1953 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1954 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1957 const char *name(CYPoolCString(pool, context, property));
1959 const char **data(objc_copyClassNamesForImage(internal, &size));
1961 for (size_t i(0); i != size; ++i)
1962 if (strcmp(name, data[i]) == 0) {
1963 if (Class _class = objc_getClass(name)) {
1964 value = CYMakeInstance(context, _class, true);
1975 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1976 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1978 const char **data(objc_copyClassNamesForImage(internal, &size));
1979 for (size_t i(0); i != size; ++i)
1980 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1984 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1986 const char *name(CYPoolCString(pool, context, property));
1988 const char **data(objc_copyImageNames(&size));
1989 for (size_t i(0); i != size; ++i)
1990 if (strcmp(name, data[i]) == 0) {
1999 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2000 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2004 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2006 const char **data(objc_copyImageNames(&size));
2007 for (size_t i(0); i != size; ++i)
2008 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2013 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2015 const char *name(CYPoolCString(pool, context, property));
2016 if (Protocol *protocol = objc_getProtocol(name))
2017 return CYMakeInstance(context, protocol, true);
2021 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2022 #if OBJC_API_VERSION >= 2
2024 Protocol **data(objc_copyProtocolList(&size));
2025 for (size_t i(0); i != size; ++i)
2026 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2034 static bool stret(ffi_type *ffi_type) {
2035 return ffi_type->type == FFI_TYPE_STRUCT && (
2036 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2037 struct_forward_array[ffi_type->size] != 0
2042 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 {
2046 _class = object_getClass(self);
2050 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2051 imp = method_getImplementation(method);
2052 type = method_getTypeEncoding(method);
2057 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2059 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2060 type = CYPoolCString(pool, context, [method _typeString]);
2068 sig::Signature signature;
2069 sig::Parse(pool, &signature, type, &Structor_);
2072 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2076 if (stret(cif.rtype))
2077 imp = class_getMethodImplementation_stret(_class, _cmd);
2079 imp = class_getMethodImplementation(_class, _cmd);
2081 objc_super super = {self, _class};
2082 imp = objc_msg_lookup_super(&super, _cmd);
2086 void (*function)() = reinterpret_cast<void (*)()>(imp);
2087 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2090 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2092 throw CYJSError(context, "too few arguments to objc_msgSend");
2102 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2103 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2104 self = internal->GetValue();
2105 _class = internal->class_;;
2106 uninitialized = false;
2107 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2108 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2109 self = internal->GetValue();
2111 uninitialized = internal->IsUninitialized();
2113 internal->value_ = nil;
2115 self = CYCastNSObject(pool, context, arguments[0]);
2117 uninitialized = false;
2121 return CYJSNull(context);
2123 _cmd = CYCastSEL(context, arguments[1]);
2125 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2128 /* Hook: objc_registerClassPair {{{ */
2129 #if defined(__APPLE__) && defined(__arm__)
2130 // XXX: replace this with associated objects
2132 MSHook(void, CYDealloc, id self, SEL sel) {
2133 CYInternal *internal;
2134 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2135 if (internal != NULL)
2137 _CYDealloc(self, sel);
2140 MSHook(void, objc_registerClassPair, Class _class) {
2141 Class super(class_getSuperclass(_class));
2142 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2143 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2144 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2147 _objc_registerClassPair(_class);
2150 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2152 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2154 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2155 if (value == NULL || !CYIsClass(value))
2156 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2157 Class _class((Class) value);
2158 $objc_registerClassPair(_class);
2159 return CYJSUndefined(context);
2164 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2165 JSValueRef setup[count + 2];
2168 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2169 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2172 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2174 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2176 // XXX: handle Instance::Uninitialized?
2177 id self(CYCastNSObject(pool, context, _this));
2181 setup[1] = &internal->sel_;
2183 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2186 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2188 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2190 id self(CYCastNSObject(pool, context, arguments[0]));
2191 Class _class(CYCastClass(pool, context, arguments[1]));
2192 return cy::Super::Make(context, self, _class);
2195 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2197 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2199 const char *name(CYPoolCString(pool, context, arguments[0]));
2200 return CYMakeSelector(context, sel_registerName(name));
2203 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2205 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2206 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2207 return CYMakeInstance(context, self, false);
2210 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2211 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2212 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2215 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2216 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2217 Type_privateData *typical(internal->GetType());
2222 if (typical == NULL) {
2226 type = typical->type_;
2227 ffi = typical->ffi_;
2230 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2233 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2234 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2235 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2238 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2239 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2240 id self(internal->GetValue());
2241 if (!CYIsClass(self))
2242 return CYJSUndefined(context);
2243 return CYGetClassPrototype(context, self);
2246 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2247 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2248 id self(internal->GetValue());
2249 if (!CYIsClass(self))
2250 return CYJSUndefined(context);
2251 return Messages::Make(context, (Class) self);
2254 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2255 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2258 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2259 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2262 static JSValueRef Instance_callAsFunction_toJSON(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)));
2273 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2274 // XXX: check for support of cy$toJSON?
2275 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2277 } CYCatch return /*XXX*/ NULL; }
2280 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2281 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2284 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2285 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2286 } CYCatch return /*XXX*/ NULL; }
2289 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2290 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2293 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2294 // XXX: but... but... THIS ISN'T A POINTER! :(
2295 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2296 } CYCatch return /*XXX*/ NULL; }
2298 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2299 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2302 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2304 id value(internal->GetValue());
2306 return CYCastJSValue(context, "nil");
2309 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2310 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2312 } CYCatch return /*XXX*/ NULL; }
2314 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2315 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2316 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2319 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2320 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2323 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2324 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2325 const char *name(sel_getName(internal->GetValue()));
2328 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2329 return CYCastJSValue(context, CYJSString(context, string));
2331 } CYCatch return /*XXX*/ NULL; }
2333 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2335 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2338 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2339 SEL sel(internal->GetValue());
2341 objc_method *method;
2342 if (Class _class = CYCastClass(pool, context, arguments[0]))
2343 method = class_getInstanceMethod(_class, sel);
2347 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2348 return CYCastJSValue(context, CYJSString(type));
2350 return CYJSNull(context);
2353 static JSStaticValue Selector_staticValues[2] = {
2354 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2355 {NULL, NULL, NULL, 0}
2358 static JSStaticValue Instance_staticValues[5] = {
2359 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2360 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2361 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2362 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2363 {NULL, NULL, NULL, 0}
2366 static JSStaticFunction Instance_staticFunctions[6] = {
2367 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2368 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2369 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2370 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2371 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2372 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2376 static JSStaticFunction Internal_staticFunctions[2] = {
2377 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2381 static JSStaticFunction Selector_staticFunctions[5] = {
2382 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2383 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2384 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2385 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2389 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2390 apr_pool_t *pool(CYGetGlobalPool());
2392 Object_type = new(pool) Type_privateData("@");
2393 Selector_type = new(pool) Type_privateData(":");
2396 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2397 NSCFType_ = objc_getClass("NSCFType");
2398 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2399 NSZombie_ = objc_getClass("_NSZombie_");
2401 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2404 NSArray_ = objc_getClass("NSArray");
2405 NSDictionary_ = objc_getClass("NSDictionary");
2406 Object_ = objc_getClass("Object");
2408 JSClassDefinition definition;
2410 definition = kJSClassDefinitionEmpty;
2411 definition.className = "Instance";
2412 definition.staticValues = Instance_staticValues;
2413 definition.staticFunctions = Instance_staticFunctions;
2414 definition.hasProperty = &Instance_hasProperty;
2415 definition.getProperty = &Instance_getProperty;
2416 definition.setProperty = &Instance_setProperty;
2417 definition.deleteProperty = &Instance_deleteProperty;
2418 definition.getPropertyNames = &Instance_getPropertyNames;
2419 definition.callAsConstructor = &Instance_callAsConstructor;
2420 definition.hasInstance = &Instance_hasInstance;
2421 definition.finalize = &CYFinalize;
2422 Instance_ = JSClassCreate(&definition);
2424 definition = kJSClassDefinitionEmpty;
2425 definition.className = "Internal";
2426 definition.staticFunctions = Internal_staticFunctions;
2427 definition.hasProperty = &Internal_hasProperty;
2428 definition.getProperty = &Internal_getProperty;
2429 definition.setProperty = &Internal_setProperty;
2430 definition.getPropertyNames = &Internal_getPropertyNames;
2431 definition.finalize = &CYFinalize;
2432 Internal_ = JSClassCreate(&definition);
2434 definition = kJSClassDefinitionEmpty;
2435 definition.className = "Message";
2436 definition.staticFunctions = cy::Functor::StaticFunctions;
2437 definition.callAsFunction = &Message_callAsFunction;
2438 definition.finalize = &CYFinalize;
2439 Message_ = JSClassCreate(&definition);
2441 definition = kJSClassDefinitionEmpty;
2442 definition.className = "Messages";
2443 definition.hasProperty = &Messages_hasProperty;
2444 definition.getProperty = &Messages_getProperty;
2445 definition.setProperty = &Messages_setProperty;
2446 #if 0 && OBJC_API_VERSION < 2
2447 definition.deleteProperty = &Messages_deleteProperty;
2449 definition.getPropertyNames = &Messages_getPropertyNames;
2450 definition.finalize = &CYFinalize;
2451 Messages_ = JSClassCreate(&definition);
2453 definition = kJSClassDefinitionEmpty;
2454 definition.className = "Selector";
2455 definition.staticValues = Selector_staticValues;
2456 definition.staticFunctions = Selector_staticFunctions;
2457 definition.callAsFunction = &Selector_callAsFunction;
2458 definition.finalize = &CYFinalize;
2459 Selector_ = JSClassCreate(&definition);
2461 definition = kJSClassDefinitionEmpty;
2462 definition.className = "Super";
2463 definition.staticFunctions = Internal_staticFunctions;
2464 definition.finalize = &CYFinalize;
2465 Super_ = JSClassCreate(&definition);
2467 definition = kJSClassDefinitionEmpty;
2468 definition.className = "ObjectiveC::Classes";
2469 definition.getProperty = &ObjectiveC_Classes_getProperty;
2470 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2471 ObjectiveC_Classes_ = JSClassCreate(&definition);
2473 #if OBJC_API_VERSION >= 2
2474 definition = kJSClassDefinitionEmpty;
2475 definition.className = "ObjectiveC::Images";
2476 definition.getProperty = &ObjectiveC_Images_getProperty;
2477 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2478 ObjectiveC_Images_ = JSClassCreate(&definition);
2480 definition = kJSClassDefinitionEmpty;
2481 definition.className = "ObjectiveC::Image::Classes";
2482 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2483 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2484 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2487 definition = kJSClassDefinitionEmpty;
2488 definition.className = "ObjectiveC::Protocols";
2489 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2490 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2491 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2493 #if defined(__APPLE__) && defined(__arm__)
2494 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2498 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2502 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2503 JSObjectRef global(CYGetGlobalObject(context));
2504 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2505 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2506 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2508 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2509 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2511 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2512 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2514 #if OBJC_API_VERSION >= 2
2515 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2518 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2519 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2520 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2521 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2523 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2524 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2526 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2527 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2528 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2530 #if defined(__APPLE__) && defined(__arm__)
2531 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2534 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2536 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2537 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2538 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2541 static CYHooks CYObjectiveCHooks = {
2542 &CYObjectiveC_ExecuteStart,
2543 &CYObjectiveC_ExecuteEnd,
2544 &CYObjectiveC_RuntimeProperty,
2545 &CYObjectiveC_CallFunction,
2546 &CYObjectiveC_Initialize,
2547 &CYObjectiveC_SetupContext,
2548 &CYObjectiveC_PoolFFI,
2549 &CYObjectiveC_FromFFI,
2552 struct CYObjectiveC {
2554 hooks_ = &CYObjectiveCHooks;
2555 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2556 _assert(hooks_ != NULL);