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 Internal_;
238 static JSClassRef Message_;
239 static JSClassRef Messages_;
240 static JSClassRef Selector_;
241 static JSClassRef StringInstance_;
242 static JSClassRef Super_;
244 static JSClassRef ObjectiveC_Classes_;
245 static JSClassRef ObjectiveC_Constants_;
246 static JSClassRef ObjectiveC_Protocols_;
249 static JSClassRef ObjectiveC_Image_Classes_;
250 static JSClassRef ObjectiveC_Images_;
254 static Class NSCFBoolean_;
255 static Class NSCFType_;
256 static Class NSGenericDeallocHandler_;
257 static Class NSMessageBuilder_;
258 static Class NSZombie_;
260 static Class NSBoolNumber_;
263 static Class NSArray_;
264 static Class NSDictionary_;
265 static Class NSString_;
266 static Class Object_;
268 static Type_privateData *Object_type;
269 static Type_privateData *Selector_type;
271 Type_privateData *Instance::GetType() const {
275 Type_privateData *Selector_privateData::GetType() const {
276 return Selector_type;
279 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
281 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
283 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
285 JSObjectRef global(CYGetGlobalObject(context));
286 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
289 sprintf(label, "i%p", self);
290 CYJSString name(label);
292 JSValueRef value(CYGetProperty(context, cy, name));
293 if (!JSValueIsUndefined(context, value))
296 JSClassRef _class(NULL);
297 JSValueRef prototype;
299 if (self == NSArray_)
300 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
301 else if (self == NSDictionary_)
302 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
303 else if (self == NSString_)
304 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
306 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
308 JSObjectRef object(JSObjectMake(context, _class, NULL));
309 JSObjectSetPrototype(context, object, prototype);
310 CYSetProperty(context, cy, name, object);
315 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
316 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
317 if (_class == NSArray_)
319 if (Class super = class_getSuperclass(_class))
320 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
322 JSObjectSetPrototype(context, value, Array_prototype_);*/
326 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
327 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
331 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
332 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
336 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
337 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
338 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
342 Instance::~Instance() {
343 if ((flags_ & Transient) == 0)
344 // XXX: does this handle background threads correctly?
345 // XXX: this simply does not work on the console because I'm stupid
346 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
349 struct Message_privateData :
354 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
355 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
361 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
362 Instance::Flags flags;
365 flags = Instance::Transient;
367 flags = Instance::None;
368 object = [object retain];
371 return Instance::Make(context, object, flags);
374 @interface NSMethodSignature (Cycript)
375 - (NSString *) _typeString;
378 @interface NSObject (Cycript)
380 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
381 - (JSType) cy$JSType;
383 - (NSObject *) cy$toJSON:(NSString *)key;
384 - (NSString *) cy$toCYON;
385 - (NSString *) cy$toKey;
387 - (bool) cy$hasProperty:(NSString *)name;
388 - (NSObject *) cy$getProperty:(NSString *)name;
389 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
390 - (bool) cy$deleteProperty:(NSString *)name;
391 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
393 + (bool) cy$hasImplicitProperties;
398 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
401 NSString *CYCastNSCYON(id value) {
407 Class _class(object_getClass(value));
408 SEL sel(@selector(cy$toCYON));
410 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
411 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
412 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
413 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
414 string = [value cy$toCYON];
419 else if (value == NSZombie_)
420 string = @"_NSZombie_";
421 else if (_class == NSZombie_)
422 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
423 // XXX: frowny /in/ the pants
424 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
428 string = [NSString stringWithFormat:@"%@", value];
433 string = @"undefined";
440 struct PropertyAttributes {
445 const char *variable;
458 PropertyAttributes(objc_property_t property) :
470 name = property_getName(property);
471 const char *attributes(property_getAttributes(property));
473 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
475 case 'R': readonly = true; break;
476 case 'C': copy = true; break;
477 case '&': retain = true; break;
478 case 'N': nonatomic = true; break;
479 case 'G': getter_ = token + 1; break;
480 case 'S': setter_ = token + 1; break;
481 case 'V': variable = token + 1; break;
485 /*if (variable == NULL) {
486 variable = property_getName(property);
487 size_t size(strlen(variable));
488 char *name(new(pool_) char[size + 2]);
490 memcpy(name + 1, variable, size);
491 name[size + 1] = '\0';
496 const char *Getter() {
498 getter_ = apr_pstrdup(pool_, name);
502 const char *Setter() {
503 if (setter_ == NULL && !readonly) {
504 size_t length(strlen(name));
506 char *temp(new(pool_) char[length + 5]);
512 temp[3] = toupper(name[0]);
513 memcpy(temp + 4, name + 1, length - 1);
516 temp[length + 3] = ':';
517 temp[length + 4] = '\0';
528 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
529 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
534 @interface CYWebUndefined : NSObject {
537 + (CYWebUndefined *) undefined;
541 @implementation CYWebUndefined
543 + (CYWebUndefined *) undefined {
544 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
550 #define WebUndefined CYWebUndefined
553 /* Bridge: CYJSObject {{{ */
554 @interface CYJSObject : NSMutableDictionary {
556 JSContextRef context_;
559 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
561 - (NSObject *) cy$toJSON:(NSString *)key;
563 - (NSUInteger) count;
564 - (id) objectForKey:(id)key;
565 - (NSEnumerator *) keyEnumerator;
566 - (void) setObject:(id)object forKey:(id)key;
567 - (void) removeObjectForKey:(id)key;
571 /* Bridge: CYJSArray {{{ */
572 @interface CYJSArray : NSMutableArray {
574 JSContextRef context_;
577 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
579 - (NSUInteger) count;
580 - (id) objectAtIndex:(NSUInteger)index;
582 - (void) addObject:(id)anObject;
583 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
584 - (void) removeLastObject;
585 - (void) removeObjectAtIndex:(NSUInteger)index;
586 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
591 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
592 JSObjectRef Array(CYGetCachedObject(context, Array_s));
593 JSValueRef exception(NULL);
594 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
595 CYThrow(context, exception);
596 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
597 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
600 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
601 if (!JSValueIsObjectOfClass(context, object, Instance_))
602 return CYCastNSObject_(pool, context, object);
604 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
605 return internal->GetValue();
609 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
610 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
614 @interface NSBoolNumber : NSNumber {
619 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
623 switch (JSType type = JSValueGetType(context, value)) {
624 case kJSTypeUndefined:
625 object = [WebUndefined undefined];
635 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
638 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
644 object = CYCopyNSNumber(context, value);
649 object = CYCopyNSString(context, value);
654 // XXX: this might could be more efficient
655 object = CYCastNSObject(pool, context, (JSObjectRef) value);
660 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
667 return CYPoolRelease(pool, object);
669 return [object retain];
672 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
673 return CYNSObject(pool, context, value, true);
676 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
677 return CYNSObject(pool, context, value, false);
680 /* Bridge: NSArray {{{ */
681 @implementation NSArray (Cycript)
683 - (NSString *) cy$toCYON {
684 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
685 [json appendString:@"["];
689 for (id object in self) {
691 for (size_t index(0), count([self count]); index != count; ++index) {
692 id object([self objectAtIndex:index]);
695 [json appendString:@","];
698 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
699 [json appendString:CYCastNSCYON(object)];
701 [json appendString:@","];
706 [json appendString:@"]"];
710 - (bool) cy$hasProperty:(NSString *)name {
711 if ([name isEqualToString:@"length"])
714 size_t index(CYGetIndex(name));
715 if (index == _not(size_t) || index >= [self count])
716 return [super cy$hasProperty:name];
721 - (NSObject *) cy$getProperty:(NSString *)name {
722 if ([name isEqualToString:@"length"]) {
723 NSUInteger count([self count]);
725 return [NSNumber numberWithUnsignedInteger:count];
727 return [NSNumber numberWithUnsignedInt:count];
731 size_t index(CYGetIndex(name));
732 if (index == _not(size_t) || index >= [self count])
733 return [super cy$getProperty:name];
735 return [self objectAtIndex:index];
738 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
739 [super cy$getPropertyNames:names inContext:context];
741 for (size_t index(0), count([self count]); index != count; ++index) {
742 id object([self objectAtIndex:index]);
743 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
745 sprintf(name, "%zu", index);
746 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
751 + (bool) cy$hasImplicitProperties {
757 /* Bridge: NSBoolNumber {{{ */
759 @implementation NSBoolNumber (Cycript)
761 - (JSType) cy$JSType {
762 return kJSTypeBoolean;
765 - (NSObject *) cy$toJSON:(NSString *)key {
769 - (NSString *) cy$toCYON {
770 return [self boolValue] ? @"true" : @"false";
773 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
774 return CYCastJSValue(context, (bool) [self boolValue]);
780 /* Bridge: NSDictionary {{{ */
781 @implementation NSDictionary (Cycript)
783 - (NSString *) cy$toCYON {
784 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
785 [json appendString:@"{"];
789 for (NSObject *key in self) {
791 NSEnumerator *keys([self keyEnumerator]);
792 while (NSObject *key = [keys nextObject]) {
795 [json appendString:@","];
798 [json appendString:[key cy$toKey]];
799 [json appendString:@":"];
800 NSObject *object([self objectForKey:key]);
801 [json appendString:CYCastNSCYON(object)];
804 [json appendString:@"}"];
808 - (bool) cy$hasProperty:(NSString *)name {
809 return [self objectForKey:name] != nil;
812 - (NSObject *) cy$getProperty:(NSString *)name {
813 return [self objectForKey:name];
816 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
817 [super cy$getPropertyNames:names inContext:context];
820 for (NSObject *key in self) {
822 NSEnumerator *keys([self keyEnumerator]);
823 while (NSObject *key = [keys nextObject]) {
825 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
829 + (bool) cy$hasImplicitProperties {
835 /* Bridge: NSMutableArray {{{ */
836 @implementation NSMutableArray (Cycript)
838 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
839 if ([name isEqualToString:@"length"]) {
840 // XXX: is this not intelligent?
841 NSNumber *number(reinterpret_cast<NSNumber *>(value));
843 NSUInteger size([number unsignedIntegerValue]);
845 NSUInteger size([number unsignedIntValue]);
847 NSUInteger count([self count]);
849 [self removeObjectsInRange:NSMakeRange(size, count - size)];
850 else if (size != count) {
851 WebUndefined *undefined([WebUndefined undefined]);
852 for (size_t i(count); i != size; ++i)
853 [self addObject:undefined];
858 size_t index(CYGetIndex(name));
859 if (index == _not(size_t))
860 return [super cy$setProperty:name to:value];
862 id object(value ?: [NSNull null]);
864 size_t count([self count]);
866 [self replaceObjectAtIndex:index withObject:object];
868 if (index != count) {
869 WebUndefined *undefined([WebUndefined undefined]);
870 for (size_t i(count); i != index; ++i)
871 [self addObject:undefined];
874 [self addObject:object];
880 - (bool) cy$deleteProperty:(NSString *)name {
881 size_t index(CYGetIndex(name));
882 if (index == _not(size_t) || index >= [self count])
883 return [super cy$deleteProperty:name];
884 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
890 /* Bridge: NSMutableDictionary {{{ */
891 @implementation NSMutableDictionary (Cycript)
893 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
894 [self setObject:(value ?: [NSNull null]) forKey:name];
898 - (bool) cy$deleteProperty:(NSString *)name {
899 if ([self objectForKey:name] == nil)
902 [self removeObjectForKey:name];
909 /* Bridge: NSNumber {{{ */
910 @implementation NSNumber (Cycript)
912 - (JSType) cy$JSType {
914 // XXX: this just seems stupid
915 if ([self class] == NSCFBoolean_)
916 return kJSTypeBoolean;
918 return kJSTypeNumber;
921 - (NSObject *) cy$toJSON:(NSString *)key {
925 - (NSString *) cy$toCYON {
926 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
929 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
930 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
935 /* Bridge: NSNull {{{ */
936 @implementation NSNull (Cycript)
938 - (JSType) cy$JSType {
942 - (NSObject *) cy$toJSON:(NSString *)key {
946 - (NSString *) cy$toCYON {
952 /* Bridge: NSObject {{{ */
953 @implementation NSObject (Cycript)
955 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
956 return CYMakeInstance(context, self, false);
959 - (JSType) cy$JSType {
960 return kJSTypeObject;
963 - (NSObject *) cy$toJSON:(NSString *)key {
964 return [self description];
967 - (NSString *) cy$toCYON {
968 return [[self cy$toJSON:@""] cy$toCYON];
971 - (NSString *) cy$toKey {
972 return [self cy$toCYON];
975 - (bool) cy$hasProperty:(NSString *)name {
979 - (NSObject *) cy$getProperty:(NSString *)name {
983 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
987 - (bool) cy$deleteProperty:(NSString *)name {
991 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
994 + (bool) cy$hasImplicitProperties {
1000 /* Bridge: NSProxy {{{ */
1001 @implementation NSProxy (Cycript)
1003 - (NSObject *) cy$toJSON:(NSString *)key {
1004 return [self description];
1007 - (NSString *) cy$toCYON {
1008 return [[self cy$toJSON:@""] cy$toCYON];
1013 /* Bridge: NSString {{{ */
1014 @implementation NSString (Cycript)
1016 - (JSType) cy$JSType {
1017 return kJSTypeString;
1020 - (NSObject *) cy$toJSON:(NSString *)key {
1024 - (NSString *) cy$toCYON {
1025 std::ostringstream str;
1026 CYUTF8String string(CYCastUTF8String(self));
1027 CYStringify(str, string.data, string.size);
1028 std::string value(str.str());
1029 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1032 - (NSString *) cy$toKey {
1033 if (CYIsKey(CYCastUTF8String(self)))
1035 return [self cy$toCYON];
1038 - (bool) cy$hasProperty:(NSString *)name {
1039 if ([name isEqualToString:@"length"])
1042 size_t index(CYGetIndex(name));
1043 if (index == _not(size_t) || index >= [self length])
1044 return [super cy$hasProperty:name];
1049 - (NSObject *) cy$getProperty:(NSString *)name {
1050 if ([name isEqualToString:@"length"]) {
1051 NSUInteger count([self length]);
1053 return [NSNumber numberWithUnsignedInteger:count];
1055 return [NSNumber numberWithUnsignedInt:count];
1059 size_t index(CYGetIndex(name));
1060 if (index == _not(size_t) || index >= [self length])
1061 return [super cy$getProperty:name];
1063 return [self substringWithRange:NSMakeRange(index, 1)];
1066 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1067 [super cy$getPropertyNames:names inContext:context];
1069 for (size_t index(0), length([self length]); index != length; ++index) {
1071 sprintf(name, "%zu", index);
1072 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1076 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1077 + (bool) cy$hasImplicitProperties {
1083 /* Bridge: WebUndefined {{{ */
1084 @implementation WebUndefined (Cycript)
1086 - (JSType) cy$JSType {
1087 return kJSTypeUndefined;
1090 - (NSObject *) cy$toJSON:(NSString *)key {
1094 - (NSString *) cy$toCYON {
1095 return @"undefined";
1098 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1099 return CYJSUndefined(context);
1100 } CYObjectiveCatch }
1105 static bool CYIsClass(id self) {
1107 // XXX: this is a lame object_isClass
1108 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1110 return GSObjCIsClass(self);
1114 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1115 id self(CYCastNSObject(pool, context, value));
1116 if (CYIsClass(self))
1117 return (Class) self;
1118 throw CYJSError(context, "got something that is not a Class");
1122 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1124 size_t size(JSPropertyNameArrayGetCount(names));
1125 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1126 for (size_t index(0); index != size; ++index)
1127 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1131 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1133 return CYJSNull(context);
1134 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1135 return [value cy$JSValueInContext:context];
1137 return CYMakeInstance(context, value, false);
1138 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1140 @implementation CYJSObject
1142 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1143 if ((self = [super init]) != nil) {
1145 context_ = CYGetJSContext(context);
1146 //XXX:JSGlobalContextRetain(context_);
1147 JSValueProtect(context_, object_);
1149 } CYObjectiveCatch }
1151 - (void) dealloc { CYObjectiveTry {
1152 JSValueUnprotect(context_, object_);
1153 //XXX:JSGlobalContextRelease(context_);
1155 } CYObjectiveCatch }
1157 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1158 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1159 if (!CYIsCallable(context_, toJSON))
1160 return [super cy$toJSON:key];
1162 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1163 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1164 // XXX: do I really want an NSNull here?!
1165 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1167 } CYObjectiveCatch }
1169 - (NSString *) cy$toCYON { CYObjectiveTry {
1171 JSValueRef exception(NULL);
1172 const char *cyon(CYPoolCCYON(pool, context_, object_));
1173 CYThrow(context_, exception);
1175 return [super cy$toCYON];
1177 return [NSString stringWithUTF8String:cyon];
1178 } CYObjectiveCatch }
1180 - (NSUInteger) count { CYObjectiveTry {
1181 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1182 size_t size(JSPropertyNameArrayGetCount(names));
1183 JSPropertyNameArrayRelease(names);
1185 } CYObjectiveCatch }
1187 - (id) objectForKey:(id)key { CYObjectiveTry {
1188 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1189 if (JSValueIsUndefined(context_, value))
1191 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1192 } CYObjectiveCatch }
1194 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1195 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1196 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1197 JSPropertyNameArrayRelease(names);
1199 } CYObjectiveCatch }
1201 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1202 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1203 } CYObjectiveCatch }
1205 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1206 JSValueRef exception(NULL);
1207 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1208 CYThrow(context_, exception);
1209 } CYObjectiveCatch }
1213 @implementation CYJSArray
1215 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1216 if ((self = [super init]) != nil) {
1218 context_ = CYGetJSContext(context);
1219 //XXX:JSGlobalContextRetain(context_);
1220 JSValueProtect(context_, object_);
1222 } CYObjectiveCatch }
1224 - (void) dealloc { CYObjectiveTry {
1225 JSValueUnprotect(context_, object_);
1226 //XXX:JSGlobalContextRelease(context_);
1228 } CYObjectiveCatch }
1230 - (NSUInteger) count { CYObjectiveTry {
1231 return CYArrayLength(context_, object_);
1232 } CYObjectiveCatch }
1234 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1235 size_t bounds([self count]);
1236 if (index >= bounds)
1237 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1238 JSValueRef exception(NULL);
1239 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1240 CYThrow(context_, exception);
1241 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1242 } CYObjectiveCatch }
1244 - (void) addObject:(id)object { CYObjectiveTry {
1245 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1246 } CYObjectiveCatch }
1248 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1249 size_t bounds([self count] + 1);
1250 if (index >= bounds)
1251 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1252 JSValueRef exception(NULL);
1253 JSValueRef arguments[3];
1254 arguments[0] = CYCastJSValue(context_, index);
1255 arguments[1] = CYCastJSValue(context_, 0);
1256 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1257 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1258 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1259 CYThrow(context_, exception);
1260 } CYObjectiveCatch }
1262 - (void) removeLastObject { CYObjectiveTry {
1263 JSValueRef exception(NULL);
1264 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1265 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1266 CYThrow(context_, exception);
1267 } CYObjectiveCatch }
1269 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1270 size_t bounds([self count]);
1271 if (index >= bounds)
1272 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1273 JSValueRef exception(NULL);
1274 JSValueRef arguments[2];
1275 arguments[0] = CYCastJSValue(context_, index);
1276 arguments[1] = CYCastJSValue(context_, 1);
1277 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1278 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1279 CYThrow(context_, exception);
1280 } CYObjectiveCatch }
1282 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1283 size_t bounds([self count]);
1284 if (index >= bounds)
1285 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1286 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1287 } CYObjectiveCatch }
1291 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1295 JSObjectRef object_;
1303 // XXX: delete object_? ;(
1306 static CYInternal *Get(id self) {
1307 CYInternal *internal(NULL);
1308 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1309 // XXX: do something epic? ;P
1315 static CYInternal *Set(id self) {
1316 CYInternal *internal(NULL);
1317 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1318 if (internal == NULL) {
1319 internal = new CYInternal();
1320 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1323 // XXX: do something epic? ;P
1329 bool HasProperty(JSContextRef context, JSStringRef name) {
1330 if (object_ == NULL)
1332 return JSObjectHasProperty(context, object_, name);
1335 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1336 if (object_ == NULL)
1338 return CYGetProperty(context, object_, name);
1341 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1342 if (object_ == NULL)
1343 object_ = JSObjectMake(context, NULL, NULL);
1344 CYSetProperty(context, object_, name, value);
1348 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1349 Selector_privateData *internal(new Selector_privateData(sel));
1350 return JSObjectMake(context, Selector_, internal);
1353 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1354 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1355 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1356 return reinterpret_cast<SEL>(internal->value_);
1358 return CYCastPointer<SEL>(context, value);
1361 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1362 return (void *) [[NSAutoreleasePool alloc] init];
1363 } CYSadCatch(NULL) }
1365 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1366 return [(NSAutoreleasePool *) handle release];
1369 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1371 return Instance::Make(context, nil);
1372 if (Class _class = objc_getClass(name.data))
1373 return CYMakeInstance(context, _class, true);
1374 if (Protocol *protocol = objc_getProtocol(name.data))
1375 return CYMakeInstance(context, protocol, true);
1377 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1379 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1380 ffi_call(cif, function, value, values);
1383 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1384 switch (type->primitive) {
1385 // XXX: do something epic about blocks
1388 case sig::typename_P:
1389 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1392 case sig::selector_P:
1393 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1401 } CYSadCatch(false) }
1403 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1404 switch (type->primitive) {
1405 // XXX: do something epic about blocks
1408 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1409 JSValueRef value(CYCastJSValue(context, object));
1415 case sig::typename_P:
1416 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1418 case sig::selector_P:
1419 if (SEL sel = *reinterpret_cast<SEL *>(data))
1420 return CYMakeSelector(context, sel);
1424 return CYJSNull(context);
1428 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1430 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1431 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1434 #if OBJC_API_VERSION >= 2
1436 method_getReturnType(method, type, sizeof(type));
1438 const char *type(method_getTypeEncoding(method));
1444 // XXX: possibly use a more "awesome" check?
1448 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1450 return method_getTypeEncoding(method);
1452 const char *name(sel_getName(sel));
1453 size_t length(strlen(name));
1455 char keyed[length + 2];
1457 keyed[length + 1] = '\0';
1458 memcpy(keyed + 1, name, length);
1460 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1461 return entry->value_;
1466 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1467 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1469 JSContextRef context(internal->context_);
1471 size_t count(internal->cif_.nargs);
1472 JSValueRef values[count];
1474 for (size_t index(0); index != count; ++index)
1475 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1477 JSObjectRef _this(CYCastJSObject(context, values[0]));
1479 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1480 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1483 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1484 Message_privateData *internal(new Message_privateData(sel, type, imp));
1485 return JSObjectMake(context, Message_, internal);
1488 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1489 JSObjectRef function(CYCastJSObject(context, value));
1490 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1491 // XXX: see notes in Library.cpp about needing to leak
1492 return reinterpret_cast<IMP>(internal->GetValue());
1495 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1496 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1497 Class _class(internal->GetValue());
1500 const char *name(CYPoolCString(pool, context, property));
1502 if (SEL sel = sel_getUid(name))
1503 if (class_getInstanceMethod(_class, sel) != NULL)
1509 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1510 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1511 Class _class(internal->GetValue());
1514 const char *name(CYPoolCString(pool, context, property));
1516 if (SEL sel = sel_getUid(name))
1517 if (objc_method *method = class_getInstanceMethod(_class, sel))
1518 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1523 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1524 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1525 Class _class(internal->GetValue());
1528 const char *name(CYPoolCString(pool, context, property));
1530 SEL sel(sel_registerName(name));
1532 objc_method *method(class_getInstanceMethod(_class, sel));
1537 if (JSValueIsObjectOfClass(context, value, Message_)) {
1538 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1539 type = sig::Unparse(pool, &message->signature_);
1540 imp = reinterpret_cast<IMP>(message->GetValue());
1542 type = CYPoolTypeEncoding(pool, context, sel, method);
1543 imp = CYMakeMessage(context, value, type);
1547 method_setImplementation(method, imp);
1550 GSMethodList list(GSAllocMethodList(1));
1551 GSAppendMethodToList(list, sel, type, imp, YES);
1552 GSAddMethodList(_class, list, YES);
1553 GSFlushMethodCacheForClass(_class);
1555 class_addMethod(_class, sel, imp, type);
1562 #if 0 && OBJC_API_VERSION < 2
1563 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1564 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1565 Class _class(internal->GetValue());
1568 const char *name(CYPoolCString(pool, context, property));
1570 if (SEL sel = sel_getUid(name))
1571 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1572 objc_method_list list = {NULL, 1, {method}};
1573 class_removeMethods(_class, &list);
1581 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1582 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1583 Class _class(internal->GetValue());
1585 #if OBJC_API_VERSION >= 2
1587 objc_method **data(class_copyMethodList(_class, &size));
1588 for (size_t i(0); i != size; ++i)
1589 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1592 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1593 for (int i(0); i != methods->method_count; ++i)
1594 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1598 static bool CYHasImplicitProperties(Class _class) {
1599 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1600 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1602 return [_class cy$hasImplicitProperties];
1605 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1606 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1607 id self(internal->GetValue());
1609 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1613 NSString *name(CYCastNSString(pool, context, property));
1615 if (CYInternal *internal = CYInternal::Get(self))
1616 if (internal->HasProperty(context, property))
1619 Class _class(object_getClass(self));
1622 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1623 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1624 if ([self cy$hasProperty:name])
1626 } CYPoolCatch(false)
1628 const char *string(CYPoolCString(pool, context, name));
1631 if (class_getProperty(_class, string) != NULL)
1635 if (CYHasImplicitProperties(_class))
1636 if (SEL sel = sel_getUid(string))
1637 if (CYImplements(self, _class, sel, true))
1643 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1644 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1645 id self(internal->GetValue());
1647 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1648 return Internal::Make(context, self, object);
1651 NSString *name(CYCastNSString(pool, context, property));
1653 if (CYInternal *internal = CYInternal::Get(self))
1654 if (JSValueRef value = internal->GetProperty(context, property))
1658 if (NSObject *data = [self cy$getProperty:name])
1659 return CYCastJSValue(context, data);
1662 const char *string(CYPoolCString(pool, context, name));
1663 Class _class(object_getClass(self));
1666 if (objc_property_t property = class_getProperty(_class, string)) {
1667 PropertyAttributes attributes(property);
1668 SEL sel(sel_registerName(attributes.Getter()));
1669 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1673 if (CYHasImplicitProperties(_class))
1674 if (SEL sel = sel_getUid(string))
1675 if (CYImplements(self, _class, sel, true))
1676 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1681 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1682 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1683 id self(internal->GetValue());
1687 NSString *name(CYCastNSString(pool, context, property));
1688 NSObject *data(CYCastNSObject(pool, context, value));
1691 if ([self cy$setProperty:name to:data])
1695 const char *string(CYPoolCString(pool, context, name));
1696 Class _class(object_getClass(self));
1699 if (objc_property_t property = class_getProperty(_class, string)) {
1700 PropertyAttributes attributes(property);
1701 if (const char *setter = attributes.Setter()) {
1702 SEL sel(sel_registerName(setter));
1703 JSValueRef arguments[1] = {value};
1704 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1710 size_t length(strlen(string));
1712 char set[length + 5];
1718 if (string[0] != '\0') {
1719 set[3] = toupper(string[0]);
1720 memcpy(set + 4, string + 1, length - 1);
1723 set[length + 3] = ':';
1724 set[length + 4] = '\0';
1726 if (SEL sel = sel_getUid(set))
1727 if (CYImplements(self, _class, sel, false)) {
1728 JSValueRef arguments[1] = {value};
1729 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1732 if (CYInternal *internal = CYInternal::Set(self)) {
1733 internal->SetProperty(context, property, value);
1740 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1741 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1742 id self(internal->GetValue());
1745 NSString *name(CYCastNSString(NULL, context, property));
1746 return [self cy$deleteProperty:name];
1748 } CYCatch return /*XXX*/ NULL; }
1750 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1751 const char *name(sel_getName(method_getName(method)));
1752 if (strchr(name, ':') != NULL)
1755 const char *type(method_getTypeEncoding(method));
1756 if (type == NULL || *type == '\0' || *type == 'v')
1759 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1762 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1763 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1764 id self(internal->GetValue());
1767 Class _class(object_getClass(self));
1772 objc_property_t *data(class_copyPropertyList(_class, &size));
1773 for (size_t i(0); i != size; ++i)
1774 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1779 if (CYHasImplicitProperties(_class))
1780 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1781 #if OBJC_API_VERSION >= 2
1783 objc_method **data(class_copyMethodList(current, &size));
1784 for (size_t i(0); i != size; ++i)
1785 Instance_getPropertyNames_message(names, data[i]);
1788 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1789 for (int i(0); i != methods->method_count; ++i)
1790 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1795 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1796 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1797 [self cy$getPropertyNames:names inContext:context];
1801 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1802 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1803 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1807 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1808 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1809 Class _class(internal->GetValue());
1810 if (!CYIsClass(_class))
1813 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1814 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1815 // XXX: this isn't always safe
1816 return [linternal->GetValue() isKindOfClass:_class];
1822 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1823 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1826 id self(internal->GetValue());
1827 const char *name(CYPoolCString(pool, context, property));
1829 if (object_getInstanceVariable(self, name, NULL) != NULL)
1835 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1836 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1839 id self(internal->GetValue());
1840 const char *name(CYPoolCString(pool, context, property));
1842 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1843 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1844 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1845 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1851 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1852 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1855 id self(internal->GetValue());
1856 const char *name(CYPoolCString(pool, context, property));
1858 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1859 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1860 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1867 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1868 if (Class super = class_getSuperclass(_class))
1869 Internal_getPropertyNames_(super, names);
1871 #if OBJC_API_VERSION >= 2
1873 objc_ivar **data(class_copyIvarList(_class, &size));
1874 for (size_t i(0); i != size; ++i)
1875 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1878 if (objc_ivar_list *ivars = _class->ivars)
1879 for (int i(0); i != ivars->ivar_count; ++i)
1880 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1884 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1885 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1888 id self(internal->GetValue());
1889 Class _class(object_getClass(self));
1891 Internal_getPropertyNames_(_class, names);
1894 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1895 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1896 return internal->GetOwner();
1899 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1901 NSString *name(CYCastNSString(pool, context, property));
1902 if (Class _class = NSClassFromString(name))
1903 return CYMakeInstance(context, _class, true);
1907 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1909 size_t size(objc_getClassList(NULL, 0));
1910 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1913 size_t writ(objc_getClassList(data, size));
1916 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1922 for (size_t i(0); i != writ; ++i)
1923 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1929 while (Class _class = objc_next_class(&state))
1930 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1934 #if OBJC_API_VERSION >= 2
1935 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1936 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1939 const char *name(CYPoolCString(pool, context, property));
1941 const char **data(objc_copyClassNamesForImage(internal, &size));
1943 for (size_t i(0); i != size; ++i)
1944 if (strcmp(name, data[i]) == 0) {
1945 if (Class _class = objc_getClass(name)) {
1946 value = CYMakeInstance(context, _class, true);
1957 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1958 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1960 const char **data(objc_copyClassNamesForImage(internal, &size));
1961 for (size_t i(0); i != size; ++i)
1962 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1966 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1968 const char *name(CYPoolCString(pool, context, property));
1970 const char **data(objc_copyImageNames(&size));
1971 for (size_t i(0); i != size; ++i)
1972 if (strcmp(name, data[i]) == 0) {
1981 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1982 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1986 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1988 const char **data(objc_copyImageNames(&size));
1989 for (size_t i(0); i != size; ++i)
1990 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1995 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1997 const char *name(CYPoolCString(pool, context, property));
1998 if (Protocol *protocol = objc_getProtocol(name))
1999 return CYMakeInstance(context, protocol, true);
2003 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2004 #if OBJC_API_VERSION >= 2
2006 Protocol **data(objc_copyProtocolList(&size));
2007 for (size_t i(0); i != size; ++i)
2008 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2015 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2017 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2019 return Instance::Make(context, nil);
2023 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2024 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2028 static bool stret(ffi_type *ffi_type) {
2029 return ffi_type->type == FFI_TYPE_STRUCT && (
2030 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2031 struct_forward_array[ffi_type->size] != 0
2036 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 {
2040 _class = object_getClass(self);
2044 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2045 imp = method_getImplementation(method);
2046 type = method_getTypeEncoding(method);
2051 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2053 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2054 type = CYPoolCString(pool, context, [method _typeString]);
2062 sig::Signature signature;
2063 sig::Parse(pool, &signature, type, &Structor_);
2066 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2070 if (stret(cif.rtype))
2071 imp = class_getMethodImplementation_stret(_class, _cmd);
2073 imp = class_getMethodImplementation(_class, _cmd);
2075 objc_super super = {self, _class};
2076 imp = objc_msg_lookup_super(&super, _cmd);
2080 void (*function)() = reinterpret_cast<void (*)()>(imp);
2081 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2084 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2086 throw CYJSError(context, "too few arguments to objc_msgSend");
2096 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2097 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2098 self = internal->GetValue();
2099 _class = internal->class_;;
2100 uninitialized = false;
2101 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2102 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2103 self = internal->GetValue();
2105 uninitialized = internal->IsUninitialized();
2107 internal->value_ = nil;
2109 self = CYCastNSObject(pool, context, arguments[0]);
2111 uninitialized = false;
2115 return CYJSNull(context);
2117 _cmd = CYCastSEL(context, arguments[1]);
2119 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2122 /* Hook: objc_registerClassPair {{{ */
2123 #if defined(__APPLE__) && defined(__arm__) && 0
2124 // XXX: replace this with associated objects
2126 MSHook(void, CYDealloc, id self, SEL sel) {
2127 CYInternal *internal;
2128 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2129 if (internal != NULL)
2131 _CYDealloc(self, sel);
2134 MSHook(void, objc_registerClassPair, Class _class) {
2135 Class super(class_getSuperclass(_class));
2136 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2137 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2138 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2141 _objc_registerClassPair(_class);
2144 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2146 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2148 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2149 if (value == NULL || !CYIsClass(value))
2150 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2151 Class _class((Class) value);
2152 $objc_registerClassPair(_class);
2153 return CYJSUndefined(context);
2158 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2159 JSValueRef setup[count + 2];
2162 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2163 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2166 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2168 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2170 // XXX: handle Instance::Uninitialized?
2171 id self(CYCastNSObject(pool, context, _this));
2175 setup[1] = &internal->sel_;
2177 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2180 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2182 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2184 id self(CYCastNSObject(pool, context, arguments[0]));
2185 Class _class(CYCastClass(pool, context, arguments[1]));
2186 return cy::Super::Make(context, self, _class);
2189 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2191 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2193 const char *name(CYPoolCString(pool, context, arguments[0]));
2194 return CYMakeSelector(context, sel_registerName(name));
2197 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2199 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2200 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2201 return CYMakeInstance(context, self, false);
2204 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2205 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2206 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2209 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2210 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2211 Type_privateData *typical(internal->GetType());
2216 if (typical == NULL) {
2220 type = typical->type_;
2221 ffi = typical->ffi_;
2224 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2227 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2228 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2229 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2232 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2233 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2234 id self(internal->GetValue());
2235 if (!CYIsClass(self))
2236 return CYJSUndefined(context);
2237 return CYGetClassPrototype(context, self);
2240 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2241 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2242 id self(internal->GetValue());
2243 if (!CYIsClass(self))
2244 return CYJSUndefined(context);
2245 return Messages::Make(context, (Class) self);
2248 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2249 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2252 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2253 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2256 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2257 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2260 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2267 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2268 // XXX: check for support of cy$toJSON?
2269 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2271 } CYCatch return /*XXX*/ NULL; }
2274 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2275 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2278 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2279 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2280 } CYCatch return /*XXX*/ NULL; }
2283 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2284 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2287 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2288 // XXX: but... but... THIS ISN'T A POINTER! :(
2289 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2290 } CYCatch return /*XXX*/ NULL; }
2292 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2293 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2296 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2298 id value(internal->GetValue());
2300 return CYCastJSValue(context, "nil");
2303 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2304 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2306 } CYCatch return /*XXX*/ NULL; }
2308 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2309 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2310 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2313 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2314 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2317 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2318 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2319 const char *name(sel_getName(internal->GetValue()));
2322 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2323 return CYCastJSValue(context, CYJSString(context, string));
2325 } CYCatch return /*XXX*/ NULL; }
2327 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2329 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2332 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2333 SEL sel(internal->GetValue());
2335 objc_method *method;
2336 if (Class _class = CYCastClass(pool, context, arguments[0]))
2337 method = class_getInstanceMethod(_class, sel);
2341 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2342 return CYCastJSValue(context, CYJSString(type));
2344 return CYJSNull(context);
2347 static JSStaticValue Selector_staticValues[2] = {
2348 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2349 {NULL, NULL, NULL, 0}
2352 static JSStaticValue Instance_staticValues[5] = {
2353 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2354 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2355 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2356 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2357 {NULL, NULL, NULL, 0}
2360 static JSStaticFunction Instance_staticFunctions[6] = {
2361 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2362 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2363 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2364 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2365 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2366 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2370 static JSStaticFunction Internal_staticFunctions[2] = {
2371 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2375 static JSStaticFunction Selector_staticFunctions[5] = {
2376 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2377 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2378 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2379 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2383 static JSStaticFunction StringInstance_staticFunctions[2] = {
2384 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2385 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2389 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2390 apr_pool_t *pool(CYGetGlobalPool());
2392 Object_type = new(pool) Type_privateData("@");
2393 Selector_type = new(pool) Type_privateData(":");
2396 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2397 NSCFType_ = objc_getClass("NSCFType");
2398 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2399 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2400 NSZombie_ = objc_getClass("_NSZombie_");
2402 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2405 NSArray_ = objc_getClass("NSArray");
2406 NSDictionary_ = objc_getClass("NSDictionary");
2407 NSString_ = objc_getClass("NSString");
2408 Object_ = objc_getClass("Object");
2410 JSClassDefinition definition;
2412 definition = kJSClassDefinitionEmpty;
2413 definition.className = "Instance";
2414 definition.staticValues = Instance_staticValues;
2415 definition.staticFunctions = Instance_staticFunctions;
2416 definition.hasProperty = &Instance_hasProperty;
2417 definition.getProperty = &Instance_getProperty;
2418 definition.setProperty = &Instance_setProperty;
2419 definition.deleteProperty = &Instance_deleteProperty;
2420 definition.getPropertyNames = &Instance_getPropertyNames;
2421 definition.callAsConstructor = &Instance_callAsConstructor;
2422 definition.hasInstance = &Instance_hasInstance;
2423 definition.finalize = &CYFinalize;
2424 Instance_ = JSClassCreate(&definition);
2426 definition = kJSClassDefinitionEmpty;
2427 definition.className = "Internal";
2428 definition.staticFunctions = Internal_staticFunctions;
2429 definition.hasProperty = &Internal_hasProperty;
2430 definition.getProperty = &Internal_getProperty;
2431 definition.setProperty = &Internal_setProperty;
2432 definition.getPropertyNames = &Internal_getPropertyNames;
2433 definition.finalize = &CYFinalize;
2434 Internal_ = JSClassCreate(&definition);
2436 definition = kJSClassDefinitionEmpty;
2437 definition.className = "Message";
2438 definition.staticFunctions = cy::Functor::StaticFunctions;
2439 definition.callAsFunction = &Message_callAsFunction;
2440 definition.finalize = &CYFinalize;
2441 Message_ = JSClassCreate(&definition);
2443 definition = kJSClassDefinitionEmpty;
2444 definition.className = "Messages";
2445 definition.hasProperty = &Messages_hasProperty;
2446 definition.getProperty = &Messages_getProperty;
2447 definition.setProperty = &Messages_setProperty;
2448 #if 0 && OBJC_API_VERSION < 2
2449 definition.deleteProperty = &Messages_deleteProperty;
2451 definition.getPropertyNames = &Messages_getPropertyNames;
2452 definition.finalize = &CYFinalize;
2453 Messages_ = JSClassCreate(&definition);
2455 definition = kJSClassDefinitionEmpty;
2456 definition.className = "Selector";
2457 definition.staticValues = Selector_staticValues;
2458 definition.staticFunctions = Selector_staticFunctions;
2459 definition.callAsFunction = &Selector_callAsFunction;
2460 definition.finalize = &CYFinalize;
2461 Selector_ = JSClassCreate(&definition);
2463 definition = kJSClassDefinitionEmpty;
2464 definition.className = "StringInstance";
2465 definition.staticFunctions = StringInstance_staticFunctions;
2466 StringInstance_ = JSClassCreate(&definition);
2468 definition = kJSClassDefinitionEmpty;
2469 definition.className = "Super";
2470 definition.staticFunctions = Internal_staticFunctions;
2471 definition.finalize = &CYFinalize;
2472 Super_ = JSClassCreate(&definition);
2474 definition = kJSClassDefinitionEmpty;
2475 definition.className = "ObjectiveC::Classes";
2476 definition.getProperty = &ObjectiveC_Classes_getProperty;
2477 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2478 ObjectiveC_Classes_ = JSClassCreate(&definition);
2480 definition = kJSClassDefinitionEmpty;
2481 definition.className = "ObjectiveC::Constants";
2482 definition.getProperty = &ObjectiveC_Constants_getProperty;
2483 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2484 ObjectiveC_Constants_ = JSClassCreate(&definition);
2486 #if OBJC_API_VERSION >= 2
2487 definition = kJSClassDefinitionEmpty;
2488 definition.className = "ObjectiveC::Images";
2489 definition.getProperty = &ObjectiveC_Images_getProperty;
2490 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2491 ObjectiveC_Images_ = JSClassCreate(&definition);
2493 definition = kJSClassDefinitionEmpty;
2494 definition.className = "ObjectiveC::Image::Classes";
2495 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2496 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2497 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2500 definition = kJSClassDefinitionEmpty;
2501 definition.className = "ObjectiveC::Protocols";
2502 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2503 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2504 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2506 #if defined(__APPLE__) && defined(__arm__) && 0
2507 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2511 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2515 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2516 JSObjectRef global(CYGetGlobalObject(context));
2517 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2518 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2519 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2520 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2522 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2523 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2525 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2526 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2527 CYArrayPush(context, alls, protocols);
2529 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2530 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2531 CYArrayPush(context, alls, classes);
2533 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2534 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2535 CYArrayPush(context, alls, constants);
2537 #if OBJC_API_VERSION >= 2
2538 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2541 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2542 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2543 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2544 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2545 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2547 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2548 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2550 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2551 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2553 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2554 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2556 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2557 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2558 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2560 #if defined(__APPLE__) && defined(__arm__) && 0
2561 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2564 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2566 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2567 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2568 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2571 static CYHooks CYObjectiveCHooks = {
2572 &CYObjectiveC_ExecuteStart,
2573 &CYObjectiveC_ExecuteEnd,
2574 &CYObjectiveC_CallFunction,
2575 &CYObjectiveC_Initialize,
2576 &CYObjectiveC_SetupContext,
2577 &CYObjectiveC_PoolFFI,
2578 &CYObjectiveC_FromFFI,
2581 struct CYObjectiveC {
2583 hooks_ = &CYObjectiveCHooks;
2584 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2585 _assert(hooks_ != NULL);