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 NSString_;
285 static Class Object_;
287 static Type_privateData *Object_type;
288 static Type_privateData *Selector_type;
290 Type_privateData *Instance::GetType() const {
294 Type_privateData *Selector_privateData::GetType() const {
295 return Selector_type;
298 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
300 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
302 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
304 JSObjectRef global(CYGetGlobalObject(context));
305 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
308 sprintf(label, "i%p", self);
309 CYJSString name(label);
311 JSValueRef value(CYGetProperty(context, cy, name));
312 if (!JSValueIsUndefined(context, value))
315 JSClassRef _class(NULL);
316 JSValueRef prototype;
318 JSObjectRef object(JSObjectMake(context, _class, NULL));
320 if (self == NSArray_)
321 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
322 else if (self == NSDictionary_)
323 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
324 else if (self == NSString_) {
325 prototype = CYGetCachedObject(context, CYJSString("String_prototype"));
327 CYSetProperty(context, object, toString_s, &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete);
329 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
331 JSObjectSetPrototype(context, object, prototype);
332 CYSetProperty(context, cy, name, object);
337 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
338 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
339 if (_class == NSArray_)
341 if (Class super = class_getSuperclass(_class))
342 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
344 JSObjectSetPrototype(context, value, Array_prototype_);*/
348 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
349 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
353 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
354 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
358 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
359 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
360 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
364 Instance::~Instance() {
365 if ((flags_ & Transient) == 0)
366 // XXX: does this handle background threads correctly?
367 // XXX: this simply does not work on the console because I'm stupid
368 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
371 struct Message_privateData :
376 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
377 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
383 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
384 Instance::Flags flags;
387 flags = Instance::Transient;
389 flags = Instance::None;
390 object = [object retain];
393 return Instance::Make(context, object, flags);
396 @interface NSMethodSignature (Cycript)
397 - (NSString *) _typeString;
400 @interface NSObject (Cycript)
402 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
403 - (JSType) cy$JSType;
405 - (NSObject *) cy$toJSON:(NSString *)key;
406 - (NSString *) cy$toCYON;
407 - (NSString *) cy$toKey;
409 - (bool) cy$hasProperty:(NSString *)name;
410 - (NSObject *) cy$getProperty:(NSString *)name;
411 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
412 - (bool) cy$deleteProperty:(NSString *)name;
413 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
415 + (bool) cy$hasImplicitProperties;
420 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
423 NSString *CYCastNSCYON(id value) {
429 Class _class(object_getClass(value));
430 SEL sel(@selector(cy$toCYON));
432 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
433 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
434 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
435 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
436 string = [value cy$toCYON];
441 else if (value == NSZombie_)
442 string = @"_NSZombie_";
443 else if (_class == NSZombie_)
444 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
445 // XXX: frowny /in/ the pants
446 else if (value == NSMessageBuilder_ || value == Object_)
450 string = [NSString stringWithFormat:@"%@", value];
455 string = @"undefined";
462 struct PropertyAttributes {
467 const char *variable;
480 PropertyAttributes(objc_property_t property) :
492 name = property_getName(property);
493 const char *attributes(property_getAttributes(property));
495 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
497 case 'R': readonly = true; break;
498 case 'C': copy = true; break;
499 case '&': retain = true; break;
500 case 'N': nonatomic = true; break;
501 case 'G': getter_ = token + 1; break;
502 case 'S': setter_ = token + 1; break;
503 case 'V': variable = token + 1; break;
507 /*if (variable == NULL) {
508 variable = property_getName(property);
509 size_t size(strlen(variable));
510 char *name(new(pool_) char[size + 2]);
512 memcpy(name + 1, variable, size);
513 name[size + 1] = '\0';
518 const char *Getter() {
520 getter_ = apr_pstrdup(pool_, name);
524 const char *Setter() {
525 if (setter_ == NULL && !readonly) {
526 size_t length(strlen(name));
528 char *temp(new(pool_) char[length + 5]);
534 temp[3] = toupper(name[0]);
535 memcpy(temp + 4, name + 1, length - 1);
538 temp[length + 3] = ':';
539 temp[length + 4] = '\0';
550 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
551 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
556 @interface CYWebUndefined : NSObject {
559 + (CYWebUndefined *) undefined;
563 @implementation CYWebUndefined
565 + (CYWebUndefined *) undefined {
566 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
572 #define WebUndefined CYWebUndefined
575 /* Bridge: CYJSObject {{{ */
576 @interface CYJSObject : NSMutableDictionary {
578 JSContextRef context_;
581 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
583 - (NSObject *) cy$toJSON:(NSString *)key;
585 - (NSUInteger) count;
586 - (id) objectForKey:(id)key;
587 - (NSEnumerator *) keyEnumerator;
588 - (void) setObject:(id)object forKey:(id)key;
589 - (void) removeObjectForKey:(id)key;
593 /* Bridge: CYJSArray {{{ */
594 @interface CYJSArray : NSMutableArray {
596 JSContextRef context_;
599 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
601 - (NSUInteger) count;
602 - (id) objectAtIndex:(NSUInteger)index;
604 - (void) addObject:(id)anObject;
605 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
606 - (void) removeLastObject;
607 - (void) removeObjectAtIndex:(NSUInteger)index;
608 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
613 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
614 JSObjectRef Array(CYGetCachedObject(context, Array_s));
615 JSValueRef exception(NULL);
616 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
617 CYThrow(context, exception);
618 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
619 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
622 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
623 if (!JSValueIsObjectOfClass(context, object, Instance_))
624 return CYCastNSObject_(pool, context, object);
626 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
627 return internal->GetValue();
631 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
632 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
636 @interface NSBoolNumber : NSNumber {
641 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
645 switch (JSType type = JSValueGetType(context, value)) {
646 case kJSTypeUndefined:
647 object = [WebUndefined undefined];
657 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
660 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
666 object = CYCopyNSNumber(context, value);
671 object = CYCopyNSString(context, value);
676 // XXX: this might could be more efficient
677 object = CYCastNSObject(pool, context, (JSObjectRef) value);
682 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
689 return CYPoolRelease(pool, object);
691 return [object retain];
694 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
695 return CYNSObject(pool, context, value, true);
698 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
699 return CYNSObject(pool, context, value, false);
702 /* Bridge: NSArray {{{ */
703 @implementation NSArray (Cycript)
705 - (NSString *) cy$toCYON {
706 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
707 [json appendString:@"["];
711 for (id object in self) {
713 for (size_t index(0), count([self count]); index != count; ++index) {
714 id object([self objectAtIndex:index]);
717 [json appendString:@","];
720 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
721 [json appendString:CYCastNSCYON(object)];
723 [json appendString:@","];
728 [json appendString:@"]"];
732 - (bool) cy$hasProperty:(NSString *)name {
733 if ([name isEqualToString:@"length"])
736 size_t index(CYGetIndex(name));
737 if (index == _not(size_t) || index >= [self count])
738 return [super cy$hasProperty:name];
743 - (NSObject *) cy$getProperty:(NSString *)name {
744 if ([name isEqualToString:@"length"]) {
745 NSUInteger count([self count]);
747 return [NSNumber numberWithUnsignedInteger:count];
749 return [NSNumber numberWithUnsignedInt:count];
753 size_t index(CYGetIndex(name));
754 if (index == _not(size_t) || index >= [self count])
755 return [super cy$getProperty:name];
757 return [self objectAtIndex:index];
760 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
761 [super cy$getPropertyNames:names inContext:context];
763 for (size_t index(0), count([self count]); index != count; ++index) {
764 id object([self objectAtIndex:index]);
765 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
767 sprintf(name, "%zu", index);
768 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
773 + (bool) cy$hasImplicitProperties {
779 /* Bridge: NSBoolNumber {{{ */
781 @implementation NSBoolNumber (Cycript)
783 - (JSType) cy$JSType {
784 return kJSTypeBoolean;
787 - (NSObject *) cy$toJSON:(NSString *)key {
791 - (NSString *) cy$toCYON {
792 return [self boolValue] ? @"true" : @"false";
795 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
796 return CYCastJSValue(context, (bool) [self boolValue]);
802 /* Bridge: NSDictionary {{{ */
803 @implementation NSDictionary (Cycript)
805 - (NSString *) cy$toCYON {
806 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
807 [json appendString:@"{"];
811 for (NSObject *key in self) {
813 NSEnumerator *keys([self keyEnumerator]);
814 while (NSObject *key = [keys nextObject]) {
817 [json appendString:@","];
820 [json appendString:[key cy$toKey]];
821 [json appendString:@":"];
822 NSObject *object([self objectForKey:key]);
823 [json appendString:CYCastNSCYON(object)];
826 [json appendString:@"}"];
830 - (bool) cy$hasProperty:(NSString *)name {
831 return [self objectForKey:name] != nil;
834 - (NSObject *) cy$getProperty:(NSString *)name {
835 return [self objectForKey:name];
838 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
839 [super cy$getPropertyNames:names inContext:context];
842 for (NSObject *key in self) {
844 NSEnumerator *keys([self keyEnumerator]);
845 while (NSObject *key = [keys nextObject]) {
847 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
851 + (bool) cy$hasImplicitProperties {
857 /* Bridge: NSMutableArray {{{ */
858 @implementation NSMutableArray (Cycript)
860 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
861 if ([name isEqualToString:@"length"]) {
862 // XXX: is this not intelligent?
863 NSNumber *number(reinterpret_cast<NSNumber *>(value));
865 NSUInteger size([number unsignedIntegerValue]);
867 NSUInteger size([number unsignedIntValue]);
869 NSUInteger count([self count]);
871 [self removeObjectsInRange:NSMakeRange(size, count - size)];
872 else if (size != count) {
873 WebUndefined *undefined([WebUndefined undefined]);
874 for (size_t i(count); i != size; ++i)
875 [self addObject:undefined];
880 size_t index(CYGetIndex(name));
881 if (index == _not(size_t))
882 return [super cy$setProperty:name to:value];
884 id object(value ?: [NSNull null]);
886 size_t count([self count]);
888 [self replaceObjectAtIndex:index withObject:object];
890 if (index != count) {
891 WebUndefined *undefined([WebUndefined undefined]);
892 for (size_t i(count); i != index; ++i)
893 [self addObject:undefined];
896 [self addObject:object];
902 - (bool) cy$deleteProperty:(NSString *)name {
903 size_t index(CYGetIndex(name));
904 if (index == _not(size_t) || index >= [self count])
905 return [super cy$deleteProperty:name];
906 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
912 /* Bridge: NSMutableDictionary {{{ */
913 @implementation NSMutableDictionary (Cycript)
915 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
916 [self setObject:(value ?: [NSNull null]) forKey:name];
920 - (bool) cy$deleteProperty:(NSString *)name {
921 if ([self objectForKey:name] == nil)
924 [self removeObjectForKey:name];
931 /* Bridge: NSNumber {{{ */
932 @implementation NSNumber (Cycript)
934 - (JSType) cy$JSType {
936 // XXX: this just seems stupid
937 if ([self class] == NSCFBoolean_)
938 return kJSTypeBoolean;
940 return kJSTypeNumber;
943 - (NSObject *) cy$toJSON:(NSString *)key {
947 - (NSString *) cy$toCYON {
948 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
951 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
952 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
957 /* Bridge: NSNull {{{ */
958 @implementation NSNull (Cycript)
960 - (JSType) cy$JSType {
964 - (NSObject *) cy$toJSON:(NSString *)key {
968 - (NSString *) cy$toCYON {
974 /* Bridge: NSObject {{{ */
975 @implementation NSObject (Cycript)
977 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
978 return CYMakeInstance(context, self, false);
981 - (JSType) cy$JSType {
982 return kJSTypeObject;
985 - (NSObject *) cy$toJSON:(NSString *)key {
986 return [self description];
989 - (NSString *) cy$toCYON {
990 return [[self cy$toJSON:@""] cy$toCYON];
993 - (NSString *) cy$toKey {
994 return [self cy$toCYON];
997 - (bool) cy$hasProperty:(NSString *)name {
1001 - (NSObject *) cy$getProperty:(NSString *)name {
1005 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1009 - (bool) cy$deleteProperty:(NSString *)name {
1013 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1016 + (bool) cy$hasImplicitProperties {
1022 /* Bridge: NSProxy {{{ */
1023 @implementation NSProxy (Cycript)
1025 - (NSObject *) cy$toJSON:(NSString *)key {
1026 return [self description];
1029 - (NSString *) cy$toCYON {
1030 return [[self cy$toJSON:@""] cy$toCYON];
1035 /* Bridge: NSString {{{ */
1036 @implementation NSString (Cycript)
1038 - (JSType) cy$JSType {
1039 return kJSTypeString;
1042 - (NSObject *) cy$toJSON:(NSString *)key {
1046 - (NSString *) cy$toCYON {
1047 std::ostringstream str;
1048 CYUTF8String string(CYCastUTF8String(self));
1049 CYStringify(str, string.data, string.size);
1050 std::string value(str.str());
1051 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1054 - (NSString *) cy$toKey {
1055 if (CYIsKey(CYCastUTF8String(self)))
1057 return [self cy$toCYON];
1060 - (bool) cy$hasProperty:(NSString *)name {
1061 if ([name isEqualToString:@"length"])
1064 size_t index(CYGetIndex(name));
1065 if (index == _not(size_t) || index >= [self length])
1066 return [super cy$hasProperty:name];
1071 - (NSObject *) cy$getProperty:(NSString *)name {
1072 if ([name isEqualToString:@"length"]) {
1073 NSUInteger count([self length]);
1075 return [NSNumber numberWithUnsignedInteger:count];
1077 return [NSNumber numberWithUnsignedInt:count];
1081 size_t index(CYGetIndex(name));
1082 if (index == _not(size_t) || index >= [self length])
1083 return [super cy$getProperty:name];
1085 return [self substringWithRange:NSMakeRange(index, 1)];
1088 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1089 [super cy$getPropertyNames:names inContext:context];
1091 for (size_t index(0), length([self length]); index != length; ++index) {
1093 sprintf(name, "%zu", index);
1094 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1098 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1099 + (bool) cy$hasImplicitProperties {
1105 /* Bridge: WebUndefined {{{ */
1106 @implementation WebUndefined (Cycript)
1108 - (JSType) cy$JSType {
1109 return kJSTypeUndefined;
1112 - (NSObject *) cy$toJSON:(NSString *)key {
1116 - (NSString *) cy$toCYON {
1117 return @"undefined";
1120 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1121 return CYJSUndefined(context);
1122 } CYObjectiveCatch }
1127 static bool CYIsClass(id self) {
1129 // XXX: this is a lame object_isClass
1130 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1132 return GSObjCIsClass(self);
1136 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1137 id self(CYCastNSObject(pool, context, value));
1138 if (CYIsClass(self))
1139 return (Class) self;
1140 throw CYJSError(context, "got something that is not a Class");
1144 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1146 size_t size(JSPropertyNameArrayGetCount(names));
1147 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1148 for (size_t index(0); index != size; ++index)
1149 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1153 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1155 return CYJSNull(context);
1156 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1157 return [value cy$JSValueInContext:context];
1159 return CYMakeInstance(context, value, false);
1160 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1162 @implementation CYJSObject
1164 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1165 if ((self = [super init]) != nil) {
1167 context_ = CYGetJSContext(context);
1168 //XXX:JSGlobalContextRetain(context_);
1169 JSValueProtect(context_, object_);
1171 } CYObjectiveCatch }
1173 - (void) dealloc { CYObjectiveTry {
1174 JSValueUnprotect(context_, object_);
1175 //XXX:JSGlobalContextRelease(context_);
1177 } CYObjectiveCatch }
1179 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1180 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1181 if (!CYIsCallable(context_, toJSON))
1182 return [super cy$toJSON:key];
1184 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1185 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1186 // XXX: do I really want an NSNull here?!
1187 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1189 } CYObjectiveCatch }
1191 - (NSString *) cy$toCYON { CYObjectiveTry {
1193 JSValueRef exception(NULL);
1194 const char *cyon(CYPoolCCYON(pool, context_, object_));
1195 CYThrow(context_, exception);
1197 return [super cy$toCYON];
1199 return [NSString stringWithUTF8String:cyon];
1200 } CYObjectiveCatch }
1202 - (NSUInteger) count { CYObjectiveTry {
1203 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1204 size_t size(JSPropertyNameArrayGetCount(names));
1205 JSPropertyNameArrayRelease(names);
1207 } CYObjectiveCatch }
1209 - (id) objectForKey:(id)key { CYObjectiveTry {
1210 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1211 if (JSValueIsUndefined(context_, value))
1213 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1214 } CYObjectiveCatch }
1216 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1217 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1218 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1219 JSPropertyNameArrayRelease(names);
1221 } CYObjectiveCatch }
1223 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1224 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1225 } CYObjectiveCatch }
1227 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1228 JSValueRef exception(NULL);
1229 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1230 CYThrow(context_, exception);
1231 } CYObjectiveCatch }
1235 @implementation CYJSArray
1237 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1238 if ((self = [super init]) != nil) {
1240 context_ = CYGetJSContext(context);
1241 //XXX:JSGlobalContextRetain(context_);
1242 JSValueProtect(context_, object_);
1244 } CYObjectiveCatch }
1246 - (void) dealloc { CYObjectiveTry {
1247 JSValueUnprotect(context_, object_);
1248 //XXX:JSGlobalContextRelease(context_);
1250 } CYObjectiveCatch }
1252 - (NSUInteger) count { CYObjectiveTry {
1253 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1254 } CYObjectiveCatch }
1256 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1257 size_t bounds([self count]);
1258 if (index >= bounds)
1259 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1260 JSValueRef exception(NULL);
1261 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1262 CYThrow(context_, exception);
1263 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1264 } CYObjectiveCatch }
1266 - (void) addObject:(id)object { CYObjectiveTry {
1267 JSValueRef exception(NULL);
1268 JSValueRef arguments[1];
1269 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1270 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1271 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1272 CYThrow(context_, exception);
1273 } CYObjectiveCatch }
1275 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1276 size_t bounds([self count] + 1);
1277 if (index >= bounds)
1278 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1279 JSValueRef exception(NULL);
1280 JSValueRef arguments[3];
1281 arguments[0] = CYCastJSValue(context_, index);
1282 arguments[1] = CYCastJSValue(context_, 0);
1283 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1284 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1285 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1286 CYThrow(context_, exception);
1287 } CYObjectiveCatch }
1289 - (void) removeLastObject { CYObjectiveTry {
1290 JSValueRef exception(NULL);
1291 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1292 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1293 CYThrow(context_, exception);
1294 } CYObjectiveCatch }
1296 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1297 size_t bounds([self count]);
1298 if (index >= bounds)
1299 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1300 JSValueRef exception(NULL);
1301 JSValueRef arguments[2];
1302 arguments[0] = CYCastJSValue(context_, index);
1303 arguments[1] = CYCastJSValue(context_, 1);
1304 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1305 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1306 CYThrow(context_, exception);
1307 } CYObjectiveCatch }
1309 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1310 size_t bounds([self count]);
1311 if (index >= bounds)
1312 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1313 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1314 } CYObjectiveCatch }
1318 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1322 JSObjectRef object_;
1330 // XXX: delete object_? ;(
1333 static CYInternal *Get(id self) {
1334 CYInternal *internal(NULL);
1335 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1336 // XXX: do something epic? ;P
1342 static CYInternal *Set(id self) {
1343 CYInternal *internal(NULL);
1344 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1345 if (internal == NULL) {
1346 internal = new CYInternal();
1347 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1350 // XXX: do something epic? ;P
1356 bool HasProperty(JSContextRef context, JSStringRef name) {
1357 if (object_ == NULL)
1359 return JSObjectHasProperty(context, object_, name);
1362 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1363 if (object_ == NULL)
1365 return CYGetProperty(context, object_, name);
1368 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1369 if (object_ == NULL)
1370 object_ = JSObjectMake(context, NULL, NULL);
1371 CYSetProperty(context, object_, name, value);
1375 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1376 Selector_privateData *internal(new Selector_privateData(sel));
1377 return JSObjectMake(context, Selector_, internal);
1380 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1381 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1382 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1383 return reinterpret_cast<SEL>(internal->value_);
1385 return CYCastPointer<SEL>(context, value);
1388 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1389 return (void *) [[NSAutoreleasePool alloc] init];
1390 } CYSadCatch(NULL) }
1392 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1393 return [(NSAutoreleasePool *) handle release];
1396 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1398 return Instance::Make(context, nil);
1399 if (Class _class = objc_getClass(name.data))
1400 return CYMakeInstance(context, _class, true);
1401 if (Protocol *protocol = objc_getProtocol(name.data))
1402 return CYMakeInstance(context, protocol, true);
1404 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1406 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1407 ffi_call(cif, function, value, values);
1410 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1411 switch (type->primitive) {
1412 // XXX: do something epic about blocks
1415 case sig::typename_P:
1416 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1419 case sig::selector_P:
1420 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1428 } CYSadCatch(false) }
1430 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1431 switch (type->primitive) {
1432 // XXX: do something epic about blocks
1435 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1436 JSValueRef value(CYCastJSValue(context, object));
1442 case sig::typename_P:
1443 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1445 case sig::selector_P:
1446 if (SEL sel = *reinterpret_cast<SEL *>(data))
1447 return CYMakeSelector(context, sel);
1451 return CYJSNull(context);
1455 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1457 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1458 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1461 #if OBJC_API_VERSION >= 2
1463 method_getReturnType(method, type, sizeof(type));
1465 const char *type(method_getTypeEncoding(method));
1471 // XXX: possibly use a more "awesome" check?
1475 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1477 return method_getTypeEncoding(method);
1479 const char *name(sel_getName(sel));
1480 size_t length(strlen(name));
1482 char keyed[length + 2];
1484 keyed[length + 1] = '\0';
1485 memcpy(keyed + 1, name, length);
1487 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1488 return entry->value_;
1493 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1494 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1496 JSContextRef context(internal->context_);
1498 size_t count(internal->cif_.nargs);
1499 JSValueRef values[count];
1501 for (size_t index(0); index != count; ++index)
1502 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1504 JSObjectRef _this(CYCastJSObject(context, values[0]));
1506 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1507 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1510 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1511 Message_privateData *internal(new Message_privateData(sel, type, imp));
1512 return JSObjectMake(context, Message_, internal);
1515 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1516 JSObjectRef function(CYCastJSObject(context, value));
1517 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1518 // XXX: see notes in Library.cpp about needing to leak
1519 return reinterpret_cast<IMP>(internal->GetValue());
1522 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1523 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1524 Class _class(internal->GetValue());
1527 const char *name(CYPoolCString(pool, context, property));
1529 if (SEL sel = sel_getUid(name))
1530 if (class_getInstanceMethod(_class, sel) != NULL)
1536 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1537 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1538 Class _class(internal->GetValue());
1541 const char *name(CYPoolCString(pool, context, property));
1543 if (SEL sel = sel_getUid(name))
1544 if (objc_method *method = class_getInstanceMethod(_class, sel))
1545 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1550 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1551 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1552 Class _class(internal->GetValue());
1555 const char *name(CYPoolCString(pool, context, property));
1557 SEL sel(sel_registerName(name));
1559 objc_method *method(class_getInstanceMethod(_class, sel));
1564 if (JSValueIsObjectOfClass(context, value, Message_)) {
1565 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1566 type = sig::Unparse(pool, &message->signature_);
1567 imp = reinterpret_cast<IMP>(message->GetValue());
1569 type = CYPoolTypeEncoding(pool, context, sel, method);
1570 imp = CYMakeMessage(context, value, type);
1574 method_setImplementation(method, imp);
1577 GSMethodList list(GSAllocMethodList(1));
1578 GSAppendMethodToList(list, sel, type, imp, YES);
1579 GSAddMethodList(_class, list, YES);
1580 GSFlushMethodCacheForClass(_class);
1582 class_addMethod(_class, sel, imp, type);
1589 #if 0 && OBJC_API_VERSION < 2
1590 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1591 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1592 Class _class(internal->GetValue());
1595 const char *name(CYPoolCString(pool, context, property));
1597 if (SEL sel = sel_getUid(name))
1598 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1599 objc_method_list list = {NULL, 1, {method}};
1600 class_removeMethods(_class, &list);
1608 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1609 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1610 Class _class(internal->GetValue());
1612 #if OBJC_API_VERSION >= 2
1614 objc_method **data(class_copyMethodList(_class, &size));
1615 for (size_t i(0); i != size; ++i)
1616 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1619 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1620 for (int i(0); i != methods->method_count; ++i)
1621 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1625 static bool CYHasImplicitProperties(Class _class) {
1626 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1627 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1629 return [_class cy$hasImplicitProperties];
1632 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1633 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1634 id self(internal->GetValue());
1636 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1640 NSString *name(CYCastNSString(pool, context, property));
1642 if (CYInternal *internal = CYInternal::Get(self))
1643 if (internal->HasProperty(context, property))
1646 Class _class(object_getClass(self));
1649 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1650 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1651 if ([self cy$hasProperty:name])
1653 } CYPoolCatch(false)
1655 const char *string(CYPoolCString(pool, context, name));
1658 if (class_getProperty(_class, string) != NULL)
1662 if (CYHasImplicitProperties(_class))
1663 if (SEL sel = sel_getUid(string))
1664 if (CYImplements(self, _class, sel, true))
1670 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1671 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1672 id self(internal->GetValue());
1674 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1675 return Internal::Make(context, self, object);
1678 NSString *name(CYCastNSString(pool, context, property));
1680 if (CYInternal *internal = CYInternal::Get(self))
1681 if (JSValueRef value = internal->GetProperty(context, property))
1685 if (NSObject *data = [self cy$getProperty:name])
1686 return CYCastJSValue(context, data);
1689 const char *string(CYPoolCString(pool, context, name));
1690 Class _class(object_getClass(self));
1693 if (objc_property_t property = class_getProperty(_class, string)) {
1694 PropertyAttributes attributes(property);
1695 SEL sel(sel_registerName(attributes.Getter()));
1696 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1700 if (CYHasImplicitProperties(_class))
1701 if (SEL sel = sel_getUid(string))
1702 if (CYImplements(self, _class, sel, true))
1703 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1708 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1709 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1710 id self(internal->GetValue());
1714 NSString *name(CYCastNSString(pool, context, property));
1715 NSObject *data(CYCastNSObject(pool, context, value));
1718 if ([self cy$setProperty:name to:data])
1722 const char *string(CYPoolCString(pool, context, name));
1723 Class _class(object_getClass(self));
1726 if (objc_property_t property = class_getProperty(_class, string)) {
1727 PropertyAttributes attributes(property);
1728 if (const char *setter = attributes.Setter()) {
1729 SEL sel(sel_registerName(setter));
1730 JSValueRef arguments[1] = {value};
1731 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1737 size_t length(strlen(string));
1739 char set[length + 5];
1745 if (string[0] != '\0') {
1746 set[3] = toupper(string[0]);
1747 memcpy(set + 4, string + 1, length - 1);
1750 set[length + 3] = ':';
1751 set[length + 4] = '\0';
1753 if (SEL sel = sel_getUid(set))
1754 if (CYImplements(self, _class, sel, false)) {
1755 JSValueRef arguments[1] = {value};
1756 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1759 if (CYInternal *internal = CYInternal::Set(self)) {
1760 internal->SetProperty(context, property, value);
1767 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1768 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1769 id self(internal->GetValue());
1772 NSString *name(CYCastNSString(NULL, context, property));
1773 return [self cy$deleteProperty:name];
1775 } CYCatch return /*XXX*/ NULL; }
1777 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1778 const char *name(sel_getName(method_getName(method)));
1779 if (strchr(name, ':') != NULL)
1782 const char *type(method_getTypeEncoding(method));
1783 if (type == NULL || *type == '\0' || *type == 'v')
1786 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1789 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1790 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1791 id self(internal->GetValue());
1794 Class _class(object_getClass(self));
1799 objc_property_t *data(class_copyPropertyList(_class, &size));
1800 for (size_t i(0); i != size; ++i)
1801 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1806 if (CYHasImplicitProperties(_class))
1807 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1808 #if OBJC_API_VERSION >= 2
1810 objc_method **data(class_copyMethodList(current, &size));
1811 for (size_t i(0); i != size; ++i)
1812 Instance_getPropertyNames_message(names, data[i]);
1815 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1816 for (int i(0); i != methods->method_count; ++i)
1817 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1822 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1823 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1824 [self cy$getPropertyNames:names inContext:context];
1828 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1829 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1830 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1834 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1835 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1836 Class _class(internal->GetValue());
1837 if (!CYIsClass(_class))
1840 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1841 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1842 // XXX: this isn't always safe
1843 return [linternal->GetValue() isKindOfClass:_class];
1849 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1850 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1853 id self(internal->GetValue());
1854 const char *name(CYPoolCString(pool, context, property));
1856 if (object_getInstanceVariable(self, name, NULL) != NULL)
1862 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1863 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1866 id self(internal->GetValue());
1867 const char *name(CYPoolCString(pool, context, property));
1869 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1870 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1871 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1872 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1878 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1879 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1882 id self(internal->GetValue());
1883 const char *name(CYPoolCString(pool, context, property));
1885 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1886 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1887 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1894 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1895 if (Class super = class_getSuperclass(_class))
1896 Internal_getPropertyNames_(super, names);
1898 #if OBJC_API_VERSION >= 2
1900 objc_ivar **data(class_copyIvarList(_class, &size));
1901 for (size_t i(0); i != size; ++i)
1902 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1905 if (objc_ivar_list *ivars = _class->ivars)
1906 for (int i(0); i != ivars->ivar_count; ++i)
1907 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1911 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1912 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1915 id self(internal->GetValue());
1916 Class _class(object_getClass(self));
1918 Internal_getPropertyNames_(_class, names);
1921 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1922 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1923 return internal->GetOwner();
1926 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1928 NSString *name(CYCastNSString(pool, context, property));
1929 if (Class _class = NSClassFromString(name))
1930 return CYMakeInstance(context, _class, true);
1934 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1936 size_t size(objc_getClassList(NULL, 0));
1937 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1940 size_t writ(objc_getClassList(data, size));
1943 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1949 for (size_t i(0); i != writ; ++i)
1950 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1956 while (Class _class = objc_next_class(&state))
1957 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1961 #if OBJC_API_VERSION >= 2
1962 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1963 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1966 const char *name(CYPoolCString(pool, context, property));
1968 const char **data(objc_copyClassNamesForImage(internal, &size));
1970 for (size_t i(0); i != size; ++i)
1971 if (strcmp(name, data[i]) == 0) {
1972 if (Class _class = objc_getClass(name)) {
1973 value = CYMakeInstance(context, _class, true);
1984 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1985 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1987 const char **data(objc_copyClassNamesForImage(internal, &size));
1988 for (size_t i(0); i != size; ++i)
1989 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1993 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1995 const char *name(CYPoolCString(pool, context, property));
1997 const char **data(objc_copyImageNames(&size));
1998 for (size_t i(0); i != size; ++i)
1999 if (strcmp(name, data[i]) == 0) {
2008 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2009 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2013 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2015 const char **data(objc_copyImageNames(&size));
2016 for (size_t i(0); i != size; ++i)
2017 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2022 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2024 const char *name(CYPoolCString(pool, context, property));
2025 if (Protocol *protocol = objc_getProtocol(name))
2026 return CYMakeInstance(context, protocol, true);
2030 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2031 #if OBJC_API_VERSION >= 2
2033 Protocol **data(objc_copyProtocolList(&size));
2034 for (size_t i(0); i != size; ++i)
2035 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2043 static bool stret(ffi_type *ffi_type) {
2044 return ffi_type->type == FFI_TYPE_STRUCT && (
2045 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2046 struct_forward_array[ffi_type->size] != 0
2051 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 {
2055 _class = object_getClass(self);
2059 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2060 imp = method_getImplementation(method);
2061 type = method_getTypeEncoding(method);
2066 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2068 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2069 type = CYPoolCString(pool, context, [method _typeString]);
2077 sig::Signature signature;
2078 sig::Parse(pool, &signature, type, &Structor_);
2081 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2085 if (stret(cif.rtype))
2086 imp = class_getMethodImplementation_stret(_class, _cmd);
2088 imp = class_getMethodImplementation(_class, _cmd);
2090 objc_super super = {self, _class};
2091 imp = objc_msg_lookup_super(&super, _cmd);
2095 void (*function)() = reinterpret_cast<void (*)()>(imp);
2096 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2099 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2101 throw CYJSError(context, "too few arguments to objc_msgSend");
2111 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2112 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2113 self = internal->GetValue();
2114 _class = internal->class_;;
2115 uninitialized = false;
2116 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2117 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2118 self = internal->GetValue();
2120 uninitialized = internal->IsUninitialized();
2122 internal->value_ = nil;
2124 self = CYCastNSObject(pool, context, arguments[0]);
2126 uninitialized = false;
2130 return CYJSNull(context);
2132 _cmd = CYCastSEL(context, arguments[1]);
2134 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2137 /* Hook: objc_registerClassPair {{{ */
2138 #if defined(__APPLE__) && defined(__arm__)
2139 // XXX: replace this with associated objects
2141 MSHook(void, CYDealloc, id self, SEL sel) {
2142 CYInternal *internal;
2143 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2144 if (internal != NULL)
2146 _CYDealloc(self, sel);
2149 MSHook(void, objc_registerClassPair, Class _class) {
2150 Class super(class_getSuperclass(_class));
2151 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2152 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2153 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2156 _objc_registerClassPair(_class);
2159 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2161 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2163 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2164 if (value == NULL || !CYIsClass(value))
2165 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2166 Class _class((Class) value);
2167 $objc_registerClassPair(_class);
2168 return CYJSUndefined(context);
2173 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2174 JSValueRef setup[count + 2];
2177 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2178 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2181 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2183 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2185 // XXX: handle Instance::Uninitialized?
2186 id self(CYCastNSObject(pool, context, _this));
2190 setup[1] = &internal->sel_;
2192 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2195 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2197 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2199 id self(CYCastNSObject(pool, context, arguments[0]));
2200 Class _class(CYCastClass(pool, context, arguments[1]));
2201 return cy::Super::Make(context, self, _class);
2204 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2206 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2208 const char *name(CYPoolCString(pool, context, arguments[0]));
2209 return CYMakeSelector(context, sel_registerName(name));
2212 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2214 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2215 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2216 return CYMakeInstance(context, self, false);
2219 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2220 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2221 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2224 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2225 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2226 Type_privateData *typical(internal->GetType());
2231 if (typical == NULL) {
2235 type = typical->type_;
2236 ffi = typical->ffi_;
2239 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2242 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2243 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2244 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2247 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2248 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2249 id self(internal->GetValue());
2250 if (!CYIsClass(self))
2251 return CYJSUndefined(context);
2252 return CYGetClassPrototype(context, self);
2255 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2256 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2257 id self(internal->GetValue());
2258 if (!CYIsClass(self))
2259 return CYJSUndefined(context);
2260 return Messages::Make(context, (Class) self);
2263 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2264 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2267 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2268 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2271 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2272 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2275 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2282 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2283 // XXX: check for support of cy$toJSON?
2284 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2286 } CYCatch return /*XXX*/ NULL; }
2289 static JSValueRef Instance_callAsFunction_valueOf(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 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2295 } CYCatch return /*XXX*/ NULL; }
2298 static JSValueRef Instance_callAsFunction_toPointer(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)));
2303 // XXX: but... but... THIS ISN'T A POINTER! :(
2304 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2305 } CYCatch return /*XXX*/ NULL; }
2307 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2308 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2311 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2313 id value(internal->GetValue());
2315 return CYCastJSValue(context, "nil");
2318 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2319 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2321 } CYCatch return /*XXX*/ NULL; }
2323 static JSValueRef Selector_callAsFunction_toString(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 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2328 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2329 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2332 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2333 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2334 const char *name(sel_getName(internal->GetValue()));
2337 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2338 return CYCastJSValue(context, CYJSString(context, string));
2340 } CYCatch return /*XXX*/ NULL; }
2342 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2344 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2347 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2348 SEL sel(internal->GetValue());
2350 objc_method *method;
2351 if (Class _class = CYCastClass(pool, context, arguments[0]))
2352 method = class_getInstanceMethod(_class, sel);
2356 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2357 return CYCastJSValue(context, CYJSString(type));
2359 return CYJSNull(context);
2362 static JSStaticValue Selector_staticValues[2] = {
2363 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2364 {NULL, NULL, NULL, 0}
2367 static JSStaticValue Instance_staticValues[5] = {
2368 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2369 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2370 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2371 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2372 {NULL, NULL, NULL, 0}
2375 static JSStaticFunction Instance_staticFunctions[6] = {
2376 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2377 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2378 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2379 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2380 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2381 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2385 static JSStaticFunction Internal_staticFunctions[2] = {
2386 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2390 static JSStaticFunction Selector_staticFunctions[5] = {
2391 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2392 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2393 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2394 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2398 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2399 apr_pool_t *pool(CYGetGlobalPool());
2401 Object_type = new(pool) Type_privateData("@");
2402 Selector_type = new(pool) Type_privateData(":");
2405 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2406 NSCFType_ = objc_getClass("NSCFType");
2407 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2408 NSZombie_ = objc_getClass("_NSZombie_");
2410 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2413 NSArray_ = objc_getClass("NSArray");
2414 NSDictionary_ = objc_getClass("NSDictionary");
2415 NSString_ = objc_getClass("NSString");
2416 Object_ = objc_getClass("Object");
2418 JSClassDefinition definition;
2420 definition = kJSClassDefinitionEmpty;
2421 definition.className = "Instance";
2422 definition.staticValues = Instance_staticValues;
2423 definition.staticFunctions = Instance_staticFunctions;
2424 definition.hasProperty = &Instance_hasProperty;
2425 definition.getProperty = &Instance_getProperty;
2426 definition.setProperty = &Instance_setProperty;
2427 definition.deleteProperty = &Instance_deleteProperty;
2428 definition.getPropertyNames = &Instance_getPropertyNames;
2429 definition.callAsConstructor = &Instance_callAsConstructor;
2430 definition.hasInstance = &Instance_hasInstance;
2431 definition.finalize = &CYFinalize;
2432 Instance_ = JSClassCreate(&definition);
2434 definition = kJSClassDefinitionEmpty;
2435 definition.className = "Internal";
2436 definition.staticFunctions = Internal_staticFunctions;
2437 definition.hasProperty = &Internal_hasProperty;
2438 definition.getProperty = &Internal_getProperty;
2439 definition.setProperty = &Internal_setProperty;
2440 definition.getPropertyNames = &Internal_getPropertyNames;
2441 definition.finalize = &CYFinalize;
2442 Internal_ = JSClassCreate(&definition);
2444 definition = kJSClassDefinitionEmpty;
2445 definition.className = "Message";
2446 definition.staticFunctions = cy::Functor::StaticFunctions;
2447 definition.callAsFunction = &Message_callAsFunction;
2448 definition.finalize = &CYFinalize;
2449 Message_ = JSClassCreate(&definition);
2451 definition = kJSClassDefinitionEmpty;
2452 definition.className = "Messages";
2453 definition.hasProperty = &Messages_hasProperty;
2454 definition.getProperty = &Messages_getProperty;
2455 definition.setProperty = &Messages_setProperty;
2456 #if 0 && OBJC_API_VERSION < 2
2457 definition.deleteProperty = &Messages_deleteProperty;
2459 definition.getPropertyNames = &Messages_getPropertyNames;
2460 definition.finalize = &CYFinalize;
2461 Messages_ = JSClassCreate(&definition);
2463 definition = kJSClassDefinitionEmpty;
2464 definition.className = "Selector";
2465 definition.staticValues = Selector_staticValues;
2466 definition.staticFunctions = Selector_staticFunctions;
2467 definition.callAsFunction = &Selector_callAsFunction;
2468 definition.finalize = &CYFinalize;
2469 Selector_ = JSClassCreate(&definition);
2471 definition = kJSClassDefinitionEmpty;
2472 definition.className = "Super";
2473 definition.staticFunctions = Internal_staticFunctions;
2474 definition.finalize = &CYFinalize;
2475 Super_ = JSClassCreate(&definition);
2477 definition = kJSClassDefinitionEmpty;
2478 definition.className = "ObjectiveC::Classes";
2479 definition.getProperty = &ObjectiveC_Classes_getProperty;
2480 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2481 ObjectiveC_Classes_ = JSClassCreate(&definition);
2483 #if OBJC_API_VERSION >= 2
2484 definition = kJSClassDefinitionEmpty;
2485 definition.className = "ObjectiveC::Images";
2486 definition.getProperty = &ObjectiveC_Images_getProperty;
2487 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2488 ObjectiveC_Images_ = JSClassCreate(&definition);
2490 definition = kJSClassDefinitionEmpty;
2491 definition.className = "ObjectiveC::Image::Classes";
2492 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2493 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2494 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2497 definition = kJSClassDefinitionEmpty;
2498 definition.className = "ObjectiveC::Protocols";
2499 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2500 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2501 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2503 #if defined(__APPLE__) && defined(__arm__)
2504 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2508 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2512 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2513 JSObjectRef global(CYGetGlobalObject(context));
2514 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2515 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2516 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2518 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2519 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2521 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2522 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2524 #if OBJC_API_VERSION >= 2
2525 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2528 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2529 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2530 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2531 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2533 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2534 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2536 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2537 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2538 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2540 #if defined(__APPLE__) && defined(__arm__)
2541 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2544 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2546 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2547 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2548 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2551 static CYHooks CYObjectiveCHooks = {
2552 &CYObjectiveC_ExecuteStart,
2553 &CYObjectiveC_ExecuteEnd,
2554 &CYObjectiveC_RuntimeProperty,
2555 &CYObjectiveC_CallFunction,
2556 &CYObjectiveC_Initialize,
2557 &CYObjectiveC_SetupContext,
2558 &CYObjectiveC_PoolFFI,
2559 &CYObjectiveC_FromFFI,
2562 struct CYObjectiveC {
2564 hooks_ = &CYObjectiveCHooks;
2565 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2566 _assert(hooks_ != NULL);