1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2010 Jay Freeman (saurik)
5 /* GNU Lesser General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
26 #include <Foundation/Foundation.h>
28 #include "ObjectiveC/Internal.hpp"
30 #include <objc/objc-api.h>
32 #include "cycript.hpp"
34 #include "ObjectiveC/Internal.hpp"
37 #include <CoreFoundation/CoreFoundation.h>
38 #include <JavaScriptCore/JSStringRefCF.h>
39 #include <WebKit/WebScriptObject.h>
40 #include <objc/runtime.h>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
51 #define CYObjectiveTry_(context) { \
52 JSContextRef context_(context); \
54 #define CYObjectiveTry { \
56 #define CYObjectiveCatch \
57 catch (const CYException &error) { \
58 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
64 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
66 #define CYPoolCatch(value) \
67 @catch (NSException *error) { \
68 _saved = [error retain]; \
69 throw CYJSError(context, CYCastJSValue(context, error)); \
74 [_saved autorelease]; \
80 #define CYSadCatch(value) \
81 @catch (NSException *error ) { \
82 throw CYJSError(context, CYCastJSValue(context, error)); \
87 #define class_getSuperclass GSObjCSuper
88 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
89 #define class_getName GSNameFromClass
91 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
93 #define ivar_getName(ivar) ((ivar)->ivar_name)
94 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
95 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
97 #define method_getName(method) ((method)->method_name)
98 #define method_getImplementation(method) ((method)->method_imp)
99 #define method_getTypeEncoding(method) ((method)->method_types)
100 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
103 #define objc_getClass GSClassFromName
105 #define objc_getProtocol GSProtocolFromName
107 #define object_getClass GSObjCClass
109 #define object_getInstanceVariable(object, name, value) ({ \
110 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
111 _assert(value != NULL); \
113 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
117 #define object_setIvar(object, ivar, value) ({ \
118 void *data = (value); \
119 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
122 #define protocol_getName(protocol) [(protocol) name]
125 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
127 /* Objective-C Pool Release {{{ */
128 apr_status_t CYPoolRelease_(void *data) {
129 id object(reinterpret_cast<id>(data));
134 id CYPoolRelease_(apr_pool_t *pool, id object) {
137 else if (pool == NULL)
138 return [object autorelease];
140 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
145 template <typename Type_>
146 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
147 return (Type_) CYPoolRelease_(pool, (id) object);
150 /* Objective-C Strings {{{ */
151 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
153 return [value UTF8String];
155 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
156 char *string(new(pool) char[size]);
157 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
158 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
163 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
165 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
168 return CYCopyJSString(CYPoolCString(pool, context, value));
172 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
175 // XXX: this definition scares me; is anyone using this?!
176 NSString *string([value description]);
177 return CYCopyJSString(context, string);
180 NSString *CYCopyNSString(const CYUTF8String &value) {
182 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
184 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
188 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
190 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
193 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
197 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
198 return CYCopyNSString(context, CYJSString(context, value));
201 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
202 return CYPoolRelease(pool, CYCopyNSString(value));
205 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
206 const char *name(sel_getName(sel));
207 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
210 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
211 return CYPoolRelease(pool, CYCopyNSString(context, value));
214 CYUTF8String CYCastUTF8String(NSString *value) {
215 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
216 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
220 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
222 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
223 if (exception == NULL)
225 *exception = CYCastJSValue(context, error);
228 size_t CYGetIndex(NSString *value) {
229 return CYGetIndex(CYCastUTF8String(value));
232 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
233 return CYGetOffset(CYPoolCString(pool, context, value), index);
236 static JSClassRef Instance_;
237 static JSClassRef Internal_;
238 static JSClassRef Message_;
239 static JSClassRef Messages_;
240 static JSClassRef Selector_;
241 static JSClassRef StringInstance_;
242 static JSClassRef Super_;
244 static JSClassRef ObjectiveC_Classes_;
245 static JSClassRef ObjectiveC_Protocols_;
248 static JSClassRef ObjectiveC_Image_Classes_;
249 static JSClassRef ObjectiveC_Images_;
253 static Class NSCFBoolean_;
254 static Class NSCFType_;
255 static Class NSMessageBuilder_;
256 static Class NSZombie_;
258 static Class NSBoolNumber_;
261 static Class NSArray_;
262 static Class NSDictionary_;
263 static Class NSString_;
264 static Class Object_;
266 static Type_privateData *Object_type;
267 static Type_privateData *Selector_type;
269 Type_privateData *Instance::GetType() const {
273 Type_privateData *Selector_privateData::GetType() const {
274 return Selector_type;
277 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
279 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
281 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
283 JSObjectRef global(CYGetGlobalObject(context));
284 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
287 sprintf(label, "i%p", self);
288 CYJSString name(label);
290 JSValueRef value(CYGetProperty(context, cy, name));
291 if (!JSValueIsUndefined(context, value))
294 JSClassRef _class(NULL);
295 JSValueRef prototype;
297 if (self == NSArray_)
298 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
299 else if (self == NSDictionary_)
300 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
301 else if (self == NSString_)
302 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
304 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
306 JSObjectRef object(JSObjectMake(context, _class, NULL));
307 JSObjectSetPrototype(context, object, prototype);
308 CYSetProperty(context, cy, name, object);
313 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
314 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
315 if (_class == NSArray_)
317 if (Class super = class_getSuperclass(_class))
318 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
320 JSObjectSetPrototype(context, value, Array_prototype_);*/
324 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
325 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
329 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
330 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
334 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
335 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
336 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
340 Instance::~Instance() {
341 if ((flags_ & Transient) == 0)
342 // XXX: does this handle background threads correctly?
343 // XXX: this simply does not work on the console because I'm stupid
344 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
347 struct Message_privateData :
352 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
353 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
359 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
360 Instance::Flags flags;
363 flags = Instance::Transient;
365 flags = Instance::None;
366 object = [object retain];
369 return Instance::Make(context, object, flags);
372 @interface NSMethodSignature (Cycript)
373 - (NSString *) _typeString;
376 @interface NSObject (Cycript)
378 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
379 - (JSType) cy$JSType;
381 - (NSObject *) cy$toJSON:(NSString *)key;
382 - (NSString *) cy$toCYON;
383 - (NSString *) cy$toKey;
385 - (bool) cy$hasProperty:(NSString *)name;
386 - (NSObject *) cy$getProperty:(NSString *)name;
387 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
388 - (bool) cy$deleteProperty:(NSString *)name;
389 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
391 + (bool) cy$hasImplicitProperties;
396 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
399 NSString *CYCastNSCYON(id value) {
405 Class _class(object_getClass(value));
406 SEL sel(@selector(cy$toCYON));
408 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
409 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
410 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
411 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
412 string = [value cy$toCYON];
417 else if (value == NSZombie_)
418 string = @"_NSZombie_";
419 else if (_class == NSZombie_)
420 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
421 // XXX: frowny /in/ the pants
422 else if (value == NSMessageBuilder_ || value == Object_)
426 string = [NSString stringWithFormat:@"%@", value];
431 string = @"undefined";
438 struct PropertyAttributes {
443 const char *variable;
456 PropertyAttributes(objc_property_t property) :
468 name = property_getName(property);
469 const char *attributes(property_getAttributes(property));
471 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
473 case 'R': readonly = true; break;
474 case 'C': copy = true; break;
475 case '&': retain = true; break;
476 case 'N': nonatomic = true; break;
477 case 'G': getter_ = token + 1; break;
478 case 'S': setter_ = token + 1; break;
479 case 'V': variable = token + 1; break;
483 /*if (variable == NULL) {
484 variable = property_getName(property);
485 size_t size(strlen(variable));
486 char *name(new(pool_) char[size + 2]);
488 memcpy(name + 1, variable, size);
489 name[size + 1] = '\0';
494 const char *Getter() {
496 getter_ = apr_pstrdup(pool_, name);
500 const char *Setter() {
501 if (setter_ == NULL && !readonly) {
502 size_t length(strlen(name));
504 char *temp(new(pool_) char[length + 5]);
510 temp[3] = toupper(name[0]);
511 memcpy(temp + 4, name + 1, length - 1);
514 temp[length + 3] = ':';
515 temp[length + 4] = '\0';
526 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
527 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
532 @interface CYWebUndefined : NSObject {
535 + (CYWebUndefined *) undefined;
539 @implementation CYWebUndefined
541 + (CYWebUndefined *) undefined {
542 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
548 #define WebUndefined CYWebUndefined
551 /* Bridge: CYJSObject {{{ */
552 @interface CYJSObject : NSMutableDictionary {
554 JSContextRef context_;
557 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
559 - (NSObject *) cy$toJSON:(NSString *)key;
561 - (NSUInteger) count;
562 - (id) objectForKey:(id)key;
563 - (NSEnumerator *) keyEnumerator;
564 - (void) setObject:(id)object forKey:(id)key;
565 - (void) removeObjectForKey:(id)key;
569 /* Bridge: CYJSArray {{{ */
570 @interface CYJSArray : NSMutableArray {
572 JSContextRef context_;
575 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
577 - (NSUInteger) count;
578 - (id) objectAtIndex:(NSUInteger)index;
580 - (void) addObject:(id)anObject;
581 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
582 - (void) removeLastObject;
583 - (void) removeObjectAtIndex:(NSUInteger)index;
584 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
589 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
590 JSObjectRef Array(CYGetCachedObject(context, Array_s));
591 JSValueRef exception(NULL);
592 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
593 CYThrow(context, exception);
594 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
595 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
598 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
599 if (!JSValueIsObjectOfClass(context, object, Instance_))
600 return CYCastNSObject_(pool, context, object);
602 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
603 return internal->GetValue();
607 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
608 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
612 @interface NSBoolNumber : NSNumber {
617 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
621 switch (JSType type = JSValueGetType(context, value)) {
622 case kJSTypeUndefined:
623 object = [WebUndefined undefined];
633 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
636 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
642 object = CYCopyNSNumber(context, value);
647 object = CYCopyNSString(context, value);
652 // XXX: this might could be more efficient
653 object = CYCastNSObject(pool, context, (JSObjectRef) value);
658 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
665 return CYPoolRelease(pool, object);
667 return [object retain];
670 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
671 return CYNSObject(pool, context, value, true);
674 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
675 return CYNSObject(pool, context, value, false);
678 /* Bridge: NSArray {{{ */
679 @implementation NSArray (Cycript)
681 - (NSString *) cy$toCYON {
682 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
683 [json appendString:@"["];
687 for (id object in self) {
689 for (size_t index(0), count([self count]); index != count; ++index) {
690 id object([self objectAtIndex:index]);
693 [json appendString:@","];
696 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
697 [json appendString:CYCastNSCYON(object)];
699 [json appendString:@","];
704 [json appendString:@"]"];
708 - (bool) cy$hasProperty:(NSString *)name {
709 if ([name isEqualToString:@"length"])
712 size_t index(CYGetIndex(name));
713 if (index == _not(size_t) || index >= [self count])
714 return [super cy$hasProperty:name];
719 - (NSObject *) cy$getProperty:(NSString *)name {
720 if ([name isEqualToString:@"length"]) {
721 NSUInteger count([self count]);
723 return [NSNumber numberWithUnsignedInteger:count];
725 return [NSNumber numberWithUnsignedInt:count];
729 size_t index(CYGetIndex(name));
730 if (index == _not(size_t) || index >= [self count])
731 return [super cy$getProperty:name];
733 return [self objectAtIndex:index];
736 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
737 [super cy$getPropertyNames:names inContext:context];
739 for (size_t index(0), count([self count]); index != count; ++index) {
740 id object([self objectAtIndex:index]);
741 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
743 sprintf(name, "%zu", index);
744 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
749 + (bool) cy$hasImplicitProperties {
755 /* Bridge: NSBoolNumber {{{ */
757 @implementation NSBoolNumber (Cycript)
759 - (JSType) cy$JSType {
760 return kJSTypeBoolean;
763 - (NSObject *) cy$toJSON:(NSString *)key {
767 - (NSString *) cy$toCYON {
768 return [self boolValue] ? @"true" : @"false";
771 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
772 return CYCastJSValue(context, (bool) [self boolValue]);
778 /* Bridge: NSDictionary {{{ */
779 @implementation NSDictionary (Cycript)
781 - (NSString *) cy$toCYON {
782 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
783 [json appendString:@"{"];
787 for (NSObject *key in self) {
789 NSEnumerator *keys([self keyEnumerator]);
790 while (NSObject *key = [keys nextObject]) {
793 [json appendString:@","];
796 [json appendString:[key cy$toKey]];
797 [json appendString:@":"];
798 NSObject *object([self objectForKey:key]);
799 [json appendString:CYCastNSCYON(object)];
802 [json appendString:@"}"];
806 - (bool) cy$hasProperty:(NSString *)name {
807 return [self objectForKey:name] != nil;
810 - (NSObject *) cy$getProperty:(NSString *)name {
811 return [self objectForKey:name];
814 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
815 [super cy$getPropertyNames:names inContext:context];
818 for (NSObject *key in self) {
820 NSEnumerator *keys([self keyEnumerator]);
821 while (NSObject *key = [keys nextObject]) {
823 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
827 + (bool) cy$hasImplicitProperties {
833 /* Bridge: NSMutableArray {{{ */
834 @implementation NSMutableArray (Cycript)
836 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
837 if ([name isEqualToString:@"length"]) {
838 // XXX: is this not intelligent?
839 NSNumber *number(reinterpret_cast<NSNumber *>(value));
841 NSUInteger size([number unsignedIntegerValue]);
843 NSUInteger size([number unsignedIntValue]);
845 NSUInteger count([self count]);
847 [self removeObjectsInRange:NSMakeRange(size, count - size)];
848 else if (size != count) {
849 WebUndefined *undefined([WebUndefined undefined]);
850 for (size_t i(count); i != size; ++i)
851 [self addObject:undefined];
856 size_t index(CYGetIndex(name));
857 if (index == _not(size_t))
858 return [super cy$setProperty:name to:value];
860 id object(value ?: [NSNull null]);
862 size_t count([self count]);
864 [self replaceObjectAtIndex:index withObject:object];
866 if (index != count) {
867 WebUndefined *undefined([WebUndefined undefined]);
868 for (size_t i(count); i != index; ++i)
869 [self addObject:undefined];
872 [self addObject:object];
878 - (bool) cy$deleteProperty:(NSString *)name {
879 size_t index(CYGetIndex(name));
880 if (index == _not(size_t) || index >= [self count])
881 return [super cy$deleteProperty:name];
882 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
888 /* Bridge: NSMutableDictionary {{{ */
889 @implementation NSMutableDictionary (Cycript)
891 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
892 [self setObject:(value ?: [NSNull null]) forKey:name];
896 - (bool) cy$deleteProperty:(NSString *)name {
897 if ([self objectForKey:name] == nil)
900 [self removeObjectForKey:name];
907 /* Bridge: NSNumber {{{ */
908 @implementation NSNumber (Cycript)
910 - (JSType) cy$JSType {
912 // XXX: this just seems stupid
913 if ([self class] == NSCFBoolean_)
914 return kJSTypeBoolean;
916 return kJSTypeNumber;
919 - (NSObject *) cy$toJSON:(NSString *)key {
923 - (NSString *) cy$toCYON {
924 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
927 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
928 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
933 /* Bridge: NSNull {{{ */
934 @implementation NSNull (Cycript)
936 - (JSType) cy$JSType {
940 - (NSObject *) cy$toJSON:(NSString *)key {
944 - (NSString *) cy$toCYON {
950 /* Bridge: NSObject {{{ */
951 @implementation NSObject (Cycript)
953 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
954 return CYMakeInstance(context, self, false);
957 - (JSType) cy$JSType {
958 return kJSTypeObject;
961 - (NSObject *) cy$toJSON:(NSString *)key {
962 return [self description];
965 - (NSString *) cy$toCYON {
966 return [[self cy$toJSON:@""] cy$toCYON];
969 - (NSString *) cy$toKey {
970 return [self cy$toCYON];
973 - (bool) cy$hasProperty:(NSString *)name {
977 - (NSObject *) cy$getProperty:(NSString *)name {
981 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
985 - (bool) cy$deleteProperty:(NSString *)name {
989 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
992 + (bool) cy$hasImplicitProperties {
998 /* Bridge: NSProxy {{{ */
999 @implementation NSProxy (Cycript)
1001 - (NSObject *) cy$toJSON:(NSString *)key {
1002 return [self description];
1005 - (NSString *) cy$toCYON {
1006 return [[self cy$toJSON:@""] cy$toCYON];
1011 /* Bridge: NSString {{{ */
1012 @implementation NSString (Cycript)
1014 - (JSType) cy$JSType {
1015 return kJSTypeString;
1018 - (NSObject *) cy$toJSON:(NSString *)key {
1022 - (NSString *) cy$toCYON {
1023 std::ostringstream str;
1024 CYUTF8String string(CYCastUTF8String(self));
1025 CYStringify(str, string.data, string.size);
1026 std::string value(str.str());
1027 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1030 - (NSString *) cy$toKey {
1031 if (CYIsKey(CYCastUTF8String(self)))
1033 return [self cy$toCYON];
1036 - (bool) cy$hasProperty:(NSString *)name {
1037 if ([name isEqualToString:@"length"])
1040 size_t index(CYGetIndex(name));
1041 if (index == _not(size_t) || index >= [self length])
1042 return [super cy$hasProperty:name];
1047 - (NSObject *) cy$getProperty:(NSString *)name {
1048 if ([name isEqualToString:@"length"]) {
1049 NSUInteger count([self length]);
1051 return [NSNumber numberWithUnsignedInteger:count];
1053 return [NSNumber numberWithUnsignedInt:count];
1057 size_t index(CYGetIndex(name));
1058 if (index == _not(size_t) || index >= [self length])
1059 return [super cy$getProperty:name];
1061 return [self substringWithRange:NSMakeRange(index, 1)];
1064 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1065 [super cy$getPropertyNames:names inContext:context];
1067 for (size_t index(0), length([self length]); index != length; ++index) {
1069 sprintf(name, "%zu", index);
1070 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1074 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1075 + (bool) cy$hasImplicitProperties {
1081 /* Bridge: WebUndefined {{{ */
1082 @implementation WebUndefined (Cycript)
1084 - (JSType) cy$JSType {
1085 return kJSTypeUndefined;
1088 - (NSObject *) cy$toJSON:(NSString *)key {
1092 - (NSString *) cy$toCYON {
1093 return @"undefined";
1096 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1097 return CYJSUndefined(context);
1098 } CYObjectiveCatch }
1103 static bool CYIsClass(id self) {
1105 // XXX: this is a lame object_isClass
1106 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1108 return GSObjCIsClass(self);
1112 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1113 id self(CYCastNSObject(pool, context, value));
1114 if (CYIsClass(self))
1115 return (Class) self;
1116 throw CYJSError(context, "got something that is not a Class");
1120 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1122 size_t size(JSPropertyNameArrayGetCount(names));
1123 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1124 for (size_t index(0); index != size; ++index)
1125 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1129 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1131 return CYJSNull(context);
1132 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1133 return [value cy$JSValueInContext:context];
1135 return CYMakeInstance(context, value, false);
1136 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1138 @implementation CYJSObject
1140 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1141 if ((self = [super init]) != nil) {
1143 context_ = CYGetJSContext(context);
1144 //XXX:JSGlobalContextRetain(context_);
1145 JSValueProtect(context_, object_);
1147 } CYObjectiveCatch }
1149 - (void) dealloc { CYObjectiveTry {
1150 JSValueUnprotect(context_, object_);
1151 //XXX:JSGlobalContextRelease(context_);
1153 } CYObjectiveCatch }
1155 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1156 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1157 if (!CYIsCallable(context_, toJSON))
1158 return [super cy$toJSON:key];
1160 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1161 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1162 // XXX: do I really want an NSNull here?!
1163 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1165 } CYObjectiveCatch }
1167 - (NSString *) cy$toCYON { CYObjectiveTry {
1169 JSValueRef exception(NULL);
1170 const char *cyon(CYPoolCCYON(pool, context_, object_));
1171 CYThrow(context_, exception);
1173 return [super cy$toCYON];
1175 return [NSString stringWithUTF8String:cyon];
1176 } CYObjectiveCatch }
1178 - (NSUInteger) count { CYObjectiveTry {
1179 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1180 size_t size(JSPropertyNameArrayGetCount(names));
1181 JSPropertyNameArrayRelease(names);
1183 } CYObjectiveCatch }
1185 - (id) objectForKey:(id)key { CYObjectiveTry {
1186 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1187 if (JSValueIsUndefined(context_, value))
1189 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1190 } CYObjectiveCatch }
1192 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1193 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1194 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1195 JSPropertyNameArrayRelease(names);
1197 } CYObjectiveCatch }
1199 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1200 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1201 } CYObjectiveCatch }
1203 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1204 JSValueRef exception(NULL);
1205 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1206 CYThrow(context_, exception);
1207 } CYObjectiveCatch }
1211 @implementation CYJSArray
1213 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1214 if ((self = [super init]) != nil) {
1216 context_ = CYGetJSContext(context);
1217 //XXX:JSGlobalContextRetain(context_);
1218 JSValueProtect(context_, object_);
1220 } CYObjectiveCatch }
1222 - (void) dealloc { CYObjectiveTry {
1223 JSValueUnprotect(context_, object_);
1224 //XXX:JSGlobalContextRelease(context_);
1226 } CYObjectiveCatch }
1228 - (NSUInteger) count { CYObjectiveTry {
1229 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
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 JSValueRef exception(NULL);
1244 JSValueRef arguments[1];
1245 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1246 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1247 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1248 CYThrow(context_, exception);
1249 } CYObjectiveCatch }
1251 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1252 size_t bounds([self count] + 1);
1253 if (index >= bounds)
1254 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1255 JSValueRef exception(NULL);
1256 JSValueRef arguments[3];
1257 arguments[0] = CYCastJSValue(context_, index);
1258 arguments[1] = CYCastJSValue(context_, 0);
1259 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1260 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1261 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1262 CYThrow(context_, exception);
1263 } CYObjectiveCatch }
1265 - (void) removeLastObject { CYObjectiveTry {
1266 JSValueRef exception(NULL);
1267 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1268 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1269 CYThrow(context_, exception);
1270 } CYObjectiveCatch }
1272 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1273 size_t bounds([self count]);
1274 if (index >= bounds)
1275 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1276 JSValueRef exception(NULL);
1277 JSValueRef arguments[2];
1278 arguments[0] = CYCastJSValue(context_, index);
1279 arguments[1] = CYCastJSValue(context_, 1);
1280 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1281 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1282 CYThrow(context_, exception);
1283 } CYObjectiveCatch }
1285 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1286 size_t bounds([self count]);
1287 if (index >= bounds)
1288 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1289 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1290 } CYObjectiveCatch }
1294 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1298 JSObjectRef object_;
1306 // XXX: delete object_? ;(
1309 static CYInternal *Get(id self) {
1310 CYInternal *internal(NULL);
1311 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1312 // XXX: do something epic? ;P
1318 static CYInternal *Set(id self) {
1319 CYInternal *internal(NULL);
1320 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1321 if (internal == NULL) {
1322 internal = new CYInternal();
1323 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1326 // XXX: do something epic? ;P
1332 bool HasProperty(JSContextRef context, JSStringRef name) {
1333 if (object_ == NULL)
1335 return JSObjectHasProperty(context, object_, name);
1338 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1339 if (object_ == NULL)
1341 return CYGetProperty(context, object_, name);
1344 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1345 if (object_ == NULL)
1346 object_ = JSObjectMake(context, NULL, NULL);
1347 CYSetProperty(context, object_, name, value);
1351 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1352 Selector_privateData *internal(new Selector_privateData(sel));
1353 return JSObjectMake(context, Selector_, internal);
1356 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1357 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1358 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1359 return reinterpret_cast<SEL>(internal->value_);
1361 return CYCastPointer<SEL>(context, value);
1364 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1365 return (void *) [[NSAutoreleasePool alloc] init];
1366 } CYSadCatch(NULL) }
1368 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1369 return [(NSAutoreleasePool *) handle release];
1372 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1374 return Instance::Make(context, nil);
1375 if (Class _class = objc_getClass(name.data))
1376 return CYMakeInstance(context, _class, true);
1377 if (Protocol *protocol = objc_getProtocol(name.data))
1378 return CYMakeInstance(context, protocol, true);
1380 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1382 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1383 ffi_call(cif, function, value, values);
1386 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1387 switch (type->primitive) {
1388 // XXX: do something epic about blocks
1391 case sig::typename_P:
1392 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1395 case sig::selector_P:
1396 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1404 } CYSadCatch(false) }
1406 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1407 switch (type->primitive) {
1408 // XXX: do something epic about blocks
1411 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1412 JSValueRef value(CYCastJSValue(context, object));
1418 case sig::typename_P:
1419 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1421 case sig::selector_P:
1422 if (SEL sel = *reinterpret_cast<SEL *>(data))
1423 return CYMakeSelector(context, sel);
1427 return CYJSNull(context);
1431 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1433 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1434 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1437 #if OBJC_API_VERSION >= 2
1439 method_getReturnType(method, type, sizeof(type));
1441 const char *type(method_getTypeEncoding(method));
1447 // XXX: possibly use a more "awesome" check?
1451 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1453 return method_getTypeEncoding(method);
1455 const char *name(sel_getName(sel));
1456 size_t length(strlen(name));
1458 char keyed[length + 2];
1460 keyed[length + 1] = '\0';
1461 memcpy(keyed + 1, name, length);
1463 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1464 return entry->value_;
1469 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1470 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1472 JSContextRef context(internal->context_);
1474 size_t count(internal->cif_.nargs);
1475 JSValueRef values[count];
1477 for (size_t index(0); index != count; ++index)
1478 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1480 JSObjectRef _this(CYCastJSObject(context, values[0]));
1482 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1483 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1486 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1487 Message_privateData *internal(new Message_privateData(sel, type, imp));
1488 return JSObjectMake(context, Message_, internal);
1491 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1492 JSObjectRef function(CYCastJSObject(context, value));
1493 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1494 // XXX: see notes in Library.cpp about needing to leak
1495 return reinterpret_cast<IMP>(internal->GetValue());
1498 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1499 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1500 Class _class(internal->GetValue());
1503 const char *name(CYPoolCString(pool, context, property));
1505 if (SEL sel = sel_getUid(name))
1506 if (class_getInstanceMethod(_class, sel) != NULL)
1512 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1513 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1514 Class _class(internal->GetValue());
1517 const char *name(CYPoolCString(pool, context, property));
1519 if (SEL sel = sel_getUid(name))
1520 if (objc_method *method = class_getInstanceMethod(_class, sel))
1521 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1526 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1527 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1528 Class _class(internal->GetValue());
1531 const char *name(CYPoolCString(pool, context, property));
1533 SEL sel(sel_registerName(name));
1535 objc_method *method(class_getInstanceMethod(_class, sel));
1540 if (JSValueIsObjectOfClass(context, value, Message_)) {
1541 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1542 type = sig::Unparse(pool, &message->signature_);
1543 imp = reinterpret_cast<IMP>(message->GetValue());
1545 type = CYPoolTypeEncoding(pool, context, sel, method);
1546 imp = CYMakeMessage(context, value, type);
1550 method_setImplementation(method, imp);
1553 GSMethodList list(GSAllocMethodList(1));
1554 GSAppendMethodToList(list, sel, type, imp, YES);
1555 GSAddMethodList(_class, list, YES);
1556 GSFlushMethodCacheForClass(_class);
1558 class_addMethod(_class, sel, imp, type);
1565 #if 0 && OBJC_API_VERSION < 2
1566 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1567 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1568 Class _class(internal->GetValue());
1571 const char *name(CYPoolCString(pool, context, property));
1573 if (SEL sel = sel_getUid(name))
1574 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1575 objc_method_list list = {NULL, 1, {method}};
1576 class_removeMethods(_class, &list);
1584 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1585 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1586 Class _class(internal->GetValue());
1588 #if OBJC_API_VERSION >= 2
1590 objc_method **data(class_copyMethodList(_class, &size));
1591 for (size_t i(0); i != size; ++i)
1592 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1595 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1596 for (int i(0); i != methods->method_count; ++i)
1597 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1601 static bool CYHasImplicitProperties(Class _class) {
1602 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1603 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1605 return [_class cy$hasImplicitProperties];
1608 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1609 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1610 id self(internal->GetValue());
1612 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1616 NSString *name(CYCastNSString(pool, context, property));
1618 if (CYInternal *internal = CYInternal::Get(self))
1619 if (internal->HasProperty(context, property))
1622 Class _class(object_getClass(self));
1625 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1626 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1627 if ([self cy$hasProperty:name])
1629 } CYPoolCatch(false)
1631 const char *string(CYPoolCString(pool, context, name));
1634 if (class_getProperty(_class, string) != NULL)
1638 if (CYHasImplicitProperties(_class))
1639 if (SEL sel = sel_getUid(string))
1640 if (CYImplements(self, _class, sel, true))
1646 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1647 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1648 id self(internal->GetValue());
1650 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1651 return Internal::Make(context, self, object);
1654 NSString *name(CYCastNSString(pool, context, property));
1656 if (CYInternal *internal = CYInternal::Get(self))
1657 if (JSValueRef value = internal->GetProperty(context, property))
1661 if (NSObject *data = [self cy$getProperty:name])
1662 return CYCastJSValue(context, data);
1665 const char *string(CYPoolCString(pool, context, name));
1666 Class _class(object_getClass(self));
1669 if (objc_property_t property = class_getProperty(_class, string)) {
1670 PropertyAttributes attributes(property);
1671 SEL sel(sel_registerName(attributes.Getter()));
1672 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1676 if (CYHasImplicitProperties(_class))
1677 if (SEL sel = sel_getUid(string))
1678 if (CYImplements(self, _class, sel, true))
1679 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1684 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1685 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1686 id self(internal->GetValue());
1690 NSString *name(CYCastNSString(pool, context, property));
1691 NSObject *data(CYCastNSObject(pool, context, value));
1694 if ([self cy$setProperty:name to:data])
1698 const char *string(CYPoolCString(pool, context, name));
1699 Class _class(object_getClass(self));
1702 if (objc_property_t property = class_getProperty(_class, string)) {
1703 PropertyAttributes attributes(property);
1704 if (const char *setter = attributes.Setter()) {
1705 SEL sel(sel_registerName(setter));
1706 JSValueRef arguments[1] = {value};
1707 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1713 size_t length(strlen(string));
1715 char set[length + 5];
1721 if (string[0] != '\0') {
1722 set[3] = toupper(string[0]);
1723 memcpy(set + 4, string + 1, length - 1);
1726 set[length + 3] = ':';
1727 set[length + 4] = '\0';
1729 if (SEL sel = sel_getUid(set))
1730 if (CYImplements(self, _class, sel, false)) {
1731 JSValueRef arguments[1] = {value};
1732 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1735 if (CYInternal *internal = CYInternal::Set(self)) {
1736 internal->SetProperty(context, property, value);
1743 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1744 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1745 id self(internal->GetValue());
1748 NSString *name(CYCastNSString(NULL, context, property));
1749 return [self cy$deleteProperty:name];
1751 } CYCatch return /*XXX*/ NULL; }
1753 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1754 const char *name(sel_getName(method_getName(method)));
1755 if (strchr(name, ':') != NULL)
1758 const char *type(method_getTypeEncoding(method));
1759 if (type == NULL || *type == '\0' || *type == 'v')
1762 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1765 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1766 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1767 id self(internal->GetValue());
1770 Class _class(object_getClass(self));
1775 objc_property_t *data(class_copyPropertyList(_class, &size));
1776 for (size_t i(0); i != size; ++i)
1777 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1782 if (CYHasImplicitProperties(_class))
1783 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1784 #if OBJC_API_VERSION >= 2
1786 objc_method **data(class_copyMethodList(current, &size));
1787 for (size_t i(0); i != size; ++i)
1788 Instance_getPropertyNames_message(names, data[i]);
1791 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1792 for (int i(0); i != methods->method_count; ++i)
1793 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1798 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1799 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1800 [self cy$getPropertyNames:names inContext:context];
1804 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1805 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1806 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1810 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1811 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1812 Class _class(internal->GetValue());
1813 if (!CYIsClass(_class))
1816 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1817 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1818 // XXX: this isn't always safe
1819 return [linternal->GetValue() isKindOfClass:_class];
1825 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1826 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1829 id self(internal->GetValue());
1830 const char *name(CYPoolCString(pool, context, property));
1832 if (object_getInstanceVariable(self, name, NULL) != NULL)
1838 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1839 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1842 id self(internal->GetValue());
1843 const char *name(CYPoolCString(pool, context, property));
1845 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1846 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1847 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1848 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1854 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1855 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1858 id self(internal->GetValue());
1859 const char *name(CYPoolCString(pool, context, property));
1861 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1862 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1863 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1870 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1871 if (Class super = class_getSuperclass(_class))
1872 Internal_getPropertyNames_(super, names);
1874 #if OBJC_API_VERSION >= 2
1876 objc_ivar **data(class_copyIvarList(_class, &size));
1877 for (size_t i(0); i != size; ++i)
1878 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1881 if (objc_ivar_list *ivars = _class->ivars)
1882 for (int i(0); i != ivars->ivar_count; ++i)
1883 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1887 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1888 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1891 id self(internal->GetValue());
1892 Class _class(object_getClass(self));
1894 Internal_getPropertyNames_(_class, names);
1897 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1898 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1899 return internal->GetOwner();
1902 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1904 NSString *name(CYCastNSString(pool, context, property));
1905 if (Class _class = NSClassFromString(name))
1906 return CYMakeInstance(context, _class, true);
1910 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1912 size_t size(objc_getClassList(NULL, 0));
1913 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1916 size_t writ(objc_getClassList(data, size));
1919 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1925 for (size_t i(0); i != writ; ++i)
1926 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1932 while (Class _class = objc_next_class(&state))
1933 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1937 #if OBJC_API_VERSION >= 2
1938 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1939 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1942 const char *name(CYPoolCString(pool, context, property));
1944 const char **data(objc_copyClassNamesForImage(internal, &size));
1946 for (size_t i(0); i != size; ++i)
1947 if (strcmp(name, data[i]) == 0) {
1948 if (Class _class = objc_getClass(name)) {
1949 value = CYMakeInstance(context, _class, true);
1960 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1961 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1963 const char **data(objc_copyClassNamesForImage(internal, &size));
1964 for (size_t i(0); i != size; ++i)
1965 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1969 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1971 const char *name(CYPoolCString(pool, context, property));
1973 const char **data(objc_copyImageNames(&size));
1974 for (size_t i(0); i != size; ++i)
1975 if (strcmp(name, data[i]) == 0) {
1984 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1985 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1989 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1991 const char **data(objc_copyImageNames(&size));
1992 for (size_t i(0); i != size; ++i)
1993 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1998 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2000 const char *name(CYPoolCString(pool, context, property));
2001 if (Protocol *protocol = objc_getProtocol(name))
2002 return CYMakeInstance(context, protocol, true);
2006 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2007 #if OBJC_API_VERSION >= 2
2009 Protocol **data(objc_copyProtocolList(&size));
2010 for (size_t i(0); i != size; ++i)
2011 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2019 static bool stret(ffi_type *ffi_type) {
2020 return ffi_type->type == FFI_TYPE_STRUCT && (
2021 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2022 struct_forward_array[ffi_type->size] != 0
2027 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 {
2031 _class = object_getClass(self);
2035 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2036 imp = method_getImplementation(method);
2037 type = method_getTypeEncoding(method);
2042 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2044 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2045 type = CYPoolCString(pool, context, [method _typeString]);
2053 sig::Signature signature;
2054 sig::Parse(pool, &signature, type, &Structor_);
2057 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2061 if (stret(cif.rtype))
2062 imp = class_getMethodImplementation_stret(_class, _cmd);
2064 imp = class_getMethodImplementation(_class, _cmd);
2066 objc_super super = {self, _class};
2067 imp = objc_msg_lookup_super(&super, _cmd);
2071 void (*function)() = reinterpret_cast<void (*)()>(imp);
2072 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2075 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2077 throw CYJSError(context, "too few arguments to objc_msgSend");
2087 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2088 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2089 self = internal->GetValue();
2090 _class = internal->class_;;
2091 uninitialized = false;
2092 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2093 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2094 self = internal->GetValue();
2096 uninitialized = internal->IsUninitialized();
2098 internal->value_ = nil;
2100 self = CYCastNSObject(pool, context, arguments[0]);
2102 uninitialized = false;
2106 return CYJSNull(context);
2108 _cmd = CYCastSEL(context, arguments[1]);
2110 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2113 /* Hook: objc_registerClassPair {{{ */
2114 #if defined(__APPLE__) && defined(__arm__) && 0
2115 // XXX: replace this with associated objects
2117 MSHook(void, CYDealloc, id self, SEL sel) {
2118 CYInternal *internal;
2119 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2120 if (internal != NULL)
2122 _CYDealloc(self, sel);
2125 MSHook(void, objc_registerClassPair, Class _class) {
2126 Class super(class_getSuperclass(_class));
2127 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2128 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2129 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2132 _objc_registerClassPair(_class);
2135 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2137 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2139 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2140 if (value == NULL || !CYIsClass(value))
2141 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2142 Class _class((Class) value);
2143 $objc_registerClassPair(_class);
2144 return CYJSUndefined(context);
2149 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2150 JSValueRef setup[count + 2];
2153 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2154 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2157 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2159 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2161 // XXX: handle Instance::Uninitialized?
2162 id self(CYCastNSObject(pool, context, _this));
2166 setup[1] = &internal->sel_;
2168 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2171 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2173 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2175 id self(CYCastNSObject(pool, context, arguments[0]));
2176 Class _class(CYCastClass(pool, context, arguments[1]));
2177 return cy::Super::Make(context, self, _class);
2180 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2182 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2184 const char *name(CYPoolCString(pool, context, arguments[0]));
2185 return CYMakeSelector(context, sel_registerName(name));
2188 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2190 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2191 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2192 return CYMakeInstance(context, self, false);
2195 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2196 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2197 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2200 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2201 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2202 Type_privateData *typical(internal->GetType());
2207 if (typical == NULL) {
2211 type = typical->type_;
2212 ffi = typical->ffi_;
2215 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2218 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2219 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2220 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2223 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2224 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2225 id self(internal->GetValue());
2226 if (!CYIsClass(self))
2227 return CYJSUndefined(context);
2228 return CYGetClassPrototype(context, self);
2231 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2232 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2233 id self(internal->GetValue());
2234 if (!CYIsClass(self))
2235 return CYJSUndefined(context);
2236 return Messages::Make(context, (Class) self);
2239 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2240 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2243 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2244 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2247 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2248 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2251 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2258 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2259 // XXX: check for support of cy$toJSON?
2260 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2262 } CYCatch return /*XXX*/ NULL; }
2265 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2266 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2269 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2270 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2271 } CYCatch return /*XXX*/ NULL; }
2274 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2275 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2278 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2279 // XXX: but... but... THIS ISN'T A POINTER! :(
2280 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2281 } CYCatch return /*XXX*/ NULL; }
2283 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2284 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2287 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2289 id value(internal->GetValue());
2291 return CYCastJSValue(context, "nil");
2294 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2295 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2297 } CYCatch return /*XXX*/ NULL; }
2299 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2300 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2301 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2304 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2305 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2308 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2309 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2310 const char *name(sel_getName(internal->GetValue()));
2313 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2314 return CYCastJSValue(context, CYJSString(context, string));
2316 } CYCatch return /*XXX*/ NULL; }
2318 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2320 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2323 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2324 SEL sel(internal->GetValue());
2326 objc_method *method;
2327 if (Class _class = CYCastClass(pool, context, arguments[0]))
2328 method = class_getInstanceMethod(_class, sel);
2332 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2333 return CYCastJSValue(context, CYJSString(type));
2335 return CYJSNull(context);
2338 static JSStaticValue Selector_staticValues[2] = {
2339 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2340 {NULL, NULL, NULL, 0}
2343 static JSStaticValue Instance_staticValues[5] = {
2344 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2345 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2346 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2347 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2348 {NULL, NULL, NULL, 0}
2351 static JSStaticFunction Instance_staticFunctions[6] = {
2352 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2353 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2354 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2355 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2356 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2357 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2361 static JSStaticFunction Internal_staticFunctions[2] = {
2362 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2366 static JSStaticFunction Selector_staticFunctions[5] = {
2367 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2368 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2369 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2370 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2374 static JSStaticFunction StringInstance_staticFunctions[2] = {
2375 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2376 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2380 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2381 apr_pool_t *pool(CYGetGlobalPool());
2383 Object_type = new(pool) Type_privateData("@");
2384 Selector_type = new(pool) Type_privateData(":");
2387 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2388 NSCFType_ = objc_getClass("NSCFType");
2389 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2390 NSZombie_ = objc_getClass("_NSZombie_");
2392 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2395 NSArray_ = objc_getClass("NSArray");
2396 NSDictionary_ = objc_getClass("NSDictionary");
2397 NSString_ = objc_getClass("NSString");
2398 Object_ = objc_getClass("Object");
2400 JSClassDefinition definition;
2402 definition = kJSClassDefinitionEmpty;
2403 definition.className = "Instance";
2404 definition.staticValues = Instance_staticValues;
2405 definition.staticFunctions = Instance_staticFunctions;
2406 definition.hasProperty = &Instance_hasProperty;
2407 definition.getProperty = &Instance_getProperty;
2408 definition.setProperty = &Instance_setProperty;
2409 definition.deleteProperty = &Instance_deleteProperty;
2410 definition.getPropertyNames = &Instance_getPropertyNames;
2411 definition.callAsConstructor = &Instance_callAsConstructor;
2412 definition.hasInstance = &Instance_hasInstance;
2413 definition.finalize = &CYFinalize;
2414 Instance_ = JSClassCreate(&definition);
2416 definition = kJSClassDefinitionEmpty;
2417 definition.className = "Internal";
2418 definition.staticFunctions = Internal_staticFunctions;
2419 definition.hasProperty = &Internal_hasProperty;
2420 definition.getProperty = &Internal_getProperty;
2421 definition.setProperty = &Internal_setProperty;
2422 definition.getPropertyNames = &Internal_getPropertyNames;
2423 definition.finalize = &CYFinalize;
2424 Internal_ = JSClassCreate(&definition);
2426 definition = kJSClassDefinitionEmpty;
2427 definition.className = "Message";
2428 definition.staticFunctions = cy::Functor::StaticFunctions;
2429 definition.callAsFunction = &Message_callAsFunction;
2430 definition.finalize = &CYFinalize;
2431 Message_ = JSClassCreate(&definition);
2433 definition = kJSClassDefinitionEmpty;
2434 definition.className = "Messages";
2435 definition.hasProperty = &Messages_hasProperty;
2436 definition.getProperty = &Messages_getProperty;
2437 definition.setProperty = &Messages_setProperty;
2438 #if 0 && OBJC_API_VERSION < 2
2439 definition.deleteProperty = &Messages_deleteProperty;
2441 definition.getPropertyNames = &Messages_getPropertyNames;
2442 definition.finalize = &CYFinalize;
2443 Messages_ = JSClassCreate(&definition);
2445 definition = kJSClassDefinitionEmpty;
2446 definition.className = "Selector";
2447 definition.staticValues = Selector_staticValues;
2448 definition.staticFunctions = Selector_staticFunctions;
2449 definition.callAsFunction = &Selector_callAsFunction;
2450 definition.finalize = &CYFinalize;
2451 Selector_ = JSClassCreate(&definition);
2453 definition = kJSClassDefinitionEmpty;
2454 definition.className = "StringInstance";
2455 definition.staticFunctions = StringInstance_staticFunctions;
2456 StringInstance_ = JSClassCreate(&definition);
2458 definition = kJSClassDefinitionEmpty;
2459 definition.className = "Super";
2460 definition.staticFunctions = Internal_staticFunctions;
2461 definition.finalize = &CYFinalize;
2462 Super_ = JSClassCreate(&definition);
2464 definition = kJSClassDefinitionEmpty;
2465 definition.className = "ObjectiveC::Classes";
2466 definition.getProperty = &ObjectiveC_Classes_getProperty;
2467 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2468 ObjectiveC_Classes_ = JSClassCreate(&definition);
2470 #if OBJC_API_VERSION >= 2
2471 definition = kJSClassDefinitionEmpty;
2472 definition.className = "ObjectiveC::Images";
2473 definition.getProperty = &ObjectiveC_Images_getProperty;
2474 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2475 ObjectiveC_Images_ = JSClassCreate(&definition);
2477 definition = kJSClassDefinitionEmpty;
2478 definition.className = "ObjectiveC::Image::Classes";
2479 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2480 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2481 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2484 definition = kJSClassDefinitionEmpty;
2485 definition.className = "ObjectiveC::Protocols";
2486 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2487 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2488 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2490 #if defined(__APPLE__) && defined(__arm__) && 0
2491 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2495 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2499 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2500 JSObjectRef global(CYGetGlobalObject(context));
2501 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2502 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2503 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2505 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2506 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2508 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2509 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2511 #if OBJC_API_VERSION >= 2
2512 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2515 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2516 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2517 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2518 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2519 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2521 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2522 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2524 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2525 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2527 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2528 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2530 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2531 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2532 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2534 #if defined(__APPLE__) && defined(__arm__) && 0
2535 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2538 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2540 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2541 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2542 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2545 static CYHooks CYObjectiveCHooks = {
2546 &CYObjectiveC_ExecuteStart,
2547 &CYObjectiveC_ExecuteEnd,
2548 &CYObjectiveC_RuntimeProperty,
2549 &CYObjectiveC_CallFunction,
2550 &CYObjectiveC_Initialize,
2551 &CYObjectiveC_SetupContext,
2552 &CYObjectiveC_PoolFFI,
2553 &CYObjectiveC_FromFFI,
2556 struct CYObjectiveC {
2558 hooks_ = &CYObjectiveCHooks;
2559 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2560 _assert(hooks_ != NULL);