1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2012 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"
53 #define CYObjectiveTry_(context) { \
54 JSContextRef context_(context); \
56 #define CYObjectiveTry { \
58 #define CYObjectiveCatch \
59 catch (const CYException &error) { \
60 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
66 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
68 #define CYPoolCatch(value) \
69 @catch (NSException *error) { \
70 _saved = [error retain]; \
71 throw CYJSError(context, CYCastJSValue(context, error)); \
76 [_saved autorelease]; \
82 #define CYSadCatch(value) \
83 @catch (NSException *error ) { \
84 throw CYJSError(context, CYCastJSValue(context, error)); \
89 #define class_getSuperclass GSObjCSuper
90 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
91 #define class_getName GSNameFromClass
93 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
95 #define ivar_getName(ivar) ((ivar)->ivar_name)
96 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
97 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
99 #define method_getName(method) ((method)->method_name)
100 #define method_getImplementation(method) ((method)->method_imp)
101 #define method_getTypeEncoding(method) ((method)->method_types)
102 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
105 #define objc_getClass GSClassFromName
107 #define objc_getProtocol GSProtocolFromName
109 #define object_getClass GSObjCClass
111 #define object_getInstanceVariable(object, name, value) ({ \
112 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
113 _assert(value != NULL); \
115 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
119 #define object_setIvar(object, ivar, value) ({ \
120 void *data = (value); \
121 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
124 #define protocol_getName(protocol) [(protocol) name]
127 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
128 static id (*$objc_getAssociatedObject)(id object, void *key);
129 static void (*$objc_removeAssociatedObjects)(id object);
131 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
133 /* Objective-C Pool Release {{{ */
134 apr_status_t CYPoolRelease_(void *data) {
135 id object(reinterpret_cast<id>(data));
140 id CYPoolRelease_(apr_pool_t *pool, id object) {
143 else if (pool == NULL)
144 return [object autorelease];
146 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
151 template <typename Type_>
152 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
153 return (Type_) CYPoolRelease_(pool, (id) object);
156 /* Objective-C Strings {{{ */
157 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
159 return [value UTF8String];
161 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
162 char *string(new(pool) char[size]);
163 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
164 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
169 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
171 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
174 return CYCopyJSString(CYPoolCString(pool, context, value));
178 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
181 // XXX: this definition scares me; is anyone using this?!
182 NSString *string([value description]);
183 return CYCopyJSString(context, string);
186 NSString *CYCopyNSString(const CYUTF8String &value) {
188 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
190 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
194 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
196 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
199 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
203 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
204 return CYCopyNSString(context, CYJSString(context, value));
207 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
208 return CYPoolRelease(pool, CYCopyNSString(value));
211 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
212 const char *name(sel_getName(sel));
213 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
216 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
217 return CYPoolRelease(pool, CYCopyNSString(context, value));
220 CYUTF8String CYCastUTF8String(NSString *value) {
221 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
222 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
226 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
228 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
229 if (exception == NULL)
231 *exception = CYCastJSValue(context, error);
234 size_t CYGetIndex(NSString *value) {
235 return CYGetIndex(CYCastUTF8String(value));
238 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
239 return CYGetOffset(CYPoolCString(pool, context, value), index);
242 static JSClassRef Instance_;
244 static JSClassRef ArrayInstance_;
245 static JSClassRef FunctionInstance_;
246 static JSClassRef ObjectInstance_;
247 static JSClassRef StringInstance_;
248 static JSClassRef TypeInstance_;
250 static JSClassRef Internal_;
251 static JSClassRef Message_;
252 static JSClassRef Messages_;
253 static JSClassRef Selector_;
254 static JSClassRef Super_;
256 static JSClassRef ObjectiveC_Classes_;
257 static JSClassRef ObjectiveC_Constants_;
258 static JSClassRef ObjectiveC_Protocols_;
261 static JSClassRef ObjectiveC_Image_Classes_;
262 static JSClassRef ObjectiveC_Images_;
266 static Class NSCFBoolean_;
267 static Class NSCFType_;
268 static Class NSGenericDeallocHandler_;
269 static Class NSMessageBuilder_;
270 static Class NSZombie_;
272 static Class NSBoolNumber_;
275 static Class NSArray_;
276 static Class NSBlock_;
277 static Class NSDictionary_;
278 static Class NSString_;
279 static Class Object_;
281 static Type_privateData *Object_type;
282 static Type_privateData *Selector_type;
284 Type_privateData *Instance::GetType() const {
288 Type_privateData *Selector_privateData::GetType() const {
289 return Selector_type;
292 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
294 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
296 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
297 else if (meta && !class_isMetaClass(self))
298 return CYGetCachedObject(context, CYJSString("TypeInstance_prototype"));
300 JSObjectRef global(CYGetGlobalObject(context));
301 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
304 sprintf(label, "i%p", self);
305 CYJSString name(label);
307 JSValueRef value(CYGetProperty(context, cy, name));
308 if (!JSValueIsUndefined(context, value))
311 JSClassRef _class(NULL);
312 JSValueRef prototype;
314 if (self == NSArray_)
315 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
316 else if (self == NSBlock_)
317 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
318 else if (self == NSDictionary_)
319 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
320 else if (self == NSString_)
321 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
323 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
325 JSObjectRef object(JSObjectMake(context, _class, NULL));
326 JSObjectSetPrototype(context, object, prototype);
327 CYSetProperty(context, cy, name, object);
332 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
333 return CYGetClassPrototype(context, self, class_isMetaClass(self));
336 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
337 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
338 if (Class super = class_getSuperclass(_class))
339 JSObjectSetPrototype(context, value, Messages::Make(context, super));
343 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
344 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
348 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
349 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
353 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
354 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
355 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
359 Instance::~Instance() {
360 if ((flags_ & Transient) == 0)
361 // XXX: does this handle background threads correctly?
362 // XXX: this simply does not work on the console because I'm stupid
363 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
366 struct Message_privateData :
371 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
372 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
378 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
379 Instance::Flags flags;
382 flags = Instance::Transient;
384 flags = Instance::None;
385 object = [object retain];
388 return Instance::Make(context, object, flags);
391 @interface NSMethodSignature (Cycript)
392 - (NSString *) _typeString;
395 @interface NSObject (Cycript)
397 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
398 - (JSType) cy$JSType;
400 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
401 - (NSString *) cy$toCYON:(bool)objective;
403 - (bool) cy$hasProperty:(NSString *)name;
404 - (NSObject *) cy$getProperty:(NSString *)name;
405 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
406 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
407 - (bool) cy$deleteProperty:(NSString *)name;
408 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
410 + (bool) cy$hasImplicitProperties;
416 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
419 NSString *CYCastNSCYON(id value, bool objective) {
425 Class _class(object_getClass(value));
426 SEL sel(@selector(cy$toCYON:));
428 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
429 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
430 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
431 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
432 string = [value cy$toCYON:objective];
437 else if (value == NSZombie_)
438 string = @"_NSZombie_";
439 else if (_class == NSZombie_)
440 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
441 // XXX: frowny /in/ the pants
442 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
446 string = [NSString stringWithFormat:@"%@", value];
451 string = @"undefined";
458 struct PropertyAttributes {
463 const char *variable;
476 PropertyAttributes(objc_property_t property) :
488 name = property_getName(property);
489 const char *attributes(property_getAttributes(property));
491 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
493 case 'R': readonly = true; break;
494 case 'C': copy = true; break;
495 case '&': retain = true; break;
496 case 'N': nonatomic = true; break;
497 case 'G': getter_ = token + 1; break;
498 case 'S': setter_ = token + 1; break;
499 case 'V': variable = token + 1; break;
503 /*if (variable == NULL) {
504 variable = property_getName(property);
505 size_t size(strlen(variable));
506 char *name(new(pool_) char[size + 2]);
508 memcpy(name + 1, variable, size);
509 name[size + 1] = '\0';
514 const char *Getter() {
516 getter_ = apr_pstrdup(pool_, name);
520 const char *Setter() {
521 if (setter_ == NULL && !readonly) {
522 size_t length(strlen(name));
524 char *temp(new(pool_) char[length + 5]);
530 temp[3] = toupper(name[0]);
531 memcpy(temp + 4, name + 1, length - 1);
534 temp[length + 3] = ':';
535 temp[length + 4] = '\0';
546 @interface CYWebUndefined : NSObject {
549 + (CYWebUndefined *) undefined;
553 @implementation CYWebUndefined
555 + (CYWebUndefined *) undefined {
556 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
562 #define WebUndefined CYWebUndefined
565 /* Bridge: CYJSObject {{{ */
566 @interface CYJSObject : NSMutableDictionary {
568 JSGlobalContextRef context_;
571 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
573 - (NSUInteger) count;
574 - (id) objectForKey:(id)key;
575 - (NSEnumerator *) keyEnumerator;
576 - (void) setObject:(id)object forKey:(id)key;
577 - (void) removeObjectForKey:(id)key;
581 /* Bridge: CYJSArray {{{ */
582 @interface CYJSArray : NSMutableArray {
584 JSGlobalContextRef context_;
587 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
589 - (NSUInteger) count;
590 - (id) objectAtIndex:(NSUInteger)index;
592 - (void) addObject:(id)anObject;
593 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
594 - (void) removeLastObject;
595 - (void) removeObjectAtIndex:(NSUInteger)index;
596 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
601 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
602 return JSValueIsObjectOfClass(context, value, Instance_);
605 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
606 JSValueRef exception(NULL);
607 JSObjectRef constructor(CYGetCachedObject(context, cache));
608 bool is(JSValueIsInstanceOfConstructor(context, value, constructor, &exception));
609 CYThrow(context, exception);
613 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
614 if (CYJSValueIsNSObject(context, object)) {
615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
616 return internal->GetValue();
619 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
620 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
621 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
624 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
625 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
629 @interface NSBoolNumber : NSNumber {
634 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
638 switch (JSType type = JSValueGetType(context, value)) {
639 case kJSTypeUndefined:
640 object = [WebUndefined undefined];
650 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
653 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
659 object = CYCopyNSNumber(context, value);
664 object = CYCopyNSString(context, value);
669 // XXX: this might could be more efficient
670 object = CYCastNSObject(pool, context, (JSObjectRef) value);
675 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
682 return CYPoolRelease(pool, object);
684 return [object retain];
687 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
688 return CYNSObject(pool, context, value, true);
691 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
692 return CYNSObject(pool, context, value, false);
695 /* Bridge: NSArray {{{ */
696 @implementation NSArray (Cycript)
699 return [[self mutableCopy] autorelease];
702 - (NSString *) cy$toCYON:(bool)objective {
703 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
704 [json appendString:@"@["];
708 for (id object in self) {
710 for (size_t index(0), count([self count]); index != count; ++index) {
711 id object([self objectAtIndex:index]);
714 [json appendString:@","];
717 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
718 [json appendString:CYCastNSCYON(object, true)];
720 [json appendString:@","];
725 [json appendString:@"]"];
729 - (bool) cy$hasProperty:(NSString *)name {
730 if ([name isEqualToString:@"length"])
733 size_t index(CYGetIndex(name));
734 if (index == _not(size_t) || index >= [self count])
735 return [super cy$hasProperty:name];
740 - (NSObject *) cy$getProperty:(NSString *)name {
741 size_t index(CYGetIndex(name));
742 if (index == _not(size_t) || index >= [self count])
743 return [super cy$getProperty:name];
745 return [self objectAtIndex:index];
748 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
749 CYObjectiveTry_(context) {
750 if ([name isEqualToString:@"length"])
751 return CYCastJSValue(context, [self count]);
754 return [super cy$getProperty:name inContext:context];
757 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
758 [super cy$getPropertyNames:names inContext:context];
760 for (size_t index(0), count([self count]); index != count; ++index) {
761 id object([self objectAtIndex:index]);
762 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
764 sprintf(name, "%zu", index);
765 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
770 + (bool) cy$hasImplicitProperties {
776 /* Bridge: NSBlock {{{ */
783 /* Bridge: NSBoolNumber {{{ */
785 @implementation NSBoolNumber (Cycript)
787 - (JSType) cy$JSType {
788 return kJSTypeBoolean;
791 - (NSString *) cy$toCYON:(bool)objective {
792 NSString *value([self boolValue] ? @"true" : @"false");
793 return objective ? value : [NSString stringWithFormat:@"@%@", value];
796 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
797 return CYCastJSValue(context, (bool) [self boolValue]);
803 /* Bridge: NSDictionary {{{ */
804 @implementation NSDictionary (Cycript)
807 return [[self mutableCopy] autorelease];
810 - (NSString *) cy$toCYON:(bool)objective {
811 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
812 [json appendString:@"@{"];
816 for (NSObject *key in self) {
818 NSEnumerator *keys([self keyEnumerator]);
819 while (NSObject *key = [keys nextObject]) {
822 [json appendString:@","];
825 [json appendString:CYCastNSCYON(key, true)];
826 [json appendString:@":"];
827 NSObject *object([self objectForKey:key]);
828 [json appendString:CYCastNSCYON(object, true)];
831 [json appendString:@"}"];
835 - (bool) cy$hasProperty:(NSString *)name {
836 return [self objectForKey:name] != nil;
839 - (NSObject *) cy$getProperty:(NSString *)name {
840 return [self objectForKey:name];
843 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
844 [super cy$getPropertyNames:names inContext:context];
847 for (NSObject *key in self) {
849 NSEnumerator *keys([self keyEnumerator]);
850 while (NSObject *key = [keys nextObject]) {
852 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
856 + (bool) cy$hasImplicitProperties {
862 /* Bridge: NSMutableArray {{{ */
863 @implementation NSMutableArray (Cycript)
865 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
866 if ([name isEqualToString:@"length"]) {
867 // XXX: is this not intelligent?
868 NSNumber *number(reinterpret_cast<NSNumber *>(value));
870 NSUInteger size([number unsignedIntegerValue]);
872 NSUInteger size([number unsignedIntValue]);
874 NSUInteger count([self count]);
876 [self removeObjectsInRange:NSMakeRange(size, count - size)];
877 else if (size != count) {
878 WebUndefined *undefined([WebUndefined undefined]);
879 for (size_t i(count); i != size; ++i)
880 [self addObject:undefined];
885 size_t index(CYGetIndex(name));
886 if (index == _not(size_t))
887 return [super cy$setProperty:name to:value];
889 id object(value ?: [NSNull null]);
891 size_t count([self count]);
893 [self replaceObjectAtIndex:index withObject:object];
895 if (index != count) {
896 WebUndefined *undefined([WebUndefined undefined]);
897 for (size_t i(count); i != index; ++i)
898 [self addObject:undefined];
901 [self addObject:object];
907 - (bool) cy$deleteProperty:(NSString *)name {
908 size_t index(CYGetIndex(name));
909 if (index == _not(size_t) || index >= [self count])
910 return [super cy$deleteProperty:name];
911 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
917 /* Bridge: NSMutableDictionary {{{ */
918 @implementation NSMutableDictionary (Cycript)
920 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
921 [self setObject:(value ?: [NSNull null]) forKey:name];
925 - (bool) cy$deleteProperty:(NSString *)name {
926 if ([self objectForKey:name] == nil)
929 [self removeObjectForKey:name];
936 /* Bridge: NSNumber {{{ */
937 @implementation NSNumber (Cycript)
939 - (JSType) cy$JSType {
941 // XXX: this just seems stupid
942 if ([self class] == NSCFBoolean_)
943 return kJSTypeBoolean;
945 return kJSTypeNumber;
948 - (NSString *) cy$toCYON:(bool)objective {
949 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
950 return objective ? value : [NSString stringWithFormat:@"@%@", value];
953 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
954 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
959 /* Bridge: NSNull {{{ */
960 @implementation NSNull (Cycript)
962 - (JSType) cy$JSType {
966 - (NSString *) cy$toCYON:(bool)objective {
967 NSString *value(@"null");
968 return objective ? value : [NSString stringWithFormat:@"@%@", value];
971 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
972 return CYJSNull(context);
977 /* Bridge: NSObject {{{ */
978 @implementation NSObject (Cycript)
984 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
985 return [self cy$valueOfInContext:context];
988 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
992 - (JSType) cy$JSType {
993 return kJSTypeObject;
996 - (NSString *) cy$toCYON:(bool)objective {
997 return [[self description] cy$toCYON:objective];
1000 - (bool) cy$hasProperty:(NSString *)name {
1004 - (NSObject *) cy$getProperty:(NSString *)name {
1008 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_(context) {
1009 if (NSObject *value = [self cy$getProperty:name])
1010 return CYCastJSValue(context, value);
1012 } CYObjectiveCatch }
1014 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1018 - (bool) cy$deleteProperty:(NSString *)name {
1022 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1025 + (bool) cy$hasImplicitProperties {
1031 /* Bridge: NSProxy {{{ */
1032 @implementation NSProxy (Cycript)
1034 - (NSString *) cy$toCYON:(bool)objective {
1035 return [[self description] cy$toCYON:objective];
1040 /* Bridge: NSString {{{ */
1041 @implementation NSString (Cycript)
1044 return [[self copy] autorelease];
1047 - (JSType) cy$JSType {
1048 return kJSTypeString;
1051 - (NSString *) cy$toCYON:(bool)objective {
1052 std::ostringstream str;
1055 CYUTF8String string(CYCastUTF8String(self));
1056 CYStringify(str, string.data, string.size);
1057 std::string value(str.str());
1058 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1061 - (bool) cy$hasProperty:(NSString *)name {
1062 size_t index(CYGetIndex(name));
1063 if (index == _not(size_t) || index >= [self length])
1064 return [super cy$hasProperty:name];
1069 - (NSObject *) cy$getProperty:(NSString *)name {
1070 size_t index(CYGetIndex(name));
1071 if (index == _not(size_t) || index >= [self length])
1072 return [super cy$getProperty:name];
1074 return [self substringWithRange:NSMakeRange(index, 1)];
1077 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1078 [super cy$getPropertyNames:names inContext:context];
1080 for (size_t index(0), length([self length]); index != length; ++index) {
1082 sprintf(name, "%zu", index);
1083 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1087 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1088 return CYCastJSValue(context, CYJSString(context, self));
1089 } CYObjectiveCatch }
1093 /* Bridge: WebUndefined {{{ */
1094 @implementation WebUndefined (Cycript)
1096 - (JSType) cy$JSType {
1097 return kJSTypeUndefined;
1100 - (NSString *) cy$toCYON:(bool)objective {
1101 NSString *value(@"undefined");
1102 return value; // XXX: maybe use the below code, adding @undefined?
1103 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1106 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1107 return CYJSUndefined(context);
1108 } CYObjectiveCatch }
1113 static bool CYIsClass(id self) {
1115 return class_isMetaClass(object_getClass(self));
1117 return GSObjCIsClass(self);
1121 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1122 id self(CYCastNSObject(pool, context, value));
1123 if (CYIsClass(self))
1124 return (Class) self;
1125 throw CYJSError(context, "got something that is not a Class");
1129 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1131 size_t size(JSPropertyNameArrayGetCount(names));
1132 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1133 for (size_t index(0); index != size; ++index)
1134 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1138 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1140 return CYJSNull(context);
1142 return CYMakeInstance(context, value, false);
1143 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1145 @implementation CYJSObject
1147 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1148 if ((self = [super init]) != nil) {
1150 context_ = CYGetJSContext(context);
1151 JSGlobalContextRetain(context_);
1152 JSValueProtect(context_, object_);
1154 } CYObjectiveCatch }
1156 - (void) dealloc { CYObjectiveTry {
1157 JSValueUnprotect(context_, object_);
1158 JSGlobalContextRelease(context_);
1160 } CYObjectiveCatch }
1162 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1164 JSValueRef exception(NULL);
1165 const char *cyon(CYPoolCCYON(pool, context_, object_));
1166 CYThrow(context_, exception);
1168 return [super cy$toCYON:objective];
1170 return [NSString stringWithUTF8String:cyon];
1171 } CYObjectiveCatch }
1173 - (NSUInteger) count { CYObjectiveTry {
1174 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1175 size_t size(JSPropertyNameArrayGetCount(names));
1176 JSPropertyNameArrayRelease(names);
1178 } CYObjectiveCatch }
1180 - (id) objectForKey:(id)key { CYObjectiveTry {
1181 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1182 if (JSValueIsUndefined(context_, value))
1184 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1185 } CYObjectiveCatch }
1187 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1188 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1189 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1190 JSPropertyNameArrayRelease(names);
1192 } CYObjectiveCatch }
1194 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1195 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1196 } CYObjectiveCatch }
1198 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1199 JSValueRef exception(NULL);
1200 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1201 CYThrow(context_, exception);
1202 } CYObjectiveCatch }
1206 @implementation CYJSArray
1208 - (NSString *) cy$toCYON:(bool)objective {
1210 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1213 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1214 if ((self = [super init]) != nil) {
1216 context_ = CYGetJSContext(context);
1217 JSGlobalContextRetain(context_);
1218 JSValueProtect(context_, object_);
1220 } CYObjectiveCatch }
1222 - (void) dealloc { CYObjectiveTry {
1223 JSValueUnprotect(context_, object_);
1224 JSGlobalContextRelease(context_);
1226 } CYObjectiveCatch }
1228 - (NSUInteger) count { CYObjectiveTry {
1229 return CYArrayLength(context_, object_);
1230 } CYObjectiveCatch }
1232 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1233 size_t bounds([self count]);
1234 if (index >= bounds)
1235 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1236 JSValueRef exception(NULL);
1237 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1238 CYThrow(context_, exception);
1239 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1240 } CYObjectiveCatch }
1242 - (void) addObject:(id)object { CYObjectiveTry {
1243 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1244 } CYObjectiveCatch }
1246 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1247 size_t bounds([self count] + 1);
1248 if (index >= bounds)
1249 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1250 JSValueRef exception(NULL);
1251 JSValueRef arguments[3];
1252 arguments[0] = CYCastJSValue(context_, index);
1253 arguments[1] = CYCastJSValue(context_, 0);
1254 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1255 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1256 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1257 CYThrow(context_, exception);
1258 } CYObjectiveCatch }
1260 - (void) removeLastObject { CYObjectiveTry {
1261 JSValueRef exception(NULL);
1262 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1263 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1264 CYThrow(context_, exception);
1265 } CYObjectiveCatch }
1267 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1268 size_t bounds([self count]);
1269 if (index >= bounds)
1270 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1271 JSValueRef exception(NULL);
1272 JSValueRef arguments[2];
1273 arguments[0] = CYCastJSValue(context_, index);
1274 arguments[1] = CYCastJSValue(context_, 1);
1275 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1276 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1277 CYThrow(context_, exception);
1278 } CYObjectiveCatch }
1280 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1281 size_t bounds([self count]);
1282 if (index >= bounds)
1283 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1284 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1285 } CYObjectiveCatch }
1289 // XXX: inherit from or replace with CYJSObject
1290 @interface CYInternal : NSObject {
1291 JSGlobalContextRef context_;
1292 JSObjectRef object_;
1297 @implementation CYInternal
1300 JSValueUnprotect(context_, object_);
1301 JSGlobalContextRelease(context_);
1305 - (id) initInContext:(JSContextRef)context {
1306 if ((self = [super init]) != nil) {
1307 context_ = CYGetJSContext(context);
1308 JSGlobalContextRetain(context_);
1312 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1313 if (object_ == NULL)
1316 return JSObjectHasProperty(context, object_, name);
1319 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1320 if (object_ == NULL)
1323 return CYGetProperty(context, object_, name);
1326 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1327 @synchronized (self) {
1328 if (object_ == NULL) {
1329 object_ = JSObjectMake(context, NULL, NULL);
1330 JSValueProtect(context, object_);
1334 CYSetProperty(context, object_, name, value);
1337 + (CYInternal *) get:(id)object {
1338 if ($objc_getAssociatedObject == NULL)
1341 @synchronized (object) {
1342 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1349 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1350 if ($objc_getAssociatedObject == NULL)
1353 @synchronized (object) {
1354 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1357 if ($objc_setAssociatedObject == NULL)
1360 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1361 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1370 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1371 Selector_privateData *internal(new Selector_privateData(sel));
1372 return JSObjectMake(context, Selector_, internal);
1375 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1376 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1377 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1378 return reinterpret_cast<SEL>(internal->value_);
1380 return CYCastPointer<SEL>(context, value);
1383 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1384 return (void *) [[NSAutoreleasePool alloc] init];
1385 } CYSadCatch(NULL) }
1387 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1388 return [(NSAutoreleasePool *) handle release];
1391 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1393 return Instance::Make(context, nil);
1394 if (Class _class = objc_getClass(name.data))
1395 return CYMakeInstance(context, _class, true);
1396 if (Protocol *protocol = objc_getProtocol(name.data))
1397 return CYMakeInstance(context, protocol, true);
1399 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1401 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1402 ffi_call(cif, function, value, values);
1405 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1406 switch (type->primitive) {
1407 // XXX: do something epic about blocks
1410 case sig::typename_P:
1411 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1414 case sig::selector_P:
1415 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1423 } CYSadCatch(false) }
1425 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1426 switch (type->primitive) {
1427 // XXX: do something epic about blocks
1430 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1431 JSValueRef value(CYCastJSValue(context, object));
1437 case sig::typename_P:
1438 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1440 case sig::selector_P:
1441 if (SEL sel = *reinterpret_cast<SEL *>(data))
1442 return CYMakeSelector(context, sel);
1446 return CYJSNull(context);
1450 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1452 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1453 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1456 #if OBJC_API_VERSION >= 2
1458 method_getReturnType(method, type, sizeof(type));
1460 const char *type(method_getTypeEncoding(method));
1466 // XXX: possibly use a more "awesome" check?
1470 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1472 return method_getTypeEncoding(method);
1474 const char *name(sel_getName(sel));
1475 size_t length(strlen(name));
1477 char keyed[length + 2];
1479 keyed[length + 1] = '\0';
1480 memcpy(keyed + 1, name, length);
1482 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1483 return entry->value_;
1488 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1489 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1491 JSContextRef context(internal->context_);
1493 size_t count(internal->cif_.nargs);
1494 JSValueRef values[count];
1496 for (size_t index(0); index != count; ++index)
1497 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1499 JSObjectRef _this(CYCastJSObject(context, values[0]));
1501 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1502 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1505 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1506 Message_privateData *internal(new Message_privateData(sel, type, imp));
1507 return JSObjectMake(context, Message_, internal);
1510 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1511 JSObjectRef function(CYCastJSObject(context, value));
1512 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1513 // XXX: see notes in Library.cpp about needing to leak
1514 return reinterpret_cast<IMP>(internal->GetValue());
1517 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1518 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1519 Class _class(internal->GetValue());
1522 const char *name(CYPoolCString(pool, context, property));
1524 if (SEL sel = sel_getUid(name))
1525 if (class_getInstanceMethod(_class, sel) != NULL)
1531 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1532 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1533 Class _class(internal->GetValue());
1536 const char *name(CYPoolCString(pool, context, property));
1538 if (SEL sel = sel_getUid(name))
1539 if (objc_method *method = class_getInstanceMethod(_class, sel))
1540 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1545 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1546 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1547 Class _class(internal->GetValue());
1550 const char *name(CYPoolCString(pool, context, property));
1552 SEL sel(sel_registerName(name));
1554 objc_method *method(class_getInstanceMethod(_class, sel));
1559 if (JSValueIsObjectOfClass(context, value, Message_)) {
1560 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1561 type = sig::Unparse(pool, &message->signature_);
1562 imp = reinterpret_cast<IMP>(message->GetValue());
1564 type = CYPoolTypeEncoding(pool, context, sel, method);
1565 imp = CYMakeMessage(context, value, type);
1569 method_setImplementation(method, imp);
1572 GSMethodList list(GSAllocMethodList(1));
1573 GSAppendMethodToList(list, sel, type, imp, YES);
1574 GSAddMethodList(_class, list, YES);
1575 GSFlushMethodCacheForClass(_class);
1577 class_addMethod(_class, sel, imp, type);
1584 #if 0 && OBJC_API_VERSION < 2
1585 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1586 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1587 Class _class(internal->GetValue());
1590 const char *name(CYPoolCString(pool, context, property));
1592 if (SEL sel = sel_getUid(name))
1593 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1594 objc_method_list list = {NULL, 1, {method}};
1595 class_removeMethods(_class, &list);
1603 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1604 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1605 Class _class(internal->GetValue());
1607 #if OBJC_API_VERSION >= 2
1609 objc_method **data(class_copyMethodList(_class, &size));
1610 for (size_t i(0); i != size; ++i)
1611 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1614 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1615 for (int i(0); i != methods->method_count; ++i)
1616 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1620 static bool CYHasImplicitProperties(Class _class) {
1621 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1622 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1624 return [_class cy$hasImplicitProperties];
1627 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1628 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1629 id self(internal->GetValue());
1631 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1635 NSString *name(CYCastNSString(pool, context, property));
1637 if (CYInternal *internal = [CYInternal get:self])
1638 if ([internal hasProperty:property inContext:context])
1641 Class _class(object_getClass(self));
1644 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1645 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1646 if ([self cy$hasProperty:name])
1648 } CYPoolCatch(false)
1650 const char *string(CYPoolCString(pool, context, name));
1653 if (class_getProperty(_class, string) != NULL)
1657 if (CYHasImplicitProperties(_class))
1658 if (SEL sel = sel_getUid(string))
1659 if (CYImplements(self, _class, sel, true))
1665 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1666 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1667 id self(internal->GetValue());
1669 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1670 return Internal::Make(context, self, object);
1673 NSString *name(CYCastNSString(pool, context, property));
1675 if (CYInternal *internal = [CYInternal get:self])
1676 if (JSValueRef value = [internal getProperty:property inContext:context])
1680 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1684 const char *string(CYPoolCString(pool, context, name));
1685 Class _class(object_getClass(self));
1688 if (objc_property_t property = class_getProperty(_class, string)) {
1689 PropertyAttributes attributes(property);
1690 SEL sel(sel_registerName(attributes.Getter()));
1691 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1695 if (CYHasImplicitProperties(_class))
1696 if (SEL sel = sel_getUid(string))
1697 if (CYImplements(self, _class, sel, true))
1698 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1703 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1709 NSString *name(CYCastNSString(pool, context, property));
1710 NSObject *data(CYCastNSObject(pool, context, value));
1713 if ([self cy$setProperty:name to:data])
1717 const char *string(CYPoolCString(pool, context, name));
1718 Class _class(object_getClass(self));
1721 if (objc_property_t property = class_getProperty(_class, string)) {
1722 PropertyAttributes attributes(property);
1723 if (const char *setter = attributes.Setter()) {
1724 SEL sel(sel_registerName(setter));
1725 JSValueRef arguments[1] = {value};
1726 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1732 size_t length(strlen(string));
1734 char set[length + 5];
1740 if (string[0] != '\0') {
1741 set[3] = toupper(string[0]);
1742 memcpy(set + 4, string + 1, length - 1);
1745 set[length + 3] = ':';
1746 set[length + 4] = '\0';
1748 if (SEL sel = sel_getUid(set))
1749 if (CYImplements(self, _class, sel)) {
1750 JSValueRef arguments[1] = {value};
1751 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1755 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1756 [internal setProperty:property toValue:value inContext:context];
1763 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1764 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1765 id self(internal->GetValue());
1768 NSString *name(CYCastNSString(NULL, context, property));
1769 return [self cy$deleteProperty:name];
1771 } CYCatch return /*XXX*/ NULL; }
1773 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1774 const char *name(sel_getName(method_getName(method)));
1775 if (strchr(name, ':') != NULL)
1778 const char *type(method_getTypeEncoding(method));
1779 if (type == NULL || *type == '\0' || *type == 'v')
1782 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1785 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1786 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1787 id self(internal->GetValue());
1790 Class _class(object_getClass(self));
1795 objc_property_t *data(class_copyPropertyList(_class, &size));
1796 for (size_t i(0); i != size; ++i)
1797 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1802 if (CYHasImplicitProperties(_class))
1803 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1804 #if OBJC_API_VERSION >= 2
1806 objc_method **data(class_copyMethodList(current, &size));
1807 for (size_t i(0); i != size; ++i)
1808 Instance_getPropertyNames_message(names, data[i]);
1811 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1812 for (int i(0); i != methods->method_count; ++i)
1813 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1818 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1819 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1820 [self cy$getPropertyNames:names inContext:context];
1824 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1825 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1826 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1830 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1831 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1832 id self(internal->GetValue());
1834 if (![self isKindOfClass:NSBlock_])
1835 CYThrow("non-NSBlock object is not a function");
1836 // XXX: replace above logic with the following assertion
1837 //_assert([self isKindOfClass:NSBlock_]);
1838 // to do this, make it so FunctionInstance_ is the class of blocks
1839 // to do /that/, generalize the various "is exactly Instance_" checks
1840 // then, move Instance_callAsFunction to only be on FunctionInstance
1842 struct BlockDescriptor1 {
1843 unsigned long int reserved;
1844 unsigned long int size;
1847 struct BlockDescriptor2 {
1848 void (*copy_helper)(void *dst, void *src);
1849 void (*dispose_helper)(void *src);
1852 struct BlockDescriptor3 {
1853 const char *signature;
1857 struct BlockLiteral {
1861 void (*invoke)(void *, ...);
1863 } *literal = reinterpret_cast<BlockLiteral *>(self);
1866 BLOCK_DEALLOCATING = 0x0001,
1867 BLOCK_REFCOUNT_MASK = 0xfffe,
1868 BLOCK_NEEDS_FREE = 1 << 24,
1869 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1870 BLOCK_HAS_CTOR = 1 << 26,
1871 BLOCK_IS_GC = 1 << 27,
1872 BLOCK_IS_GLOBAL = 1 << 28,
1873 BLOCK_HAS_STRET = 1 << 29,
1874 BLOCK_HAS_SIGNATURE = 1 << 30,
1877 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1878 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1879 descriptor += sizeof(BlockDescriptor1);
1880 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1881 descriptor += sizeof(BlockDescriptor2);
1882 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1884 if (const char *type = descriptor3->signature) {
1890 sig::Signature signature;
1891 sig::Parse(pool, &signature, type, &Structor_);
1894 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1896 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1897 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1902 CYThrow("NSBlock without signature field passed arguments");
1906 } CYPoolCatch(NULL);
1911 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1912 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1913 Class _class(internal->GetValue());
1914 if (!CYIsClass(_class))
1917 if (CYJSValueIsNSObject(context, instance)) {
1918 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1919 // XXX: this isn't always safe
1920 return [linternal->GetValue() isKindOfClass:_class];
1926 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1928 throw CYJSError(context, "incorrect number of arguments to Instance");
1930 id value(CYCastNSObject(pool, context, arguments[0]));
1932 value = [NSNull null];
1933 return CYCastJSValue(context, [value cy$box]);
1936 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1937 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1940 id self(internal->GetValue());
1941 const char *name(CYPoolCString(pool, context, property));
1943 if (object_getInstanceVariable(self, name, NULL) != NULL)
1949 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1950 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1953 id self(internal->GetValue());
1954 const char *name(CYPoolCString(pool, context, property));
1956 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1957 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1958 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1959 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1965 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1966 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1969 id self(internal->GetValue());
1970 const char *name(CYPoolCString(pool, context, property));
1972 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1973 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1974 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1981 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1982 if (Class super = class_getSuperclass(_class))
1983 Internal_getPropertyNames_(super, names);
1985 #if OBJC_API_VERSION >= 2
1987 objc_ivar **data(class_copyIvarList(_class, &size));
1988 for (size_t i(0); i != size; ++i)
1989 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1992 if (objc_ivar_list *ivars = _class->ivars)
1993 for (int i(0); i != ivars->ivar_count; ++i)
1994 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1998 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1999 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2002 id self(internal->GetValue());
2003 Class _class(object_getClass(self));
2005 Internal_getPropertyNames_(_class, names);
2008 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2009 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2010 return internal->GetOwner();
2013 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2015 NSString *name(CYCastNSString(pool, context, property));
2016 if (Class _class = NSClassFromString(name))
2017 return CYMakeInstance(context, _class, true);
2021 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2023 size_t size(objc_getClassList(NULL, 0));
2024 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2027 size_t writ(objc_getClassList(data, size));
2030 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2036 for (size_t i(0); i != writ; ++i)
2037 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2043 while (Class _class = objc_next_class(&state))
2044 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2048 #if OBJC_API_VERSION >= 2
2049 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2050 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2053 const char *name(CYPoolCString(pool, context, property));
2055 const char **data(objc_copyClassNamesForImage(internal, &size));
2057 for (size_t i(0); i != size; ++i)
2058 if (strcmp(name, data[i]) == 0) {
2059 if (Class _class = objc_getClass(name)) {
2060 value = CYMakeInstance(context, _class, true);
2071 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2072 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2074 const char **data(objc_copyClassNamesForImage(internal, &size));
2075 for (size_t i(0); i != size; ++i)
2076 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2080 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2082 const char *name(CYPoolCString(pool, context, property));
2084 const char **data(objc_copyImageNames(&size));
2085 for (size_t i(0); i != size; ++i)
2086 if (strcmp(name, data[i]) == 0) {
2095 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2096 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2100 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2102 const char **data(objc_copyImageNames(&size));
2103 for (size_t i(0); i != size; ++i)
2104 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2109 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2111 const char *name(CYPoolCString(pool, context, property));
2112 if (Protocol *protocol = objc_getProtocol(name))
2113 return CYMakeInstance(context, protocol, true);
2117 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2118 #if OBJC_API_VERSION >= 2
2120 Protocol **data(objc_copyProtocolList(&size));
2121 for (size_t i(0); i != size; ++i)
2122 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2129 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2131 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2133 return Instance::Make(context, nil);
2137 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2138 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2142 static bool stret(ffi_type *ffi_type) {
2143 return ffi_type->type == FFI_TYPE_STRUCT && (
2144 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2145 struct_forward_array[ffi_type->size] != 0
2150 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 {
2154 _class = object_getClass(self);
2158 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2159 imp = method_getImplementation(method);
2160 type = method_getTypeEncoding(method);
2165 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2167 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2168 type = CYPoolCString(pool, context, [method _typeString]);
2176 sig::Signature signature;
2177 sig::Parse(pool, &signature, type, &Structor_);
2179 size_t used(count + 3);
2180 if (used > signature.count) {
2181 sig::Element *elements(new (pool) sig::Element[used]);
2182 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2184 for (size_t index(signature.count); index != used; ++index) {
2185 sig::Element *element(&elements[index]);
2186 element->name = NULL;
2187 element->offset = _not(size_t);
2189 sig::Type *type(new (pool) sig::Type);
2190 memset(type, 0, sizeof(*type));
2191 type->primitive = sig::object_P;
2192 element->type = type;
2195 signature.elements = elements;
2196 signature.count = used;
2200 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2204 if (stret(cif.rtype))
2205 imp = class_getMethodImplementation_stret(_class, _cmd);
2207 imp = class_getMethodImplementation(_class, _cmd);
2209 objc_super super = {self, _class};
2210 imp = objc_msg_lookup_super(&super, _cmd);
2214 void (*function)() = reinterpret_cast<void (*)()>(imp);
2215 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2218 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2220 throw CYJSError(context, "too few arguments to objc_msgSend");
2230 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2231 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2232 self = internal->GetValue();
2233 _class = internal->class_;;
2234 uninitialized = false;
2235 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2236 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2237 self = internal->GetValue();
2239 uninitialized = internal->IsUninitialized();
2241 internal->value_ = nil;
2243 self = CYCastNSObject(pool, context, arguments[0]);
2245 uninitialized = false;
2249 return CYJSNull(context);
2251 _cmd = CYCastSEL(context, arguments[1]);
2253 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2256 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2257 JSValueRef setup[count + 2];
2260 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2261 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2264 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2266 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2268 // XXX: handle Instance::Uninitialized?
2269 id self(CYCastNSObject(pool, context, _this));
2273 setup[1] = &internal->sel_;
2275 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2278 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2280 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2282 id self(CYCastNSObject(pool, context, arguments[0]));
2283 Class _class(CYCastClass(pool, context, arguments[1]));
2284 return cy::Super::Make(context, self, _class);
2287 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2289 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2291 const char *name(CYPoolCString(pool, context, arguments[0]));
2292 return CYMakeSelector(context, sel_registerName(name));
2295 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2297 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2298 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2299 return CYMakeInstance(context, self, false);
2302 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2303 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2304 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2307 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2308 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2309 Type_privateData *typical(internal->GetType());
2314 if (typical == NULL) {
2318 type = typical->type_;
2319 ffi = typical->ffi_;
2322 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2325 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2326 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2327 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2330 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2331 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2332 id self(internal->GetValue());
2333 if (!CYIsClass(self))
2334 return CYJSUndefined(context);
2335 return CYGetClassPrototype(context, self);
2338 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2339 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2340 id self(internal->GetValue());
2341 if (!CYIsClass(self))
2342 return CYJSUndefined(context);
2343 return Messages::Make(context, (Class) self);
2346 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2347 if (!CYJSValueIsNSObject(context, _this))
2350 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2351 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2354 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2355 if (!CYJSValueIsNSObject(context, _this))
2358 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2359 id value(internal->GetValue());
2366 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2368 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2369 return CYJSUndefined(context);
2370 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2373 return CYCastJSValue(context, CYJSString(context, [value description]));
2375 } CYCatch return /*XXX*/ NULL; }
2377 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2378 if (!CYJSValueIsNSObject(context, _this))
2381 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2382 id value(internal->GetValue());
2384 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2387 if (JSValueRef result = [value cy$valueOfInContext:context])
2391 } CYCatch return /*XXX*/ NULL; }
2393 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2394 if (!CYJSValueIsNSObject(context, _this))
2397 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2398 // XXX: but... but... THIS ISN'T A POINTER! :(
2399 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2400 } CYCatch return /*XXX*/ NULL; }
2402 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2403 if (!CYJSValueIsNSObject(context, _this))
2406 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2407 id value(internal->GetValue());
2410 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2411 return CYCastJSValue(context, CYJSString(context, [value description]));
2413 } CYCatch return /*XXX*/ NULL; }
2415 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2416 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2417 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2420 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2421 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2424 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2425 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2426 const char *name(sel_getName(internal->GetValue()));
2429 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2430 return CYCastJSValue(context, CYJSString(context, string));
2432 } CYCatch return /*XXX*/ NULL; }
2434 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2436 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2439 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2440 SEL sel(internal->GetValue());
2442 objc_method *method;
2443 if (Class _class = CYCastClass(pool, context, arguments[0]))
2444 method = class_getInstanceMethod(_class, sel);
2448 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2449 return CYCastJSValue(context, CYJSString(type));
2451 return CYJSNull(context);
2454 static JSStaticValue Selector_staticValues[2] = {
2455 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2456 {NULL, NULL, NULL, 0}
2459 static JSStaticValue Instance_staticValues[5] = {
2460 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2461 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2462 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2463 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2464 {NULL, NULL, NULL, 0}
2467 static JSStaticFunction Instance_staticFunctions[7] = {
2468 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2469 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2470 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2471 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2472 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2473 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2477 static JSStaticFunction Internal_staticFunctions[2] = {
2478 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2482 static JSStaticFunction Selector_staticFunctions[5] = {
2483 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2484 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2485 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2486 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2491 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_(context) {
2492 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2493 } CYObjectiveCatch }
2496 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2497 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2498 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2499 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2501 apr_pool_t *pool(CYGetGlobalPool());
2503 Object_type = new(pool) Type_privateData("@");
2504 Selector_type = new(pool) Type_privateData(":");
2507 // XXX: apparently, iOS now has both of these
2508 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2509 if (NSCFBoolean_ == nil)
2510 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2512 NSCFType_ = objc_getClass("NSCFType");
2513 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2514 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2515 NSZombie_ = objc_getClass("_NSZombie_");
2517 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2520 NSArray_ = objc_getClass("NSArray");
2521 NSBlock_ = objc_getClass("NSBlock");
2522 NSDictionary_ = objc_getClass("NSDictionary");
2523 NSString_ = objc_getClass("NSString");
2524 Object_ = objc_getClass("Object");
2526 JSClassDefinition definition;
2528 definition = kJSClassDefinitionEmpty;
2529 definition.className = "Instance";
2530 definition.staticValues = Instance_staticValues;
2531 definition.staticFunctions = Instance_staticFunctions;
2532 definition.hasProperty = &Instance_hasProperty;
2533 definition.getProperty = &Instance_getProperty;
2534 definition.setProperty = &Instance_setProperty;
2535 definition.deleteProperty = &Instance_deleteProperty;
2536 definition.getPropertyNames = &Instance_getPropertyNames;
2537 definition.callAsConstructor = &Instance_callAsConstructor;
2538 definition.callAsFunction = &Instance_callAsFunction;
2539 definition.hasInstance = &Instance_hasInstance;
2540 definition.finalize = &CYFinalize;
2541 Instance_ = JSClassCreate(&definition);
2543 definition.className = "ArrayInstance";
2544 ArrayInstance_ = JSClassCreate(&definition);
2546 definition.className = "FunctionInstance";
2547 FunctionInstance_ = JSClassCreate(&definition);
2549 definition.className = "ObjectInstance";
2550 ObjectInstance_ = JSClassCreate(&definition);
2552 definition.className = "StringInstance";
2553 StringInstance_ = JSClassCreate(&definition);
2555 definition.className = "TypeInstance";
2556 TypeInstance_ = JSClassCreate(&definition);
2558 definition = kJSClassDefinitionEmpty;
2559 definition.className = "Internal";
2560 definition.staticFunctions = Internal_staticFunctions;
2561 definition.hasProperty = &Internal_hasProperty;
2562 definition.getProperty = &Internal_getProperty;
2563 definition.setProperty = &Internal_setProperty;
2564 definition.getPropertyNames = &Internal_getPropertyNames;
2565 definition.finalize = &CYFinalize;
2566 Internal_ = JSClassCreate(&definition);
2568 definition = kJSClassDefinitionEmpty;
2569 definition.className = "Message";
2570 definition.staticFunctions = cy::Functor::StaticFunctions;
2571 definition.callAsFunction = &Message_callAsFunction;
2572 definition.finalize = &CYFinalize;
2573 Message_ = JSClassCreate(&definition);
2575 definition = kJSClassDefinitionEmpty;
2576 definition.className = "Messages";
2577 definition.hasProperty = &Messages_hasProperty;
2578 definition.getProperty = &Messages_getProperty;
2579 definition.setProperty = &Messages_setProperty;
2580 #if 0 && OBJC_API_VERSION < 2
2581 definition.deleteProperty = &Messages_deleteProperty;
2583 definition.getPropertyNames = &Messages_getPropertyNames;
2584 definition.finalize = &CYFinalize;
2585 Messages_ = JSClassCreate(&definition);
2587 definition = kJSClassDefinitionEmpty;
2588 definition.className = "Selector";
2589 definition.staticValues = Selector_staticValues;
2590 definition.staticFunctions = Selector_staticFunctions;
2591 definition.callAsFunction = &Selector_callAsFunction;
2592 definition.finalize = &CYFinalize;
2593 Selector_ = JSClassCreate(&definition);
2595 definition = kJSClassDefinitionEmpty;
2596 definition.className = "Super";
2597 definition.staticFunctions = Internal_staticFunctions;
2598 definition.finalize = &CYFinalize;
2599 Super_ = JSClassCreate(&definition);
2601 definition = kJSClassDefinitionEmpty;
2602 definition.className = "ObjectiveC::Classes";
2603 definition.getProperty = &ObjectiveC_Classes_getProperty;
2604 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2605 ObjectiveC_Classes_ = JSClassCreate(&definition);
2607 definition = kJSClassDefinitionEmpty;
2608 definition.className = "ObjectiveC::Constants";
2609 definition.getProperty = &ObjectiveC_Constants_getProperty;
2610 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2611 ObjectiveC_Constants_ = JSClassCreate(&definition);
2613 #if OBJC_API_VERSION >= 2
2614 definition = kJSClassDefinitionEmpty;
2615 definition.className = "ObjectiveC::Images";
2616 definition.getProperty = &ObjectiveC_Images_getProperty;
2617 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2618 ObjectiveC_Images_ = JSClassCreate(&definition);
2620 definition = kJSClassDefinitionEmpty;
2621 definition.className = "ObjectiveC::Image::Classes";
2622 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2623 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2624 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2627 definition = kJSClassDefinitionEmpty;
2628 definition.className = "ObjectiveC::Protocols";
2629 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2630 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2631 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2634 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2638 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2639 JSObjectRef global(CYGetGlobalObject(context));
2640 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2641 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2642 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2643 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2645 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2646 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2648 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2649 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2650 CYArrayPush(context, alls, protocols);
2652 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2653 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2654 CYArrayPush(context, alls, classes);
2656 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2657 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2658 CYArrayPush(context, alls, constants);
2660 #if OBJC_API_VERSION >= 2
2661 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2664 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2665 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2666 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2667 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2669 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2670 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2672 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2673 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2674 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2675 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2676 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2678 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2679 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2680 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2681 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2682 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2684 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2685 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2686 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2687 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2688 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2690 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2691 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2692 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2693 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2694 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2696 JSObjectRef TypeInstance(JSObjectMakeConstructor(context, TypeInstance_, NULL));
2697 JSObjectRef TypeInstance_prototype(CYCastJSObject(context, CYGetProperty(context, TypeInstance, prototype_s)));
2698 CYSetProperty(context, cy, CYJSString("TypeInstance_prototype"), TypeInstance_prototype);
2699 JSObjectRef Type_prototype(CYGetCachedObject(context, CYJSString("Type_prototype")));
2700 JSObjectSetPrototype(context, TypeInstance_prototype, Type_prototype);
2702 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2703 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2704 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2706 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2707 CYSetProperty(context, Instance, CYJSString("box"), box);
2709 #if defined(__APPLE__) && defined(__arm__) && 0
2710 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2713 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2715 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2716 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2719 static CYHooks CYObjectiveCHooks = {
2720 &CYObjectiveC_ExecuteStart,
2721 &CYObjectiveC_ExecuteEnd,
2722 &CYObjectiveC_CallFunction,
2723 &CYObjectiveC_Initialize,
2724 &CYObjectiveC_SetupContext,
2725 &CYObjectiveC_PoolFFI,
2726 &CYObjectiveC_FromFFI,
2729 struct CYObjectiveC {
2731 hooks_ = &CYObjectiveCHooks;
2732 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2733 _assert(hooks_ != NULL);