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));
766 /* Bridge: NSBoolNumber {{{ */
768 @implementation NSBoolNumber (Cycript)
770 - (JSType) cy$JSType {
771 return kJSTypeBoolean;
774 - (NSObject *) cy$toJSON:(NSString *)key {
778 - (NSString *) cy$toCYON {
779 return [self boolValue] ? @"true" : @"false";
782 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
783 return CYCastJSValue(context, (bool) [self boolValue]);
789 /* Bridge: NSDictionary {{{ */
790 @implementation NSDictionary (Cycript)
792 - (NSString *) cy$toCYON {
793 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
794 [json appendString:@"{"];
798 for (NSObject *key in self) {
800 NSEnumerator *keys([self keyEnumerator]);
801 while (NSObject *key = [keys nextObject]) {
804 [json appendString:@","];
807 [json appendString:[key cy$toKey]];
808 [json appendString:@":"];
809 NSObject *object([self objectForKey:key]);
810 [json appendString:CYCastNSCYON(object)];
813 [json appendString:@"}"];
817 - (bool) cy$hasProperty:(NSString *)name {
818 return [self objectForKey:name] != nil;
821 - (NSObject *) cy$getProperty:(NSString *)name {
822 return [self objectForKey:name];
825 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
826 [super cy$getPropertyNames:names inContext:context];
829 for (NSObject *key in self) {
831 NSEnumerator *keys([self keyEnumerator]);
832 while (NSObject *key = [keys nextObject]) {
834 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
838 + (bool) cy$hasImplicitProperties {
844 /* Bridge: NSMutableArray {{{ */
845 @implementation NSMutableArray (Cycript)
847 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
848 if ([name isEqualToString:@"length"]) {
849 // XXX: is this not intelligent?
850 NSNumber *number(reinterpret_cast<NSNumber *>(value));
852 NSUInteger size([number unsignedIntegerValue]);
854 NSUInteger size([number unsignedIntValue]);
856 NSUInteger count([self count]);
858 [self removeObjectsInRange:NSMakeRange(size, count - size)];
859 else if (size != count) {
860 WebUndefined *undefined([WebUndefined undefined]);
861 for (size_t i(count); i != size; ++i)
862 [self addObject:undefined];
867 size_t index(CYGetIndex(name));
868 if (index == _not(size_t))
869 return [super cy$setProperty:name to:value];
871 id object(value ?: [NSNull null]);
873 size_t count([self count]);
875 [self replaceObjectAtIndex:index withObject:object];
877 if (index != count) {
878 WebUndefined *undefined([WebUndefined undefined]);
879 for (size_t i(count); i != index; ++i)
880 [self addObject:undefined];
883 [self addObject:object];
889 - (bool) cy$deleteProperty:(NSString *)name {
890 size_t index(CYGetIndex(name));
891 if (index == _not(size_t) || index >= [self count])
892 return [super cy$deleteProperty:name];
893 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
899 /* Bridge: NSMutableDictionary {{{ */
900 @implementation NSMutableDictionary (Cycript)
902 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
903 [self setObject:(value ?: [NSNull null]) forKey:name];
907 - (bool) cy$deleteProperty:(NSString *)name {
908 if ([self objectForKey:name] == nil)
911 [self removeObjectForKey:name];
918 /* Bridge: NSNumber {{{ */
919 @implementation NSNumber (Cycript)
921 - (JSType) cy$JSType {
923 // XXX: this just seems stupid
924 if ([self class] == NSCFBoolean_)
925 return kJSTypeBoolean;
927 return kJSTypeNumber;
930 - (NSObject *) cy$toJSON:(NSString *)key {
934 - (NSString *) cy$toCYON {
935 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
938 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
939 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
944 /* Bridge: NSNull {{{ */
945 @implementation NSNull (Cycript)
947 - (JSType) cy$JSType {
951 - (NSObject *) cy$toJSON:(NSString *)key {
955 - (NSString *) cy$toCYON {
961 /* Bridge: NSObject {{{ */
962 @implementation NSObject (Cycript)
964 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
965 return CYMakeInstance(context, self, false);
968 - (JSType) cy$JSType {
969 return kJSTypeObject;
972 - (NSObject *) cy$toJSON:(NSString *)key {
973 return [self description];
976 - (NSString *) cy$toCYON {
977 return [[self cy$toJSON:@""] cy$toCYON];
980 - (NSString *) cy$toKey {
981 return [self cy$toCYON];
984 - (bool) cy$hasProperty:(NSString *)name {
988 - (NSObject *) cy$getProperty:(NSString *)name {
992 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
996 - (bool) cy$deleteProperty:(NSString *)name {
1000 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1003 + (bool) cy$hasImplicitProperties {
1009 /* Bridge: NSProxy {{{ */
1010 @implementation NSProxy (Cycript)
1012 - (NSObject *) cy$toJSON:(NSString *)key {
1013 return [self description];
1016 - (NSString *) cy$toCYON {
1017 return [[self cy$toJSON:@""] cy$toCYON];
1022 /* Bridge: NSString {{{ */
1023 @implementation NSString (Cycript)
1025 - (JSType) cy$JSType {
1026 return kJSTypeString;
1029 - (NSObject *) cy$toJSON:(NSString *)key {
1033 - (NSString *) cy$toCYON {
1034 std::ostringstream str;
1035 CYUTF8String string(CYCastUTF8String(self));
1036 CYStringify(str, string.data, string.size);
1037 std::string value(str.str());
1038 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1041 - (NSString *) cy$toKey {
1042 if (CYIsKey(CYCastUTF8String(self)))
1044 return [self cy$toCYON];
1049 /* Bridge: WebUndefined {{{ */
1050 @implementation WebUndefined (Cycript)
1052 - (JSType) cy$JSType {
1053 return kJSTypeUndefined;
1056 - (NSObject *) cy$toJSON:(NSString *)key {
1060 - (NSString *) cy$toCYON {
1061 return @"undefined";
1064 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1065 return CYJSUndefined(context);
1066 } CYObjectiveCatch }
1071 static bool CYIsClass(id self) {
1073 // XXX: this is a lame object_isClass
1074 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1076 return GSObjCIsClass(self);
1080 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1081 id self(CYCastNSObject(pool, context, value));
1082 if (CYIsClass(self))
1083 return (Class) self;
1084 throw CYJSError(context, "got something that is not a Class");
1088 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1090 size_t size(JSPropertyNameArrayGetCount(names));
1091 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1092 for (size_t index(0); index != size; ++index)
1093 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1097 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1099 return CYJSNull(context);
1100 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1101 return [value cy$JSValueInContext:context];
1103 return CYMakeInstance(context, value, false);
1104 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1106 @implementation CYJSObject
1108 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1109 if ((self = [super init]) != nil) {
1111 context_ = CYGetJSContext(context);
1112 //XXX:JSGlobalContextRetain(context_);
1113 JSValueProtect(context_, object_);
1115 } CYObjectiveCatch }
1117 - (void) dealloc { CYObjectiveTry {
1118 JSValueUnprotect(context_, object_);
1119 //XXX:JSGlobalContextRelease(context_);
1121 } CYObjectiveCatch }
1123 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1124 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1125 if (!CYIsCallable(context_, toJSON))
1126 return [super cy$toJSON:key];
1128 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1129 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1130 // XXX: do I really want an NSNull here?!
1131 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1133 } CYObjectiveCatch }
1135 - (NSString *) cy$toCYON { CYObjectiveTry {
1137 JSValueRef exception(NULL);
1138 const char *cyon(CYPoolCCYON(pool, context_, object_));
1139 CYThrow(context_, exception);
1141 return [super cy$toCYON];
1143 return [NSString stringWithUTF8String:cyon];
1144 } CYObjectiveCatch }
1146 - (NSUInteger) count { CYObjectiveTry {
1147 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1148 size_t size(JSPropertyNameArrayGetCount(names));
1149 JSPropertyNameArrayRelease(names);
1151 } CYObjectiveCatch }
1153 - (id) objectForKey:(id)key { CYObjectiveTry {
1154 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1155 if (JSValueIsUndefined(context_, value))
1157 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1158 } CYObjectiveCatch }
1160 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1161 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1162 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1163 JSPropertyNameArrayRelease(names);
1165 } CYObjectiveCatch }
1167 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1168 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1169 } CYObjectiveCatch }
1171 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1172 JSValueRef exception(NULL);
1173 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1174 CYThrow(context_, exception);
1175 } CYObjectiveCatch }
1179 @implementation CYJSArray
1181 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1182 if ((self = [super init]) != nil) {
1184 context_ = CYGetJSContext(context);
1185 //XXX:JSGlobalContextRetain(context_);
1186 JSValueProtect(context_, object_);
1188 } CYObjectiveCatch }
1190 - (void) dealloc { CYObjectiveTry {
1191 JSValueUnprotect(context_, object_);
1192 //XXX:JSGlobalContextRelease(context_);
1194 } CYObjectiveCatch }
1196 - (NSUInteger) count { CYObjectiveTry {
1197 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1198 } CYObjectiveCatch }
1200 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1201 size_t bounds([self count]);
1202 if (index >= bounds)
1203 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1204 JSValueRef exception(NULL);
1205 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1206 CYThrow(context_, exception);
1207 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1208 } CYObjectiveCatch }
1210 - (void) addObject:(id)object { CYObjectiveTry {
1211 JSValueRef exception(NULL);
1212 JSValueRef arguments[1];
1213 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1214 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1215 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1216 CYThrow(context_, exception);
1217 } CYObjectiveCatch }
1219 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1220 size_t bounds([self count] + 1);
1221 if (index >= bounds)
1222 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1223 JSValueRef exception(NULL);
1224 JSValueRef arguments[3];
1225 arguments[0] = CYCastJSValue(context_, index);
1226 arguments[1] = CYCastJSValue(context_, 0);
1227 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1228 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1229 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1230 CYThrow(context_, exception);
1231 } CYObjectiveCatch }
1233 - (void) removeLastObject { CYObjectiveTry {
1234 JSValueRef exception(NULL);
1235 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1236 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1237 CYThrow(context_, exception);
1238 } CYObjectiveCatch }
1240 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1241 size_t bounds([self count]);
1242 if (index >= bounds)
1243 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1244 JSValueRef exception(NULL);
1245 JSValueRef arguments[2];
1246 arguments[0] = CYCastJSValue(context_, index);
1247 arguments[1] = CYCastJSValue(context_, 1);
1248 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1249 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1250 CYThrow(context_, exception);
1251 } CYObjectiveCatch }
1253 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1254 size_t bounds([self count]);
1255 if (index >= bounds)
1256 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1257 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1258 } CYObjectiveCatch }
1262 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1266 JSObjectRef object_;
1274 // XXX: delete object_? ;(
1277 static CYInternal *Get(id self) {
1278 CYInternal *internal(NULL);
1279 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1280 // XXX: do something epic? ;P
1286 static CYInternal *Set(id self) {
1287 CYInternal *internal(NULL);
1288 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1289 if (internal == NULL) {
1290 internal = new CYInternal();
1291 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1294 // XXX: do something epic? ;P
1300 bool HasProperty(JSContextRef context, JSStringRef name) {
1301 if (object_ == NULL)
1303 return JSObjectHasProperty(context, object_, name);
1306 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1307 if (object_ == NULL)
1309 return CYGetProperty(context, object_, name);
1312 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1313 if (object_ == NULL)
1314 object_ = JSObjectMake(context, NULL, NULL);
1315 CYSetProperty(context, object_, name, value);
1319 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1320 Selector_privateData *internal(new Selector_privateData(sel));
1321 return JSObjectMake(context, Selector_, internal);
1324 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1325 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1326 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1327 return reinterpret_cast<SEL>(internal->value_);
1329 return CYCastPointer<SEL>(context, value);
1332 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1333 return (void *) [[NSAutoreleasePool alloc] init];
1334 } CYSadCatch(NULL) }
1336 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1337 return [(NSAutoreleasePool *) handle release];
1340 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1342 return Instance::Make(context, nil);
1343 if (Class _class = objc_getClass(name.data))
1344 return CYMakeInstance(context, _class, true);
1345 if (Protocol *protocol = objc_getProtocol(name.data))
1346 return CYMakeInstance(context, protocol, true);
1348 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1350 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1351 ffi_call(cif, function, value, values);
1354 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1355 switch (type->primitive) {
1356 // XXX: do something epic about blocks
1359 case sig::typename_P:
1360 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1363 case sig::selector_P:
1364 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1372 } CYSadCatch(false) }
1374 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1375 switch (type->primitive) {
1376 // XXX: do something epic about blocks
1379 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1380 JSValueRef value(CYCastJSValue(context, object));
1386 case sig::typename_P:
1387 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1389 case sig::selector_P:
1390 if (SEL sel = *reinterpret_cast<SEL *>(data))
1391 return CYMakeSelector(context, sel);
1395 return CYJSNull(context);
1399 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1401 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1402 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1405 #if OBJC_API_VERSION >= 2
1407 method_getReturnType(method, type, sizeof(type));
1409 const char *type(method_getTypeEncoding(method));
1415 // XXX: possibly use a more "awesome" check?
1419 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1421 return method_getTypeEncoding(method);
1423 const char *name(sel_getName(sel));
1424 size_t length(strlen(name));
1426 char keyed[length + 2];
1428 keyed[length + 1] = '\0';
1429 memcpy(keyed + 1, name, length);
1431 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1432 return entry->value_;
1437 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1438 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1440 JSContextRef context(internal->context_);
1442 size_t count(internal->cif_.nargs);
1443 JSValueRef values[count];
1445 for (size_t index(0); index != count; ++index)
1446 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1448 JSObjectRef _this(CYCastJSObject(context, values[0]));
1450 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1451 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1454 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1455 Message_privateData *internal(new Message_privateData(sel, type, imp));
1456 return JSObjectMake(context, Message_, internal);
1459 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1460 JSObjectRef function(CYCastJSObject(context, value));
1461 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1462 // XXX: see notes in Library.cpp about needing to leak
1463 return reinterpret_cast<IMP>(internal->GetValue());
1466 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1467 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1468 Class _class(internal->GetValue());
1471 const char *name(CYPoolCString(pool, context, property));
1473 if (SEL sel = sel_getUid(name))
1474 if (class_getInstanceMethod(_class, sel) != NULL)
1480 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1481 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1482 Class _class(internal->GetValue());
1485 const char *name(CYPoolCString(pool, context, property));
1487 if (SEL sel = sel_getUid(name))
1488 if (objc_method *method = class_getInstanceMethod(_class, sel))
1489 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1494 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1495 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1496 Class _class(internal->GetValue());
1499 const char *name(CYPoolCString(pool, context, property));
1501 SEL sel(sel_registerName(name));
1503 objc_method *method(class_getInstanceMethod(_class, sel));
1508 if (JSValueIsObjectOfClass(context, value, Message_)) {
1509 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1510 type = sig::Unparse(pool, &message->signature_);
1511 imp = reinterpret_cast<IMP>(message->GetValue());
1513 type = CYPoolTypeEncoding(pool, context, sel, method);
1514 imp = CYMakeMessage(context, value, type);
1518 method_setImplementation(method, imp);
1521 GSMethodList list(GSAllocMethodList(1));
1522 GSAppendMethodToList(list, sel, type, imp, YES);
1523 GSAddMethodList(_class, list, YES);
1524 GSFlushMethodCacheForClass(_class);
1526 class_addMethod(_class, sel, imp, type);
1533 #if 0 && OBJC_API_VERSION < 2
1534 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1535 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1536 Class _class(internal->GetValue());
1539 const char *name(CYPoolCString(pool, context, property));
1541 if (SEL sel = sel_getUid(name))
1542 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1543 objc_method_list list = {NULL, 1, {method}};
1544 class_removeMethods(_class, &list);
1552 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1553 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1554 Class _class(internal->GetValue());
1556 #if OBJC_API_VERSION >= 2
1558 objc_method **data(class_copyMethodList(_class, &size));
1559 for (size_t i(0); i != size; ++i)
1560 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1563 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1564 for (int i(0); i != methods->method_count; ++i)
1565 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1569 static bool CYHasImplicitProperties(Class _class) {
1570 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1571 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1573 return [_class cy$hasImplicitProperties];
1576 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1577 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1578 id self(internal->GetValue());
1580 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1584 NSString *name(CYCastNSString(pool, context, property));
1586 if (CYInternal *internal = CYInternal::Get(self))
1587 if (internal->HasProperty(context, property))
1590 Class _class(object_getClass(self));
1593 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1594 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1595 if ([self cy$hasProperty:name])
1597 } CYPoolCatch(false)
1599 const char *string(CYPoolCString(pool, context, name));
1602 if (class_getProperty(_class, string) != NULL)
1606 if (CYHasImplicitProperties(_class))
1607 if (SEL sel = sel_getUid(string))
1608 if (CYImplements(self, _class, sel, true))
1614 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1616 id self(internal->GetValue());
1618 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1619 return Internal::Make(context, self, object);
1622 NSString *name(CYCastNSString(pool, context, property));
1624 if (CYInternal *internal = CYInternal::Get(self))
1625 if (JSValueRef value = internal->GetProperty(context, property))
1629 if (NSObject *data = [self cy$getProperty:name])
1630 return CYCastJSValue(context, data);
1633 const char *string(CYPoolCString(pool, context, name));
1634 Class _class(object_getClass(self));
1637 if (objc_property_t property = class_getProperty(_class, string)) {
1638 PropertyAttributes attributes(property);
1639 SEL sel(sel_registerName(attributes.Getter()));
1640 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1644 if (CYHasImplicitProperties(_class))
1645 if (SEL sel = sel_getUid(string))
1646 if (CYImplements(self, _class, sel, true))
1647 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1652 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1653 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1654 id self(internal->GetValue());
1658 NSString *name(CYCastNSString(pool, context, property));
1659 NSObject *data(CYCastNSObject(pool, context, value));
1662 if ([self cy$setProperty:name to:data])
1666 const char *string(CYPoolCString(pool, context, name));
1667 Class _class(object_getClass(self));
1670 if (objc_property_t property = class_getProperty(_class, string)) {
1671 PropertyAttributes attributes(property);
1672 if (const char *setter = attributes.Setter()) {
1673 SEL sel(sel_registerName(setter));
1674 JSValueRef arguments[1] = {value};
1675 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1681 size_t length(strlen(string));
1683 char set[length + 5];
1689 if (string[0] != '\0') {
1690 set[3] = toupper(string[0]);
1691 memcpy(set + 4, string + 1, length - 1);
1694 set[length + 3] = ':';
1695 set[length + 4] = '\0';
1697 if (SEL sel = sel_getUid(set))
1698 if (CYImplements(self, _class, sel, false)) {
1699 JSValueRef arguments[1] = {value};
1700 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1703 if (CYInternal *internal = CYInternal::Set(self)) {
1704 internal->SetProperty(context, property, value);
1711 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1712 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1713 id self(internal->GetValue());
1716 NSString *name(CYCastNSString(NULL, context, property));
1717 return [self cy$deleteProperty:name];
1719 } CYCatch return /*XXX*/ NULL; }
1721 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1722 const char *name(sel_getName(method_getName(method)));
1723 if (strchr(name, ':') != NULL)
1726 const char *type(method_getTypeEncoding(method));
1727 if (type == NULL || *type == '\0' || *type == 'v')
1730 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1733 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1734 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1735 id self(internal->GetValue());
1738 Class _class(object_getClass(self));
1743 objc_property_t *data(class_copyPropertyList(_class, &size));
1744 for (size_t i(0); i != size; ++i)
1745 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1750 if (CYHasImplicitProperties(_class)) {
1751 #if OBJC_API_VERSION >= 2
1753 objc_method **data(class_copyMethodList(_class, &size));
1754 for (size_t i(0); i != size; ++i)
1755 Instance_getPropertyNames_message(names, data[i]);
1758 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1759 for (int i(0); i != methods->method_count; ++i)
1760 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1765 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1766 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1767 [self cy$getPropertyNames:names inContext:context];
1771 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1772 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1773 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1777 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1778 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1779 Class _class(internal->GetValue());
1780 if (!CYIsClass(_class))
1783 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1784 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1785 // XXX: this isn't always safe
1786 return [linternal->GetValue() isKindOfClass:_class];
1792 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1793 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1796 id self(internal->GetValue());
1797 const char *name(CYPoolCString(pool, context, property));
1799 if (object_getInstanceVariable(self, name, NULL) != NULL)
1805 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1806 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1809 id self(internal->GetValue());
1810 const char *name(CYPoolCString(pool, context, property));
1812 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1813 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1814 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1815 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1821 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1822 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1825 id self(internal->GetValue());
1826 const char *name(CYPoolCString(pool, context, property));
1828 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1829 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1830 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1837 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1838 if (Class super = class_getSuperclass(_class))
1839 Internal_getPropertyNames_(super, names);
1841 #if OBJC_API_VERSION >= 2
1843 objc_ivar **data(class_copyIvarList(_class, &size));
1844 for (size_t i(0); i != size; ++i)
1845 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1848 if (objc_ivar_list *ivars = _class->ivars)
1849 for (int i(0); i != ivars->ivar_count; ++i)
1850 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1854 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1855 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1858 id self(internal->GetValue());
1859 Class _class(object_getClass(self));
1861 Internal_getPropertyNames_(_class, names);
1864 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1865 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1866 return internal->GetOwner();
1869 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1871 NSString *name(CYCastNSString(pool, context, property));
1872 if (Class _class = NSClassFromString(name))
1873 return CYMakeInstance(context, _class, true);
1877 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1879 size_t size(objc_getClassList(NULL, 0));
1880 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1883 size_t writ(objc_getClassList(data, size));
1886 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1892 for (size_t i(0); i != writ; ++i)
1893 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1899 while (Class _class = objc_next_class(&state))
1900 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1904 #if OBJC_API_VERSION >= 2
1905 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1906 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1909 const char *name(CYPoolCString(pool, context, property));
1911 const char **data(objc_copyClassNamesForImage(internal, &size));
1913 for (size_t i(0); i != size; ++i)
1914 if (strcmp(name, data[i]) == 0) {
1915 if (Class _class = objc_getClass(name)) {
1916 value = CYMakeInstance(context, _class, true);
1927 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1928 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1930 const char **data(objc_copyClassNamesForImage(internal, &size));
1931 for (size_t i(0); i != size; ++i)
1932 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1936 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1938 const char *name(CYPoolCString(pool, context, property));
1940 const char **data(objc_copyImageNames(&size));
1941 for (size_t i(0); i != size; ++i)
1942 if (strcmp(name, data[i]) == 0) {
1951 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1952 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1956 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1958 const char **data(objc_copyImageNames(&size));
1959 for (size_t i(0); i != size; ++i)
1960 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1965 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1967 const char *name(CYPoolCString(pool, context, property));
1968 if (Protocol *protocol = objc_getProtocol(name))
1969 return CYMakeInstance(context, protocol, true);
1973 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1974 #if OBJC_API_VERSION >= 2
1976 Protocol **data(objc_copyProtocolList(&size));
1977 for (size_t i(0); i != size; ++i)
1978 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1986 static bool stret(ffi_type *ffi_type) {
1987 return ffi_type->type == FFI_TYPE_STRUCT && (
1988 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1989 struct_forward_array[ffi_type->size] != 0
1994 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 {
1998 _class = object_getClass(self);
2002 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2003 imp = method_getImplementation(method);
2004 type = method_getTypeEncoding(method);
2009 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2011 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2012 type = CYPoolCString(pool, context, [method _typeString]);
2020 sig::Signature signature;
2021 sig::Parse(pool, &signature, type, &Structor_);
2024 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2028 if (stret(cif.rtype))
2029 imp = class_getMethodImplementation_stret(_class, _cmd);
2031 imp = class_getMethodImplementation(_class, _cmd);
2033 objc_super super = {self, _class};
2034 imp = objc_msg_lookup_super(&super, _cmd);
2038 void (*function)() = reinterpret_cast<void (*)()>(imp);
2039 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2042 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2044 throw CYJSError(context, "too few arguments to objc_msgSend");
2054 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2055 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2056 self = internal->GetValue();
2057 _class = internal->class_;;
2058 uninitialized = false;
2059 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2060 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2061 self = internal->GetValue();
2063 uninitialized = internal->IsUninitialized();
2065 internal->value_ = nil;
2067 self = CYCastNSObject(pool, context, arguments[0]);
2069 uninitialized = false;
2073 return CYJSNull(context);
2075 _cmd = CYCastSEL(context, arguments[1]);
2077 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2080 /* Hook: objc_registerClassPair {{{ */
2081 #if defined(__APPLE__) && defined(__arm__)
2082 // XXX: replace this with associated objects
2084 MSHook(void, CYDealloc, id self, SEL sel) {
2085 CYInternal *internal;
2086 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2087 if (internal != NULL)
2089 _CYDealloc(self, sel);
2092 MSHook(void, objc_registerClassPair, Class _class) {
2093 Class super(class_getSuperclass(_class));
2094 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2095 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2096 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2099 _objc_registerClassPair(_class);
2102 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2104 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2106 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2107 if (value == NULL || !CYIsClass(value))
2108 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2109 Class _class((Class) value);
2110 $objc_registerClassPair(_class);
2111 return CYJSUndefined(context);
2116 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2117 JSValueRef setup[count + 2];
2120 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2121 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2124 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2126 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2128 // XXX: handle Instance::Uninitialized?
2129 id self(CYCastNSObject(pool, context, _this));
2133 setup[1] = &internal->sel_;
2135 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2138 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2140 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2142 id self(CYCastNSObject(pool, context, arguments[0]));
2143 Class _class(CYCastClass(pool, context, arguments[1]));
2144 return cy::Super::Make(context, self, _class);
2147 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2149 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2151 const char *name(CYPoolCString(pool, context, arguments[0]));
2152 return CYMakeSelector(context, sel_registerName(name));
2155 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2157 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2158 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2159 return CYMakeInstance(context, self, false);
2162 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2163 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2164 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2167 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2168 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2169 Type_privateData *typical(internal->GetType());
2174 if (typical == NULL) {
2178 type = typical->type_;
2179 ffi = typical->ffi_;
2182 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2185 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2186 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2187 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2190 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2191 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2192 id self(internal->GetValue());
2193 if (!CYIsClass(self))
2194 return CYJSUndefined(context);
2195 return CYGetClassPrototype(context, self);
2198 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2199 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2200 id self(internal->GetValue());
2201 if (!CYIsClass(self))
2202 return CYJSUndefined(context);
2203 return Messages::Make(context, (Class) self);
2206 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2207 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2210 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2211 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2214 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2215 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2218 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2225 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2226 // XXX: check for support of cy$toJSON?
2227 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2229 } CYCatch return /*XXX*/ NULL; }
2232 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2233 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2236 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2237 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2238 } CYCatch return /*XXX*/ NULL; }
2241 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2242 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2245 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2246 // XXX: but... but... THIS ISN'T A POINTER! :(
2247 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2248 } CYCatch return /*XXX*/ NULL; }
2250 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2251 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2254 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2256 id value(internal->GetValue());
2258 return CYCastJSValue(context, "nil");
2261 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2262 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2264 } CYCatch return /*XXX*/ NULL; }
2266 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2267 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2268 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2271 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2272 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2275 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2276 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2277 const char *name(sel_getName(internal->GetValue()));
2280 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2281 return CYCastJSValue(context, CYJSString(context, string));
2283 } CYCatch return /*XXX*/ NULL; }
2285 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2287 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2290 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2291 SEL sel(internal->GetValue());
2293 objc_method *method;
2294 if (Class _class = CYCastClass(pool, context, arguments[0]))
2295 method = class_getInstanceMethod(_class, sel);
2299 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2300 return CYCastJSValue(context, CYJSString(type));
2302 return CYJSNull(context);
2305 static JSStaticValue Selector_staticValues[2] = {
2306 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2307 {NULL, NULL, NULL, 0}
2310 static JSStaticValue Instance_staticValues[5] = {
2311 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2312 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2313 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2314 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2315 {NULL, NULL, NULL, 0}
2318 static JSStaticFunction Instance_staticFunctions[6] = {
2319 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2320 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2321 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2322 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2323 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2324 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2328 static JSStaticFunction Internal_staticFunctions[2] = {
2329 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2333 static JSStaticFunction Selector_staticFunctions[5] = {
2334 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2335 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2336 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2337 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2341 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2342 apr_pool_t *pool(CYGetGlobalPool());
2344 Object_type = new(pool) Type_privateData("@");
2345 Selector_type = new(pool) Type_privateData(":");
2348 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2349 NSCFType_ = objc_getClass("NSCFType");
2350 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2351 NSZombie_ = objc_getClass("_NSZombie_");
2353 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2356 NSArray_ = objc_getClass("NSArray");
2357 NSDictionary_ = objc_getClass("NSDictionary");
2358 Object_ = objc_getClass("Object");
2360 JSClassDefinition definition;
2362 definition = kJSClassDefinitionEmpty;
2363 definition.className = "Instance";
2364 definition.staticValues = Instance_staticValues;
2365 definition.staticFunctions = Instance_staticFunctions;
2366 definition.hasProperty = &Instance_hasProperty;
2367 definition.getProperty = &Instance_getProperty;
2368 definition.setProperty = &Instance_setProperty;
2369 definition.deleteProperty = &Instance_deleteProperty;
2370 definition.getPropertyNames = &Instance_getPropertyNames;
2371 definition.callAsConstructor = &Instance_callAsConstructor;
2372 definition.hasInstance = &Instance_hasInstance;
2373 definition.finalize = &CYFinalize;
2374 Instance_ = JSClassCreate(&definition);
2376 definition = kJSClassDefinitionEmpty;
2377 definition.className = "Internal";
2378 definition.staticFunctions = Internal_staticFunctions;
2379 definition.hasProperty = &Internal_hasProperty;
2380 definition.getProperty = &Internal_getProperty;
2381 definition.setProperty = &Internal_setProperty;
2382 definition.getPropertyNames = &Internal_getPropertyNames;
2383 definition.finalize = &CYFinalize;
2384 Internal_ = JSClassCreate(&definition);
2386 definition = kJSClassDefinitionEmpty;
2387 definition.className = "Message";
2388 definition.staticFunctions = cy::Functor::StaticFunctions;
2389 definition.callAsFunction = &Message_callAsFunction;
2390 definition.finalize = &CYFinalize;
2391 Message_ = JSClassCreate(&definition);
2393 definition = kJSClassDefinitionEmpty;
2394 definition.className = "Messages";
2395 definition.hasProperty = &Messages_hasProperty;
2396 definition.getProperty = &Messages_getProperty;
2397 definition.setProperty = &Messages_setProperty;
2398 #if 0 && OBJC_API_VERSION < 2
2399 definition.deleteProperty = &Messages_deleteProperty;
2401 definition.getPropertyNames = &Messages_getPropertyNames;
2402 definition.finalize = &CYFinalize;
2403 Messages_ = JSClassCreate(&definition);
2405 definition = kJSClassDefinitionEmpty;
2406 definition.className = "Selector";
2407 definition.staticValues = Selector_staticValues;
2408 definition.staticFunctions = Selector_staticFunctions;
2409 definition.callAsFunction = &Selector_callAsFunction;
2410 definition.finalize = &CYFinalize;
2411 Selector_ = JSClassCreate(&definition);
2413 definition = kJSClassDefinitionEmpty;
2414 definition.className = "Super";
2415 definition.staticFunctions = Internal_staticFunctions;
2416 definition.finalize = &CYFinalize;
2417 Super_ = JSClassCreate(&definition);
2419 definition = kJSClassDefinitionEmpty;
2420 definition.className = "ObjectiveC::Classes";
2421 definition.getProperty = &ObjectiveC_Classes_getProperty;
2422 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2423 ObjectiveC_Classes_ = JSClassCreate(&definition);
2425 #if OBJC_API_VERSION >= 2
2426 definition = kJSClassDefinitionEmpty;
2427 definition.className = "ObjectiveC::Images";
2428 definition.getProperty = &ObjectiveC_Images_getProperty;
2429 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2430 ObjectiveC_Images_ = JSClassCreate(&definition);
2432 definition = kJSClassDefinitionEmpty;
2433 definition.className = "ObjectiveC::Image::Classes";
2434 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2435 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2436 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2439 definition = kJSClassDefinitionEmpty;
2440 definition.className = "ObjectiveC::Protocols";
2441 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2442 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2443 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2445 #if defined(__APPLE__) && defined(__arm__)
2446 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2450 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2454 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2455 JSObjectRef global(CYGetGlobalObject(context));
2456 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2457 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2458 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2460 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2461 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2463 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2464 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2466 #if OBJC_API_VERSION >= 2
2467 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2470 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2471 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2472 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2473 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2475 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2476 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2478 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2479 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2480 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2482 #if defined(__APPLE__) && defined(__arm__)
2483 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2486 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2488 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2489 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2490 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2493 static CYHooks CYObjectiveCHooks = {
2494 &CYObjectiveC_ExecuteStart,
2495 &CYObjectiveC_ExecuteEnd,
2496 &CYObjectiveC_RuntimeProperty,
2497 &CYObjectiveC_CallFunction,
2498 &CYObjectiveC_Initialize,
2499 &CYObjectiveC_SetupContext,
2500 &CYObjectiveC_PoolFFI,
2501 &CYObjectiveC_FromFFI,
2504 struct CYObjectiveC {
2506 hooks_ = &CYObjectiveCHooks;
2507 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2508 _assert(hooks_ != NULL);