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"
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 Super_;
265 static JSClassRef ObjectiveC_Classes_;
266 static JSClassRef ObjectiveC_Protocols_;
269 static JSClassRef ObjectiveC_Image_Classes_;
270 static JSClassRef ObjectiveC_Images_;
274 static Class NSCFBoolean_;
275 static Class NSCFType_;
276 static Class NSMessageBuilder_;
277 static Class NSZombie_;
279 static Class NSBoolNumber_;
282 static Class NSArray_;
283 static Class NSDictionary_;
284 static Class Object_;
286 static Type_privateData *Object_type;
287 static Type_privateData *Selector_type;
289 Type_privateData *Instance::GetType() const {
293 Type_privateData *Selector_privateData::GetType() const {
294 return Selector_type;
297 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
299 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
301 JSObjectRef global(CYGetGlobalObject(context));
302 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
305 sprintf(label, "i%p", self);
306 CYJSString name(label);
308 JSValueRef value(CYGetProperty(context, cy, name));
309 if (!JSValueIsUndefined(context, value))
312 JSClassRef _class(NULL);
313 JSValueRef prototype;
315 if (self == NSArray_)
316 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
317 else if (self == NSDictionary_)
318 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
320 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
322 JSObjectRef object(JSObjectMake(context, _class, NULL));
323 JSObjectSetPrototype(context, object, prototype);
324 CYSetProperty(context, cy, name, object);
328 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
329 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
330 if (_class == NSArray_)
332 if (Class super = class_getSuperclass(_class))
333 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
335 JSObjectSetPrototype(context, value, Array_prototype_);*/
339 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
340 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
344 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
345 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
349 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
350 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
351 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
355 Instance::~Instance() {
356 if ((flags_ & Transient) == 0)
357 // XXX: does this handle background threads correctly?
358 // XXX: this simply does not work on the console because I'm stupid
359 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
362 struct Message_privateData :
367 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
368 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
374 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
375 Instance::Flags flags;
378 flags = Instance::Transient;
380 flags = Instance::None;
381 object = [object retain];
384 return Instance::Make(context, object, flags);
387 @interface NSMethodSignature (Cycript)
388 - (NSString *) _typeString;
391 @interface NSObject (Cycript)
393 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
394 - (JSType) cy$JSType;
396 - (NSObject *) cy$toJSON:(NSString *)key;
397 - (NSString *) cy$toCYON;
398 - (NSString *) cy$toKey;
400 - (bool) cy$hasProperty:(NSString *)name;
401 - (NSObject *) cy$getProperty:(NSString *)name;
402 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
403 - (bool) cy$deleteProperty:(NSString *)name;
404 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
409 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
412 NSString *CYCastNSCYON(id value) {
418 Class _class(object_getClass(value));
419 SEL sel(@selector(cy$toCYON));
421 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
422 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
423 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
424 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
425 string = [value cy$toCYON];
430 else if (value == NSZombie_)
431 string = @"_NSZombie_";
432 else if (_class == NSZombie_)
433 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
434 // XXX: frowny /in/ the pants
435 else if (value == NSMessageBuilder_ || value == Object_)
439 string = [NSString stringWithFormat:@"%@", value];
444 string = @"undefined";
451 struct PropertyAttributes {
456 const char *variable;
469 PropertyAttributes(objc_property_t property) :
481 name = property_getName(property);
482 const char *attributes(property_getAttributes(property));
484 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
486 case 'R': readonly = true; break;
487 case 'C': copy = true; break;
488 case '&': retain = true; break;
489 case 'N': nonatomic = true; break;
490 case 'G': getter_ = token + 1; break;
491 case 'S': setter_ = token + 1; break;
492 case 'V': variable = token + 1; break;
496 /*if (variable == NULL) {
497 variable = property_getName(property);
498 size_t size(strlen(variable));
499 char *name(new(pool_) char[size + 2]);
501 memcpy(name + 1, variable, size);
502 name[size + 1] = '\0';
507 const char *Getter() {
509 getter_ = apr_pstrdup(pool_, name);
513 const char *Setter() {
514 if (setter_ == NULL && !readonly) {
515 size_t length(strlen(name));
517 char *temp(new(pool_) char[length + 5]);
523 temp[3] = toupper(name[0]);
524 memcpy(temp + 4, name + 1, length - 1);
527 temp[length + 3] = ':';
528 temp[length + 4] = '\0';
539 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
540 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
545 @interface CYWebUndefined : NSObject {
548 + (CYWebUndefined *) undefined;
552 @implementation CYWebUndefined
554 + (CYWebUndefined *) undefined {
555 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
561 #define WebUndefined CYWebUndefined
564 /* Bridge: CYJSObject {{{ */
565 @interface CYJSObject : NSMutableDictionary {
567 JSContextRef context_;
570 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
572 - (NSObject *) cy$toJSON:(NSString *)key;
574 - (NSUInteger) count;
575 - (id) objectForKey:(id)key;
576 - (NSEnumerator *) keyEnumerator;
577 - (void) setObject:(id)object forKey:(id)key;
578 - (void) removeObjectForKey:(id)key;
582 /* Bridge: CYJSArray {{{ */
583 @interface CYJSArray : NSMutableArray {
585 JSContextRef context_;
588 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
590 - (NSUInteger) count;
591 - (id) objectAtIndex:(NSUInteger)index;
593 - (void) addObject:(id)anObject;
594 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
595 - (void) removeLastObject;
596 - (void) removeObjectAtIndex:(NSUInteger)index;
597 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
602 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
603 JSObjectRef Array(CYGetCachedObject(context, Array_s));
604 JSValueRef exception(NULL);
605 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
606 CYThrow(context, exception);
607 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
608 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
611 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
612 if (!JSValueIsObjectOfClass(context, object, Instance_))
613 return CYCastNSObject_(pool, context, object);
615 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
616 return internal->GetValue();
620 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
621 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
625 @interface NSBoolNumber : NSNumber {
630 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
634 switch (JSType type = JSValueGetType(context, value)) {
635 case kJSTypeUndefined:
636 object = [WebUndefined undefined];
646 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
649 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
655 object = CYCopyNSNumber(context, value);
660 object = CYCopyNSString(context, value);
665 // XXX: this might could be more efficient
666 object = CYCastNSObject(pool, context, (JSObjectRef) value);
671 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
678 return CYPoolRelease(pool, object);
680 return [object retain];
683 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
684 return CYNSObject(pool, context, value, true);
687 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
688 return CYNSObject(pool, context, value, false);
691 /* Bridge: NSArray {{{ */
692 @implementation NSArray (Cycript)
694 - (NSString *) cy$toCYON {
695 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
696 [json appendString:@"["];
700 for (id object in self) {
702 for (size_t index(0), count([self count]); index != count; ++index) {
703 id object([self objectAtIndex:index]);
706 [json appendString:@","];
709 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
710 [json appendString:CYCastNSCYON(object)];
712 [json appendString:@","];
717 [json appendString:@"]"];
721 - (bool) cy$hasProperty:(NSString *)name {
722 if ([name isEqualToString:@"length"])
725 size_t index(CYGetIndex(name));
726 if (index == _not(size_t) || index >= [self count])
727 return [super cy$hasProperty:name];
732 - (NSObject *) cy$getProperty:(NSString *)name {
733 if ([name isEqualToString:@"length"]) {
734 NSUInteger count([self count]);
736 return [NSNumber numberWithUnsignedInteger:count];
738 return [NSNumber numberWithUnsignedInt:count];
742 size_t index(CYGetIndex(name));
743 if (index == _not(size_t) || index >= [self count])
744 return [super cy$getProperty:name];
746 return [self objectAtIndex:index];
749 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
750 [super cy$getPropertyNames:names inContext:context];
752 for (size_t index(0), count([self count]); index != count; ++index) {
753 id object([self objectAtIndex:index]);
754 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
756 sprintf(name, "%zu", index);
757 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
764 /* Bridge: NSBoolNumber {{{ */
766 @implementation NSBoolNumber (Cycript)
768 - (JSType) cy$JSType {
769 return kJSTypeBoolean;
772 - (NSObject *) cy$toJSON:(NSString *)key {
776 - (NSString *) cy$toCYON {
777 return [self boolValue] ? @"true" : @"false";
780 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
781 return CYCastJSValue(context, (bool) [self boolValue]);
787 /* Bridge: NSDictionary {{{ */
788 @implementation NSDictionary (Cycript)
790 - (NSString *) cy$toCYON {
791 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
792 [json appendString:@"{"];
796 for (NSObject *key in self) {
798 NSEnumerator *keys([self keyEnumerator]);
799 while (NSObject *key = [keys nextObject]) {
802 [json appendString:@","];
805 [json appendString:[key cy$toKey]];
806 [json appendString:@":"];
807 NSObject *object([self objectForKey:key]);
808 [json appendString:CYCastNSCYON(object)];
811 [json appendString:@"}"];
815 - (bool) cy$hasProperty:(NSString *)name {
816 return [self objectForKey:name] != nil;
819 - (NSObject *) cy$getProperty:(NSString *)name {
820 return [self objectForKey:name];
823 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
824 [super cy$getPropertyNames:names inContext:context];
827 for (NSObject *key in self) {
829 NSEnumerator *keys([self keyEnumerator]);
830 while (NSObject *key = [keys nextObject]) {
832 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
838 /* Bridge: NSMutableArray {{{ */
839 @implementation NSMutableArray (Cycript)
841 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
842 if ([name isEqualToString:@"length"]) {
843 // XXX: is this not intelligent?
844 NSNumber *number(reinterpret_cast<NSNumber *>(value));
846 NSUInteger size([number unsignedIntegerValue]);
848 NSUInteger size([number unsignedIntValue]);
850 NSUInteger count([self count]);
852 [self removeObjectsInRange:NSMakeRange(size, count - size)];
853 else if (size != count) {
854 WebUndefined *undefined([WebUndefined undefined]);
855 for (size_t i(count); i != size; ++i)
856 [self addObject:undefined];
861 size_t index(CYGetIndex(name));
862 if (index == _not(size_t))
863 return [super cy$setProperty:name to:value];
865 id object(value ?: [NSNull null]);
867 size_t count([self count]);
869 [self replaceObjectAtIndex:index withObject:object];
871 if (index != count) {
872 WebUndefined *undefined([WebUndefined undefined]);
873 for (size_t i(count); i != index; ++i)
874 [self addObject:undefined];
877 [self addObject:object];
883 - (bool) cy$deleteProperty:(NSString *)name {
884 size_t index(CYGetIndex(name));
885 if (index == _not(size_t) || index >= [self count])
886 return [super cy$deleteProperty:name];
887 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
893 /* Bridge: NSMutableDictionary {{{ */
894 @implementation NSMutableDictionary (Cycript)
896 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
897 [self setObject:(value ?: [NSNull null]) forKey:name];
901 - (bool) cy$deleteProperty:(NSString *)name {
902 if ([self objectForKey:name] == nil)
905 [self removeObjectForKey:name];
912 /* Bridge: NSNumber {{{ */
913 @implementation NSNumber (Cycript)
915 - (JSType) cy$JSType {
917 // XXX: this just seems stupid
918 if ([self class] == NSCFBoolean_)
919 return kJSTypeBoolean;
921 return kJSTypeNumber;
924 - (NSObject *) cy$toJSON:(NSString *)key {
928 - (NSString *) cy$toCYON {
929 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
932 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
933 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
938 /* Bridge: NSNull {{{ */
939 @implementation NSNull (Cycript)
941 - (JSType) cy$JSType {
945 - (NSObject *) cy$toJSON:(NSString *)key {
949 - (NSString *) cy$toCYON {
955 /* Bridge: NSObject {{{ */
956 @implementation NSObject (Cycript)
958 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
959 return CYMakeInstance(context, self, false);
962 - (JSType) cy$JSType {
963 return kJSTypeObject;
966 - (NSObject *) cy$toJSON:(NSString *)key {
967 return [self description];
970 - (NSString *) cy$toCYON {
971 return [[self cy$toJSON:@""] cy$toCYON];
974 - (NSString *) cy$toKey {
975 return [self cy$toCYON];
978 - (bool) cy$hasProperty:(NSString *)name {
982 - (NSObject *) cy$getProperty:(NSString *)name {
986 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
990 - (bool) cy$deleteProperty:(NSString *)name {
994 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
999 /* Bridge: NSProxy {{{ */
1000 @implementation NSProxy (Cycript)
1002 - (NSObject *) cy$toJSON:(NSString *)key {
1003 return [self description];
1006 - (NSString *) cy$toCYON {
1007 return [[self cy$toJSON:@""] cy$toCYON];
1012 /* Bridge: NSString {{{ */
1013 @implementation NSString (Cycript)
1015 - (JSType) cy$JSType {
1016 return kJSTypeString;
1019 - (NSObject *) cy$toJSON:(NSString *)key {
1023 - (NSString *) cy$toCYON {
1024 std::ostringstream str;
1025 CYUTF8String string(CYCastUTF8String(self));
1026 CYStringify(str, string.data, string.size);
1027 std::string value(str.str());
1028 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1031 - (NSString *) cy$toKey {
1032 if (CYIsKey(CYCastUTF8String(self)))
1034 return [self cy$toCYON];
1039 /* Bridge: WebUndefined {{{ */
1040 @implementation WebUndefined (Cycript)
1042 - (JSType) cy$JSType {
1043 return kJSTypeUndefined;
1046 - (NSObject *) cy$toJSON:(NSString *)key {
1050 - (NSString *) cy$toCYON {
1051 return @"undefined";
1054 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1055 return CYJSUndefined(context);
1056 } CYObjectiveCatch }
1061 static bool CYIsClass(id self) {
1063 // XXX: this is a lame object_isClass
1064 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1066 return GSObjCIsClass(self);
1070 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1071 id self(CYCastNSObject(pool, context, value));
1072 if (CYIsClass(self))
1073 return (Class) self;
1074 throw CYJSError(context, "got something that is not a Class");
1078 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1080 size_t size(JSPropertyNameArrayGetCount(names));
1081 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1082 for (size_t index(0); index != size; ++index)
1083 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1087 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1089 return CYJSNull(context);
1090 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1091 return [value cy$JSValueInContext:context];
1093 return CYMakeInstance(context, value, false);
1094 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1096 @implementation CYJSObject
1098 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1099 if ((self = [super init]) != nil) {
1101 context_ = CYGetJSContext(context);
1102 //XXX:JSGlobalContextRetain(context_);
1103 JSValueProtect(context_, object_);
1105 } CYObjectiveCatch }
1107 - (void) dealloc { CYObjectiveTry {
1108 JSValueUnprotect(context_, object_);
1109 //XXX:JSGlobalContextRelease(context_);
1111 } CYObjectiveCatch }
1113 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1114 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1115 if (!CYIsCallable(context_, toJSON))
1116 return [super cy$toJSON:key];
1118 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1119 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1120 // XXX: do I really want an NSNull here?!
1121 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1123 } CYObjectiveCatch }
1125 - (NSString *) cy$toCYON { CYObjectiveTry {
1127 JSValueRef exception(NULL);
1128 const char *cyon(CYPoolCCYON(pool, context_, object_));
1129 CYThrow(context_, exception);
1131 return [super cy$toCYON];
1133 return [NSString stringWithUTF8String:cyon];
1134 } CYObjectiveCatch }
1136 - (NSUInteger) count { CYObjectiveTry {
1137 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1138 size_t size(JSPropertyNameArrayGetCount(names));
1139 JSPropertyNameArrayRelease(names);
1141 } CYObjectiveCatch }
1143 - (id) objectForKey:(id)key { CYObjectiveTry {
1144 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1145 if (JSValueIsUndefined(context_, value))
1147 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1148 } CYObjectiveCatch }
1150 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1151 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1152 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1153 JSPropertyNameArrayRelease(names);
1155 } CYObjectiveCatch }
1157 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1158 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1159 } CYObjectiveCatch }
1161 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1162 JSValueRef exception(NULL);
1163 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1164 CYThrow(context_, exception);
1165 } CYObjectiveCatch }
1169 @implementation CYJSArray
1171 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1172 if ((self = [super init]) != nil) {
1174 context_ = CYGetJSContext(context);
1175 //XXX:JSGlobalContextRetain(context_);
1176 JSValueProtect(context_, object_);
1178 } CYObjectiveCatch }
1180 - (void) dealloc { CYObjectiveTry {
1181 JSValueUnprotect(context_, object_);
1182 //XXX:JSGlobalContextRelease(context_);
1184 } CYObjectiveCatch }
1186 - (NSUInteger) count { CYObjectiveTry {
1187 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1188 } CYObjectiveCatch }
1190 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1191 size_t bounds([self count]);
1192 if (index >= bounds)
1193 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1194 JSValueRef exception(NULL);
1195 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1196 CYThrow(context_, exception);
1197 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1198 } CYObjectiveCatch }
1200 - (void) addObject:(id)object { CYObjectiveTry {
1201 JSValueRef exception(NULL);
1202 JSValueRef arguments[1];
1203 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1204 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1205 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1206 CYThrow(context_, exception);
1207 } CYObjectiveCatch }
1209 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1210 size_t bounds([self count] + 1);
1211 if (index >= bounds)
1212 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1213 JSValueRef exception(NULL);
1214 JSValueRef arguments[3];
1215 arguments[0] = CYCastJSValue(context_, index);
1216 arguments[1] = CYCastJSValue(context_, 0);
1217 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1218 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1219 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1220 CYThrow(context_, exception);
1221 } CYObjectiveCatch }
1223 - (void) removeLastObject { CYObjectiveTry {
1224 JSValueRef exception(NULL);
1225 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1226 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1227 CYThrow(context_, exception);
1228 } CYObjectiveCatch }
1230 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1231 size_t bounds([self count]);
1232 if (index >= bounds)
1233 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1234 JSValueRef exception(NULL);
1235 JSValueRef arguments[2];
1236 arguments[0] = CYCastJSValue(context_, index);
1237 arguments[1] = CYCastJSValue(context_, 1);
1238 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1239 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1240 CYThrow(context_, exception);
1241 } CYObjectiveCatch }
1243 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1244 size_t bounds([self count]);
1245 if (index >= bounds)
1246 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1247 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1248 } CYObjectiveCatch }
1252 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1256 JSObjectRef object_;
1264 // XXX: delete object_? ;(
1267 static CYInternal *Get(id self) {
1268 CYInternal *internal(NULL);
1269 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1270 // XXX: do something epic? ;P
1276 static CYInternal *Set(id self) {
1277 CYInternal *internal(NULL);
1278 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1279 if (internal == NULL) {
1280 internal = new CYInternal();
1281 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1284 // XXX: do something epic? ;P
1290 bool HasProperty(JSContextRef context, JSStringRef name) {
1291 if (object_ == NULL)
1293 return JSObjectHasProperty(context, object_, name);
1296 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1297 if (object_ == NULL)
1299 return CYGetProperty(context, object_, name);
1302 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1303 if (object_ == NULL)
1304 object_ = JSObjectMake(context, NULL, NULL);
1305 CYSetProperty(context, object_, name, value);
1309 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1310 Selector_privateData *internal(new Selector_privateData(sel));
1311 return JSObjectMake(context, Selector_, internal);
1314 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1315 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1316 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1317 return reinterpret_cast<SEL>(internal->value_);
1319 return CYCastPointer<SEL>(context, value);
1322 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1323 return (void *) [[NSAutoreleasePool alloc] init];
1324 } CYSadCatch(NULL) }
1326 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1327 return [(NSAutoreleasePool *) handle release];
1330 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1332 return Instance::Make(context, nil);
1333 if (Class _class = objc_getClass(name.data))
1334 return CYMakeInstance(context, _class, true);
1336 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1338 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1339 ffi_call(cif, function, value, values);
1342 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1343 switch (type->primitive) {
1345 case sig::typename_P:
1346 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1349 case sig::selector_P:
1350 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1358 } CYSadCatch(false) }
1360 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1361 switch (type->primitive) {
1363 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1364 JSValueRef value(CYCastJSValue(context, object));
1370 case sig::typename_P:
1371 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1373 case sig::selector_P:
1374 if (SEL sel = *reinterpret_cast<SEL *>(data))
1375 return CYMakeSelector(context, sel);
1379 return CYJSNull(context);
1383 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1385 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1386 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1389 #if OBJC_API_VERSION >= 2
1391 method_getReturnType(method, type, sizeof(type));
1393 const char *type(method_getTypeEncoding(method));
1399 // XXX: possibly use a more "awesome" check?
1403 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1405 return method_getTypeEncoding(method);
1407 const char *name(sel_getName(sel));
1408 size_t length(strlen(name));
1410 char keyed[length + 2];
1412 keyed[length + 1] = '\0';
1413 memcpy(keyed + 1, name, length);
1415 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1416 return entry->value_;
1421 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1422 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1424 JSContextRef context(internal->context_);
1426 size_t count(internal->cif_.nargs);
1427 JSValueRef values[count];
1429 for (size_t index(0); index != count; ++index)
1430 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1432 JSObjectRef _this(CYCastJSObject(context, values[0]));
1434 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1435 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1438 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1439 Message_privateData *internal(new Message_privateData(sel, type, imp));
1440 return JSObjectMake(context, Message_, internal);
1443 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1444 JSObjectRef function(CYCastJSObject(context, value));
1445 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1446 // XXX: see notes in Library.cpp about needing to leak
1447 return reinterpret_cast<IMP>(internal->GetValue());
1450 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1451 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1452 Class _class(internal->GetValue());
1455 const char *name(CYPoolCString(pool, context, property));
1457 if (SEL sel = sel_getUid(name))
1458 if (class_getInstanceMethod(_class, sel) != NULL)
1464 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1465 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1466 Class _class(internal->GetValue());
1469 const char *name(CYPoolCString(pool, context, property));
1471 if (SEL sel = sel_getUid(name))
1472 if (objc_method *method = class_getInstanceMethod(_class, sel))
1473 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1478 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1479 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1480 Class _class(internal->GetValue());
1483 const char *name(CYPoolCString(pool, context, property));
1485 SEL sel(sel_registerName(name));
1487 objc_method *method(class_getInstanceMethod(_class, sel));
1492 if (JSValueIsObjectOfClass(context, value, Message_)) {
1493 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1494 type = sig::Unparse(pool, &message->signature_);
1495 imp = reinterpret_cast<IMP>(message->GetValue());
1497 type = CYPoolTypeEncoding(pool, context, sel, method);
1498 imp = CYMakeMessage(context, value, type);
1502 method_setImplementation(method, imp);
1505 GSMethodList list(GSAllocMethodList(1));
1506 GSAppendMethodToList(list, sel, type, imp, YES);
1507 GSAddMethodList(_class, list, YES);
1508 GSFlushMethodCacheForClass(_class);
1510 class_addMethod(_class, sel, imp, type);
1517 #if 0 && OBJC_API_VERSION < 2
1518 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1519 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1520 Class _class(internal->GetValue());
1523 const char *name(CYPoolCString(pool, context, property));
1525 if (SEL sel = sel_getUid(name))
1526 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1527 objc_method_list list = {NULL, 1, {method}};
1528 class_removeMethods(_class, &list);
1536 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1537 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1538 Class _class(internal->GetValue());
1540 #if OBJC_API_VERSION >= 2
1542 objc_method **data(class_copyMethodList(_class, &size));
1543 for (size_t i(0); i != size; ++i)
1544 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1547 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1548 for (int i(0); i != methods->method_count; ++i)
1549 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1553 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1554 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1555 id self(internal->GetValue());
1557 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1561 NSString *name(CYCastNSString(pool, context, property));
1563 if (CYInternal *internal = CYInternal::Get(self))
1564 if (internal->HasProperty(context, property))
1567 Class _class(object_getClass(self));
1570 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1571 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1572 if ([self cy$hasProperty:name])
1574 } CYPoolCatch(false)
1576 const char *string(CYPoolCString(pool, context, name));
1579 if (class_getProperty(_class, string) != NULL)
1583 if (SEL sel = sel_getUid(string))
1584 if (CYImplements(self, _class, sel, true))
1590 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1591 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1592 id self(internal->GetValue());
1594 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1595 return Internal::Make(context, self, object);
1598 NSString *name(CYCastNSString(pool, context, property));
1600 if (CYInternal *internal = CYInternal::Get(self))
1601 if (JSValueRef value = internal->GetProperty(context, property))
1605 if (NSObject *data = [self cy$getProperty:name])
1606 return CYCastJSValue(context, data);
1609 const char *string(CYPoolCString(pool, context, name));
1610 Class _class(object_getClass(self));
1613 if (objc_property_t property = class_getProperty(_class, string)) {
1614 PropertyAttributes attributes(property);
1615 SEL sel(sel_registerName(attributes.Getter()));
1616 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1620 if (SEL sel = sel_getUid(string))
1621 if (CYImplements(self, _class, sel, true))
1622 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1627 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1628 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1629 id self(internal->GetValue());
1633 NSString *name(CYCastNSString(pool, context, property));
1634 NSObject *data(CYCastNSObject(pool, context, value));
1637 if ([self cy$setProperty:name to:data])
1641 const char *string(CYPoolCString(pool, context, name));
1642 Class _class(object_getClass(self));
1645 if (objc_property_t property = class_getProperty(_class, string)) {
1646 PropertyAttributes attributes(property);
1647 if (const char *setter = attributes.Setter()) {
1648 SEL sel(sel_registerName(setter));
1649 JSValueRef arguments[1] = {value};
1650 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1656 size_t length(strlen(string));
1658 char set[length + 5];
1664 if (string[0] != '\0') {
1665 set[3] = toupper(string[0]);
1666 memcpy(set + 4, string + 1, length - 1);
1669 set[length + 3] = ':';
1670 set[length + 4] = '\0';
1672 if (SEL sel = sel_getUid(set))
1673 if (CYImplements(self, _class, sel, false)) {
1674 JSValueRef arguments[1] = {value};
1675 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1678 if (CYInternal *internal = CYInternal::Set(self)) {
1679 internal->SetProperty(context, property, value);
1686 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1687 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1688 id self(internal->GetValue());
1691 NSString *name(CYCastNSString(NULL, context, property));
1692 return [self cy$deleteProperty:name];
1694 } CYCatch return /*XXX*/ NULL; }
1696 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1697 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1698 id self(internal->GetValue());
1701 Class _class(object_getClass(self));
1706 objc_property_t *data(class_copyPropertyList(_class, &size));
1707 for (size_t i(0); i != size; ++i)
1708 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1714 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1715 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1716 [self cy$getPropertyNames:names inContext:context];
1720 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1721 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1722 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1726 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1727 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1728 Class _class(internal->GetValue());
1729 if (!CYIsClass(_class))
1732 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1733 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1734 // XXX: this isn't always safe
1735 return [linternal->GetValue() isKindOfClass:_class];
1741 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1742 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1745 id self(internal->GetValue());
1746 const char *name(CYPoolCString(pool, context, property));
1748 if (object_getInstanceVariable(self, name, NULL) != NULL)
1754 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1755 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1758 id self(internal->GetValue());
1759 const char *name(CYPoolCString(pool, context, property));
1761 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1762 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1763 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1764 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1770 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1771 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1774 id self(internal->GetValue());
1775 const char *name(CYPoolCString(pool, context, property));
1777 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1778 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1779 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1786 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1787 if (Class super = class_getSuperclass(_class))
1788 Internal_getPropertyNames_(super, names);
1790 #if OBJC_API_VERSION >= 2
1792 objc_ivar **data(class_copyIvarList(_class, &size));
1793 for (size_t i(0); i != size; ++i)
1794 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1797 if (objc_ivar_list *ivars = _class->ivars)
1798 for (int i(0); i != ivars->ivar_count; ++i)
1799 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1803 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1804 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1807 id self(internal->GetValue());
1808 Class _class(object_getClass(self));
1810 Internal_getPropertyNames_(_class, names);
1813 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1814 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1815 return internal->GetOwner();
1818 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1820 NSString *name(CYCastNSString(pool, context, property));
1821 if (Class _class = NSClassFromString(name))
1822 return CYMakeInstance(context, _class, true);
1826 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1828 size_t size(objc_getClassList(NULL, 0));
1829 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1832 size_t writ(objc_getClassList(data, size));
1835 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1841 for (size_t i(0); i != writ; ++i)
1842 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1848 while (Class _class = objc_next_class(&state))
1849 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1853 #if OBJC_API_VERSION >= 2
1854 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1855 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1858 const char *name(CYPoolCString(pool, context, property));
1860 const char **data(objc_copyClassNamesForImage(internal, &size));
1862 for (size_t i(0); i != size; ++i)
1863 if (strcmp(name, data[i]) == 0) {
1864 if (Class _class = objc_getClass(name)) {
1865 value = CYMakeInstance(context, _class, true);
1876 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1877 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1879 const char **data(objc_copyClassNamesForImage(internal, &size));
1880 for (size_t i(0); i != size; ++i)
1881 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1885 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1887 const char *name(CYPoolCString(pool, context, property));
1889 const char **data(objc_copyImageNames(&size));
1890 for (size_t i(0); i != size; ++i)
1891 if (strcmp(name, data[i]) == 0) {
1900 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1901 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1905 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1907 const char **data(objc_copyImageNames(&size));
1908 for (size_t i(0); i != size; ++i)
1909 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1914 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1916 const char *name(CYPoolCString(pool, context, property));
1917 if (Protocol *protocol = objc_getProtocol(name))
1918 return CYMakeInstance(context, protocol, true);
1922 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1923 #if OBJC_API_VERSION >= 2
1925 Protocol **data(objc_copyProtocolList(&size));
1926 for (size_t i(0); i != size; ++i)
1927 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1935 static bool stret(ffi_type *ffi_type) {
1936 return ffi_type->type == FFI_TYPE_STRUCT && (
1937 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1938 struct_forward_array[ffi_type->size] != 0
1943 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 {
1947 _class = object_getClass(self);
1951 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
1952 imp = method_getImplementation(method);
1953 type = method_getTypeEncoding(method);
1958 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1960 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
1961 type = CYPoolCString(pool, context, [method _typeString]);
1969 sig::Signature signature;
1970 sig::Parse(pool, &signature, type, &Structor_);
1973 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1977 if (stret(cif.rtype))
1978 imp = class_getMethodImplementation_stret(_class, _cmd);
1980 imp = class_getMethodImplementation(_class, _cmd);
1982 objc_super super = {self, _class};
1983 imp = objc_msg_lookup_super(&super, _cmd);
1987 void (*function)() = reinterpret_cast<void (*)()>(imp);
1988 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1991 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1993 throw CYJSError(context, "too few arguments to objc_msgSend");
2003 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2004 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2005 self = internal->GetValue();
2006 _class = internal->class_;;
2007 uninitialized = false;
2008 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2009 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2010 self = internal->GetValue();
2012 uninitialized = internal->IsUninitialized();
2014 internal->value_ = nil;
2016 self = CYCastNSObject(pool, context, arguments[0]);
2018 uninitialized = false;
2022 return CYJSNull(context);
2024 _cmd = CYCastSEL(context, arguments[1]);
2026 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2029 /* Hook: objc_registerClassPair {{{ */
2030 #if defined(__APPLE__) && defined(__arm__)
2031 // XXX: replace this with associated objects
2033 MSHook(void, CYDealloc, id self, SEL sel) {
2034 CYInternal *internal;
2035 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2036 if (internal != NULL)
2038 _CYDealloc(self, sel);
2041 MSHook(void, objc_registerClassPair, Class _class) {
2042 Class super(class_getSuperclass(_class));
2043 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2044 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2045 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2048 _objc_registerClassPair(_class);
2051 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2053 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2055 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2056 if (value == NULL || !CYIsClass(value))
2057 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2058 Class _class((Class) value);
2059 $objc_registerClassPair(_class);
2060 return CYJSUndefined(context);
2065 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2066 JSValueRef setup[count + 2];
2069 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2070 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2073 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2075 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2077 // XXX: handle Instance::Uninitialized?
2078 id self(CYCastNSObject(pool, context, _this));
2082 setup[1] = &internal->sel_;
2084 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2087 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2089 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2091 id self(CYCastNSObject(pool, context, arguments[0]));
2092 Class _class(CYCastClass(pool, context, arguments[1]));
2093 return cy::Super::Make(context, self, _class);
2096 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2098 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2100 const char *name(CYPoolCString(pool, context, arguments[0]));
2101 return CYMakeSelector(context, sel_registerName(name));
2104 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2106 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2107 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2108 return Instance::Make(context, self);
2111 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2112 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2113 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2116 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2117 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2118 Type_privateData *typical(internal->GetType());
2123 if (typical == NULL) {
2127 type = typical->type_;
2128 ffi = typical->ffi_;
2131 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2134 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2135 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2136 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2139 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2140 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2141 id self(internal->GetValue());
2142 if (!CYIsClass(self))
2143 return CYJSUndefined(context);
2144 return CYGetClassPrototype(context, self);
2147 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2148 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2149 id self(internal->GetValue());
2150 if (!CYIsClass(self))
2151 return CYJSUndefined(context);
2152 return Messages::Make(context, (Class) self);
2155 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2156 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2159 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2160 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2163 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2164 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2167 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2174 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2175 // XXX: check for support of cy$toJSON?
2176 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2178 } CYCatch return /*XXX*/ NULL; }
2180 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2181 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2184 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2187 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2188 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2190 } CYCatch return /*XXX*/ NULL; }
2192 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2193 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2194 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2197 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2198 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2201 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2202 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2203 const char *name(sel_getName(internal->GetValue()));
2206 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2207 return CYCastJSValue(context, CYJSString(context, string));
2209 } CYCatch return /*XXX*/ NULL; }
2211 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2213 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2216 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2217 SEL sel(internal->GetValue());
2219 objc_method *method;
2220 if (Class _class = CYCastClass(pool, context, arguments[0]))
2221 method = class_getInstanceMethod(_class, sel);
2225 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2226 return CYCastJSValue(context, CYJSString(type));
2228 return CYJSNull(context);
2231 static JSStaticValue Selector_staticValues[2] = {
2232 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2233 {NULL, NULL, NULL, 0}
2236 static JSStaticValue Instance_staticValues[5] = {
2237 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2238 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2239 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2240 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2241 {NULL, NULL, NULL, 0}
2244 static JSStaticFunction Instance_staticFunctions[5] = {
2245 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2246 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2247 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2248 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2252 static JSStaticFunction Internal_staticFunctions[2] = {
2253 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2257 static JSStaticFunction Selector_staticFunctions[5] = {
2258 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2259 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2260 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2261 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2265 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2266 apr_pool_t *pool(CYGetGlobalPool());
2268 Object_type = new(pool) Type_privateData("@");
2269 Selector_type = new(pool) Type_privateData(":");
2272 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2273 NSCFType_ = objc_getClass("NSCFType");
2274 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2275 NSZombie_ = objc_getClass("_NSZombie_");
2277 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2280 NSArray_ = objc_getClass("NSArray");
2281 NSDictionary_ = objc_getClass("NSDictionary");
2282 Object_ = objc_getClass("Object");
2284 JSClassDefinition definition;
2286 definition = kJSClassDefinitionEmpty;
2287 definition.className = "Instance";
2288 definition.staticValues = Instance_staticValues;
2289 definition.staticFunctions = Instance_staticFunctions;
2290 definition.hasProperty = &Instance_hasProperty;
2291 definition.getProperty = &Instance_getProperty;
2292 definition.setProperty = &Instance_setProperty;
2293 definition.deleteProperty = &Instance_deleteProperty;
2294 definition.getPropertyNames = &Instance_getPropertyNames;
2295 definition.callAsConstructor = &Instance_callAsConstructor;
2296 definition.hasInstance = &Instance_hasInstance;
2297 definition.finalize = &CYFinalize;
2298 Instance_ = JSClassCreate(&definition);
2300 definition = kJSClassDefinitionEmpty;
2301 definition.className = "Internal";
2302 definition.staticFunctions = Internal_staticFunctions;
2303 definition.hasProperty = &Internal_hasProperty;
2304 definition.getProperty = &Internal_getProperty;
2305 definition.setProperty = &Internal_setProperty;
2306 definition.getPropertyNames = &Internal_getPropertyNames;
2307 definition.finalize = &CYFinalize;
2308 Internal_ = JSClassCreate(&definition);
2310 definition = kJSClassDefinitionEmpty;
2311 definition.className = "Message";
2312 definition.staticFunctions = cy::Functor::StaticFunctions;
2313 definition.callAsFunction = &Message_callAsFunction;
2314 definition.finalize = &CYFinalize;
2315 Message_ = JSClassCreate(&definition);
2317 definition = kJSClassDefinitionEmpty;
2318 definition.className = "Messages";
2319 definition.hasProperty = &Messages_hasProperty;
2320 definition.getProperty = &Messages_getProperty;
2321 definition.setProperty = &Messages_setProperty;
2322 #if 0 && OBJC_API_VERSION < 2
2323 definition.deleteProperty = &Messages_deleteProperty;
2325 definition.getPropertyNames = &Messages_getPropertyNames;
2326 definition.finalize = &CYFinalize;
2327 Messages_ = JSClassCreate(&definition);
2329 definition = kJSClassDefinitionEmpty;
2330 definition.className = "Selector";
2331 definition.staticValues = Selector_staticValues;
2332 definition.staticFunctions = Selector_staticFunctions;
2333 definition.callAsFunction = &Selector_callAsFunction;
2334 definition.finalize = &CYFinalize;
2335 Selector_ = JSClassCreate(&definition);
2337 definition = kJSClassDefinitionEmpty;
2338 definition.className = "Super";
2339 definition.staticFunctions = Internal_staticFunctions;
2340 definition.finalize = &CYFinalize;
2341 Super_ = JSClassCreate(&definition);
2343 definition = kJSClassDefinitionEmpty;
2344 definition.className = "ObjectiveC::Classes";
2345 definition.getProperty = &ObjectiveC_Classes_getProperty;
2346 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2347 ObjectiveC_Classes_ = JSClassCreate(&definition);
2349 #if OBJC_API_VERSION >= 2
2350 definition = kJSClassDefinitionEmpty;
2351 definition.className = "ObjectiveC::Images";
2352 definition.getProperty = &ObjectiveC_Images_getProperty;
2353 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2354 ObjectiveC_Images_ = JSClassCreate(&definition);
2356 definition = kJSClassDefinitionEmpty;
2357 definition.className = "ObjectiveC::Image::Classes";
2358 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2359 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2360 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2363 definition = kJSClassDefinitionEmpty;
2364 definition.className = "ObjectiveC::Protocols";
2365 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2366 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2367 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2369 #if defined(__APPLE__) && defined(__arm__)
2370 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2374 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2378 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2379 JSObjectRef global(CYGetGlobalObject(context));
2380 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2381 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2382 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2384 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2385 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2387 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2388 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2390 #if OBJC_API_VERSION >= 2
2391 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2394 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2395 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2396 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2397 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2399 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2400 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2402 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2403 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2404 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2406 #if defined(__APPLE__) && defined(__arm__)
2407 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2410 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2412 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2413 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2414 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2417 static CYHooks CYObjectiveCHooks = {
2418 &CYObjectiveC_ExecuteStart,
2419 &CYObjectiveC_ExecuteEnd,
2420 &CYObjectiveC_RuntimeProperty,
2421 &CYObjectiveC_CallFunction,
2422 &CYObjectiveC_Initialize,
2423 &CYObjectiveC_SetupContext,
2424 &CYObjectiveC_PoolFFI,
2425 &CYObjectiveC_FromFFI,
2428 struct CYObjectiveC {
2430 hooks_ = &CYObjectiveCHooks;