1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2010 Jay Freeman (saurik)
5 /* GNU Lesser General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
22 #if defined(__APPLE__) && defined(__arm__)
23 #include <substrate.h>
25 #include <objc/objc-api.h>
32 #include <Foundation/Foundation.h>
34 #include "ObjectiveC/Internal.hpp"
36 #include <objc/Protocol.h>
38 #include "cycript.hpp"
40 #include "ObjectiveC/Internal.hpp"
43 #include <CoreFoundation/CoreFoundation.h>
44 #include <JavaScriptCore/JSStringRefCF.h>
45 #include <WebKit/WebScriptObject.h>
49 #include "JavaScript.hpp"
51 #include "Execute.hpp"
56 #define CYObjectiveTry_(context) { \
57 JSContextRef context_(context); \
59 #define CYObjectiveTry { \
61 #define CYObjectiveCatch \
62 catch (const CYException &error) { \
63 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
69 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
71 #define CYPoolCatch(value) \
72 @catch (NSException *error) { \
73 _saved = [error retain]; \
74 throw CYJSError(context, CYCastJSValue(context, error)); \
79 [_saved autorelease]; \
85 #define CYSadCatch(value) \
86 @catch (NSException *error ) { \
87 throw CYJSError(context, CYCastJSValue(context, error)); \
92 #define class_getSuperclass GSObjCSuper
93 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
94 #define class_getName GSNameFromClass
96 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
98 #define ivar_getName(ivar) ((ivar)->ivar_name)
99 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
100 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
102 #define method_getName(method) ((method)->method_name)
103 #define method_getImplementation(method) ((method)->method_imp)
104 #define method_getTypeEncoding(method) ((method)->method_types)
105 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
108 #define objc_getClass GSClassFromName
110 #define objc_getProtocol GSProtocolFromName
112 #define object_getClass GSObjCClass
114 #define object_getInstanceVariable(object, name, value) ({ \
115 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
116 _assert(value != NULL); \
118 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
122 #define object_setIvar(object, ivar, value) ({ \
123 void *data = (value); \
124 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
127 #define protocol_getName(protocol) [(protocol) name]
130 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
132 /* Objective-C Pool Release {{{ */
133 apr_status_t CYPoolRelease_(void *data) {
134 id object(reinterpret_cast<id>(data));
139 id CYPoolRelease_(apr_pool_t *pool, id object) {
142 else if (pool == NULL)
143 return [object autorelease];
145 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
150 template <typename Type_>
151 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
152 return (Type_) CYPoolRelease_(pool, (id) object);
155 /* Objective-C Strings {{{ */
156 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
158 return [value UTF8String];
160 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
161 char *string(new(pool) char[size]);
162 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
163 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
168 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
170 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
173 return CYCopyJSString(CYPoolCString(pool, context, value));
177 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
180 // XXX: this definition scares me; is anyone using this?!
181 NSString *string([value description]);
182 return CYCopyJSString(context, string);
185 NSString *CYCopyNSString(const CYUTF8String &value) {
187 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
189 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
193 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
195 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
198 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
202 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
203 return CYCopyNSString(context, CYJSString(context, value));
206 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
207 return CYPoolRelease(pool, CYCopyNSString(value));
210 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
211 const char *name(sel_getName(sel));
212 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
215 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
216 return CYPoolRelease(pool, CYCopyNSString(context, value));
219 CYUTF8String CYCastUTF8String(NSString *value) {
220 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
221 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
225 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
227 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
228 if (exception == NULL)
230 *exception = CYCastJSValue(context, error);
233 size_t CYGetIndex(NSString *value) {
234 return CYGetIndex(CYCastUTF8String(value));
237 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
238 return CYGetOffset(CYPoolCString(pool, context, value), index);
241 static JSClassRef Instance_;
242 static JSClassRef Internal_;
243 static JSClassRef Message_;
244 static JSClassRef Messages_;
245 static JSClassRef Selector_;
246 static JSClassRef StringInstance_;
247 static JSClassRef Super_;
249 static JSClassRef ObjectiveC_Classes_;
250 static JSClassRef ObjectiveC_Protocols_;
253 static JSClassRef ObjectiveC_Image_Classes_;
254 static JSClassRef ObjectiveC_Images_;
258 static Class NSCFBoolean_;
259 static Class NSCFType_;
260 static Class NSMessageBuilder_;
261 static Class NSZombie_;
263 static Class NSBoolNumber_;
266 static Class NSArray_;
267 static Class NSDictionary_;
268 static Class NSString_;
269 static Class Object_;
271 static Type_privateData *Object_type;
272 static Type_privateData *Selector_type;
274 Type_privateData *Instance::GetType() const {
278 Type_privateData *Selector_privateData::GetType() const {
279 return Selector_type;
282 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
284 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
286 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
288 JSObjectRef global(CYGetGlobalObject(context));
289 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
292 sprintf(label, "i%p", self);
293 CYJSString name(label);
295 JSValueRef value(CYGetProperty(context, cy, name));
296 if (!JSValueIsUndefined(context, value))
299 JSClassRef _class(NULL);
300 JSValueRef prototype;
302 if (self == NSArray_)
303 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
304 else if (self == NSDictionary_)
305 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
306 else if (self == NSString_)
307 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
309 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
311 JSObjectRef object(JSObjectMake(context, _class, NULL));
312 JSObjectSetPrototype(context, object, prototype);
313 CYSetProperty(context, cy, name, object);
318 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
319 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
320 if (_class == NSArray_)
322 if (Class super = class_getSuperclass(_class))
323 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
325 JSObjectSetPrototype(context, value, Array_prototype_);*/
329 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
330 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
334 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
335 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
339 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
340 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
341 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
345 Instance::~Instance() {
346 if ((flags_ & Transient) == 0)
347 // XXX: does this handle background threads correctly?
348 // XXX: this simply does not work on the console because I'm stupid
349 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
352 struct Message_privateData :
357 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
358 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
364 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
365 Instance::Flags flags;
368 flags = Instance::Transient;
370 flags = Instance::None;
371 object = [object retain];
374 return Instance::Make(context, object, flags);
377 @interface NSMethodSignature (Cycript)
378 - (NSString *) _typeString;
381 @interface NSObject (Cycript)
383 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
384 - (JSType) cy$JSType;
386 - (NSObject *) cy$toJSON:(NSString *)key;
387 - (NSString *) cy$toCYON;
388 - (NSString *) cy$toKey;
390 - (bool) cy$hasProperty:(NSString *)name;
391 - (NSObject *) cy$getProperty:(NSString *)name;
392 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
393 - (bool) cy$deleteProperty:(NSString *)name;
394 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
396 + (bool) cy$hasImplicitProperties;
401 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
404 NSString *CYCastNSCYON(id value) {
410 Class _class(object_getClass(value));
411 SEL sel(@selector(cy$toCYON));
413 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
414 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
415 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
416 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
417 string = [value cy$toCYON];
422 else if (value == NSZombie_)
423 string = @"_NSZombie_";
424 else if (_class == NSZombie_)
425 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
426 // XXX: frowny /in/ the pants
427 else if (value == NSMessageBuilder_ || value == Object_)
431 string = [NSString stringWithFormat:@"%@", value];
436 string = @"undefined";
443 struct PropertyAttributes {
448 const char *variable;
461 PropertyAttributes(objc_property_t property) :
473 name = property_getName(property);
474 const char *attributes(property_getAttributes(property));
476 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
478 case 'R': readonly = true; break;
479 case 'C': copy = true; break;
480 case '&': retain = true; break;
481 case 'N': nonatomic = true; break;
482 case 'G': getter_ = token + 1; break;
483 case 'S': setter_ = token + 1; break;
484 case 'V': variable = token + 1; break;
488 /*if (variable == NULL) {
489 variable = property_getName(property);
490 size_t size(strlen(variable));
491 char *name(new(pool_) char[size + 2]);
493 memcpy(name + 1, variable, size);
494 name[size + 1] = '\0';
499 const char *Getter() {
501 getter_ = apr_pstrdup(pool_, name);
505 const char *Setter() {
506 if (setter_ == NULL && !readonly) {
507 size_t length(strlen(name));
509 char *temp(new(pool_) char[length + 5]);
515 temp[3] = toupper(name[0]);
516 memcpy(temp + 4, name + 1, length - 1);
519 temp[length + 3] = ':';
520 temp[length + 4] = '\0';
531 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
532 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
537 @interface CYWebUndefined : NSObject {
540 + (CYWebUndefined *) undefined;
544 @implementation CYWebUndefined
546 + (CYWebUndefined *) undefined {
547 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
553 #define WebUndefined CYWebUndefined
556 /* Bridge: CYJSObject {{{ */
557 @interface CYJSObject : NSMutableDictionary {
559 JSContextRef context_;
562 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
564 - (NSObject *) cy$toJSON:(NSString *)key;
566 - (NSUInteger) count;
567 - (id) objectForKey:(id)key;
568 - (NSEnumerator *) keyEnumerator;
569 - (void) setObject:(id)object forKey:(id)key;
570 - (void) removeObjectForKey:(id)key;
574 /* Bridge: CYJSArray {{{ */
575 @interface CYJSArray : NSMutableArray {
577 JSContextRef context_;
580 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
582 - (NSUInteger) count;
583 - (id) objectAtIndex:(NSUInteger)index;
585 - (void) addObject:(id)anObject;
586 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
587 - (void) removeLastObject;
588 - (void) removeObjectAtIndex:(NSUInteger)index;
589 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
594 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
595 JSObjectRef Array(CYGetCachedObject(context, Array_s));
596 JSValueRef exception(NULL);
597 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
598 CYThrow(context, exception);
599 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
600 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
603 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
604 if (!JSValueIsObjectOfClass(context, object, Instance_))
605 return CYCastNSObject_(pool, context, object);
607 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
608 return internal->GetValue();
612 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
613 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
617 @interface NSBoolNumber : NSNumber {
622 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
626 switch (JSType type = JSValueGetType(context, value)) {
627 case kJSTypeUndefined:
628 object = [WebUndefined undefined];
638 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
641 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
647 object = CYCopyNSNumber(context, value);
652 object = CYCopyNSString(context, value);
657 // XXX: this might could be more efficient
658 object = CYCastNSObject(pool, context, (JSObjectRef) value);
663 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
670 return CYPoolRelease(pool, object);
672 return [object retain];
675 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
676 return CYNSObject(pool, context, value, true);
679 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
680 return CYNSObject(pool, context, value, false);
683 /* Bridge: NSArray {{{ */
684 @implementation NSArray (Cycript)
686 - (NSString *) cy$toCYON {
687 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
688 [json appendString:@"["];
692 for (id object in self) {
694 for (size_t index(0), count([self count]); index != count; ++index) {
695 id object([self objectAtIndex:index]);
698 [json appendString:@","];
701 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
702 [json appendString:CYCastNSCYON(object)];
704 [json appendString:@","];
709 [json appendString:@"]"];
713 - (bool) cy$hasProperty:(NSString *)name {
714 if ([name isEqualToString:@"length"])
717 size_t index(CYGetIndex(name));
718 if (index == _not(size_t) || index >= [self count])
719 return [super cy$hasProperty:name];
724 - (NSObject *) cy$getProperty:(NSString *)name {
725 if ([name isEqualToString:@"length"]) {
726 NSUInteger count([self count]);
728 return [NSNumber numberWithUnsignedInteger:count];
730 return [NSNumber numberWithUnsignedInt:count];
734 size_t index(CYGetIndex(name));
735 if (index == _not(size_t) || index >= [self count])
736 return [super cy$getProperty:name];
738 return [self objectAtIndex:index];
741 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
742 [super cy$getPropertyNames:names inContext:context];
744 for (size_t index(0), count([self count]); index != count; ++index) {
745 id object([self objectAtIndex:index]);
746 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
748 sprintf(name, "%zu", index);
749 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
754 + (bool) cy$hasImplicitProperties {
760 /* Bridge: NSBoolNumber {{{ */
762 @implementation NSBoolNumber (Cycript)
764 - (JSType) cy$JSType {
765 return kJSTypeBoolean;
768 - (NSObject *) cy$toJSON:(NSString *)key {
772 - (NSString *) cy$toCYON {
773 return [self boolValue] ? @"true" : @"false";
776 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
777 return CYCastJSValue(context, (bool) [self boolValue]);
783 /* Bridge: NSDictionary {{{ */
784 @implementation NSDictionary (Cycript)
786 - (NSString *) cy$toCYON {
787 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
788 [json appendString:@"{"];
792 for (NSObject *key in self) {
794 NSEnumerator *keys([self keyEnumerator]);
795 while (NSObject *key = [keys nextObject]) {
798 [json appendString:@","];
801 [json appendString:[key cy$toKey]];
802 [json appendString:@":"];
803 NSObject *object([self objectForKey:key]);
804 [json appendString:CYCastNSCYON(object)];
807 [json appendString:@"}"];
811 - (bool) cy$hasProperty:(NSString *)name {
812 return [self objectForKey:name] != nil;
815 - (NSObject *) cy$getProperty:(NSString *)name {
816 return [self objectForKey:name];
819 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
820 [super cy$getPropertyNames:names inContext:context];
823 for (NSObject *key in self) {
825 NSEnumerator *keys([self keyEnumerator]);
826 while (NSObject *key = [keys nextObject]) {
828 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
832 + (bool) cy$hasImplicitProperties {
838 /* Bridge: NSMutableArray {{{ */
839 @implementation NSMutableArray (Cycript)
841 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
842 if ([name isEqualToString:@"length"]) {
843 // XXX: is this not intelligent?
844 NSNumber *number(reinterpret_cast<NSNumber *>(value));
846 NSUInteger size([number unsignedIntegerValue]);
848 NSUInteger size([number unsignedIntValue]);
850 NSUInteger count([self count]);
852 [self removeObjectsInRange:NSMakeRange(size, count - size)];
853 else if (size != count) {
854 WebUndefined *undefined([WebUndefined undefined]);
855 for (size_t i(count); i != size; ++i)
856 [self addObject:undefined];
861 size_t index(CYGetIndex(name));
862 if (index == _not(size_t))
863 return [super cy$setProperty:name to:value];
865 id object(value ?: [NSNull null]);
867 size_t count([self count]);
869 [self replaceObjectAtIndex:index withObject:object];
871 if (index != count) {
872 WebUndefined *undefined([WebUndefined undefined]);
873 for (size_t i(count); i != index; ++i)
874 [self addObject:undefined];
877 [self addObject:object];
883 - (bool) cy$deleteProperty:(NSString *)name {
884 size_t index(CYGetIndex(name));
885 if (index == _not(size_t) || index >= [self count])
886 return [super cy$deleteProperty:name];
887 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
893 /* Bridge: NSMutableDictionary {{{ */
894 @implementation NSMutableDictionary (Cycript)
896 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
897 [self setObject:(value ?: [NSNull null]) forKey:name];
901 - (bool) cy$deleteProperty:(NSString *)name {
902 if ([self objectForKey:name] == nil)
905 [self removeObjectForKey:name];
912 /* Bridge: NSNumber {{{ */
913 @implementation NSNumber (Cycript)
915 - (JSType) cy$JSType {
917 // XXX: this just seems stupid
918 if ([self class] == NSCFBoolean_)
919 return kJSTypeBoolean;
921 return kJSTypeNumber;
924 - (NSObject *) cy$toJSON:(NSString *)key {
928 - (NSString *) cy$toCYON {
929 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
932 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
933 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
938 /* Bridge: NSNull {{{ */
939 @implementation NSNull (Cycript)
941 - (JSType) cy$JSType {
945 - (NSObject *) cy$toJSON:(NSString *)key {
949 - (NSString *) cy$toCYON {
955 /* Bridge: NSObject {{{ */
956 @implementation NSObject (Cycript)
958 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
959 return CYMakeInstance(context, self, false);
962 - (JSType) cy$JSType {
963 return kJSTypeObject;
966 - (NSObject *) cy$toJSON:(NSString *)key {
967 return [self description];
970 - (NSString *) cy$toCYON {
971 return [[self cy$toJSON:@""] cy$toCYON];
974 - (NSString *) cy$toKey {
975 return [self cy$toCYON];
978 - (bool) cy$hasProperty:(NSString *)name {
982 - (NSObject *) cy$getProperty:(NSString *)name {
986 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
990 - (bool) cy$deleteProperty:(NSString *)name {
994 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
997 + (bool) cy$hasImplicitProperties {
1003 /* Bridge: NSProxy {{{ */
1004 @implementation NSProxy (Cycript)
1006 - (NSObject *) cy$toJSON:(NSString *)key {
1007 return [self description];
1010 - (NSString *) cy$toCYON {
1011 return [[self cy$toJSON:@""] cy$toCYON];
1016 /* Bridge: NSString {{{ */
1017 @implementation NSString (Cycript)
1019 - (JSType) cy$JSType {
1020 return kJSTypeString;
1023 - (NSObject *) cy$toJSON:(NSString *)key {
1027 - (NSString *) cy$toCYON {
1028 std::ostringstream str;
1029 CYUTF8String string(CYCastUTF8String(self));
1030 CYStringify(str, string.data, string.size);
1031 std::string value(str.str());
1032 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1035 - (NSString *) cy$toKey {
1036 if (CYIsKey(CYCastUTF8String(self)))
1038 return [self cy$toCYON];
1041 - (bool) cy$hasProperty:(NSString *)name {
1042 if ([name isEqualToString:@"length"])
1045 size_t index(CYGetIndex(name));
1046 if (index == _not(size_t) || index >= [self length])
1047 return [super cy$hasProperty:name];
1052 - (NSObject *) cy$getProperty:(NSString *)name {
1053 if ([name isEqualToString:@"length"]) {
1054 NSUInteger count([self length]);
1056 return [NSNumber numberWithUnsignedInteger:count];
1058 return [NSNumber numberWithUnsignedInt:count];
1062 size_t index(CYGetIndex(name));
1063 if (index == _not(size_t) || index >= [self length])
1064 return [super cy$getProperty:name];
1066 return [self substringWithRange:NSMakeRange(index, 1)];
1069 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1070 [super cy$getPropertyNames:names inContext:context];
1072 for (size_t index(0), length([self length]); index != length; ++index) {
1074 sprintf(name, "%zu", index);
1075 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1079 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1080 + (bool) cy$hasImplicitProperties {
1086 /* Bridge: WebUndefined {{{ */
1087 @implementation WebUndefined (Cycript)
1089 - (JSType) cy$JSType {
1090 return kJSTypeUndefined;
1093 - (NSObject *) cy$toJSON:(NSString *)key {
1097 - (NSString *) cy$toCYON {
1098 return @"undefined";
1101 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1102 return CYJSUndefined(context);
1103 } CYObjectiveCatch }
1108 static bool CYIsClass(id self) {
1110 // XXX: this is a lame object_isClass
1111 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1113 return GSObjCIsClass(self);
1117 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1118 id self(CYCastNSObject(pool, context, value));
1119 if (CYIsClass(self))
1120 return (Class) self;
1121 throw CYJSError(context, "got something that is not a Class");
1125 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1127 size_t size(JSPropertyNameArrayGetCount(names));
1128 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1129 for (size_t index(0); index != size; ++index)
1130 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1134 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1136 return CYJSNull(context);
1137 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1138 return [value cy$JSValueInContext:context];
1140 return CYMakeInstance(context, value, false);
1141 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1143 @implementation CYJSObject
1145 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1146 if ((self = [super init]) != nil) {
1148 context_ = CYGetJSContext(context);
1149 //XXX:JSGlobalContextRetain(context_);
1150 JSValueProtect(context_, object_);
1152 } CYObjectiveCatch }
1154 - (void) dealloc { CYObjectiveTry {
1155 JSValueUnprotect(context_, object_);
1156 //XXX:JSGlobalContextRelease(context_);
1158 } CYObjectiveCatch }
1160 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1161 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1162 if (!CYIsCallable(context_, toJSON))
1163 return [super cy$toJSON:key];
1165 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1166 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1167 // XXX: do I really want an NSNull here?!
1168 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1170 } CYObjectiveCatch }
1172 - (NSString *) cy$toCYON { CYObjectiveTry {
1174 JSValueRef exception(NULL);
1175 const char *cyon(CYPoolCCYON(pool, context_, object_));
1176 CYThrow(context_, exception);
1178 return [super cy$toCYON];
1180 return [NSString stringWithUTF8String:cyon];
1181 } CYObjectiveCatch }
1183 - (NSUInteger) count { CYObjectiveTry {
1184 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1185 size_t size(JSPropertyNameArrayGetCount(names));
1186 JSPropertyNameArrayRelease(names);
1188 } CYObjectiveCatch }
1190 - (id) objectForKey:(id)key { CYObjectiveTry {
1191 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1192 if (JSValueIsUndefined(context_, value))
1194 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1195 } CYObjectiveCatch }
1197 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1198 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1199 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1200 JSPropertyNameArrayRelease(names);
1202 } CYObjectiveCatch }
1204 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1205 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1206 } CYObjectiveCatch }
1208 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1209 JSValueRef exception(NULL);
1210 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1211 CYThrow(context_, exception);
1212 } CYObjectiveCatch }
1216 @implementation CYJSArray
1218 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1219 if ((self = [super init]) != nil) {
1221 context_ = CYGetJSContext(context);
1222 //XXX:JSGlobalContextRetain(context_);
1223 JSValueProtect(context_, object_);
1225 } CYObjectiveCatch }
1227 - (void) dealloc { CYObjectiveTry {
1228 JSValueUnprotect(context_, object_);
1229 //XXX:JSGlobalContextRelease(context_);
1231 } CYObjectiveCatch }
1233 - (NSUInteger) count { CYObjectiveTry {
1234 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1235 } CYObjectiveCatch }
1237 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1238 size_t bounds([self count]);
1239 if (index >= bounds)
1240 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1241 JSValueRef exception(NULL);
1242 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1243 CYThrow(context_, exception);
1244 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1245 } CYObjectiveCatch }
1247 - (void) addObject:(id)object { CYObjectiveTry {
1248 JSValueRef exception(NULL);
1249 JSValueRef arguments[1];
1250 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1251 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1252 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1253 CYThrow(context_, exception);
1254 } CYObjectiveCatch }
1256 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1257 size_t bounds([self count] + 1);
1258 if (index >= bounds)
1259 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1260 JSValueRef exception(NULL);
1261 JSValueRef arguments[3];
1262 arguments[0] = CYCastJSValue(context_, index);
1263 arguments[1] = CYCastJSValue(context_, 0);
1264 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1265 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1266 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1267 CYThrow(context_, exception);
1268 } CYObjectiveCatch }
1270 - (void) removeLastObject { CYObjectiveTry {
1271 JSValueRef exception(NULL);
1272 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1273 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1274 CYThrow(context_, exception);
1275 } CYObjectiveCatch }
1277 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1278 size_t bounds([self count]);
1279 if (index >= bounds)
1280 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1281 JSValueRef exception(NULL);
1282 JSValueRef arguments[2];
1283 arguments[0] = CYCastJSValue(context_, index);
1284 arguments[1] = CYCastJSValue(context_, 1);
1285 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1286 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1287 CYThrow(context_, exception);
1288 } CYObjectiveCatch }
1290 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1291 size_t bounds([self count]);
1292 if (index >= bounds)
1293 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1294 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1295 } CYObjectiveCatch }
1299 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1303 JSObjectRef object_;
1311 // XXX: delete object_? ;(
1314 static CYInternal *Get(id self) {
1315 CYInternal *internal(NULL);
1316 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1317 // XXX: do something epic? ;P
1323 static CYInternal *Set(id self) {
1324 CYInternal *internal(NULL);
1325 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1326 if (internal == NULL) {
1327 internal = new CYInternal();
1328 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1331 // XXX: do something epic? ;P
1337 bool HasProperty(JSContextRef context, JSStringRef name) {
1338 if (object_ == NULL)
1340 return JSObjectHasProperty(context, object_, name);
1343 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1344 if (object_ == NULL)
1346 return CYGetProperty(context, object_, name);
1349 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1350 if (object_ == NULL)
1351 object_ = JSObjectMake(context, NULL, NULL);
1352 CYSetProperty(context, object_, name, value);
1356 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1357 Selector_privateData *internal(new Selector_privateData(sel));
1358 return JSObjectMake(context, Selector_, internal);
1361 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1362 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1363 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1364 return reinterpret_cast<SEL>(internal->value_);
1366 return CYCastPointer<SEL>(context, value);
1369 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1370 return (void *) [[NSAutoreleasePool alloc] init];
1371 } CYSadCatch(NULL) }
1373 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1374 return [(NSAutoreleasePool *) handle release];
1377 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1379 return Instance::Make(context, nil);
1380 if (Class _class = objc_getClass(name.data))
1381 return CYMakeInstance(context, _class, true);
1382 if (Protocol *protocol = objc_getProtocol(name.data))
1383 return CYMakeInstance(context, protocol, true);
1385 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1387 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1388 ffi_call(cif, function, value, values);
1391 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1392 switch (type->primitive) {
1393 // XXX: do something epic about blocks
1396 case sig::typename_P:
1397 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1400 case sig::selector_P:
1401 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1409 } CYSadCatch(false) }
1411 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1412 switch (type->primitive) {
1413 // XXX: do something epic about blocks
1416 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1417 JSValueRef value(CYCastJSValue(context, object));
1423 case sig::typename_P:
1424 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1426 case sig::selector_P:
1427 if (SEL sel = *reinterpret_cast<SEL *>(data))
1428 return CYMakeSelector(context, sel);
1432 return CYJSNull(context);
1436 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1438 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1439 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1442 #if OBJC_API_VERSION >= 2
1444 method_getReturnType(method, type, sizeof(type));
1446 const char *type(method_getTypeEncoding(method));
1452 // XXX: possibly use a more "awesome" check?
1456 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1458 return method_getTypeEncoding(method);
1460 const char *name(sel_getName(sel));
1461 size_t length(strlen(name));
1463 char keyed[length + 2];
1465 keyed[length + 1] = '\0';
1466 memcpy(keyed + 1, name, length);
1468 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1469 return entry->value_;
1474 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1475 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1477 JSContextRef context(internal->context_);
1479 size_t count(internal->cif_.nargs);
1480 JSValueRef values[count];
1482 for (size_t index(0); index != count; ++index)
1483 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1485 JSObjectRef _this(CYCastJSObject(context, values[0]));
1487 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1488 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1491 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1492 Message_privateData *internal(new Message_privateData(sel, type, imp));
1493 return JSObjectMake(context, Message_, internal);
1496 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1497 JSObjectRef function(CYCastJSObject(context, value));
1498 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1499 // XXX: see notes in Library.cpp about needing to leak
1500 return reinterpret_cast<IMP>(internal->GetValue());
1503 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1504 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1505 Class _class(internal->GetValue());
1508 const char *name(CYPoolCString(pool, context, property));
1510 if (SEL sel = sel_getUid(name))
1511 if (class_getInstanceMethod(_class, sel) != NULL)
1517 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1518 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1519 Class _class(internal->GetValue());
1522 const char *name(CYPoolCString(pool, context, property));
1524 if (SEL sel = sel_getUid(name))
1525 if (objc_method *method = class_getInstanceMethod(_class, sel))
1526 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1531 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1532 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1533 Class _class(internal->GetValue());
1536 const char *name(CYPoolCString(pool, context, property));
1538 SEL sel(sel_registerName(name));
1540 objc_method *method(class_getInstanceMethod(_class, sel));
1545 if (JSValueIsObjectOfClass(context, value, Message_)) {
1546 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1547 type = sig::Unparse(pool, &message->signature_);
1548 imp = reinterpret_cast<IMP>(message->GetValue());
1550 type = CYPoolTypeEncoding(pool, context, sel, method);
1551 imp = CYMakeMessage(context, value, type);
1555 method_setImplementation(method, imp);
1558 GSMethodList list(GSAllocMethodList(1));
1559 GSAppendMethodToList(list, sel, type, imp, YES);
1560 GSAddMethodList(_class, list, YES);
1561 GSFlushMethodCacheForClass(_class);
1563 class_addMethod(_class, sel, imp, type);
1570 #if 0 && OBJC_API_VERSION < 2
1571 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1572 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1573 Class _class(internal->GetValue());
1576 const char *name(CYPoolCString(pool, context, property));
1578 if (SEL sel = sel_getUid(name))
1579 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1580 objc_method_list list = {NULL, 1, {method}};
1581 class_removeMethods(_class, &list);
1589 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1590 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1591 Class _class(internal->GetValue());
1593 #if OBJC_API_VERSION >= 2
1595 objc_method **data(class_copyMethodList(_class, &size));
1596 for (size_t i(0); i != size; ++i)
1597 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1600 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1601 for (int i(0); i != methods->method_count; ++i)
1602 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1606 static bool CYHasImplicitProperties(Class _class) {
1607 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1608 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1610 return [_class cy$hasImplicitProperties];
1613 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1614 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1615 id self(internal->GetValue());
1617 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1621 NSString *name(CYCastNSString(pool, context, property));
1623 if (CYInternal *internal = CYInternal::Get(self))
1624 if (internal->HasProperty(context, property))
1627 Class _class(object_getClass(self));
1630 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1631 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1632 if ([self cy$hasProperty:name])
1634 } CYPoolCatch(false)
1636 const char *string(CYPoolCString(pool, context, name));
1639 if (class_getProperty(_class, string) != NULL)
1643 if (CYHasImplicitProperties(_class))
1644 if (SEL sel = sel_getUid(string))
1645 if (CYImplements(self, _class, sel, true))
1651 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1652 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1653 id self(internal->GetValue());
1655 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1656 return Internal::Make(context, self, object);
1659 NSString *name(CYCastNSString(pool, context, property));
1661 if (CYInternal *internal = CYInternal::Get(self))
1662 if (JSValueRef value = internal->GetProperty(context, property))
1666 if (NSObject *data = [self cy$getProperty:name])
1667 return CYCastJSValue(context, data);
1670 const char *string(CYPoolCString(pool, context, name));
1671 Class _class(object_getClass(self));
1674 if (objc_property_t property = class_getProperty(_class, string)) {
1675 PropertyAttributes attributes(property);
1676 SEL sel(sel_registerName(attributes.Getter()));
1677 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1681 if (CYHasImplicitProperties(_class))
1682 if (SEL sel = sel_getUid(string))
1683 if (CYImplements(self, _class, sel, true))
1684 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1689 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1690 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1691 id self(internal->GetValue());
1695 NSString *name(CYCastNSString(pool, context, property));
1696 NSObject *data(CYCastNSObject(pool, context, value));
1699 if ([self cy$setProperty:name to:data])
1703 const char *string(CYPoolCString(pool, context, name));
1704 Class _class(object_getClass(self));
1707 if (objc_property_t property = class_getProperty(_class, string)) {
1708 PropertyAttributes attributes(property);
1709 if (const char *setter = attributes.Setter()) {
1710 SEL sel(sel_registerName(setter));
1711 JSValueRef arguments[1] = {value};
1712 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1718 size_t length(strlen(string));
1720 char set[length + 5];
1726 if (string[0] != '\0') {
1727 set[3] = toupper(string[0]);
1728 memcpy(set + 4, string + 1, length - 1);
1731 set[length + 3] = ':';
1732 set[length + 4] = '\0';
1734 if (SEL sel = sel_getUid(set))
1735 if (CYImplements(self, _class, sel, false)) {
1736 JSValueRef arguments[1] = {value};
1737 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1740 if (CYInternal *internal = CYInternal::Set(self)) {
1741 internal->SetProperty(context, property, value);
1748 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1750 id self(internal->GetValue());
1753 NSString *name(CYCastNSString(NULL, context, property));
1754 return [self cy$deleteProperty:name];
1756 } CYCatch return /*XXX*/ NULL; }
1758 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1759 const char *name(sel_getName(method_getName(method)));
1760 if (strchr(name, ':') != NULL)
1763 const char *type(method_getTypeEncoding(method));
1764 if (type == NULL || *type == '\0' || *type == 'v')
1767 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1770 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1771 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1772 id self(internal->GetValue());
1775 Class _class(object_getClass(self));
1780 objc_property_t *data(class_copyPropertyList(_class, &size));
1781 for (size_t i(0); i != size; ++i)
1782 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1787 if (CYHasImplicitProperties(_class))
1788 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1789 #if OBJC_API_VERSION >= 2
1791 objc_method **data(class_copyMethodList(current, &size));
1792 for (size_t i(0); i != size; ++i)
1793 Instance_getPropertyNames_message(names, data[i]);
1796 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1797 for (int i(0); i != methods->method_count; ++i)
1798 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1803 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1804 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1805 [self cy$getPropertyNames:names inContext:context];
1809 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1810 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1811 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1815 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1816 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1817 Class _class(internal->GetValue());
1818 if (!CYIsClass(_class))
1821 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1822 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1823 // XXX: this isn't always safe
1824 return [linternal->GetValue() isKindOfClass:_class];
1830 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1831 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1834 id self(internal->GetValue());
1835 const char *name(CYPoolCString(pool, context, property));
1837 if (object_getInstanceVariable(self, name, NULL) != NULL)
1843 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1844 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1847 id self(internal->GetValue());
1848 const char *name(CYPoolCString(pool, context, property));
1850 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1851 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1852 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1853 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1859 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1860 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1863 id self(internal->GetValue());
1864 const char *name(CYPoolCString(pool, context, property));
1866 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1867 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1868 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1875 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1876 if (Class super = class_getSuperclass(_class))
1877 Internal_getPropertyNames_(super, names);
1879 #if OBJC_API_VERSION >= 2
1881 objc_ivar **data(class_copyIvarList(_class, &size));
1882 for (size_t i(0); i != size; ++i)
1883 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1886 if (objc_ivar_list *ivars = _class->ivars)
1887 for (int i(0); i != ivars->ivar_count; ++i)
1888 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1892 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1893 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1896 id self(internal->GetValue());
1897 Class _class(object_getClass(self));
1899 Internal_getPropertyNames_(_class, names);
1902 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1903 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1904 return internal->GetOwner();
1907 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1909 NSString *name(CYCastNSString(pool, context, property));
1910 if (Class _class = NSClassFromString(name))
1911 return CYMakeInstance(context, _class, true);
1915 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1917 size_t size(objc_getClassList(NULL, 0));
1918 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1921 size_t writ(objc_getClassList(data, size));
1924 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1930 for (size_t i(0); i != writ; ++i)
1931 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1937 while (Class _class = objc_next_class(&state))
1938 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1942 #if OBJC_API_VERSION >= 2
1943 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1944 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1947 const char *name(CYPoolCString(pool, context, property));
1949 const char **data(objc_copyClassNamesForImage(internal, &size));
1951 for (size_t i(0); i != size; ++i)
1952 if (strcmp(name, data[i]) == 0) {
1953 if (Class _class = objc_getClass(name)) {
1954 value = CYMakeInstance(context, _class, true);
1965 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1966 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1968 const char **data(objc_copyClassNamesForImage(internal, &size));
1969 for (size_t i(0); i != size; ++i)
1970 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1974 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1976 const char *name(CYPoolCString(pool, context, property));
1978 const char **data(objc_copyImageNames(&size));
1979 for (size_t i(0); i != size; ++i)
1980 if (strcmp(name, data[i]) == 0) {
1989 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1990 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1994 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1996 const char **data(objc_copyImageNames(&size));
1997 for (size_t i(0); i != size; ++i)
1998 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2003 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2005 const char *name(CYPoolCString(pool, context, property));
2006 if (Protocol *protocol = objc_getProtocol(name))
2007 return CYMakeInstance(context, protocol, true);
2011 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2012 #if OBJC_API_VERSION >= 2
2014 Protocol **data(objc_copyProtocolList(&size));
2015 for (size_t i(0); i != size; ++i)
2016 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2024 static bool stret(ffi_type *ffi_type) {
2025 return ffi_type->type == FFI_TYPE_STRUCT && (
2026 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2027 struct_forward_array[ffi_type->size] != 0
2032 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 {
2036 _class = object_getClass(self);
2040 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2041 imp = method_getImplementation(method);
2042 type = method_getTypeEncoding(method);
2047 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2049 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2050 type = CYPoolCString(pool, context, [method _typeString]);
2058 sig::Signature signature;
2059 sig::Parse(pool, &signature, type, &Structor_);
2062 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2066 if (stret(cif.rtype))
2067 imp = class_getMethodImplementation_stret(_class, _cmd);
2069 imp = class_getMethodImplementation(_class, _cmd);
2071 objc_super super = {self, _class};
2072 imp = objc_msg_lookup_super(&super, _cmd);
2076 void (*function)() = reinterpret_cast<void (*)()>(imp);
2077 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2080 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2082 throw CYJSError(context, "too few arguments to objc_msgSend");
2092 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2093 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2094 self = internal->GetValue();
2095 _class = internal->class_;;
2096 uninitialized = false;
2097 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2098 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2099 self = internal->GetValue();
2101 uninitialized = internal->IsUninitialized();
2103 internal->value_ = nil;
2105 self = CYCastNSObject(pool, context, arguments[0]);
2107 uninitialized = false;
2111 return CYJSNull(context);
2113 _cmd = CYCastSEL(context, arguments[1]);
2115 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2118 /* Hook: objc_registerClassPair {{{ */
2119 #if defined(__APPLE__) && defined(__arm__)
2120 // XXX: replace this with associated objects
2122 MSHook(void, CYDealloc, id self, SEL sel) {
2123 CYInternal *internal;
2124 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2125 if (internal != NULL)
2127 _CYDealloc(self, sel);
2130 MSHook(void, objc_registerClassPair, Class _class) {
2131 Class super(class_getSuperclass(_class));
2132 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2133 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2134 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2137 _objc_registerClassPair(_class);
2140 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2142 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2144 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2145 if (value == NULL || !CYIsClass(value))
2146 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2147 Class _class((Class) value);
2148 $objc_registerClassPair(_class);
2149 return CYJSUndefined(context);
2154 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2155 JSValueRef setup[count + 2];
2158 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2159 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2162 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2164 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2166 // XXX: handle Instance::Uninitialized?
2167 id self(CYCastNSObject(pool, context, _this));
2171 setup[1] = &internal->sel_;
2173 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2176 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2178 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2180 id self(CYCastNSObject(pool, context, arguments[0]));
2181 Class _class(CYCastClass(pool, context, arguments[1]));
2182 return cy::Super::Make(context, self, _class);
2185 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2187 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2189 const char *name(CYPoolCString(pool, context, arguments[0]));
2190 return CYMakeSelector(context, sel_registerName(name));
2193 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2195 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2196 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2197 return CYMakeInstance(context, self, false);
2200 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2201 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2202 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2205 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2206 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2207 Type_privateData *typical(internal->GetType());
2212 if (typical == NULL) {
2216 type = typical->type_;
2217 ffi = typical->ffi_;
2220 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2223 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2224 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2225 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2228 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2229 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2230 id self(internal->GetValue());
2231 if (!CYIsClass(self))
2232 return CYJSUndefined(context);
2233 return CYGetClassPrototype(context, self);
2236 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2237 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2238 id self(internal->GetValue());
2239 if (!CYIsClass(self))
2240 return CYJSUndefined(context);
2241 return Messages::Make(context, (Class) self);
2244 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2245 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2248 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2249 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2252 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2253 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2256 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2263 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2264 // XXX: check for support of cy$toJSON?
2265 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2267 } CYCatch return /*XXX*/ NULL; }
2270 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2271 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2274 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2275 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2276 } CYCatch return /*XXX*/ NULL; }
2279 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2280 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2283 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2284 // XXX: but... but... THIS ISN'T A POINTER! :(
2285 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2286 } CYCatch return /*XXX*/ NULL; }
2288 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2289 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2292 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2294 id value(internal->GetValue());
2296 return CYCastJSValue(context, "nil");
2299 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2300 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2302 } CYCatch return /*XXX*/ NULL; }
2304 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2305 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2306 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2309 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2310 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2313 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2314 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2315 const char *name(sel_getName(internal->GetValue()));
2318 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2319 return CYCastJSValue(context, CYJSString(context, string));
2321 } CYCatch return /*XXX*/ NULL; }
2323 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2325 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2328 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2329 SEL sel(internal->GetValue());
2331 objc_method *method;
2332 if (Class _class = CYCastClass(pool, context, arguments[0]))
2333 method = class_getInstanceMethod(_class, sel);
2337 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2338 return CYCastJSValue(context, CYJSString(type));
2340 return CYJSNull(context);
2343 static JSStaticValue Selector_staticValues[2] = {
2344 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2345 {NULL, NULL, NULL, 0}
2348 static JSStaticValue Instance_staticValues[5] = {
2349 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2350 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2351 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2352 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2353 {NULL, NULL, NULL, 0}
2356 static JSStaticFunction Instance_staticFunctions[6] = {
2357 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2358 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2359 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2360 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2361 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2362 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2366 static JSStaticFunction Internal_staticFunctions[2] = {
2367 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2371 static JSStaticFunction Selector_staticFunctions[5] = {
2372 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2373 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2374 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2375 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2379 static JSStaticFunction StringInstance_staticFunctions[2] = {
2380 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2381 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2385 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2386 apr_pool_t *pool(CYGetGlobalPool());
2388 Object_type = new(pool) Type_privateData("@");
2389 Selector_type = new(pool) Type_privateData(":");
2392 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2393 NSCFType_ = objc_getClass("NSCFType");
2394 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2395 NSZombie_ = objc_getClass("_NSZombie_");
2397 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2400 NSArray_ = objc_getClass("NSArray");
2401 NSDictionary_ = objc_getClass("NSDictionary");
2402 NSString_ = objc_getClass("NSString");
2403 Object_ = objc_getClass("Object");
2405 JSClassDefinition definition;
2407 definition = kJSClassDefinitionEmpty;
2408 definition.className = "Instance";
2409 definition.staticValues = Instance_staticValues;
2410 definition.staticFunctions = Instance_staticFunctions;
2411 definition.hasProperty = &Instance_hasProperty;
2412 definition.getProperty = &Instance_getProperty;
2413 definition.setProperty = &Instance_setProperty;
2414 definition.deleteProperty = &Instance_deleteProperty;
2415 definition.getPropertyNames = &Instance_getPropertyNames;
2416 definition.callAsConstructor = &Instance_callAsConstructor;
2417 definition.hasInstance = &Instance_hasInstance;
2418 definition.finalize = &CYFinalize;
2419 Instance_ = JSClassCreate(&definition);
2421 definition = kJSClassDefinitionEmpty;
2422 definition.className = "Internal";
2423 definition.staticFunctions = Internal_staticFunctions;
2424 definition.hasProperty = &Internal_hasProperty;
2425 definition.getProperty = &Internal_getProperty;
2426 definition.setProperty = &Internal_setProperty;
2427 definition.getPropertyNames = &Internal_getPropertyNames;
2428 definition.finalize = &CYFinalize;
2429 Internal_ = JSClassCreate(&definition);
2431 definition = kJSClassDefinitionEmpty;
2432 definition.className = "Message";
2433 definition.staticFunctions = cy::Functor::StaticFunctions;
2434 definition.callAsFunction = &Message_callAsFunction;
2435 definition.finalize = &CYFinalize;
2436 Message_ = JSClassCreate(&definition);
2438 definition = kJSClassDefinitionEmpty;
2439 definition.className = "Messages";
2440 definition.hasProperty = &Messages_hasProperty;
2441 definition.getProperty = &Messages_getProperty;
2442 definition.setProperty = &Messages_setProperty;
2443 #if 0 && OBJC_API_VERSION < 2
2444 definition.deleteProperty = &Messages_deleteProperty;
2446 definition.getPropertyNames = &Messages_getPropertyNames;
2447 definition.finalize = &CYFinalize;
2448 Messages_ = JSClassCreate(&definition);
2450 definition = kJSClassDefinitionEmpty;
2451 definition.className = "Selector";
2452 definition.staticValues = Selector_staticValues;
2453 definition.staticFunctions = Selector_staticFunctions;
2454 definition.callAsFunction = &Selector_callAsFunction;
2455 definition.finalize = &CYFinalize;
2456 Selector_ = JSClassCreate(&definition);
2458 definition = kJSClassDefinitionEmpty;
2459 definition.className = "StringInstance";
2460 definition.staticFunctions = StringInstance_staticFunctions;
2461 StringInstance_ = JSClassCreate(&definition);
2463 definition = kJSClassDefinitionEmpty;
2464 definition.className = "Super";
2465 definition.staticFunctions = Internal_staticFunctions;
2466 definition.finalize = &CYFinalize;
2467 Super_ = JSClassCreate(&definition);
2469 definition = kJSClassDefinitionEmpty;
2470 definition.className = "ObjectiveC::Classes";
2471 definition.getProperty = &ObjectiveC_Classes_getProperty;
2472 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2473 ObjectiveC_Classes_ = JSClassCreate(&definition);
2475 #if OBJC_API_VERSION >= 2
2476 definition = kJSClassDefinitionEmpty;
2477 definition.className = "ObjectiveC::Images";
2478 definition.getProperty = &ObjectiveC_Images_getProperty;
2479 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2480 ObjectiveC_Images_ = JSClassCreate(&definition);
2482 definition = kJSClassDefinitionEmpty;
2483 definition.className = "ObjectiveC::Image::Classes";
2484 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2485 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2486 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2489 definition = kJSClassDefinitionEmpty;
2490 definition.className = "ObjectiveC::Protocols";
2491 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2492 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2493 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2495 #if defined(__APPLE__) && defined(__arm__)
2496 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2500 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2504 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2505 JSObjectRef global(CYGetGlobalObject(context));
2506 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2507 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2508 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2510 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2511 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2513 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2514 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2516 #if OBJC_API_VERSION >= 2
2517 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2520 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2521 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2522 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2523 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2524 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2526 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2527 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2529 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2530 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2532 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2533 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2535 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2536 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2537 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2539 #if defined(__APPLE__) && defined(__arm__)
2540 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2543 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2545 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2546 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2547 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2550 static CYHooks CYObjectiveCHooks = {
2551 &CYObjectiveC_ExecuteStart,
2552 &CYObjectiveC_ExecuteEnd,
2553 &CYObjectiveC_RuntimeProperty,
2554 &CYObjectiveC_CallFunction,
2555 &CYObjectiveC_Initialize,
2556 &CYObjectiveC_SetupContext,
2557 &CYObjectiveC_PoolFFI,
2558 &CYObjectiveC_FromFFI,
2561 struct CYObjectiveC {
2563 hooks_ = &CYObjectiveCHooks;
2564 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2565 _assert(hooks_ != NULL);