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 Super_;
243 static JSClassRef ObjectiveC_Classes_;
244 static JSClassRef ObjectiveC_Constants_;
245 static JSClassRef ObjectiveC_Protocols_;
248 static JSClassRef ObjectiveC_Image_Classes_;
249 static JSClassRef ObjectiveC_Images_;
253 static Class NSCFBoolean_;
254 static Class NSCFType_;
255 static Class NSGenericDeallocHandler_;
256 static Class NSMessageBuilder_;
257 static Class NSZombie_;
259 static Class NSBoolNumber_;
262 static Class NSArray_;
263 static Class NSDictionary_;
264 static Class NSString_;
265 static Class Object_;
267 static Type_privateData *Object_type;
268 static Type_privateData *Selector_type;
270 Type_privateData *Instance::GetType() const {
274 Type_privateData *Selector_privateData::GetType() const {
275 return Selector_type;
278 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
280 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
282 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
284 JSObjectRef global(CYGetGlobalObject(context));
285 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
288 sprintf(label, "i%p", self);
289 CYJSString name(label);
291 JSValueRef value(CYGetProperty(context, cy, name));
292 if (!JSValueIsUndefined(context, value))
295 JSClassRef _class(NULL);
296 JSValueRef prototype;
298 if (self == NSArray_)
299 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
300 else if (self == NSDictionary_)
301 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
302 else if (self == NSString_)
303 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
305 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
307 JSObjectRef object(JSObjectMake(context, _class, NULL));
308 JSObjectSetPrototype(context, object, prototype);
309 CYSetProperty(context, cy, name, object);
314 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
315 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
316 if (_class == NSArray_)
318 if (Class super = class_getSuperclass(_class))
319 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
321 JSObjectSetPrototype(context, value, Array_prototype_);*/
325 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
326 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
330 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
331 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
335 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
336 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
337 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
341 Instance::~Instance() {
342 if ((flags_ & Transient) == 0)
343 // XXX: does this handle background threads correctly?
344 // XXX: this simply does not work on the console because I'm stupid
345 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
348 struct Message_privateData :
353 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
354 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
360 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
361 Instance::Flags flags;
364 flags = Instance::Transient;
366 flags = Instance::None;
367 object = [object retain];
370 return Instance::Make(context, object, flags);
373 @interface NSMethodSignature (Cycript)
374 - (NSString *) _typeString;
377 @interface NSObject (Cycript)
379 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
380 - (JSType) cy$JSType;
382 - (NSObject *) cy$toJSON:(NSString *)key;
383 - (NSString *) cy$toCYON;
384 - (NSString *) cy$toKey;
386 - (bool) cy$hasProperty:(NSString *)name;
387 - (NSObject *) cy$getProperty:(NSString *)name;
388 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
389 - (bool) cy$deleteProperty:(NSString *)name;
390 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
392 + (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)
684 return [[self mutableCopy] autorelease];
687 - (NSString *) cy$toCYON {
688 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
689 [json appendString:@"@["];
693 for (id object in self) {
695 for (size_t index(0), count([self count]); index != count; ++index) {
696 id object([self objectAtIndex:index]);
699 [json appendString:@","];
702 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
703 [json appendString:CYCastNSCYON(object)];
705 [json appendString:@","];
710 [json appendString:@"]"];
714 - (bool) cy$hasProperty:(NSString *)name {
715 if ([name isEqualToString:@"length"])
718 size_t index(CYGetIndex(name));
719 if (index == _not(size_t) || index >= [self count])
720 return [super cy$hasProperty:name];
725 - (NSObject *) cy$getProperty:(NSString *)name {
726 if ([name isEqualToString:@"length"]) {
727 NSUInteger count([self count]);
729 return [NSNumber numberWithUnsignedInteger:count];
731 return [NSNumber numberWithUnsignedInt:count];
735 size_t index(CYGetIndex(name));
736 if (index == _not(size_t) || index >= [self count])
737 return [super cy$getProperty:name];
739 return [self objectAtIndex:index];
742 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
743 [super cy$getPropertyNames:names inContext:context];
745 for (size_t index(0), count([self count]); index != count; ++index) {
746 id object([self objectAtIndex:index]);
747 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
749 sprintf(name, "%zu", index);
750 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
755 + (bool) cy$hasImplicitProperties {
761 /* Bridge: NSBoolNumber {{{ */
763 @implementation NSBoolNumber (Cycript)
765 - (JSType) cy$JSType {
766 return kJSTypeBoolean;
769 - (NSObject *) cy$toJSON:(NSString *)key {
773 - (NSString *) cy$toCYON {
774 return [self boolValue] ? @"@true" : @"@false";
777 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
778 return CYCastJSValue(context, (bool) [self boolValue]);
784 /* Bridge: NSDictionary {{{ */
785 @implementation NSDictionary (Cycript)
788 return [[self mutableCopy] autorelease];
791 - (NSString *) cy$toCYON {
792 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
793 [json appendString:@"@{"];
797 for (NSObject *key in self) {
799 NSEnumerator *keys([self keyEnumerator]);
800 while (NSObject *key = [keys nextObject]) {
803 [json appendString:@","];
806 [json appendString:[key cy$toKey]];
807 [json appendString:@":"];
808 NSObject *object([self objectForKey:key]);
809 [json appendString:CYCastNSCYON(object)];
812 [json appendString:@"}"];
816 - (bool) cy$hasProperty:(NSString *)name {
817 return [self objectForKey:name] != nil;
820 - (NSObject *) cy$getProperty:(NSString *)name {
821 return [self objectForKey:name];
824 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
825 [super cy$getPropertyNames:names inContext:context];
828 for (NSObject *key in self) {
830 NSEnumerator *keys([self keyEnumerator]);
831 while (NSObject *key = [keys nextObject]) {
833 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
837 + (bool) cy$hasImplicitProperties {
843 /* Bridge: NSMutableArray {{{ */
844 @implementation NSMutableArray (Cycript)
846 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
847 if ([name isEqualToString:@"length"]) {
848 // XXX: is this not intelligent?
849 NSNumber *number(reinterpret_cast<NSNumber *>(value));
851 NSUInteger size([number unsignedIntegerValue]);
853 NSUInteger size([number unsignedIntValue]);
855 NSUInteger count([self count]);
857 [self removeObjectsInRange:NSMakeRange(size, count - size)];
858 else if (size != count) {
859 WebUndefined *undefined([WebUndefined undefined]);
860 for (size_t i(count); i != size; ++i)
861 [self addObject:undefined];
866 size_t index(CYGetIndex(name));
867 if (index == _not(size_t))
868 return [super cy$setProperty:name to:value];
870 id object(value ?: [NSNull null]);
872 size_t count([self count]);
874 [self replaceObjectAtIndex:index withObject:object];
876 if (index != count) {
877 WebUndefined *undefined([WebUndefined undefined]);
878 for (size_t i(count); i != index; ++i)
879 [self addObject:undefined];
882 [self addObject:object];
888 - (bool) cy$deleteProperty:(NSString *)name {
889 size_t index(CYGetIndex(name));
890 if (index == _not(size_t) || index >= [self count])
891 return [super cy$deleteProperty:name];
892 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
898 /* Bridge: NSMutableDictionary {{{ */
899 @implementation NSMutableDictionary (Cycript)
901 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
902 [self setObject:(value ?: [NSNull null]) forKey:name];
906 - (bool) cy$deleteProperty:(NSString *)name {
907 if ([self objectForKey:name] == nil)
910 [self removeObjectForKey:name];
917 /* Bridge: NSNumber {{{ */
918 @implementation NSNumber (Cycript)
920 - (JSType) cy$JSType {
922 // XXX: this just seems stupid
923 if ([self class] == NSCFBoolean_)
924 return kJSTypeBoolean;
926 return kJSTypeNumber;
929 - (NSObject *) cy$toJSON:(NSString *)key {
933 - (NSString *) cy$toCYON {
934 return [self cy$JSType] != kJSTypeBoolean ? [NSString stringWithFormat:@"@%@", self] : [self boolValue] ? @"@true" : @"@false";
937 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
938 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
943 /* Bridge: NSNull {{{ */
944 @implementation NSNull (Cycript)
946 - (JSType) cy$JSType {
950 - (NSObject *) cy$toJSON:(NSString *)key {
954 - (NSString *) cy$toCYON {
960 /* Bridge: NSObject {{{ */
961 @implementation NSObject (Cycript)
967 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
971 - (JSType) cy$JSType {
972 return kJSTypeObject;
975 - (NSObject *) cy$toJSON:(NSString *)key {
976 return [self description];
979 - (NSString *) cy$toCYON {
980 return [[self cy$toJSON:@""] cy$toCYON];
983 - (NSString *) cy$toKey {
984 return [self cy$toCYON];
987 - (bool) cy$hasProperty:(NSString *)name {
991 - (NSObject *) cy$getProperty:(NSString *)name {
995 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
999 - (bool) cy$deleteProperty:(NSString *)name {
1003 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1006 + (bool) cy$hasImplicitProperties {
1012 /* Bridge: NSProxy {{{ */
1013 @implementation NSProxy (Cycript)
1015 - (NSObject *) cy$toJSON:(NSString *)key {
1016 return [self description];
1019 - (NSString *) cy$toCYON {
1020 return [[self cy$toJSON:@""] cy$toCYON];
1025 /* Bridge: NSString {{{ */
1026 @implementation NSString (Cycript)
1029 return [[self copy] autorelease];
1032 - (JSType) cy$JSType {
1033 return kJSTypeString;
1036 - (NSObject *) cy$toJSON:(NSString *)key {
1040 - (NSString *) cy$toCYON {
1041 std::ostringstream str;
1043 CYUTF8String string(CYCastUTF8String(self));
1044 CYStringify(str, string.data, string.size);
1045 std::string value(str.str());
1046 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1049 - (NSString *) cy$toKey {
1050 if (CYIsKey(CYCastUTF8String(self)))
1052 return [self cy$toCYON];
1055 - (bool) cy$hasProperty:(NSString *)name {
1056 if ([name isEqualToString:@"length"])
1059 size_t index(CYGetIndex(name));
1060 if (index == _not(size_t) || index >= [self length])
1061 return [super cy$hasProperty:name];
1066 - (NSObject *) cy$getProperty:(NSString *)name {
1067 if ([name isEqualToString:@"length"]) {
1068 NSUInteger count([self length]);
1070 return [NSNumber numberWithUnsignedInteger:count];
1072 return [NSNumber numberWithUnsignedInt:count];
1076 size_t index(CYGetIndex(name));
1077 if (index == _not(size_t) || index >= [self length])
1078 return [super cy$getProperty:name];
1080 return [self substringWithRange:NSMakeRange(index, 1)];
1083 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1084 [super cy$getPropertyNames:names inContext:context];
1086 for (size_t index(0), length([self length]); index != length; ++index) {
1088 sprintf(name, "%zu", index);
1089 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1093 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1094 + (bool) cy$hasImplicitProperties {
1098 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1099 return CYCastJSValue(context, CYJSString(context, self));
1100 } CYObjectiveCatch }
1104 /* Bridge: WebUndefined {{{ */
1105 @implementation WebUndefined (Cycript)
1107 - (JSType) cy$JSType {
1108 return kJSTypeUndefined;
1111 - (NSObject *) cy$toJSON:(NSString *)key {
1115 - (NSString *) cy$toCYON {
1116 return @"undefined";
1119 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1120 return CYJSUndefined(context);
1121 } CYObjectiveCatch }
1126 static bool CYIsClass(id self) {
1128 // XXX: this is a lame object_isClass
1129 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1131 return GSObjCIsClass(self);
1135 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1136 id self(CYCastNSObject(pool, context, value));
1137 if (CYIsClass(self))
1138 return (Class) self;
1139 throw CYJSError(context, "got something that is not a Class");
1143 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1145 size_t size(JSPropertyNameArrayGetCount(names));
1146 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1147 for (size_t index(0); index != size; ++index)
1148 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1152 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1154 return CYJSNull(context);
1156 return CYMakeInstance(context, value, false);
1157 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1159 @implementation CYJSObject
1161 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1162 if ((self = [super init]) != nil) {
1164 context_ = CYGetJSContext(context);
1165 //XXX:JSGlobalContextRetain(context_);
1166 JSValueProtect(context_, object_);
1168 } CYObjectiveCatch }
1170 - (void) dealloc { CYObjectiveTry {
1171 JSValueUnprotect(context_, object_);
1172 //XXX:JSGlobalContextRelease(context_);
1174 } CYObjectiveCatch }
1176 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1177 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1178 if (!CYIsCallable(context_, toJSON))
1179 return [super cy$toJSON:key];
1181 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1182 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1183 // XXX: do I really want an NSNull here?!
1184 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1186 } CYObjectiveCatch }
1188 - (NSString *) cy$toCYON { CYObjectiveTry {
1190 JSValueRef exception(NULL);
1191 const char *cyon(CYPoolCCYON(pool, context_, object_));
1192 CYThrow(context_, exception);
1194 return [super cy$toCYON];
1196 return [NSString stringWithUTF8String:cyon];
1197 } CYObjectiveCatch }
1199 - (NSUInteger) count { CYObjectiveTry {
1200 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1201 size_t size(JSPropertyNameArrayGetCount(names));
1202 JSPropertyNameArrayRelease(names);
1204 } CYObjectiveCatch }
1206 - (id) objectForKey:(id)key { CYObjectiveTry {
1207 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1208 if (JSValueIsUndefined(context_, value))
1210 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1211 } CYObjectiveCatch }
1213 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1214 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1215 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1216 JSPropertyNameArrayRelease(names);
1218 } CYObjectiveCatch }
1220 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1221 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1222 } CYObjectiveCatch }
1224 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1225 JSValueRef exception(NULL);
1226 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1227 CYThrow(context_, exception);
1228 } CYObjectiveCatch }
1232 @implementation CYJSArray
1234 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1235 if ((self = [super init]) != nil) {
1237 context_ = CYGetJSContext(context);
1238 //XXX:JSGlobalContextRetain(context_);
1239 JSValueProtect(context_, object_);
1241 } CYObjectiveCatch }
1243 - (void) dealloc { CYObjectiveTry {
1244 JSValueUnprotect(context_, object_);
1245 //XXX:JSGlobalContextRelease(context_);
1247 } CYObjectiveCatch }
1249 - (NSUInteger) count { CYObjectiveTry {
1250 return CYArrayLength(context_, object_);
1251 } CYObjectiveCatch }
1253 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1254 size_t bounds([self count]);
1255 if (index >= bounds)
1256 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1257 JSValueRef exception(NULL);
1258 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1259 CYThrow(context_, exception);
1260 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1261 } CYObjectiveCatch }
1263 - (void) addObject:(id)object { CYObjectiveTry {
1264 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1265 } CYObjectiveCatch }
1267 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1268 size_t bounds([self count] + 1);
1269 if (index >= bounds)
1270 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1271 JSValueRef exception(NULL);
1272 JSValueRef arguments[3];
1273 arguments[0] = CYCastJSValue(context_, index);
1274 arguments[1] = CYCastJSValue(context_, 0);
1275 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1276 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1277 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1278 CYThrow(context_, exception);
1279 } CYObjectiveCatch }
1281 - (void) removeLastObject { CYObjectiveTry {
1282 JSValueRef exception(NULL);
1283 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1284 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1285 CYThrow(context_, exception);
1286 } CYObjectiveCatch }
1288 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1289 size_t bounds([self count]);
1290 if (index >= bounds)
1291 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1292 JSValueRef exception(NULL);
1293 JSValueRef arguments[2];
1294 arguments[0] = CYCastJSValue(context_, index);
1295 arguments[1] = CYCastJSValue(context_, 1);
1296 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1297 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1298 CYThrow(context_, exception);
1299 } CYObjectiveCatch }
1301 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1302 size_t bounds([self count]);
1303 if (index >= bounds)
1304 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1305 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1306 } CYObjectiveCatch }
1310 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1314 JSObjectRef object_;
1322 // XXX: delete object_? ;(
1325 static CYInternal *Get(id self) {
1326 CYInternal *internal(NULL);
1327 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1328 // XXX: do something epic? ;P
1334 static CYInternal *Set(id self) {
1335 CYInternal *internal(NULL);
1336 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1337 if (internal == NULL) {
1338 internal = new CYInternal();
1339 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1342 // XXX: do something epic? ;P
1348 bool HasProperty(JSContextRef context, JSStringRef name) {
1349 if (object_ == NULL)
1351 return JSObjectHasProperty(context, object_, name);
1354 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1355 if (object_ == NULL)
1357 return CYGetProperty(context, object_, name);
1360 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1361 if (object_ == NULL)
1362 object_ = JSObjectMake(context, NULL, NULL);
1363 CYSetProperty(context, object_, name, value);
1367 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1368 Selector_privateData *internal(new Selector_privateData(sel));
1369 return JSObjectMake(context, Selector_, internal);
1372 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1373 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1374 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1375 return reinterpret_cast<SEL>(internal->value_);
1377 return CYCastPointer<SEL>(context, value);
1380 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1381 return (void *) [[NSAutoreleasePool alloc] init];
1382 } CYSadCatch(NULL) }
1384 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1385 return [(NSAutoreleasePool *) handle release];
1388 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1390 return Instance::Make(context, nil);
1391 if (Class _class = objc_getClass(name.data))
1392 return CYMakeInstance(context, _class, true);
1393 if (Protocol *protocol = objc_getProtocol(name.data))
1394 return CYMakeInstance(context, protocol, true);
1396 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1398 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1399 ffi_call(cif, function, value, values);
1402 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1403 switch (type->primitive) {
1404 // XXX: do something epic about blocks
1407 case sig::typename_P:
1408 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1411 case sig::selector_P:
1412 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1420 } CYSadCatch(false) }
1422 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1423 switch (type->primitive) {
1424 // XXX: do something epic about blocks
1427 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1428 JSValueRef value(CYCastJSValue(context, object));
1434 case sig::typename_P:
1435 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1437 case sig::selector_P:
1438 if (SEL sel = *reinterpret_cast<SEL *>(data))
1439 return CYMakeSelector(context, sel);
1443 return CYJSNull(context);
1447 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1449 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1450 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1453 #if OBJC_API_VERSION >= 2
1455 method_getReturnType(method, type, sizeof(type));
1457 const char *type(method_getTypeEncoding(method));
1463 // XXX: possibly use a more "awesome" check?
1467 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1469 return method_getTypeEncoding(method);
1471 const char *name(sel_getName(sel));
1472 size_t length(strlen(name));
1474 char keyed[length + 2];
1476 keyed[length + 1] = '\0';
1477 memcpy(keyed + 1, name, length);
1479 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1480 return entry->value_;
1485 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1486 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1488 JSContextRef context(internal->context_);
1490 size_t count(internal->cif_.nargs);
1491 JSValueRef values[count];
1493 for (size_t index(0); index != count; ++index)
1494 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1496 JSObjectRef _this(CYCastJSObject(context, values[0]));
1498 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1499 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1502 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1503 Message_privateData *internal(new Message_privateData(sel, type, imp));
1504 return JSObjectMake(context, Message_, internal);
1507 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1508 JSObjectRef function(CYCastJSObject(context, value));
1509 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1510 // XXX: see notes in Library.cpp about needing to leak
1511 return reinterpret_cast<IMP>(internal->GetValue());
1514 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1515 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1516 Class _class(internal->GetValue());
1519 const char *name(CYPoolCString(pool, context, property));
1521 if (SEL sel = sel_getUid(name))
1522 if (class_getInstanceMethod(_class, sel) != NULL)
1528 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1529 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1530 Class _class(internal->GetValue());
1533 const char *name(CYPoolCString(pool, context, property));
1535 if (SEL sel = sel_getUid(name))
1536 if (objc_method *method = class_getInstanceMethod(_class, sel))
1537 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1542 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1543 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1544 Class _class(internal->GetValue());
1547 const char *name(CYPoolCString(pool, context, property));
1549 SEL sel(sel_registerName(name));
1551 objc_method *method(class_getInstanceMethod(_class, sel));
1556 if (JSValueIsObjectOfClass(context, value, Message_)) {
1557 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1558 type = sig::Unparse(pool, &message->signature_);
1559 imp = reinterpret_cast<IMP>(message->GetValue());
1561 type = CYPoolTypeEncoding(pool, context, sel, method);
1562 imp = CYMakeMessage(context, value, type);
1566 method_setImplementation(method, imp);
1569 GSMethodList list(GSAllocMethodList(1));
1570 GSAppendMethodToList(list, sel, type, imp, YES);
1571 GSAddMethodList(_class, list, YES);
1572 GSFlushMethodCacheForClass(_class);
1574 class_addMethod(_class, sel, imp, type);
1581 #if 0 && OBJC_API_VERSION < 2
1582 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1583 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1584 Class _class(internal->GetValue());
1587 const char *name(CYPoolCString(pool, context, property));
1589 if (SEL sel = sel_getUid(name))
1590 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1591 objc_method_list list = {NULL, 1, {method}};
1592 class_removeMethods(_class, &list);
1600 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1601 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1602 Class _class(internal->GetValue());
1604 #if OBJC_API_VERSION >= 2
1606 objc_method **data(class_copyMethodList(_class, &size));
1607 for (size_t i(0); i != size; ++i)
1608 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1611 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1612 for (int i(0); i != methods->method_count; ++i)
1613 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1617 static bool CYHasImplicitProperties(Class _class) {
1618 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1619 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1621 return [_class cy$hasImplicitProperties];
1624 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1625 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1626 id self(internal->GetValue());
1628 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1632 NSString *name(CYCastNSString(pool, context, property));
1634 if (CYInternal *internal = CYInternal::Get(self))
1635 if (internal->HasProperty(context, property))
1638 Class _class(object_getClass(self));
1641 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1642 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1643 if ([self cy$hasProperty:name])
1645 } CYPoolCatch(false)
1647 const char *string(CYPoolCString(pool, context, name));
1650 if (class_getProperty(_class, string) != NULL)
1654 if (CYHasImplicitProperties(_class))
1655 if (SEL sel = sel_getUid(string))
1656 if (CYImplements(self, _class, sel, true))
1662 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1663 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1664 id self(internal->GetValue());
1666 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1667 return Internal::Make(context, self, object);
1670 NSString *name(CYCastNSString(pool, context, property));
1672 if (CYInternal *internal = CYInternal::Get(self))
1673 if (JSValueRef value = internal->GetProperty(context, property))
1677 if (NSObject *data = [self cy$getProperty:name])
1678 return CYCastJSValue(context, data);
1681 const char *string(CYPoolCString(pool, context, name));
1682 Class _class(object_getClass(self));
1685 if (objc_property_t property = class_getProperty(_class, string)) {
1686 PropertyAttributes attributes(property);
1687 SEL sel(sel_registerName(attributes.Getter()));
1688 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1692 if (CYHasImplicitProperties(_class))
1693 if (SEL sel = sel_getUid(string))
1694 if (CYImplements(self, _class, sel, true))
1695 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1700 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1701 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1702 id self(internal->GetValue());
1706 NSString *name(CYCastNSString(pool, context, property));
1707 NSObject *data(CYCastNSObject(pool, context, value));
1710 if ([self cy$setProperty:name to:data])
1714 const char *string(CYPoolCString(pool, context, name));
1715 Class _class(object_getClass(self));
1718 if (objc_property_t property = class_getProperty(_class, string)) {
1719 PropertyAttributes attributes(property);
1720 if (const char *setter = attributes.Setter()) {
1721 SEL sel(sel_registerName(setter));
1722 JSValueRef arguments[1] = {value};
1723 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1729 size_t length(strlen(string));
1731 char set[length + 5];
1737 if (string[0] != '\0') {
1738 set[3] = toupper(string[0]);
1739 memcpy(set + 4, string + 1, length - 1);
1742 set[length + 3] = ':';
1743 set[length + 4] = '\0';
1745 if (SEL sel = sel_getUid(set))
1746 if (CYImplements(self, _class, sel, false)) {
1747 JSValueRef arguments[1] = {value};
1748 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1751 if (CYInternal *internal = CYInternal::Set(self)) {
1752 internal->SetProperty(context, property, value);
1759 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1760 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1761 id self(internal->GetValue());
1764 NSString *name(CYCastNSString(NULL, context, property));
1765 return [self cy$deleteProperty:name];
1767 } CYCatch return /*XXX*/ NULL; }
1769 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1770 const char *name(sel_getName(method_getName(method)));
1771 if (strchr(name, ':') != NULL)
1774 const char *type(method_getTypeEncoding(method));
1775 if (type == NULL || *type == '\0' || *type == 'v')
1778 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1781 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1782 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1783 id self(internal->GetValue());
1786 Class _class(object_getClass(self));
1791 objc_property_t *data(class_copyPropertyList(_class, &size));
1792 for (size_t i(0); i != size; ++i)
1793 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1798 if (CYHasImplicitProperties(_class))
1799 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1800 #if OBJC_API_VERSION >= 2
1802 objc_method **data(class_copyMethodList(current, &size));
1803 for (size_t i(0); i != size; ++i)
1804 Instance_getPropertyNames_message(names, data[i]);
1807 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1808 for (int i(0); i != methods->method_count; ++i)
1809 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1814 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1815 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1816 [self cy$getPropertyNames:names inContext:context];
1820 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1821 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1822 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1826 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1827 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1828 Class _class(internal->GetValue());
1829 if (!CYIsClass(_class))
1832 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1833 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1834 // XXX: this isn't always safe
1835 return [linternal->GetValue() isKindOfClass:_class];
1841 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1843 throw CYJSError(context, "incorrect number of arguments to Instance");
1845 id value(CYCastNSObject(pool, context, arguments[0]));
1847 value = [NSNull null];
1848 return CYCastJSValue(context, [value cy$box]);
1851 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1852 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1855 id self(internal->GetValue());
1856 const char *name(CYPoolCString(pool, context, property));
1858 if (object_getInstanceVariable(self, name, NULL) != NULL)
1864 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1865 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1868 id self(internal->GetValue());
1869 const char *name(CYPoolCString(pool, context, property));
1871 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1872 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1873 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1874 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1880 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1881 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1884 id self(internal->GetValue());
1885 const char *name(CYPoolCString(pool, context, property));
1887 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1888 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1889 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1896 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1897 if (Class super = class_getSuperclass(_class))
1898 Internal_getPropertyNames_(super, names);
1900 #if OBJC_API_VERSION >= 2
1902 objc_ivar **data(class_copyIvarList(_class, &size));
1903 for (size_t i(0); i != size; ++i)
1904 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1907 if (objc_ivar_list *ivars = _class->ivars)
1908 for (int i(0); i != ivars->ivar_count; ++i)
1909 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1913 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1914 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1917 id self(internal->GetValue());
1918 Class _class(object_getClass(self));
1920 Internal_getPropertyNames_(_class, names);
1923 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1924 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1925 return internal->GetOwner();
1928 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1930 NSString *name(CYCastNSString(pool, context, property));
1931 if (Class _class = NSClassFromString(name))
1932 return CYMakeInstance(context, _class, true);
1936 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1938 size_t size(objc_getClassList(NULL, 0));
1939 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1942 size_t writ(objc_getClassList(data, size));
1945 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1951 for (size_t i(0); i != writ; ++i)
1952 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1958 while (Class _class = objc_next_class(&state))
1959 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1963 #if OBJC_API_VERSION >= 2
1964 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1965 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1968 const char *name(CYPoolCString(pool, context, property));
1970 const char **data(objc_copyClassNamesForImage(internal, &size));
1972 for (size_t i(0); i != size; ++i)
1973 if (strcmp(name, data[i]) == 0) {
1974 if (Class _class = objc_getClass(name)) {
1975 value = CYMakeInstance(context, _class, true);
1986 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1987 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1989 const char **data(objc_copyClassNamesForImage(internal, &size));
1990 for (size_t i(0); i != size; ++i)
1991 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1995 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1997 const char *name(CYPoolCString(pool, context, property));
1999 const char **data(objc_copyImageNames(&size));
2000 for (size_t i(0); i != size; ++i)
2001 if (strcmp(name, data[i]) == 0) {
2010 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2011 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2015 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2017 const char **data(objc_copyImageNames(&size));
2018 for (size_t i(0); i != size; ++i)
2019 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2024 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2026 const char *name(CYPoolCString(pool, context, property));
2027 if (Protocol *protocol = objc_getProtocol(name))
2028 return CYMakeInstance(context, protocol, true);
2032 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2033 #if OBJC_API_VERSION >= 2
2035 Protocol **data(objc_copyProtocolList(&size));
2036 for (size_t i(0); i != size; ++i)
2037 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2044 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2046 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2048 return Instance::Make(context, nil);
2052 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2053 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2057 static bool stret(ffi_type *ffi_type) {
2058 return ffi_type->type == FFI_TYPE_STRUCT && (
2059 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2060 struct_forward_array[ffi_type->size] != 0
2065 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 {
2069 _class = object_getClass(self);
2073 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2074 imp = method_getImplementation(method);
2075 type = method_getTypeEncoding(method);
2080 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2082 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2083 type = CYPoolCString(pool, context, [method _typeString]);
2091 sig::Signature signature;
2092 sig::Parse(pool, &signature, type, &Structor_);
2094 size_t used(count + 3);
2095 if (used > signature.count) {
2096 sig::Element *elements(new (pool) sig::Element[used]);
2097 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2099 for (size_t index(signature.count); index != used; ++index) {
2100 sig::Element *element(&elements[index]);
2101 element->name = NULL;
2102 element->offset = _not(size_t);
2104 sig::Type *type(new (pool) sig::Type);
2105 memset(type, 0, sizeof(*type));
2106 type->primitive = sig::object_P;
2107 element->type = type;
2110 signature.elements = elements;
2111 signature.count = used;
2115 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2119 if (stret(cif.rtype))
2120 imp = class_getMethodImplementation_stret(_class, _cmd);
2122 imp = class_getMethodImplementation(_class, _cmd);
2124 objc_super super = {self, _class};
2125 imp = objc_msg_lookup_super(&super, _cmd);
2129 void (*function)() = reinterpret_cast<void (*)()>(imp);
2130 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2133 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2135 throw CYJSError(context, "too few arguments to objc_msgSend");
2145 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2146 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2147 self = internal->GetValue();
2148 _class = internal->class_;;
2149 uninitialized = false;
2150 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2151 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2152 self = internal->GetValue();
2154 uninitialized = internal->IsUninitialized();
2156 internal->value_ = nil;
2158 self = CYCastNSObject(pool, context, arguments[0]);
2160 uninitialized = false;
2164 return CYJSNull(context);
2166 _cmd = CYCastSEL(context, arguments[1]);
2168 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2171 /* Hook: objc_registerClassPair {{{ */
2172 #if defined(__APPLE__) && defined(__arm__) && 0
2173 // XXX: replace this with associated objects
2175 MSHook(void, CYDealloc, id self, SEL sel) {
2176 CYInternal *internal;
2177 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2178 if (internal != NULL)
2180 _CYDealloc(self, sel);
2183 MSHook(void, objc_registerClassPair, Class _class) {
2184 Class super(class_getSuperclass(_class));
2185 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2186 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2187 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2190 _objc_registerClassPair(_class);
2193 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2195 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2197 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2198 if (value == NULL || !CYIsClass(value))
2199 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2200 Class _class((Class) value);
2201 $objc_registerClassPair(_class);
2202 return CYJSUndefined(context);
2207 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2208 JSValueRef setup[count + 2];
2211 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2212 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2215 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2217 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2219 // XXX: handle Instance::Uninitialized?
2220 id self(CYCastNSObject(pool, context, _this));
2224 setup[1] = &internal->sel_;
2226 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2229 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2231 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2233 id self(CYCastNSObject(pool, context, arguments[0]));
2234 Class _class(CYCastClass(pool, context, arguments[1]));
2235 return cy::Super::Make(context, self, _class);
2238 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2240 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2242 const char *name(CYPoolCString(pool, context, arguments[0]));
2243 return CYMakeSelector(context, sel_registerName(name));
2246 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2248 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2249 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2250 return CYMakeInstance(context, self, false);
2253 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2254 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2255 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2258 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2259 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2260 Type_privateData *typical(internal->GetType());
2265 if (typical == NULL) {
2269 type = typical->type_;
2270 ffi = typical->ffi_;
2273 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2276 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2277 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2278 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2281 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2282 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2283 id self(internal->GetValue());
2284 if (!CYIsClass(self))
2285 return CYJSUndefined(context);
2286 return CYGetClassPrototype(context, self);
2289 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2290 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2291 id self(internal->GetValue());
2292 if (!CYIsClass(self))
2293 return CYJSUndefined(context);
2294 return Messages::Make(context, (Class) self);
2297 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2298 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2301 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2302 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2305 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2306 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2309 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2316 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2317 // XXX: check for support of cy$toJSON?
2318 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2320 } CYCatch return /*XXX*/ NULL; }
2322 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2323 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2326 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2327 id value(internal->GetValue());
2329 if (![value respondsToSelector:@selector(cy$JSValueInContext:)])
2332 if (JSValueRef result = [value cy$JSValueInContext:context])
2336 } CYCatch return /*XXX*/ NULL; }
2338 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2339 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2342 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2343 // XXX: but... but... THIS ISN'T A POINTER! :(
2344 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2345 } CYCatch return /*XXX*/ NULL; }
2347 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2348 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2351 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2352 id value(internal->GetValue());
2355 return CYCastJSValue(context, "nil");
2358 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2359 return CYCastJSValue(context, CYJSString(context, [value description]));
2361 } CYCatch return /*XXX*/ NULL; }
2363 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2364 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2365 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2368 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2369 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2372 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2373 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2374 const char *name(sel_getName(internal->GetValue()));
2377 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2378 return CYCastJSValue(context, CYJSString(context, string));
2380 } CYCatch return /*XXX*/ NULL; }
2382 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2384 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2387 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2388 SEL sel(internal->GetValue());
2390 objc_method *method;
2391 if (Class _class = CYCastClass(pool, context, arguments[0]))
2392 method = class_getInstanceMethod(_class, sel);
2396 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2397 return CYCastJSValue(context, CYJSString(type));
2399 return CYJSNull(context);
2402 static JSStaticValue Selector_staticValues[2] = {
2403 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2404 {NULL, NULL, NULL, 0}
2407 static JSStaticValue Instance_staticValues[5] = {
2408 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2409 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2410 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2411 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2412 {NULL, NULL, NULL, 0}
2415 static JSStaticFunction Instance_staticFunctions[7] = {
2416 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2417 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2418 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2419 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2420 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2421 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2425 static JSStaticFunction Internal_staticFunctions[2] = {
2426 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2430 static JSStaticFunction Selector_staticFunctions[5] = {
2431 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2432 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2433 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2434 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2438 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2439 apr_pool_t *pool(CYGetGlobalPool());
2441 Object_type = new(pool) Type_privateData("@");
2442 Selector_type = new(pool) Type_privateData(":");
2445 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2446 NSCFType_ = objc_getClass("NSCFType");
2447 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2448 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2449 NSZombie_ = objc_getClass("_NSZombie_");
2451 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2454 NSArray_ = objc_getClass("NSArray");
2455 NSDictionary_ = objc_getClass("NSDictionary");
2456 NSString_ = objc_getClass("NSString");
2457 Object_ = objc_getClass("Object");
2459 JSClassDefinition definition;
2461 definition = kJSClassDefinitionEmpty;
2462 definition.className = "Instance";
2463 definition.staticValues = Instance_staticValues;
2464 definition.staticFunctions = Instance_staticFunctions;
2465 definition.hasProperty = &Instance_hasProperty;
2466 definition.getProperty = &Instance_getProperty;
2467 definition.setProperty = &Instance_setProperty;
2468 definition.deleteProperty = &Instance_deleteProperty;
2469 definition.getPropertyNames = &Instance_getPropertyNames;
2470 definition.callAsConstructor = &Instance_callAsConstructor;
2471 definition.hasInstance = &Instance_hasInstance;
2472 definition.finalize = &CYFinalize;
2473 Instance_ = JSClassCreate(&definition);
2475 definition = kJSClassDefinitionEmpty;
2476 definition.className = "Internal";
2477 definition.staticFunctions = Internal_staticFunctions;
2478 definition.hasProperty = &Internal_hasProperty;
2479 definition.getProperty = &Internal_getProperty;
2480 definition.setProperty = &Internal_setProperty;
2481 definition.getPropertyNames = &Internal_getPropertyNames;
2482 definition.finalize = &CYFinalize;
2483 Internal_ = JSClassCreate(&definition);
2485 definition = kJSClassDefinitionEmpty;
2486 definition.className = "Message";
2487 definition.staticFunctions = cy::Functor::StaticFunctions;
2488 definition.callAsFunction = &Message_callAsFunction;
2489 definition.finalize = &CYFinalize;
2490 Message_ = JSClassCreate(&definition);
2492 definition = kJSClassDefinitionEmpty;
2493 definition.className = "Messages";
2494 definition.hasProperty = &Messages_hasProperty;
2495 definition.getProperty = &Messages_getProperty;
2496 definition.setProperty = &Messages_setProperty;
2497 #if 0 && OBJC_API_VERSION < 2
2498 definition.deleteProperty = &Messages_deleteProperty;
2500 definition.getPropertyNames = &Messages_getPropertyNames;
2501 definition.finalize = &CYFinalize;
2502 Messages_ = JSClassCreate(&definition);
2504 definition = kJSClassDefinitionEmpty;
2505 definition.className = "Selector";
2506 definition.staticValues = Selector_staticValues;
2507 definition.staticFunctions = Selector_staticFunctions;
2508 definition.callAsFunction = &Selector_callAsFunction;
2509 definition.finalize = &CYFinalize;
2510 Selector_ = JSClassCreate(&definition);
2512 definition = kJSClassDefinitionEmpty;
2513 definition.className = "Super";
2514 definition.staticFunctions = Internal_staticFunctions;
2515 definition.finalize = &CYFinalize;
2516 Super_ = JSClassCreate(&definition);
2518 definition = kJSClassDefinitionEmpty;
2519 definition.className = "ObjectiveC::Classes";
2520 definition.getProperty = &ObjectiveC_Classes_getProperty;
2521 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2522 ObjectiveC_Classes_ = JSClassCreate(&definition);
2524 definition = kJSClassDefinitionEmpty;
2525 definition.className = "ObjectiveC::Constants";
2526 definition.getProperty = &ObjectiveC_Constants_getProperty;
2527 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2528 ObjectiveC_Constants_ = JSClassCreate(&definition);
2530 #if OBJC_API_VERSION >= 2
2531 definition = kJSClassDefinitionEmpty;
2532 definition.className = "ObjectiveC::Images";
2533 definition.getProperty = &ObjectiveC_Images_getProperty;
2534 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2535 ObjectiveC_Images_ = JSClassCreate(&definition);
2537 definition = kJSClassDefinitionEmpty;
2538 definition.className = "ObjectiveC::Image::Classes";
2539 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2540 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2541 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2544 definition = kJSClassDefinitionEmpty;
2545 definition.className = "ObjectiveC::Protocols";
2546 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2547 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2548 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2550 #if defined(__APPLE__) && defined(__arm__) && 0
2551 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2555 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2559 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2560 JSObjectRef global(CYGetGlobalObject(context));
2561 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2562 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2563 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2564 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2566 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2567 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2569 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2570 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2571 CYArrayPush(context, alls, protocols);
2573 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2574 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2575 CYArrayPush(context, alls, classes);
2577 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2578 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2579 CYArrayPush(context, alls, constants);
2581 #if OBJC_API_VERSION >= 2
2582 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2585 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2586 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2587 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2588 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2590 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2591 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2593 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2594 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2595 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2596 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2597 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2599 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2600 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2601 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2602 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2603 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2605 JSObjectRef StringInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2606 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2607 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2608 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2609 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2611 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2612 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2613 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2615 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2616 CYSetProperty(context, Instance, CYJSString("box"), box);
2618 #if defined(__APPLE__) && defined(__arm__) && 0
2619 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2622 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2624 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2625 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2626 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2629 static CYHooks CYObjectiveCHooks = {
2630 &CYObjectiveC_ExecuteStart,
2631 &CYObjectiveC_ExecuteEnd,
2632 &CYObjectiveC_CallFunction,
2633 &CYObjectiveC_Initialize,
2634 &CYObjectiveC_SetupContext,
2635 &CYObjectiveC_PoolFFI,
2636 &CYObjectiveC_FromFFI,
2639 struct CYObjectiveC {
2641 hooks_ = &CYObjectiveCHooks;
2642 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2643 _assert(hooks_ != NULL);