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/>.
26 #include <Foundation/Foundation.h>
28 #include "ObjectiveC/Internal.hpp"
30 #include <objc/objc-api.h>
32 #include "cycript.hpp"
34 #include "ObjectiveC/Internal.hpp"
37 #include <CoreFoundation/CoreFoundation.h>
38 #include <JavaScriptCore/JSStringRefCF.h>
39 #include <WebKit/WebScriptObject.h>
40 #include <objc/runtime.h>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
51 #define CYObjectiveTry_(context) { \
52 JSContextRef context_(context); \
54 #define CYObjectiveTry { \
56 #define CYObjectiveCatch \
57 catch (const CYException &error) { \
58 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
64 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
66 #define CYPoolCatch(value) \
67 @catch (NSException *error) { \
68 _saved = [error retain]; \
69 throw CYJSError(context, CYCastJSValue(context, error)); \
74 [_saved autorelease]; \
80 #define CYSadCatch(value) \
81 @catch (NSException *error ) { \
82 throw CYJSError(context, CYCastJSValue(context, error)); \
87 #define class_getSuperclass GSObjCSuper
88 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
89 #define class_getName GSNameFromClass
91 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
93 #define ivar_getName(ivar) ((ivar)->ivar_name)
94 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
95 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
97 #define method_getName(method) ((method)->method_name)
98 #define method_getImplementation(method) ((method)->method_imp)
99 #define method_getTypeEncoding(method) ((method)->method_types)
100 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
103 #define objc_getClass GSClassFromName
105 #define objc_getProtocol GSProtocolFromName
107 #define object_getClass GSObjCClass
109 #define object_getInstanceVariable(object, name, value) ({ \
110 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
111 _assert(value != NULL); \
113 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
117 #define object_setIvar(object, ivar, value) ({ \
118 void *data = (value); \
119 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
122 #define protocol_getName(protocol) [(protocol) name]
125 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
127 /* Objective-C Pool Release {{{ */
128 apr_status_t CYPoolRelease_(void *data) {
129 id object(reinterpret_cast<id>(data));
134 id CYPoolRelease_(apr_pool_t *pool, id object) {
137 else if (pool == NULL)
138 return [object autorelease];
140 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
145 template <typename Type_>
146 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
147 return (Type_) CYPoolRelease_(pool, (id) object);
150 /* Objective-C Strings {{{ */
151 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
153 return [value UTF8String];
155 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
156 char *string(new(pool) char[size]);
157 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
158 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
163 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
165 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
168 return CYCopyJSString(CYPoolCString(pool, context, value));
172 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
175 // XXX: this definition scares me; is anyone using this?!
176 NSString *string([value description]);
177 return CYCopyJSString(context, string);
180 NSString *CYCopyNSString(const CYUTF8String &value) {
182 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
184 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
188 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
190 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
193 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
197 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
198 return CYCopyNSString(context, CYJSString(context, value));
201 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
202 return CYPoolRelease(pool, CYCopyNSString(value));
205 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
206 const char *name(sel_getName(sel));
207 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
210 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
211 return CYPoolRelease(pool, CYCopyNSString(context, value));
214 CYUTF8String CYCastUTF8String(NSString *value) {
215 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
216 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
220 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
222 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
223 if (exception == NULL)
225 *exception = CYCastJSValue(context, error);
228 size_t CYGetIndex(NSString *value) {
229 return CYGetIndex(CYCastUTF8String(value));
232 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
233 return CYGetOffset(CYPoolCString(pool, context, value), index);
236 static JSClassRef Instance_;
237 static JSClassRef ArrayInstance_;
238 static JSClassRef ObjectInstance_;
239 static JSClassRef StringInstance_;
241 static JSClassRef *Instances_[] = {
248 static JSClassRef Internal_;
249 static JSClassRef Message_;
250 static JSClassRef Messages_;
251 static JSClassRef Selector_;
252 static JSClassRef Super_;
254 static JSClassRef ObjectiveC_Classes_;
255 static JSClassRef ObjectiveC_Constants_;
256 static JSClassRef ObjectiveC_Protocols_;
259 static JSClassRef ObjectiveC_Image_Classes_;
260 static JSClassRef ObjectiveC_Images_;
264 static Class NSCFBoolean_;
265 static Class NSCFType_;
266 static Class NSGenericDeallocHandler_;
267 static Class NSMessageBuilder_;
268 static Class NSZombie_;
270 static Class NSBoolNumber_;
273 static Class NSArray_;
274 static Class NSDictionary_;
275 static Class NSString_;
276 static Class Object_;
278 static Type_privateData *Object_type;
279 static Type_privateData *Selector_type;
281 static bool CYValueIsObjectOfClassInstance(JSContextRef context, JSValueRef value) {
282 for (size_t i(0); i != sizeof(Instances_) / sizeof(Instances_[0]); ++i)
283 if (JSValueIsObjectOfClass(context, value, *Instances_[i]))
288 Type_privateData *Instance::GetType() const {
292 Type_privateData *Selector_privateData::GetType() const {
293 return Selector_type;
296 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
298 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
300 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
302 JSObjectRef global(CYGetGlobalObject(context));
303 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
306 sprintf(label, "i%p", self);
307 CYJSString name(label);
309 JSValueRef value(CYGetProperty(context, cy, name));
310 if (!JSValueIsUndefined(context, value))
313 JSClassRef _class(NULL);
314 JSValueRef prototype;
316 if (self == NSArray_)
317 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
318 else if (self == NSDictionary_)
319 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
320 else if (self == NSString_)
321 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
323 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
325 JSObjectRef object(JSObjectMake(context, _class, NULL));
326 JSObjectSetPrototype(context, object, prototype);
327 CYSetProperty(context, cy, name, object);
332 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
333 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
334 if (_class == NSArray_)
336 if (Class super = class_getSuperclass(_class))
337 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
339 JSObjectSetPrototype(context, value, Array_prototype_);*/
343 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
344 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
348 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
349 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
353 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
354 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
355 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
359 Instance::~Instance() {
360 if ((flags_ & Transient) == 0)
361 // XXX: does this handle background threads correctly?
362 // XXX: this simply does not work on the console because I'm stupid
363 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
366 struct Message_privateData :
371 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
372 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
378 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
379 Instance::Flags flags;
382 flags = Instance::Transient;
384 flags = Instance::None;
385 object = [object retain];
388 return Instance::Make(context, object, flags);
391 @interface NSMethodSignature (Cycript)
392 - (NSString *) _typeString;
395 @interface NSObject (Cycript)
397 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
398 - (JSType) cy$JSType;
400 - (NSObject *) cy$toJSON:(NSString *)key;
401 - (NSString *) cy$toCYON;
403 - (bool) cy$hasProperty:(NSString *)name;
404 - (NSObject *) cy$getProperty:(NSString *)name;
405 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
406 - (bool) cy$deleteProperty:(NSString *)name;
407 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
409 + (bool) cy$hasImplicitProperties;
415 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
418 NSString *CYCastNSCYON(id value) {
424 Class _class(object_getClass(value));
425 SEL sel(@selector(cy$toCYON));
427 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
428 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
429 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
430 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
431 string = [value cy$toCYON];
436 else if (value == NSZombie_)
437 string = @"_NSZombie_";
438 else if (_class == NSZombie_)
439 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
440 // XXX: frowny /in/ the pants
441 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
445 string = [NSString stringWithFormat:@"%@", value];
450 string = @"undefined";
457 struct PropertyAttributes {
462 const char *variable;
475 PropertyAttributes(objc_property_t property) :
487 name = property_getName(property);
488 const char *attributes(property_getAttributes(property));
490 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
492 case 'R': readonly = true; break;
493 case 'C': copy = true; break;
494 case '&': retain = true; break;
495 case 'N': nonatomic = true; break;
496 case 'G': getter_ = token + 1; break;
497 case 'S': setter_ = token + 1; break;
498 case 'V': variable = token + 1; break;
502 /*if (variable == NULL) {
503 variable = property_getName(property);
504 size_t size(strlen(variable));
505 char *name(new(pool_) char[size + 2]);
507 memcpy(name + 1, variable, size);
508 name[size + 1] = '\0';
513 const char *Getter() {
515 getter_ = apr_pstrdup(pool_, name);
519 const char *Setter() {
520 if (setter_ == NULL && !readonly) {
521 size_t length(strlen(name));
523 char *temp(new(pool_) char[length + 5]);
529 temp[3] = toupper(name[0]);
530 memcpy(temp + 4, name + 1, length - 1);
533 temp[length + 3] = ':';
534 temp[length + 4] = '\0';
545 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
546 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
551 @interface CYWebUndefined : NSObject {
554 + (CYWebUndefined *) undefined;
558 @implementation CYWebUndefined
560 + (CYWebUndefined *) undefined {
561 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
567 #define WebUndefined CYWebUndefined
570 /* Bridge: CYJSObject {{{ */
571 @interface CYJSObject : NSMutableDictionary {
573 JSContextRef context_;
576 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
578 - (NSObject *) cy$toJSON:(NSString *)key;
580 - (NSUInteger) count;
581 - (id) objectForKey:(id)key;
582 - (NSEnumerator *) keyEnumerator;
583 - (void) setObject:(id)object forKey:(id)key;
584 - (void) removeObjectForKey:(id)key;
588 /* Bridge: CYJSArray {{{ */
589 @interface CYJSArray : NSMutableArray {
591 JSContextRef context_;
594 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
596 - (NSUInteger) count;
597 - (id) objectAtIndex:(NSUInteger)index;
599 - (void) addObject:(id)anObject;
600 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
601 - (void) removeLastObject;
602 - (void) removeObjectAtIndex:(NSUInteger)index;
603 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
608 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
609 JSObjectRef Array(CYGetCachedObject(context, Array_s));
610 JSValueRef exception(NULL);
611 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
612 CYThrow(context, exception);
613 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
614 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
617 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
618 if (!CYValueIsObjectOfClassInstance(context, object))
619 return CYCastNSObject_(pool, context, object);
621 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
622 return internal->GetValue();
626 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
627 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
631 @interface NSBoolNumber : NSNumber {
636 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
640 switch (JSType type = JSValueGetType(context, value)) {
641 case kJSTypeUndefined:
642 object = [WebUndefined undefined];
652 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
655 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
661 object = CYCopyNSNumber(context, value);
666 object = CYCopyNSString(context, value);
671 // XXX: this might could be more efficient
672 object = CYCastNSObject(pool, context, (JSObjectRef) value);
677 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
684 return CYPoolRelease(pool, object);
686 return [object retain];
689 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
690 return CYNSObject(pool, context, value, true);
693 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
694 return CYNSObject(pool, context, value, false);
697 /* Bridge: NSArray {{{ */
698 @implementation NSArray (Cycript)
701 return [[self mutableCopy] autorelease];
704 - (NSString *) cy$toCYON {
705 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
706 [json appendString:@"@["];
710 for (id object in self) {
712 for (size_t index(0), count([self count]); index != count; ++index) {
713 id object([self objectAtIndex:index]);
716 [json appendString:@","];
719 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
720 [json appendString:CYCastNSCYON(object)];
722 [json appendString:@","];
727 [json appendString:@"]"];
731 - (bool) cy$hasProperty:(NSString *)name {
732 if ([name isEqualToString:@"length"])
735 size_t index(CYGetIndex(name));
736 if (index == _not(size_t) || index >= [self count])
737 return [super cy$hasProperty:name];
742 - (NSObject *) cy$getProperty:(NSString *)name {
743 if ([name isEqualToString:@"length"]) {
744 NSUInteger count([self count]);
746 return [NSNumber numberWithUnsignedInteger:count];
748 return [NSNumber numberWithUnsignedInt:count];
752 size_t index(CYGetIndex(name));
753 if (index == _not(size_t) || index >= [self count])
754 return [super cy$getProperty:name];
756 return [self objectAtIndex:index];
759 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
760 [super cy$getPropertyNames:names inContext:context];
762 for (size_t index(0), count([self count]); index != count; ++index) {
763 id object([self objectAtIndex:index]);
764 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
766 sprintf(name, "%zu", index);
767 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
772 + (bool) cy$hasImplicitProperties {
778 /* Bridge: NSBoolNumber {{{ */
780 @implementation NSBoolNumber (Cycript)
782 - (JSType) cy$JSType {
783 return kJSTypeBoolean;
786 - (NSObject *) cy$toJSON:(NSString *)key {
790 - (NSString *) cy$toCYON {
791 return [self boolValue] ? @"@true" : @"@false";
794 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
795 return CYCastJSValue(context, (bool) [self boolValue]);
801 /* Bridge: NSDictionary {{{ */
802 @implementation NSDictionary (Cycript)
805 return [[self mutableCopy] autorelease];
808 - (NSString *) cy$toCYON {
809 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
810 [json appendString:@"@{"];
814 for (NSObject *key in self) {
816 NSEnumerator *keys([self keyEnumerator]);
817 while (NSObject *key = [keys nextObject]) {
820 [json appendString:@","];
823 [json appendString:CYCastNSCYON(key)];
824 [json appendString:@":"];
825 NSObject *object([self objectForKey:key]);
826 [json appendString:CYCastNSCYON(object)];
829 [json appendString:@"}"];
833 - (bool) cy$hasProperty:(NSString *)name {
834 return [self objectForKey:name] != nil;
837 - (NSObject *) cy$getProperty:(NSString *)name {
838 return [self objectForKey:name];
841 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
842 [super cy$getPropertyNames:names inContext:context];
845 for (NSObject *key in self) {
847 NSEnumerator *keys([self keyEnumerator]);
848 while (NSObject *key = [keys nextObject]) {
850 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
854 + (bool) cy$hasImplicitProperties {
860 /* Bridge: NSMutableArray {{{ */
861 @implementation NSMutableArray (Cycript)
863 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
864 if ([name isEqualToString:@"length"]) {
865 // XXX: is this not intelligent?
866 NSNumber *number(reinterpret_cast<NSNumber *>(value));
868 NSUInteger size([number unsignedIntegerValue]);
870 NSUInteger size([number unsignedIntValue]);
872 NSUInteger count([self count]);
874 [self removeObjectsInRange:NSMakeRange(size, count - size)];
875 else if (size != count) {
876 WebUndefined *undefined([WebUndefined undefined]);
877 for (size_t i(count); i != size; ++i)
878 [self addObject:undefined];
883 size_t index(CYGetIndex(name));
884 if (index == _not(size_t))
885 return [super cy$setProperty:name to:value];
887 id object(value ?: [NSNull null]);
889 size_t count([self count]);
891 [self replaceObjectAtIndex:index withObject:object];
893 if (index != count) {
894 WebUndefined *undefined([WebUndefined undefined]);
895 for (size_t i(count); i != index; ++i)
896 [self addObject:undefined];
899 [self addObject:object];
905 - (bool) cy$deleteProperty:(NSString *)name {
906 size_t index(CYGetIndex(name));
907 if (index == _not(size_t) || index >= [self count])
908 return [super cy$deleteProperty:name];
909 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
915 /* Bridge: NSMutableDictionary {{{ */
916 @implementation NSMutableDictionary (Cycript)
918 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
919 [self setObject:(value ?: [NSNull null]) forKey:name];
923 - (bool) cy$deleteProperty:(NSString *)name {
924 if ([self objectForKey:name] == nil)
927 [self removeObjectForKey:name];
934 /* Bridge: NSNumber {{{ */
935 @implementation NSNumber (Cycript)
937 - (JSType) cy$JSType {
939 // XXX: this just seems stupid
940 if ([self class] == NSCFBoolean_)
941 return kJSTypeBoolean;
943 return kJSTypeNumber;
946 - (NSObject *) cy$toJSON:(NSString *)key {
950 - (NSString *) cy$toCYON {
951 return [self cy$JSType] != kJSTypeBoolean ? [NSString stringWithFormat:@"@%@", self] : [self boolValue] ? @"@true" : @"@false";
954 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
955 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
960 /* Bridge: NSNull {{{ */
961 @implementation NSNull (Cycript)
963 - (JSType) cy$JSType {
967 - (NSObject *) cy$toJSON:(NSString *)key {
971 - (NSString *) cy$toCYON {
977 /* Bridge: NSObject {{{ */
978 @implementation NSObject (Cycript)
984 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
988 - (JSType) cy$JSType {
989 return kJSTypeObject;
992 - (NSObject *) cy$toJSON:(NSString *)key {
993 return [self description];
996 - (NSString *) cy$toCYON {
997 return [[self cy$toJSON:@""] cy$toCYON];
1000 - (bool) cy$hasProperty:(NSString *)name {
1004 - (NSObject *) cy$getProperty:(NSString *)name {
1008 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1012 - (bool) cy$deleteProperty:(NSString *)name {
1016 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1019 + (bool) cy$hasImplicitProperties {
1025 /* Bridge: NSProxy {{{ */
1026 @implementation NSProxy (Cycript)
1028 - (NSObject *) cy$toJSON:(NSString *)key {
1029 return [self description];
1032 - (NSString *) cy$toCYON {
1033 return [[self cy$toJSON:@""] cy$toCYON];
1038 /* Bridge: NSString {{{ */
1039 @implementation NSString (Cycript)
1042 return [[self copy] autorelease];
1045 - (JSType) cy$JSType {
1046 return kJSTypeString;
1049 - (NSObject *) cy$toJSON:(NSString *)key {
1053 - (NSString *) cy$toCYON {
1054 std::ostringstream str;
1056 CYUTF8String string(CYCastUTF8String(self));
1057 CYStringify(str, string.data, string.size);
1058 std::string value(str.str());
1059 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1062 - (bool) cy$hasProperty:(NSString *)name {
1063 if ([name isEqualToString:@"length"])
1066 size_t index(CYGetIndex(name));
1067 if (index == _not(size_t) || index >= [self length])
1068 return [super cy$hasProperty:name];
1073 - (NSObject *) cy$getProperty:(NSString *)name {
1074 if ([name isEqualToString:@"length"]) {
1075 NSUInteger count([self length]);
1077 return [NSNumber numberWithUnsignedInteger:count];
1079 return [NSNumber numberWithUnsignedInt:count];
1083 size_t index(CYGetIndex(name));
1084 if (index == _not(size_t) || index >= [self length])
1085 return [super cy$getProperty:name];
1087 return [self substringWithRange:NSMakeRange(index, 1)];
1090 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1091 [super cy$getPropertyNames:names inContext:context];
1093 for (size_t index(0), length([self length]); index != length; ++index) {
1095 sprintf(name, "%zu", index);
1096 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1100 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1101 + (bool) cy$hasImplicitProperties {
1105 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1106 return CYCastJSValue(context, CYJSString(context, self));
1107 } CYObjectiveCatch }
1111 /* Bridge: WebUndefined {{{ */
1112 @implementation WebUndefined (Cycript)
1114 - (JSType) cy$JSType {
1115 return kJSTypeUndefined;
1118 - (NSObject *) cy$toJSON:(NSString *)key {
1122 - (NSString *) cy$toCYON {
1123 return @"undefined";
1126 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1127 return CYJSUndefined(context);
1128 } CYObjectiveCatch }
1133 static bool CYIsClass(id self) {
1135 // XXX: this is a lame object_isClass
1136 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1138 return GSObjCIsClass(self);
1142 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1143 id self(CYCastNSObject(pool, context, value));
1144 if (CYIsClass(self))
1145 return (Class) self;
1146 throw CYJSError(context, "got something that is not a Class");
1150 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1152 size_t size(JSPropertyNameArrayGetCount(names));
1153 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1154 for (size_t index(0); index != size; ++index)
1155 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1159 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1161 return CYJSNull(context);
1163 return CYMakeInstance(context, value, false);
1164 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1166 @implementation CYJSObject
1168 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1169 if ((self = [super init]) != nil) {
1171 context_ = CYGetJSContext(context);
1172 //XXX:JSGlobalContextRetain(context_);
1173 JSValueProtect(context_, object_);
1175 } CYObjectiveCatch }
1177 - (void) dealloc { CYObjectiveTry {
1178 JSValueUnprotect(context_, object_);
1179 //XXX:JSGlobalContextRelease(context_);
1181 } CYObjectiveCatch }
1183 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1184 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1185 if (!CYIsCallable(context_, toJSON))
1186 return [super cy$toJSON:key];
1188 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1189 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1190 // XXX: do I really want an NSNull here?!
1191 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1193 } CYObjectiveCatch }
1195 - (NSString *) cy$toCYON { CYObjectiveTry {
1197 JSValueRef exception(NULL);
1198 const char *cyon(CYPoolCCYON(pool, context_, object_));
1199 CYThrow(context_, exception);
1201 return [super cy$toCYON];
1203 return [NSString stringWithUTF8String:cyon];
1204 } CYObjectiveCatch }
1206 - (NSUInteger) count { CYObjectiveTry {
1207 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1208 size_t size(JSPropertyNameArrayGetCount(names));
1209 JSPropertyNameArrayRelease(names);
1211 } CYObjectiveCatch }
1213 - (id) objectForKey:(id)key { CYObjectiveTry {
1214 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1215 if (JSValueIsUndefined(context_, value))
1217 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1218 } CYObjectiveCatch }
1220 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1221 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1222 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1223 JSPropertyNameArrayRelease(names);
1225 } CYObjectiveCatch }
1227 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1228 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1229 } CYObjectiveCatch }
1231 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1232 JSValueRef exception(NULL);
1233 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1234 CYThrow(context_, exception);
1235 } CYObjectiveCatch }
1239 @implementation CYJSArray
1241 - (NSString *) cy$toCYON {
1243 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1246 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1247 if ((self = [super init]) != nil) {
1249 context_ = CYGetJSContext(context);
1250 //XXX:JSGlobalContextRetain(context_);
1251 JSValueProtect(context_, object_);
1253 } CYObjectiveCatch }
1255 - (void) dealloc { CYObjectiveTry {
1256 JSValueUnprotect(context_, object_);
1257 //XXX:JSGlobalContextRelease(context_);
1259 } CYObjectiveCatch }
1261 - (NSUInteger) count { CYObjectiveTry {
1262 return CYArrayLength(context_, object_);
1263 } CYObjectiveCatch }
1265 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1266 size_t bounds([self count]);
1267 if (index >= bounds)
1268 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1269 JSValueRef exception(NULL);
1270 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1271 CYThrow(context_, exception);
1272 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1273 } CYObjectiveCatch }
1275 - (void) addObject:(id)object { CYObjectiveTry {
1276 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1277 } CYObjectiveCatch }
1279 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1280 size_t bounds([self count] + 1);
1281 if (index >= bounds)
1282 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1283 JSValueRef exception(NULL);
1284 JSValueRef arguments[3];
1285 arguments[0] = CYCastJSValue(context_, index);
1286 arguments[1] = CYCastJSValue(context_, 0);
1287 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1288 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1289 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1290 CYThrow(context_, exception);
1291 } CYObjectiveCatch }
1293 - (void) removeLastObject { CYObjectiveTry {
1294 JSValueRef exception(NULL);
1295 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1296 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1297 CYThrow(context_, exception);
1298 } CYObjectiveCatch }
1300 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1301 size_t bounds([self count]);
1302 if (index >= bounds)
1303 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1304 JSValueRef exception(NULL);
1305 JSValueRef arguments[2];
1306 arguments[0] = CYCastJSValue(context_, index);
1307 arguments[1] = CYCastJSValue(context_, 1);
1308 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1309 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1310 CYThrow(context_, exception);
1311 } CYObjectiveCatch }
1313 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1314 size_t bounds([self count]);
1315 if (index >= bounds)
1316 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1317 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1318 } CYObjectiveCatch }
1322 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1326 JSObjectRef object_;
1334 // XXX: delete object_? ;(
1337 static CYInternal *Get(id self) {
1338 CYInternal *internal(NULL);
1339 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1340 // XXX: do something epic? ;P
1346 static CYInternal *Set(id self) {
1347 CYInternal *internal(NULL);
1348 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1349 if (internal == NULL) {
1350 internal = new CYInternal();
1351 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1354 // XXX: do something epic? ;P
1360 bool HasProperty(JSContextRef context, JSStringRef name) {
1361 if (object_ == NULL)
1363 return JSObjectHasProperty(context, object_, name);
1366 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1367 if (object_ == NULL)
1369 return CYGetProperty(context, object_, name);
1372 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1373 if (object_ == NULL)
1374 object_ = JSObjectMake(context, NULL, NULL);
1375 CYSetProperty(context, object_, name, value);
1379 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1380 Selector_privateData *internal(new Selector_privateData(sel));
1381 return JSObjectMake(context, Selector_, internal);
1384 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1385 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1386 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1387 return reinterpret_cast<SEL>(internal->value_);
1389 return CYCastPointer<SEL>(context, value);
1392 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1393 return (void *) [[NSAutoreleasePool alloc] init];
1394 } CYSadCatch(NULL) }
1396 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1397 return [(NSAutoreleasePool *) handle release];
1400 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1402 return Instance::Make(context, nil);
1403 if (Class _class = objc_getClass(name.data))
1404 return CYMakeInstance(context, _class, true);
1405 if (Protocol *protocol = objc_getProtocol(name.data))
1406 return CYMakeInstance(context, protocol, true);
1408 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1410 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1411 ffi_call(cif, function, value, values);
1414 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1415 switch (type->primitive) {
1416 // XXX: do something epic about blocks
1419 case sig::typename_P:
1420 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1423 case sig::selector_P:
1424 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1432 } CYSadCatch(false) }
1434 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1435 switch (type->primitive) {
1436 // XXX: do something epic about blocks
1439 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1440 JSValueRef value(CYCastJSValue(context, object));
1446 case sig::typename_P:
1447 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1449 case sig::selector_P:
1450 if (SEL sel = *reinterpret_cast<SEL *>(data))
1451 return CYMakeSelector(context, sel);
1455 return CYJSNull(context);
1459 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1461 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1462 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1465 #if OBJC_API_VERSION >= 2
1467 method_getReturnType(method, type, sizeof(type));
1469 const char *type(method_getTypeEncoding(method));
1475 // XXX: possibly use a more "awesome" check?
1479 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1481 return method_getTypeEncoding(method);
1483 const char *name(sel_getName(sel));
1484 size_t length(strlen(name));
1486 char keyed[length + 2];
1488 keyed[length + 1] = '\0';
1489 memcpy(keyed + 1, name, length);
1491 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1492 return entry->value_;
1497 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1498 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1500 JSContextRef context(internal->context_);
1502 size_t count(internal->cif_.nargs);
1503 JSValueRef values[count];
1505 for (size_t index(0); index != count; ++index)
1506 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1508 JSObjectRef _this(CYCastJSObject(context, values[0]));
1510 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1511 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1514 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1515 Message_privateData *internal(new Message_privateData(sel, type, imp));
1516 return JSObjectMake(context, Message_, internal);
1519 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1520 JSObjectRef function(CYCastJSObject(context, value));
1521 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1522 // XXX: see notes in Library.cpp about needing to leak
1523 return reinterpret_cast<IMP>(internal->GetValue());
1526 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1527 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1528 Class _class(internal->GetValue());
1531 const char *name(CYPoolCString(pool, context, property));
1533 if (SEL sel = sel_getUid(name))
1534 if (class_getInstanceMethod(_class, sel) != NULL)
1540 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1541 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1542 Class _class(internal->GetValue());
1545 const char *name(CYPoolCString(pool, context, property));
1547 if (SEL sel = sel_getUid(name))
1548 if (objc_method *method = class_getInstanceMethod(_class, sel))
1549 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1554 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1555 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1556 Class _class(internal->GetValue());
1559 const char *name(CYPoolCString(pool, context, property));
1561 SEL sel(sel_registerName(name));
1563 objc_method *method(class_getInstanceMethod(_class, sel));
1568 if (JSValueIsObjectOfClass(context, value, Message_)) {
1569 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1570 type = sig::Unparse(pool, &message->signature_);
1571 imp = reinterpret_cast<IMP>(message->GetValue());
1573 type = CYPoolTypeEncoding(pool, context, sel, method);
1574 imp = CYMakeMessage(context, value, type);
1578 method_setImplementation(method, imp);
1581 GSMethodList list(GSAllocMethodList(1));
1582 GSAppendMethodToList(list, sel, type, imp, YES);
1583 GSAddMethodList(_class, list, YES);
1584 GSFlushMethodCacheForClass(_class);
1586 class_addMethod(_class, sel, imp, type);
1593 #if 0 && OBJC_API_VERSION < 2
1594 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1595 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1596 Class _class(internal->GetValue());
1599 const char *name(CYPoolCString(pool, context, property));
1601 if (SEL sel = sel_getUid(name))
1602 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1603 objc_method_list list = {NULL, 1, {method}};
1604 class_removeMethods(_class, &list);
1612 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1613 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1614 Class _class(internal->GetValue());
1616 #if OBJC_API_VERSION >= 2
1618 objc_method **data(class_copyMethodList(_class, &size));
1619 for (size_t i(0); i != size; ++i)
1620 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1623 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1624 for (int i(0); i != methods->method_count; ++i)
1625 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1629 static bool CYHasImplicitProperties(Class _class) {
1630 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1631 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1633 return [_class cy$hasImplicitProperties];
1636 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1637 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1638 id self(internal->GetValue());
1640 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1644 NSString *name(CYCastNSString(pool, context, property));
1646 if (CYInternal *internal = CYInternal::Get(self))
1647 if (internal->HasProperty(context, property))
1650 Class _class(object_getClass(self));
1653 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1654 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1655 if ([self cy$hasProperty:name])
1657 } CYPoolCatch(false)
1659 const char *string(CYPoolCString(pool, context, name));
1662 if (class_getProperty(_class, string) != NULL)
1666 if (CYHasImplicitProperties(_class))
1667 if (SEL sel = sel_getUid(string))
1668 if (CYImplements(self, _class, sel, true))
1674 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1675 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1676 id self(internal->GetValue());
1678 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1679 return Internal::Make(context, self, object);
1682 NSString *name(CYCastNSString(pool, context, property));
1684 if (CYInternal *internal = CYInternal::Get(self))
1685 if (JSValueRef value = internal->GetProperty(context, property))
1689 if (NSObject *data = [self cy$getProperty:name])
1690 return CYCastJSValue(context, data);
1693 const char *string(CYPoolCString(pool, context, name));
1694 Class _class(object_getClass(self));
1697 if (objc_property_t property = class_getProperty(_class, string)) {
1698 PropertyAttributes attributes(property);
1699 SEL sel(sel_registerName(attributes.Getter()));
1700 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1704 if (CYHasImplicitProperties(_class))
1705 if (SEL sel = sel_getUid(string))
1706 if (CYImplements(self, _class, sel, true))
1707 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1712 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1713 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1714 id self(internal->GetValue());
1718 NSString *name(CYCastNSString(pool, context, property));
1719 NSObject *data(CYCastNSObject(pool, context, value));
1722 if ([self cy$setProperty:name to:data])
1726 const char *string(CYPoolCString(pool, context, name));
1727 Class _class(object_getClass(self));
1730 if (objc_property_t property = class_getProperty(_class, string)) {
1731 PropertyAttributes attributes(property);
1732 if (const char *setter = attributes.Setter()) {
1733 SEL sel(sel_registerName(setter));
1734 JSValueRef arguments[1] = {value};
1735 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1741 size_t length(strlen(string));
1743 char set[length + 5];
1749 if (string[0] != '\0') {
1750 set[3] = toupper(string[0]);
1751 memcpy(set + 4, string + 1, length - 1);
1754 set[length + 3] = ':';
1755 set[length + 4] = '\0';
1757 if (SEL sel = sel_getUid(set))
1758 if (CYImplements(self, _class, sel, false)) {
1759 JSValueRef arguments[1] = {value};
1760 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1763 if (CYInternal *internal = CYInternal::Set(self)) {
1764 internal->SetProperty(context, property, value);
1771 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1772 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1773 id self(internal->GetValue());
1776 NSString *name(CYCastNSString(NULL, context, property));
1777 return [self cy$deleteProperty:name];
1779 } CYCatch return /*XXX*/ NULL; }
1781 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1782 const char *name(sel_getName(method_getName(method)));
1783 if (strchr(name, ':') != NULL)
1786 const char *type(method_getTypeEncoding(method));
1787 if (type == NULL || *type == '\0' || *type == 'v')
1790 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1793 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1794 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1795 id self(internal->GetValue());
1798 Class _class(object_getClass(self));
1803 objc_property_t *data(class_copyPropertyList(_class, &size));
1804 for (size_t i(0); i != size; ++i)
1805 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1810 if (CYHasImplicitProperties(_class))
1811 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1812 #if OBJC_API_VERSION >= 2
1814 objc_method **data(class_copyMethodList(current, &size));
1815 for (size_t i(0); i != size; ++i)
1816 Instance_getPropertyNames_message(names, data[i]);
1819 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1820 for (int i(0); i != methods->method_count; ++i)
1821 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1826 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1827 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1828 [self cy$getPropertyNames:names inContext:context];
1832 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1833 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1834 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1838 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1839 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1840 Class _class(internal->GetValue());
1841 if (!CYIsClass(_class))
1844 if (CYValueIsObjectOfClassInstance(context, instance)) {
1845 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1846 // XXX: this isn't always safe
1847 return [linternal->GetValue() isKindOfClass:_class];
1853 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1855 throw CYJSError(context, "incorrect number of arguments to Instance");
1857 id value(CYCastNSObject(pool, context, arguments[0]));
1859 value = [NSNull null];
1860 return CYCastJSValue(context, [value cy$box]);
1863 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1864 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1867 id self(internal->GetValue());
1868 const char *name(CYPoolCString(pool, context, property));
1870 if (object_getInstanceVariable(self, name, NULL) != NULL)
1876 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1877 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1880 id self(internal->GetValue());
1881 const char *name(CYPoolCString(pool, context, property));
1883 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1884 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1885 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1886 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1892 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1893 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1896 id self(internal->GetValue());
1897 const char *name(CYPoolCString(pool, context, property));
1899 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1900 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1901 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1908 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1909 if (Class super = class_getSuperclass(_class))
1910 Internal_getPropertyNames_(super, names);
1912 #if OBJC_API_VERSION >= 2
1914 objc_ivar **data(class_copyIvarList(_class, &size));
1915 for (size_t i(0); i != size; ++i)
1916 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1919 if (objc_ivar_list *ivars = _class->ivars)
1920 for (int i(0); i != ivars->ivar_count; ++i)
1921 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1925 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1926 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1929 id self(internal->GetValue());
1930 Class _class(object_getClass(self));
1932 Internal_getPropertyNames_(_class, names);
1935 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1936 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1937 return internal->GetOwner();
1940 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1942 NSString *name(CYCastNSString(pool, context, property));
1943 if (Class _class = NSClassFromString(name))
1944 return CYMakeInstance(context, _class, true);
1948 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1950 size_t size(objc_getClassList(NULL, 0));
1951 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1954 size_t writ(objc_getClassList(data, size));
1957 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1963 for (size_t i(0); i != writ; ++i)
1964 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1970 while (Class _class = objc_next_class(&state))
1971 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1975 #if OBJC_API_VERSION >= 2
1976 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1977 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1980 const char *name(CYPoolCString(pool, context, property));
1982 const char **data(objc_copyClassNamesForImage(internal, &size));
1984 for (size_t i(0); i != size; ++i)
1985 if (strcmp(name, data[i]) == 0) {
1986 if (Class _class = objc_getClass(name)) {
1987 value = CYMakeInstance(context, _class, true);
1998 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1999 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2001 const char **data(objc_copyClassNamesForImage(internal, &size));
2002 for (size_t i(0); i != size; ++i)
2003 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2007 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2009 const char *name(CYPoolCString(pool, context, property));
2011 const char **data(objc_copyImageNames(&size));
2012 for (size_t i(0); i != size; ++i)
2013 if (strcmp(name, data[i]) == 0) {
2022 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2023 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2027 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2029 const char **data(objc_copyImageNames(&size));
2030 for (size_t i(0); i != size; ++i)
2031 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2036 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2038 const char *name(CYPoolCString(pool, context, property));
2039 if (Protocol *protocol = objc_getProtocol(name))
2040 return CYMakeInstance(context, protocol, true);
2044 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2045 #if OBJC_API_VERSION >= 2
2047 Protocol **data(objc_copyProtocolList(&size));
2048 for (size_t i(0); i != size; ++i)
2049 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2056 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2058 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2060 return Instance::Make(context, nil);
2064 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2065 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2069 static bool stret(ffi_type *ffi_type) {
2070 return ffi_type->type == FFI_TYPE_STRUCT && (
2071 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2072 struct_forward_array[ffi_type->size] != 0
2077 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 {
2081 _class = object_getClass(self);
2085 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2086 imp = method_getImplementation(method);
2087 type = method_getTypeEncoding(method);
2092 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2094 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2095 type = CYPoolCString(pool, context, [method _typeString]);
2103 sig::Signature signature;
2104 sig::Parse(pool, &signature, type, &Structor_);
2106 size_t used(count + 3);
2107 if (used > signature.count) {
2108 sig::Element *elements(new (pool) sig::Element[used]);
2109 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2111 for (size_t index(signature.count); index != used; ++index) {
2112 sig::Element *element(&elements[index]);
2113 element->name = NULL;
2114 element->offset = _not(size_t);
2116 sig::Type *type(new (pool) sig::Type);
2117 memset(type, 0, sizeof(*type));
2118 type->primitive = sig::object_P;
2119 element->type = type;
2122 signature.elements = elements;
2123 signature.count = used;
2127 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2131 if (stret(cif.rtype))
2132 imp = class_getMethodImplementation_stret(_class, _cmd);
2134 imp = class_getMethodImplementation(_class, _cmd);
2136 objc_super super = {self, _class};
2137 imp = objc_msg_lookup_super(&super, _cmd);
2141 void (*function)() = reinterpret_cast<void (*)()>(imp);
2142 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2145 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2147 throw CYJSError(context, "too few arguments to objc_msgSend");
2157 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2158 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2159 self = internal->GetValue();
2160 _class = internal->class_;;
2161 uninitialized = false;
2162 } else if (CYValueIsObjectOfClassInstance(context, arguments[0])) {
2163 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2164 self = internal->GetValue();
2166 uninitialized = internal->IsUninitialized();
2168 internal->value_ = nil;
2170 self = CYCastNSObject(pool, context, arguments[0]);
2172 uninitialized = false;
2176 return CYJSNull(context);
2178 _cmd = CYCastSEL(context, arguments[1]);
2180 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2183 /* Hook: objc_registerClassPair {{{ */
2184 #if defined(__APPLE__) && defined(__arm__) && 0
2185 // XXX: replace this with associated objects
2187 MSHook(void, CYDealloc, id self, SEL sel) {
2188 CYInternal *internal;
2189 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2190 if (internal != NULL)
2192 _CYDealloc(self, sel);
2195 MSHook(void, objc_registerClassPair, Class _class) {
2196 Class super(class_getSuperclass(_class));
2197 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2198 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2199 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2202 _objc_registerClassPair(_class);
2205 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2207 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2209 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2210 if (value == NULL || !CYIsClass(value))
2211 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2212 Class _class((Class) value);
2213 $objc_registerClassPair(_class);
2214 return CYJSUndefined(context);
2219 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2220 JSValueRef setup[count + 2];
2223 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2224 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2227 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2229 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2231 // XXX: handle Instance::Uninitialized?
2232 id self(CYCastNSObject(pool, context, _this));
2236 setup[1] = &internal->sel_;
2238 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2241 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2243 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2245 id self(CYCastNSObject(pool, context, arguments[0]));
2246 Class _class(CYCastClass(pool, context, arguments[1]));
2247 return cy::Super::Make(context, self, _class);
2250 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2252 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2254 const char *name(CYPoolCString(pool, context, arguments[0]));
2255 return CYMakeSelector(context, sel_registerName(name));
2258 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2260 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2261 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2262 return CYMakeInstance(context, self, false);
2265 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2266 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2267 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2270 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2271 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2272 Type_privateData *typical(internal->GetType());
2277 if (typical == NULL) {
2281 type = typical->type_;
2282 ffi = typical->ffi_;
2285 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2288 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2289 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2290 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2293 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2294 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2295 id self(internal->GetValue());
2296 if (!CYIsClass(self))
2297 return CYJSUndefined(context);
2298 return CYGetClassPrototype(context, self);
2301 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2302 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2303 id self(internal->GetValue());
2304 if (!CYIsClass(self))
2305 return CYJSUndefined(context);
2306 return Messages::Make(context, (Class) self);
2309 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2310 if (!CYValueIsObjectOfClassInstance(context, _this))
2313 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2314 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2317 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2318 if (!CYValueIsObjectOfClassInstance(context, _this))
2321 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2328 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2329 // XXX: check for support of cy$toJSON?
2330 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2332 } CYCatch return /*XXX*/ NULL; }
2334 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2335 if (!CYValueIsObjectOfClassInstance(context, _this))
2338 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2339 id value(internal->GetValue());
2341 if (![value respondsToSelector:@selector(cy$JSValueInContext:)])
2344 if (JSValueRef result = [value cy$JSValueInContext:context])
2348 } CYCatch return /*XXX*/ NULL; }
2350 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2351 if (!CYValueIsObjectOfClassInstance(context, _this))
2354 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2355 // XXX: but... but... THIS ISN'T A POINTER! :(
2356 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2357 } CYCatch return /*XXX*/ NULL; }
2359 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2360 if (!CYValueIsObjectOfClassInstance(context, _this))
2363 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2364 id value(internal->GetValue());
2367 return CYCastJSValue(context, "nil");
2370 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2371 return CYCastJSValue(context, CYJSString(context, [value description]));
2373 } CYCatch return /*XXX*/ NULL; }
2375 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2376 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2377 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2380 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2381 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2384 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2385 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2386 const char *name(sel_getName(internal->GetValue()));
2389 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2390 return CYCastJSValue(context, CYJSString(context, string));
2392 } CYCatch return /*XXX*/ NULL; }
2394 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2396 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2399 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2400 SEL sel(internal->GetValue());
2402 objc_method *method;
2403 if (Class _class = CYCastClass(pool, context, arguments[0]))
2404 method = class_getInstanceMethod(_class, sel);
2408 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2409 return CYCastJSValue(context, CYJSString(type));
2411 return CYJSNull(context);
2414 static JSStaticValue Selector_staticValues[2] = {
2415 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2416 {NULL, NULL, NULL, 0}
2419 static JSStaticValue Instance_staticValues[5] = {
2420 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2421 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2422 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2423 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2424 {NULL, NULL, NULL, 0}
2427 static JSStaticFunction Instance_staticFunctions[7] = {
2428 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2429 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2430 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2431 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2432 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2433 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2437 static JSStaticFunction Internal_staticFunctions[2] = {
2438 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2442 static JSStaticFunction Selector_staticFunctions[5] = {
2443 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2444 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2445 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2446 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2450 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2451 apr_pool_t *pool(CYGetGlobalPool());
2453 Object_type = new(pool) Type_privateData("@");
2454 Selector_type = new(pool) Type_privateData(":");
2457 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2458 NSCFType_ = objc_getClass("NSCFType");
2459 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2460 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2461 NSZombie_ = objc_getClass("_NSZombie_");
2463 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2466 NSArray_ = objc_getClass("NSArray");
2467 NSDictionary_ = objc_getClass("NSDictionary");
2468 NSString_ = objc_getClass("NSString");
2469 Object_ = objc_getClass("Object");
2471 JSClassDefinition definition;
2473 definition = kJSClassDefinitionEmpty;
2474 definition.className = "Instance";
2475 definition.staticValues = Instance_staticValues;
2476 definition.staticFunctions = Instance_staticFunctions;
2477 definition.hasProperty = &Instance_hasProperty;
2478 definition.getProperty = &Instance_getProperty;
2479 definition.setProperty = &Instance_setProperty;
2480 definition.deleteProperty = &Instance_deleteProperty;
2481 definition.getPropertyNames = &Instance_getPropertyNames;
2482 definition.callAsConstructor = &Instance_callAsConstructor;
2483 definition.hasInstance = &Instance_hasInstance;
2484 definition.finalize = &CYFinalize;
2485 Instance_ = JSClassCreate(&definition);
2487 definition.className = "ArrayInstance";
2488 ArrayInstance_ = JSClassCreate(&definition);
2490 definition.className = "ObjectInstance";
2491 ObjectInstance_ = JSClassCreate(&definition);
2493 definition.className = "StringInstance";
2494 StringInstance_ = JSClassCreate(&definition);
2496 definition = kJSClassDefinitionEmpty;
2497 definition.className = "Internal";
2498 definition.staticFunctions = Internal_staticFunctions;
2499 definition.hasProperty = &Internal_hasProperty;
2500 definition.getProperty = &Internal_getProperty;
2501 definition.setProperty = &Internal_setProperty;
2502 definition.getPropertyNames = &Internal_getPropertyNames;
2503 definition.finalize = &CYFinalize;
2504 Internal_ = JSClassCreate(&definition);
2506 definition = kJSClassDefinitionEmpty;
2507 definition.className = "Message";
2508 definition.staticFunctions = cy::Functor::StaticFunctions;
2509 definition.callAsFunction = &Message_callAsFunction;
2510 definition.finalize = &CYFinalize;
2511 Message_ = JSClassCreate(&definition);
2513 definition = kJSClassDefinitionEmpty;
2514 definition.className = "Messages";
2515 definition.hasProperty = &Messages_hasProperty;
2516 definition.getProperty = &Messages_getProperty;
2517 definition.setProperty = &Messages_setProperty;
2518 #if 0 && OBJC_API_VERSION < 2
2519 definition.deleteProperty = &Messages_deleteProperty;
2521 definition.getPropertyNames = &Messages_getPropertyNames;
2522 definition.finalize = &CYFinalize;
2523 Messages_ = JSClassCreate(&definition);
2525 definition = kJSClassDefinitionEmpty;
2526 definition.className = "Selector";
2527 definition.staticValues = Selector_staticValues;
2528 definition.staticFunctions = Selector_staticFunctions;
2529 definition.callAsFunction = &Selector_callAsFunction;
2530 definition.finalize = &CYFinalize;
2531 Selector_ = JSClassCreate(&definition);
2533 definition = kJSClassDefinitionEmpty;
2534 definition.className = "Super";
2535 definition.staticFunctions = Internal_staticFunctions;
2536 definition.finalize = &CYFinalize;
2537 Super_ = JSClassCreate(&definition);
2539 definition = kJSClassDefinitionEmpty;
2540 definition.className = "ObjectiveC::Classes";
2541 definition.getProperty = &ObjectiveC_Classes_getProperty;
2542 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2543 ObjectiveC_Classes_ = JSClassCreate(&definition);
2545 definition = kJSClassDefinitionEmpty;
2546 definition.className = "ObjectiveC::Constants";
2547 definition.getProperty = &ObjectiveC_Constants_getProperty;
2548 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2549 ObjectiveC_Constants_ = JSClassCreate(&definition);
2551 #if OBJC_API_VERSION >= 2
2552 definition = kJSClassDefinitionEmpty;
2553 definition.className = "ObjectiveC::Images";
2554 definition.getProperty = &ObjectiveC_Images_getProperty;
2555 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2556 ObjectiveC_Images_ = JSClassCreate(&definition);
2558 definition = kJSClassDefinitionEmpty;
2559 definition.className = "ObjectiveC::Image::Classes";
2560 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2561 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2562 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2565 definition = kJSClassDefinitionEmpty;
2566 definition.className = "ObjectiveC::Protocols";
2567 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2568 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2569 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2571 #if defined(__APPLE__) && defined(__arm__) && 0
2572 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2576 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2580 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2581 JSObjectRef global(CYGetGlobalObject(context));
2582 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2583 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2584 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2585 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2587 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2588 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2590 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2591 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2592 CYArrayPush(context, alls, protocols);
2594 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2595 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2596 CYArrayPush(context, alls, classes);
2598 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2599 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2600 CYArrayPush(context, alls, constants);
2602 #if OBJC_API_VERSION >= 2
2603 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2606 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2607 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2608 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2609 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2611 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2612 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2614 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2615 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2616 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2617 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2618 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2620 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2621 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2622 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2623 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2624 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2626 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2627 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2628 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2629 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2630 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2632 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2633 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2634 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2636 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2637 CYSetProperty(context, Instance, CYJSString("box"), box);
2639 #if defined(__APPLE__) && defined(__arm__) && 0
2640 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2643 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2645 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2646 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2647 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2650 static CYHooks CYObjectiveCHooks = {
2651 &CYObjectiveC_ExecuteStart,
2652 &CYObjectiveC_ExecuteEnd,
2653 &CYObjectiveC_CallFunction,
2654 &CYObjectiveC_Initialize,
2655 &CYObjectiveC_SetupContext,
2656 &CYObjectiveC_PoolFFI,
2657 &CYObjectiveC_FromFFI,
2660 struct CYObjectiveC {
2662 hooks_ = &CYObjectiveCHooks;
2663 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2664 _assert(hooks_ != NULL);