1 /* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 #if defined(__APPLE__) && defined(__arm__)
41 #include <substrate.h>
43 #include <objc/objc-api.h>
50 #include <Foundation/Foundation.h>
52 #include "ObjectiveC/Internal.hpp"
54 #include <objc/Protocol.h>
56 #include "cycript.hpp"
58 #include "ObjectiveC/Internal.hpp"
61 #include <CoreFoundation/CoreFoundation.h>
62 #include <JavaScriptCore/JSStringRefCF.h>
63 #include <WebKit/WebScriptObject.h>
67 #include "JavaScript.hpp"
69 #include "Execute.hpp"
74 #define CYObjectiveTry_(context) { \
75 JSContextRef context_(context); \
77 #define CYObjectiveTry { \
79 #define CYObjectiveCatch \
80 catch (const CYException &error) { \
81 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
92 throw CYJSError(context, CYCastJSValue(context, error)); \
97 [_saved autorelease]; \
103 #define CYSadCatch(value) \
104 @catch (NSException *error ) { \
105 throw CYJSError(context, CYCastJSValue(context, error)); \
110 #define class_getSuperclass GSObjCSuper
111 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
112 #define class_getName GSNameFromClass
114 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
116 #define ivar_getName(ivar) ((ivar)->ivar_name)
117 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
118 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
120 #define method_getName(method) ((method)->method_name)
121 #define method_getImplementation(method) ((method)->method_imp)
122 #define method_getTypeEncoding(method) ((method)->method_types)
123 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
126 #define objc_getClass GSClassFromName
128 #define objc_getProtocol GSProtocolFromName
130 #define object_getClass GSObjCClass
132 #define object_getInstanceVariable(object, name, value) ({ \
133 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
135 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
139 #define object_setIvar(object, ivar, value) ({ \
140 void *data = (value); \
141 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
144 #define protocol_getName(protocol) [(protocol) name]
147 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
149 /* Objective-C Pool Release {{{ */
150 apr_status_t CYPoolRelease_(void *data) {
151 id object(reinterpret_cast<id>(data));
156 id CYPoolRelease_(apr_pool_t *pool, id object) {
159 else if (pool == NULL)
160 return [object autorelease];
162 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
167 template <typename Type_>
168 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
169 return (Type_) CYPoolRelease_(pool, (id) object);
172 /* Objective-C Strings {{{ */
173 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
175 return [value UTF8String];
177 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
178 char *string(new(pool) char[size]);
179 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
180 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
185 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
187 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
190 return CYCopyJSString(CYPoolCString(pool, context, value));
194 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
197 // XXX: this definition scares me; is anyone using this?!
198 NSString *string([value description]);
199 return CYCopyJSString(context, string);
202 NSString *CYCopyNSString(const CYUTF8String &value) {
204 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
206 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
210 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
212 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
215 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
219 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
220 return CYCopyNSString(context, CYJSString(context, value));
223 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
224 return CYPoolRelease(pool, CYCopyNSString(value));
227 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
228 const char *name(sel_getName(sel));
229 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
232 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
233 return CYPoolRelease(pool, CYCopyNSString(context, value));
236 CYUTF8String CYCastUTF8String(NSString *value) {
237 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
238 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
242 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
244 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
245 if (exception == NULL)
247 *exception = CYCastJSValue(context, error);
250 size_t CYGetIndex(NSString *value) {
251 return CYGetIndex(CYCastUTF8String(value));
254 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
255 return CYGetOffset(CYPoolCString(pool, context, value), index);
258 static JSClassRef Instance_;
259 static JSClassRef Internal_;
260 static JSClassRef Message_;
261 static JSClassRef Messages_;
262 static JSClassRef Selector_;
263 static JSClassRef StringInstance_;
264 static JSClassRef Super_;
266 static JSClassRef ObjectiveC_Classes_;
267 static JSClassRef ObjectiveC_Protocols_;
270 static JSClassRef ObjectiveC_Image_Classes_;
271 static JSClassRef ObjectiveC_Images_;
275 static Class NSCFBoolean_;
276 static Class NSCFType_;
277 static Class NSMessageBuilder_;
278 static Class NSZombie_;
280 static Class NSBoolNumber_;
283 static Class NSArray_;
284 static Class NSDictionary_;
285 static Class NSString_;
286 static Class Object_;
288 static Type_privateData *Object_type;
289 static Type_privateData *Selector_type;
291 Type_privateData *Instance::GetType() const {
295 Type_privateData *Selector_privateData::GetType() const {
296 return Selector_type;
299 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
301 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
303 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
305 JSObjectRef global(CYGetGlobalObject(context));
306 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
309 sprintf(label, "i%p", self);
310 CYJSString name(label);
312 JSValueRef value(CYGetProperty(context, cy, name));
313 if (!JSValueIsUndefined(context, value))
316 JSClassRef _class(NULL);
317 JSValueRef prototype;
319 if (self == NSArray_)
320 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
321 else if (self == NSDictionary_)
322 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
323 else if (self == NSString_)
324 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
326 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
328 JSObjectRef object(JSObjectMake(context, _class, NULL));
329 JSObjectSetPrototype(context, object, prototype);
330 CYSetProperty(context, cy, name, object);
335 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
336 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
337 if (_class == NSArray_)
339 if (Class super = class_getSuperclass(_class))
340 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
342 JSObjectSetPrototype(context, value, Array_prototype_);*/
346 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
347 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
351 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
352 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
356 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
357 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
358 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
362 Instance::~Instance() {
363 if ((flags_ & Transient) == 0)
364 // XXX: does this handle background threads correctly?
365 // XXX: this simply does not work on the console because I'm stupid
366 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
369 struct Message_privateData :
374 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
375 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
381 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
382 Instance::Flags flags;
385 flags = Instance::Transient;
387 flags = Instance::None;
388 object = [object retain];
391 return Instance::Make(context, object, flags);
394 @interface NSMethodSignature (Cycript)
395 - (NSString *) _typeString;
398 @interface NSObject (Cycript)
400 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
401 - (JSType) cy$JSType;
403 - (NSObject *) cy$toJSON:(NSString *)key;
404 - (NSString *) cy$toCYON;
405 - (NSString *) cy$toKey;
407 - (bool) cy$hasProperty:(NSString *)name;
408 - (NSObject *) cy$getProperty:(NSString *)name;
409 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
410 - (bool) cy$deleteProperty:(NSString *)name;
411 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
413 + (bool) cy$hasImplicitProperties;
418 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
421 NSString *CYCastNSCYON(id value) {
427 Class _class(object_getClass(value));
428 SEL sel(@selector(cy$toCYON));
430 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
431 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
432 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
433 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
434 string = [value cy$toCYON];
439 else if (value == NSZombie_)
440 string = @"_NSZombie_";
441 else if (_class == NSZombie_)
442 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
443 // XXX: frowny /in/ the pants
444 else if (value == NSMessageBuilder_ || value == Object_)
448 string = [NSString stringWithFormat:@"%@", value];
453 string = @"undefined";
460 struct PropertyAttributes {
465 const char *variable;
478 PropertyAttributes(objc_property_t property) :
490 name = property_getName(property);
491 const char *attributes(property_getAttributes(property));
493 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
495 case 'R': readonly = true; break;
496 case 'C': copy = true; break;
497 case '&': retain = true; break;
498 case 'N': nonatomic = true; break;
499 case 'G': getter_ = token + 1; break;
500 case 'S': setter_ = token + 1; break;
501 case 'V': variable = token + 1; break;
505 /*if (variable == NULL) {
506 variable = property_getName(property);
507 size_t size(strlen(variable));
508 char *name(new(pool_) char[size + 2]);
510 memcpy(name + 1, variable, size);
511 name[size + 1] = '\0';
516 const char *Getter() {
518 getter_ = apr_pstrdup(pool_, name);
522 const char *Setter() {
523 if (setter_ == NULL && !readonly) {
524 size_t length(strlen(name));
526 char *temp(new(pool_) char[length + 5]);
532 temp[3] = toupper(name[0]);
533 memcpy(temp + 4, name + 1, length - 1);
536 temp[length + 3] = ':';
537 temp[length + 4] = '\0';
548 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
549 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
554 @interface CYWebUndefined : NSObject {
557 + (CYWebUndefined *) undefined;
561 @implementation CYWebUndefined
563 + (CYWebUndefined *) undefined {
564 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
570 #define WebUndefined CYWebUndefined
573 /* Bridge: CYJSObject {{{ */
574 @interface CYJSObject : NSMutableDictionary {
576 JSContextRef context_;
579 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
581 - (NSObject *) cy$toJSON:(NSString *)key;
583 - (NSUInteger) count;
584 - (id) objectForKey:(id)key;
585 - (NSEnumerator *) keyEnumerator;
586 - (void) setObject:(id)object forKey:(id)key;
587 - (void) removeObjectForKey:(id)key;
591 /* Bridge: CYJSArray {{{ */
592 @interface CYJSArray : NSMutableArray {
594 JSContextRef context_;
597 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
599 - (NSUInteger) count;
600 - (id) objectAtIndex:(NSUInteger)index;
602 - (void) addObject:(id)anObject;
603 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
604 - (void) removeLastObject;
605 - (void) removeObjectAtIndex:(NSUInteger)index;
606 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
611 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
612 JSObjectRef Array(CYGetCachedObject(context, Array_s));
613 JSValueRef exception(NULL);
614 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
615 CYThrow(context, exception);
616 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
617 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
620 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
621 if (!JSValueIsObjectOfClass(context, object, Instance_))
622 return CYCastNSObject_(pool, context, object);
624 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
625 return internal->GetValue();
629 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
630 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
634 @interface NSBoolNumber : NSNumber {
639 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
643 switch (JSType type = JSValueGetType(context, value)) {
644 case kJSTypeUndefined:
645 object = [WebUndefined undefined];
655 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
658 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
664 object = CYCopyNSNumber(context, value);
669 object = CYCopyNSString(context, value);
674 // XXX: this might could be more efficient
675 object = CYCastNSObject(pool, context, (JSObjectRef) value);
680 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
687 return CYPoolRelease(pool, object);
689 return [object retain];
692 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
693 return CYNSObject(pool, context, value, true);
696 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
697 return CYNSObject(pool, context, value, false);
700 /* Bridge: NSArray {{{ */
701 @implementation NSArray (Cycript)
703 - (NSString *) cy$toCYON {
704 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
705 [json appendString:@"["];
709 for (id object in self) {
711 for (size_t index(0), count([self count]); index != count; ++index) {
712 id object([self objectAtIndex:index]);
715 [json appendString:@","];
718 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
719 [json appendString:CYCastNSCYON(object)];
721 [json appendString:@","];
726 [json appendString:@"]"];
730 - (bool) cy$hasProperty:(NSString *)name {
731 if ([name isEqualToString:@"length"])
734 size_t index(CYGetIndex(name));
735 if (index == _not(size_t) || index >= [self count])
736 return [super cy$hasProperty:name];
741 - (NSObject *) cy$getProperty:(NSString *)name {
742 if ([name isEqualToString:@"length"]) {
743 NSUInteger count([self count]);
745 return [NSNumber numberWithUnsignedInteger:count];
747 return [NSNumber numberWithUnsignedInt:count];
751 size_t index(CYGetIndex(name));
752 if (index == _not(size_t) || index >= [self count])
753 return [super cy$getProperty:name];
755 return [self objectAtIndex:index];
758 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
759 [super cy$getPropertyNames:names inContext:context];
761 for (size_t index(0), count([self count]); index != count; ++index) {
762 id object([self objectAtIndex:index]);
763 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
765 sprintf(name, "%zu", index);
766 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
771 + (bool) cy$hasImplicitProperties {
777 /* Bridge: NSBoolNumber {{{ */
779 @implementation NSBoolNumber (Cycript)
781 - (JSType) cy$JSType {
782 return kJSTypeBoolean;
785 - (NSObject *) cy$toJSON:(NSString *)key {
789 - (NSString *) cy$toCYON {
790 return [self boolValue] ? @"true" : @"false";
793 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
794 return CYCastJSValue(context, (bool) [self boolValue]);
800 /* Bridge: NSDictionary {{{ */
801 @implementation NSDictionary (Cycript)
803 - (NSString *) cy$toCYON {
804 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
805 [json appendString:@"{"];
809 for (NSObject *key in self) {
811 NSEnumerator *keys([self keyEnumerator]);
812 while (NSObject *key = [keys nextObject]) {
815 [json appendString:@","];
818 [json appendString:[key cy$toKey]];
819 [json appendString:@":"];
820 NSObject *object([self objectForKey:key]);
821 [json appendString:CYCastNSCYON(object)];
824 [json appendString:@"}"];
828 - (bool) cy$hasProperty:(NSString *)name {
829 return [self objectForKey:name] != nil;
832 - (NSObject *) cy$getProperty:(NSString *)name {
833 return [self objectForKey:name];
836 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
837 [super cy$getPropertyNames:names inContext:context];
840 for (NSObject *key in self) {
842 NSEnumerator *keys([self keyEnumerator]);
843 while (NSObject *key = [keys nextObject]) {
845 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
849 + (bool) cy$hasImplicitProperties {
855 /* Bridge: NSMutableArray {{{ */
856 @implementation NSMutableArray (Cycript)
858 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
859 if ([name isEqualToString:@"length"]) {
860 // XXX: is this not intelligent?
861 NSNumber *number(reinterpret_cast<NSNumber *>(value));
863 NSUInteger size([number unsignedIntegerValue]);
865 NSUInteger size([number unsignedIntValue]);
867 NSUInteger count([self count]);
869 [self removeObjectsInRange:NSMakeRange(size, count - size)];
870 else if (size != count) {
871 WebUndefined *undefined([WebUndefined undefined]);
872 for (size_t i(count); i != size; ++i)
873 [self addObject:undefined];
878 size_t index(CYGetIndex(name));
879 if (index == _not(size_t))
880 return [super cy$setProperty:name to:value];
882 id object(value ?: [NSNull null]);
884 size_t count([self count]);
886 [self replaceObjectAtIndex:index withObject:object];
888 if (index != count) {
889 WebUndefined *undefined([WebUndefined undefined]);
890 for (size_t i(count); i != index; ++i)
891 [self addObject:undefined];
894 [self addObject:object];
900 - (bool) cy$deleteProperty:(NSString *)name {
901 size_t index(CYGetIndex(name));
902 if (index == _not(size_t) || index >= [self count])
903 return [super cy$deleteProperty:name];
904 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
910 /* Bridge: NSMutableDictionary {{{ */
911 @implementation NSMutableDictionary (Cycript)
913 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
914 [self setObject:(value ?: [NSNull null]) forKey:name];
918 - (bool) cy$deleteProperty:(NSString *)name {
919 if ([self objectForKey:name] == nil)
922 [self removeObjectForKey:name];
929 /* Bridge: NSNumber {{{ */
930 @implementation NSNumber (Cycript)
932 - (JSType) cy$JSType {
934 // XXX: this just seems stupid
935 if ([self class] == NSCFBoolean_)
936 return kJSTypeBoolean;
938 return kJSTypeNumber;
941 - (NSObject *) cy$toJSON:(NSString *)key {
945 - (NSString *) cy$toCYON {
946 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
949 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
950 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
955 /* Bridge: NSNull {{{ */
956 @implementation NSNull (Cycript)
958 - (JSType) cy$JSType {
962 - (NSObject *) cy$toJSON:(NSString *)key {
966 - (NSString *) cy$toCYON {
972 /* Bridge: NSObject {{{ */
973 @implementation NSObject (Cycript)
975 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
976 return CYMakeInstance(context, self, false);
979 - (JSType) cy$JSType {
980 return kJSTypeObject;
983 - (NSObject *) cy$toJSON:(NSString *)key {
984 return [self description];
987 - (NSString *) cy$toCYON {
988 return [[self cy$toJSON:@""] cy$toCYON];
991 - (NSString *) cy$toKey {
992 return [self cy$toCYON];
995 - (bool) cy$hasProperty:(NSString *)name {
999 - (NSObject *) cy$getProperty:(NSString *)name {
1003 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1007 - (bool) cy$deleteProperty:(NSString *)name {
1011 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1014 + (bool) cy$hasImplicitProperties {
1020 /* Bridge: NSProxy {{{ */
1021 @implementation NSProxy (Cycript)
1023 - (NSObject *) cy$toJSON:(NSString *)key {
1024 return [self description];
1027 - (NSString *) cy$toCYON {
1028 return [[self cy$toJSON:@""] cy$toCYON];
1033 /* Bridge: NSString {{{ */
1034 @implementation NSString (Cycript)
1036 - (JSType) cy$JSType {
1037 return kJSTypeString;
1040 - (NSObject *) cy$toJSON:(NSString *)key {
1044 - (NSString *) cy$toCYON {
1045 std::ostringstream str;
1046 CYUTF8String string(CYCastUTF8String(self));
1047 CYStringify(str, string.data, string.size);
1048 std::string value(str.str());
1049 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1052 - (NSString *) cy$toKey {
1053 if (CYIsKey(CYCastUTF8String(self)))
1055 return [self cy$toCYON];
1058 - (bool) cy$hasProperty:(NSString *)name {
1059 if ([name isEqualToString:@"length"])
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 if ([name isEqualToString:@"length"]) {
1071 NSUInteger count([self length]);
1073 return [NSNumber numberWithUnsignedInteger:count];
1075 return [NSNumber numberWithUnsignedInt:count];
1079 size_t index(CYGetIndex(name));
1080 if (index == _not(size_t) || index >= [self length])
1081 return [super cy$getProperty:name];
1083 return [self substringWithRange:NSMakeRange(index, 1)];
1086 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1087 [super cy$getPropertyNames:names inContext:context];
1089 for (size_t index(0), length([self length]); index != length; ++index) {
1091 sprintf(name, "%zu", index);
1092 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1096 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1097 + (bool) cy$hasImplicitProperties {
1103 /* Bridge: WebUndefined {{{ */
1104 @implementation WebUndefined (Cycript)
1106 - (JSType) cy$JSType {
1107 return kJSTypeUndefined;
1110 - (NSObject *) cy$toJSON:(NSString *)key {
1114 - (NSString *) cy$toCYON {
1115 return @"undefined";
1118 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1119 return CYJSUndefined(context);
1120 } CYObjectiveCatch }
1125 static bool CYIsClass(id self) {
1127 // XXX: this is a lame object_isClass
1128 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1130 return GSObjCIsClass(self);
1134 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1135 id self(CYCastNSObject(pool, context, value));
1136 if (CYIsClass(self))
1137 return (Class) self;
1138 throw CYJSError(context, "got something that is not a Class");
1142 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1144 size_t size(JSPropertyNameArrayGetCount(names));
1145 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1146 for (size_t index(0); index != size; ++index)
1147 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1151 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1153 return CYJSNull(context);
1154 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1155 return [value cy$JSValueInContext:context];
1157 return CYMakeInstance(context, value, false);
1158 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1160 @implementation CYJSObject
1162 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1163 if ((self = [super init]) != nil) {
1165 context_ = CYGetJSContext(context);
1166 //XXX:JSGlobalContextRetain(context_);
1167 JSValueProtect(context_, object_);
1169 } CYObjectiveCatch }
1171 - (void) dealloc { CYObjectiveTry {
1172 JSValueUnprotect(context_, object_);
1173 //XXX:JSGlobalContextRelease(context_);
1175 } CYObjectiveCatch }
1177 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1178 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1179 if (!CYIsCallable(context_, toJSON))
1180 return [super cy$toJSON:key];
1182 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1183 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1184 // XXX: do I really want an NSNull here?!
1185 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1187 } CYObjectiveCatch }
1189 - (NSString *) cy$toCYON { CYObjectiveTry {
1191 JSValueRef exception(NULL);
1192 const char *cyon(CYPoolCCYON(pool, context_, object_));
1193 CYThrow(context_, exception);
1195 return [super cy$toCYON];
1197 return [NSString stringWithUTF8String:cyon];
1198 } CYObjectiveCatch }
1200 - (NSUInteger) count { CYObjectiveTry {
1201 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1202 size_t size(JSPropertyNameArrayGetCount(names));
1203 JSPropertyNameArrayRelease(names);
1205 } CYObjectiveCatch }
1207 - (id) objectForKey:(id)key { CYObjectiveTry {
1208 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1209 if (JSValueIsUndefined(context_, value))
1211 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1212 } CYObjectiveCatch }
1214 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1215 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1216 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1217 JSPropertyNameArrayRelease(names);
1219 } CYObjectiveCatch }
1221 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1222 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1223 } CYObjectiveCatch }
1225 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1226 JSValueRef exception(NULL);
1227 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1228 CYThrow(context_, exception);
1229 } CYObjectiveCatch }
1233 @implementation CYJSArray
1235 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1236 if ((self = [super init]) != nil) {
1238 context_ = CYGetJSContext(context);
1239 //XXX:JSGlobalContextRetain(context_);
1240 JSValueProtect(context_, object_);
1242 } CYObjectiveCatch }
1244 - (void) dealloc { CYObjectiveTry {
1245 JSValueUnprotect(context_, object_);
1246 //XXX:JSGlobalContextRelease(context_);
1248 } CYObjectiveCatch }
1250 - (NSUInteger) count { CYObjectiveTry {
1251 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1252 } CYObjectiveCatch }
1254 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1255 size_t bounds([self count]);
1256 if (index >= bounds)
1257 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1258 JSValueRef exception(NULL);
1259 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1260 CYThrow(context_, exception);
1261 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1262 } CYObjectiveCatch }
1264 - (void) addObject:(id)object { CYObjectiveTry {
1265 JSValueRef exception(NULL);
1266 JSValueRef arguments[1];
1267 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1268 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1269 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1270 CYThrow(context_, exception);
1271 } CYObjectiveCatch }
1273 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1274 size_t bounds([self count] + 1);
1275 if (index >= bounds)
1276 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1277 JSValueRef exception(NULL);
1278 JSValueRef arguments[3];
1279 arguments[0] = CYCastJSValue(context_, index);
1280 arguments[1] = CYCastJSValue(context_, 0);
1281 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1282 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1283 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1284 CYThrow(context_, exception);
1285 } CYObjectiveCatch }
1287 - (void) removeLastObject { CYObjectiveTry {
1288 JSValueRef exception(NULL);
1289 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1290 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1291 CYThrow(context_, exception);
1292 } CYObjectiveCatch }
1294 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1295 size_t bounds([self count]);
1296 if (index >= bounds)
1297 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1298 JSValueRef exception(NULL);
1299 JSValueRef arguments[2];
1300 arguments[0] = CYCastJSValue(context_, index);
1301 arguments[1] = CYCastJSValue(context_, 1);
1302 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1303 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1304 CYThrow(context_, exception);
1305 } CYObjectiveCatch }
1307 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1308 size_t bounds([self count]);
1309 if (index >= bounds)
1310 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1311 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1312 } CYObjectiveCatch }
1316 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1320 JSObjectRef object_;
1328 // XXX: delete object_? ;(
1331 static CYInternal *Get(id self) {
1332 CYInternal *internal(NULL);
1333 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1334 // XXX: do something epic? ;P
1340 static CYInternal *Set(id self) {
1341 CYInternal *internal(NULL);
1342 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1343 if (internal == NULL) {
1344 internal = new CYInternal();
1345 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1348 // XXX: do something epic? ;P
1354 bool HasProperty(JSContextRef context, JSStringRef name) {
1355 if (object_ == NULL)
1357 return JSObjectHasProperty(context, object_, name);
1360 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1361 if (object_ == NULL)
1363 return CYGetProperty(context, object_, name);
1366 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1367 if (object_ == NULL)
1368 object_ = JSObjectMake(context, NULL, NULL);
1369 CYSetProperty(context, object_, name, value);
1373 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1374 Selector_privateData *internal(new Selector_privateData(sel));
1375 return JSObjectMake(context, Selector_, internal);
1378 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1379 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1380 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1381 return reinterpret_cast<SEL>(internal->value_);
1383 return CYCastPointer<SEL>(context, value);
1386 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1387 return (void *) [[NSAutoreleasePool alloc] init];
1388 } CYSadCatch(NULL) }
1390 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1391 return [(NSAutoreleasePool *) handle release];
1394 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1396 return Instance::Make(context, nil);
1397 if (Class _class = objc_getClass(name.data))
1398 return CYMakeInstance(context, _class, true);
1399 if (Protocol *protocol = objc_getProtocol(name.data))
1400 return CYMakeInstance(context, protocol, true);
1402 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1404 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1405 ffi_call(cif, function, value, values);
1408 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1409 switch (type->primitive) {
1410 // XXX: do something epic about blocks
1413 case sig::typename_P:
1414 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1417 case sig::selector_P:
1418 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1426 } CYSadCatch(false) }
1428 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1429 switch (type->primitive) {
1430 // XXX: do something epic about blocks
1433 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1434 JSValueRef value(CYCastJSValue(context, object));
1440 case sig::typename_P:
1441 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1443 case sig::selector_P:
1444 if (SEL sel = *reinterpret_cast<SEL *>(data))
1445 return CYMakeSelector(context, sel);
1449 return CYJSNull(context);
1453 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1455 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1456 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1459 #if OBJC_API_VERSION >= 2
1461 method_getReturnType(method, type, sizeof(type));
1463 const char *type(method_getTypeEncoding(method));
1469 // XXX: possibly use a more "awesome" check?
1473 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1475 return method_getTypeEncoding(method);
1477 const char *name(sel_getName(sel));
1478 size_t length(strlen(name));
1480 char keyed[length + 2];
1482 keyed[length + 1] = '\0';
1483 memcpy(keyed + 1, name, length);
1485 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1486 return entry->value_;
1491 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1492 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1494 JSContextRef context(internal->context_);
1496 size_t count(internal->cif_.nargs);
1497 JSValueRef values[count];
1499 for (size_t index(0); index != count; ++index)
1500 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1502 JSObjectRef _this(CYCastJSObject(context, values[0]));
1504 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1505 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1508 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1509 Message_privateData *internal(new Message_privateData(sel, type, imp));
1510 return JSObjectMake(context, Message_, internal);
1513 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1514 JSObjectRef function(CYCastJSObject(context, value));
1515 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1516 // XXX: see notes in Library.cpp about needing to leak
1517 return reinterpret_cast<IMP>(internal->GetValue());
1520 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1521 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1522 Class _class(internal->GetValue());
1525 const char *name(CYPoolCString(pool, context, property));
1527 if (SEL sel = sel_getUid(name))
1528 if (class_getInstanceMethod(_class, sel) != NULL)
1534 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1535 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1536 Class _class(internal->GetValue());
1539 const char *name(CYPoolCString(pool, context, property));
1541 if (SEL sel = sel_getUid(name))
1542 if (objc_method *method = class_getInstanceMethod(_class, sel))
1543 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1548 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1549 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1550 Class _class(internal->GetValue());
1553 const char *name(CYPoolCString(pool, context, property));
1555 SEL sel(sel_registerName(name));
1557 objc_method *method(class_getInstanceMethod(_class, sel));
1562 if (JSValueIsObjectOfClass(context, value, Message_)) {
1563 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1564 type = sig::Unparse(pool, &message->signature_);
1565 imp = reinterpret_cast<IMP>(message->GetValue());
1567 type = CYPoolTypeEncoding(pool, context, sel, method);
1568 imp = CYMakeMessage(context, value, type);
1572 method_setImplementation(method, imp);
1575 GSMethodList list(GSAllocMethodList(1));
1576 GSAppendMethodToList(list, sel, type, imp, YES);
1577 GSAddMethodList(_class, list, YES);
1578 GSFlushMethodCacheForClass(_class);
1580 class_addMethod(_class, sel, imp, type);
1587 #if 0 && OBJC_API_VERSION < 2
1588 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1589 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1590 Class _class(internal->GetValue());
1593 const char *name(CYPoolCString(pool, context, property));
1595 if (SEL sel = sel_getUid(name))
1596 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1597 objc_method_list list = {NULL, 1, {method}};
1598 class_removeMethods(_class, &list);
1606 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1607 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1608 Class _class(internal->GetValue());
1610 #if OBJC_API_VERSION >= 2
1612 objc_method **data(class_copyMethodList(_class, &size));
1613 for (size_t i(0); i != size; ++i)
1614 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1617 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1618 for (int i(0); i != methods->method_count; ++i)
1619 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1623 static bool CYHasImplicitProperties(Class _class) {
1624 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1625 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1627 return [_class cy$hasImplicitProperties];
1630 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1631 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1632 id self(internal->GetValue());
1634 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1638 NSString *name(CYCastNSString(pool, context, property));
1640 if (CYInternal *internal = CYInternal::Get(self))
1641 if (internal->HasProperty(context, property))
1644 Class _class(object_getClass(self));
1647 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1648 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1649 if ([self cy$hasProperty:name])
1651 } CYPoolCatch(false)
1653 const char *string(CYPoolCString(pool, context, name));
1656 if (class_getProperty(_class, string) != NULL)
1660 if (CYHasImplicitProperties(_class))
1661 if (SEL sel = sel_getUid(string))
1662 if (CYImplements(self, _class, sel, true))
1668 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1669 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1670 id self(internal->GetValue());
1672 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1673 return Internal::Make(context, self, object);
1676 NSString *name(CYCastNSString(pool, context, property));
1678 if (CYInternal *internal = CYInternal::Get(self))
1679 if (JSValueRef value = internal->GetProperty(context, property))
1683 if (NSObject *data = [self cy$getProperty:name])
1684 return CYCastJSValue(context, data);
1687 const char *string(CYPoolCString(pool, context, name));
1688 Class _class(object_getClass(self));
1691 if (objc_property_t property = class_getProperty(_class, string)) {
1692 PropertyAttributes attributes(property);
1693 SEL sel(sel_registerName(attributes.Getter()));
1694 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1698 if (CYHasImplicitProperties(_class))
1699 if (SEL sel = sel_getUid(string))
1700 if (CYImplements(self, _class, sel, true))
1701 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1706 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1707 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1708 id self(internal->GetValue());
1712 NSString *name(CYCastNSString(pool, context, property));
1713 NSObject *data(CYCastNSObject(pool, context, value));
1716 if ([self cy$setProperty:name to:data])
1720 const char *string(CYPoolCString(pool, context, name));
1721 Class _class(object_getClass(self));
1724 if (objc_property_t property = class_getProperty(_class, string)) {
1725 PropertyAttributes attributes(property);
1726 if (const char *setter = attributes.Setter()) {
1727 SEL sel(sel_registerName(setter));
1728 JSValueRef arguments[1] = {value};
1729 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1735 size_t length(strlen(string));
1737 char set[length + 5];
1743 if (string[0] != '\0') {
1744 set[3] = toupper(string[0]);
1745 memcpy(set + 4, string + 1, length - 1);
1748 set[length + 3] = ':';
1749 set[length + 4] = '\0';
1751 if (SEL sel = sel_getUid(set))
1752 if (CYImplements(self, _class, sel, false)) {
1753 JSValueRef arguments[1] = {value};
1754 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1757 if (CYInternal *internal = CYInternal::Set(self)) {
1758 internal->SetProperty(context, property, value);
1765 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1766 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1767 id self(internal->GetValue());
1770 NSString *name(CYCastNSString(NULL, context, property));
1771 return [self cy$deleteProperty:name];
1773 } CYCatch return /*XXX*/ NULL; }
1775 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1776 const char *name(sel_getName(method_getName(method)));
1777 if (strchr(name, ':') != NULL)
1780 const char *type(method_getTypeEncoding(method));
1781 if (type == NULL || *type == '\0' || *type == 'v')
1784 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1787 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1788 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1789 id self(internal->GetValue());
1792 Class _class(object_getClass(self));
1797 objc_property_t *data(class_copyPropertyList(_class, &size));
1798 for (size_t i(0); i != size; ++i)
1799 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1804 if (CYHasImplicitProperties(_class))
1805 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1806 #if OBJC_API_VERSION >= 2
1808 objc_method **data(class_copyMethodList(current, &size));
1809 for (size_t i(0); i != size; ++i)
1810 Instance_getPropertyNames_message(names, data[i]);
1813 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1814 for (int i(0); i != methods->method_count; ++i)
1815 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1820 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1821 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1822 [self cy$getPropertyNames:names inContext:context];
1826 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1827 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1828 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1832 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1833 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1834 Class _class(internal->GetValue());
1835 if (!CYIsClass(_class))
1838 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1839 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1840 // XXX: this isn't always safe
1841 return [linternal->GetValue() isKindOfClass:_class];
1847 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1848 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1851 id self(internal->GetValue());
1852 const char *name(CYPoolCString(pool, context, property));
1854 if (object_getInstanceVariable(self, name, NULL) != NULL)
1860 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1861 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1864 id self(internal->GetValue());
1865 const char *name(CYPoolCString(pool, context, property));
1867 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1868 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1869 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1870 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1876 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1877 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1880 id self(internal->GetValue());
1881 const char *name(CYPoolCString(pool, context, property));
1883 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1884 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1885 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1892 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1893 if (Class super = class_getSuperclass(_class))
1894 Internal_getPropertyNames_(super, names);
1896 #if OBJC_API_VERSION >= 2
1898 objc_ivar **data(class_copyIvarList(_class, &size));
1899 for (size_t i(0); i != size; ++i)
1900 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1903 if (objc_ivar_list *ivars = _class->ivars)
1904 for (int i(0); i != ivars->ivar_count; ++i)
1905 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1909 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1910 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1913 id self(internal->GetValue());
1914 Class _class(object_getClass(self));
1916 Internal_getPropertyNames_(_class, names);
1919 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1920 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1921 return internal->GetOwner();
1924 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1926 NSString *name(CYCastNSString(pool, context, property));
1927 if (Class _class = NSClassFromString(name))
1928 return CYMakeInstance(context, _class, true);
1932 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1934 size_t size(objc_getClassList(NULL, 0));
1935 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1938 size_t writ(objc_getClassList(data, size));
1941 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1947 for (size_t i(0); i != writ; ++i)
1948 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1954 while (Class _class = objc_next_class(&state))
1955 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1959 #if OBJC_API_VERSION >= 2
1960 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1961 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1964 const char *name(CYPoolCString(pool, context, property));
1966 const char **data(objc_copyClassNamesForImage(internal, &size));
1968 for (size_t i(0); i != size; ++i)
1969 if (strcmp(name, data[i]) == 0) {
1970 if (Class _class = objc_getClass(name)) {
1971 value = CYMakeInstance(context, _class, true);
1982 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1983 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1985 const char **data(objc_copyClassNamesForImage(internal, &size));
1986 for (size_t i(0); i != size; ++i)
1987 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1991 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1993 const char *name(CYPoolCString(pool, context, property));
1995 const char **data(objc_copyImageNames(&size));
1996 for (size_t i(0); i != size; ++i)
1997 if (strcmp(name, data[i]) == 0) {
2006 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2007 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2011 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2013 const char **data(objc_copyImageNames(&size));
2014 for (size_t i(0); i != size; ++i)
2015 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2020 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2022 const char *name(CYPoolCString(pool, context, property));
2023 if (Protocol *protocol = objc_getProtocol(name))
2024 return CYMakeInstance(context, protocol, true);
2028 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2029 #if OBJC_API_VERSION >= 2
2031 Protocol **data(objc_copyProtocolList(&size));
2032 for (size_t i(0); i != size; ++i)
2033 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2041 static bool stret(ffi_type *ffi_type) {
2042 return ffi_type->type == FFI_TYPE_STRUCT && (
2043 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2044 struct_forward_array[ffi_type->size] != 0
2049 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 {
2053 _class = object_getClass(self);
2057 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2058 imp = method_getImplementation(method);
2059 type = method_getTypeEncoding(method);
2064 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2066 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2067 type = CYPoolCString(pool, context, [method _typeString]);
2075 sig::Signature signature;
2076 sig::Parse(pool, &signature, type, &Structor_);
2079 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2083 if (stret(cif.rtype))
2084 imp = class_getMethodImplementation_stret(_class, _cmd);
2086 imp = class_getMethodImplementation(_class, _cmd);
2088 objc_super super = {self, _class};
2089 imp = objc_msg_lookup_super(&super, _cmd);
2093 void (*function)() = reinterpret_cast<void (*)()>(imp);
2094 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2097 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2099 throw CYJSError(context, "too few arguments to objc_msgSend");
2109 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2110 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2111 self = internal->GetValue();
2112 _class = internal->class_;;
2113 uninitialized = false;
2114 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2115 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2116 self = internal->GetValue();
2118 uninitialized = internal->IsUninitialized();
2120 internal->value_ = nil;
2122 self = CYCastNSObject(pool, context, arguments[0]);
2124 uninitialized = false;
2128 return CYJSNull(context);
2130 _cmd = CYCastSEL(context, arguments[1]);
2132 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2135 /* Hook: objc_registerClassPair {{{ */
2136 #if defined(__APPLE__) && defined(__arm__)
2137 // XXX: replace this with associated objects
2139 MSHook(void, CYDealloc, id self, SEL sel) {
2140 CYInternal *internal;
2141 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2142 if (internal != NULL)
2144 _CYDealloc(self, sel);
2147 MSHook(void, objc_registerClassPair, Class _class) {
2148 Class super(class_getSuperclass(_class));
2149 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2150 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2151 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2154 _objc_registerClassPair(_class);
2157 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2159 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2161 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2162 if (value == NULL || !CYIsClass(value))
2163 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2164 Class _class((Class) value);
2165 $objc_registerClassPair(_class);
2166 return CYJSUndefined(context);
2171 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2172 JSValueRef setup[count + 2];
2175 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2176 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2179 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2181 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2183 // XXX: handle Instance::Uninitialized?
2184 id self(CYCastNSObject(pool, context, _this));
2188 setup[1] = &internal->sel_;
2190 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2193 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2195 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2197 id self(CYCastNSObject(pool, context, arguments[0]));
2198 Class _class(CYCastClass(pool, context, arguments[1]));
2199 return cy::Super::Make(context, self, _class);
2202 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2204 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2206 const char *name(CYPoolCString(pool, context, arguments[0]));
2207 return CYMakeSelector(context, sel_registerName(name));
2210 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2212 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2213 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2214 return CYMakeInstance(context, self, false);
2217 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2218 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2219 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2222 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2223 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2224 Type_privateData *typical(internal->GetType());
2229 if (typical == NULL) {
2233 type = typical->type_;
2234 ffi = typical->ffi_;
2237 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2240 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2241 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2242 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2245 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2246 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2247 id self(internal->GetValue());
2248 if (!CYIsClass(self))
2249 return CYJSUndefined(context);
2250 return CYGetClassPrototype(context, self);
2253 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2254 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2255 id self(internal->GetValue());
2256 if (!CYIsClass(self))
2257 return CYJSUndefined(context);
2258 return Messages::Make(context, (Class) self);
2261 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2262 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2265 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2266 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2269 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2270 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2273 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2280 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2281 // XXX: check for support of cy$toJSON?
2282 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2284 } CYCatch return /*XXX*/ NULL; }
2287 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2288 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2291 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2292 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2293 } CYCatch return /*XXX*/ NULL; }
2296 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2297 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2300 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2301 // XXX: but... but... THIS ISN'T A POINTER! :(
2302 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2303 } CYCatch return /*XXX*/ NULL; }
2305 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2306 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2309 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2311 id value(internal->GetValue());
2313 return CYCastJSValue(context, "nil");
2316 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2317 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2319 } CYCatch return /*XXX*/ NULL; }
2321 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2322 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2323 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2326 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2327 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2330 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2331 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2332 const char *name(sel_getName(internal->GetValue()));
2335 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2336 return CYCastJSValue(context, CYJSString(context, string));
2338 } CYCatch return /*XXX*/ NULL; }
2340 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2342 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2345 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2346 SEL sel(internal->GetValue());
2348 objc_method *method;
2349 if (Class _class = CYCastClass(pool, context, arguments[0]))
2350 method = class_getInstanceMethod(_class, sel);
2354 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2355 return CYCastJSValue(context, CYJSString(type));
2357 return CYJSNull(context);
2360 static JSStaticValue Selector_staticValues[2] = {
2361 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2362 {NULL, NULL, NULL, 0}
2365 static JSStaticValue Instance_staticValues[5] = {
2366 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2367 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2368 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2369 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2370 {NULL, NULL, NULL, 0}
2373 static JSStaticFunction Instance_staticFunctions[6] = {
2374 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2375 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2376 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2377 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2378 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2379 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2383 static JSStaticFunction Internal_staticFunctions[2] = {
2384 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2388 static JSStaticFunction Selector_staticFunctions[5] = {
2389 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2390 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2391 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2392 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2396 static JSStaticFunction StringInstance_staticFunctions[2] = {
2397 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2398 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2402 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2403 apr_pool_t *pool(CYGetGlobalPool());
2405 Object_type = new(pool) Type_privateData("@");
2406 Selector_type = new(pool) Type_privateData(":");
2409 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2410 NSCFType_ = objc_getClass("NSCFType");
2411 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2412 NSZombie_ = objc_getClass("_NSZombie_");
2414 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2417 NSArray_ = objc_getClass("NSArray");
2418 NSDictionary_ = objc_getClass("NSDictionary");
2419 NSString_ = objc_getClass("NSString");
2420 Object_ = objc_getClass("Object");
2422 JSClassDefinition definition;
2424 definition = kJSClassDefinitionEmpty;
2425 definition.className = "Instance";
2426 definition.staticValues = Instance_staticValues;
2427 definition.staticFunctions = Instance_staticFunctions;
2428 definition.hasProperty = &Instance_hasProperty;
2429 definition.getProperty = &Instance_getProperty;
2430 definition.setProperty = &Instance_setProperty;
2431 definition.deleteProperty = &Instance_deleteProperty;
2432 definition.getPropertyNames = &Instance_getPropertyNames;
2433 definition.callAsConstructor = &Instance_callAsConstructor;
2434 definition.hasInstance = &Instance_hasInstance;
2435 definition.finalize = &CYFinalize;
2436 Instance_ = JSClassCreate(&definition);
2438 definition = kJSClassDefinitionEmpty;
2439 definition.className = "Internal";
2440 definition.staticFunctions = Internal_staticFunctions;
2441 definition.hasProperty = &Internal_hasProperty;
2442 definition.getProperty = &Internal_getProperty;
2443 definition.setProperty = &Internal_setProperty;
2444 definition.getPropertyNames = &Internal_getPropertyNames;
2445 definition.finalize = &CYFinalize;
2446 Internal_ = JSClassCreate(&definition);
2448 definition = kJSClassDefinitionEmpty;
2449 definition.className = "Message";
2450 definition.staticFunctions = cy::Functor::StaticFunctions;
2451 definition.callAsFunction = &Message_callAsFunction;
2452 definition.finalize = &CYFinalize;
2453 Message_ = JSClassCreate(&definition);
2455 definition = kJSClassDefinitionEmpty;
2456 definition.className = "Messages";
2457 definition.hasProperty = &Messages_hasProperty;
2458 definition.getProperty = &Messages_getProperty;
2459 definition.setProperty = &Messages_setProperty;
2460 #if 0 && OBJC_API_VERSION < 2
2461 definition.deleteProperty = &Messages_deleteProperty;
2463 definition.getPropertyNames = &Messages_getPropertyNames;
2464 definition.finalize = &CYFinalize;
2465 Messages_ = JSClassCreate(&definition);
2467 definition = kJSClassDefinitionEmpty;
2468 definition.className = "Selector";
2469 definition.staticValues = Selector_staticValues;
2470 definition.staticFunctions = Selector_staticFunctions;
2471 definition.callAsFunction = &Selector_callAsFunction;
2472 definition.finalize = &CYFinalize;
2473 Selector_ = JSClassCreate(&definition);
2475 definition = kJSClassDefinitionEmpty;
2476 definition.className = "StringInstance";
2477 definition.staticFunctions = StringInstance_staticFunctions;
2478 StringInstance_ = JSClassCreate(&definition);
2480 definition = kJSClassDefinitionEmpty;
2481 definition.className = "Super";
2482 definition.staticFunctions = Internal_staticFunctions;
2483 definition.finalize = &CYFinalize;
2484 Super_ = JSClassCreate(&definition);
2486 definition = kJSClassDefinitionEmpty;
2487 definition.className = "ObjectiveC::Classes";
2488 definition.getProperty = &ObjectiveC_Classes_getProperty;
2489 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2490 ObjectiveC_Classes_ = JSClassCreate(&definition);
2492 #if OBJC_API_VERSION >= 2
2493 definition = kJSClassDefinitionEmpty;
2494 definition.className = "ObjectiveC::Images";
2495 definition.getProperty = &ObjectiveC_Images_getProperty;
2496 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2497 ObjectiveC_Images_ = JSClassCreate(&definition);
2499 definition = kJSClassDefinitionEmpty;
2500 definition.className = "ObjectiveC::Image::Classes";
2501 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2502 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2503 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2506 definition = kJSClassDefinitionEmpty;
2507 definition.className = "ObjectiveC::Protocols";
2508 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2509 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2510 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2512 #if defined(__APPLE__) && defined(__arm__)
2513 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2517 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2521 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2522 JSObjectRef global(CYGetGlobalObject(context));
2523 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2524 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2525 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2527 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2528 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2530 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2531 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2533 #if OBJC_API_VERSION >= 2
2534 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2537 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2538 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2539 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2540 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2541 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2543 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2544 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2546 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2547 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2549 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2550 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2552 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2553 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2554 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2556 #if defined(__APPLE__) && defined(__arm__)
2557 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2560 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2562 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2563 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2564 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2567 static CYHooks CYObjectiveCHooks = {
2568 &CYObjectiveC_ExecuteStart,
2569 &CYObjectiveC_ExecuteEnd,
2570 &CYObjectiveC_RuntimeProperty,
2571 &CYObjectiveC_CallFunction,
2572 &CYObjectiveC_Initialize,
2573 &CYObjectiveC_SetupContext,
2574 &CYObjectiveC_PoolFFI,
2575 &CYObjectiveC_FromFFI,
2578 struct CYObjectiveC {
2580 hooks_ = &CYObjectiveCHooks;
2581 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2582 _assert(hooks_ != NULL);