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"
73 #define CYObjectiveTry_(context) { \
74 JSContextRef context_(context); \
76 #define CYObjectiveTry { \
78 #define CYObjectiveCatch \
79 catch (const CYException &error) { \
80 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
86 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
88 #define CYPoolCatch(value) \
89 @catch (NSException *error) { \
90 _saved = [error retain]; \
91 throw CYJSError(context, CYCastJSValue(context, error)); \
96 [_saved autorelease]; \
102 #define CYSadCatch(value) \
103 @catch (NSException *error ) { \
104 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 extern sqlite3 *Bridge_;
151 /* Objective-C Pool Release {{{ */
152 apr_status_t CYPoolRelease_(void *data) {
153 id object(reinterpret_cast<id>(data));
158 id CYPoolRelease_(apr_pool_t *pool, id object) {
161 else if (pool == NULL)
162 return [object autorelease];
164 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
169 template <typename Type_>
170 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
171 return (Type_) CYPoolRelease_(pool, (id) object);
174 /* Objective-C Strings {{{ */
175 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
177 return [value UTF8String];
179 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
180 char *string(new(pool) char[size]);
181 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
182 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
187 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
189 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
192 return CYCopyJSString(CYPoolCString(pool, context, value));
196 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
199 // XXX: this definition scares me; is anyone using this?!
200 NSString *string([value description]);
201 return CYCopyJSString(context, string);
204 NSString *CYCopyNSString(const CYUTF8String &value) {
206 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
208 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
212 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
214 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
217 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
221 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
222 return CYCopyNSString(context, CYJSString(context, value));
225 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
226 return CYPoolRelease(pool, CYCopyNSString(value));
229 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
230 const char *name(sel_getName(sel));
231 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
234 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
235 return CYPoolRelease(pool, CYCopyNSString(context, value));
238 CYUTF8String CYCastUTF8String(NSString *value) {
239 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
240 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
244 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
246 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
247 if (exception == NULL)
249 *exception = CYCastJSValue(context, error);
252 size_t CYGetIndex(NSString *value) {
253 return CYGetIndex(CYCastUTF8String(value));
256 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
257 return CYGetOffset(CYPoolCString(pool, context, value), index);
260 static JSClassRef Instance_;
261 static JSClassRef Internal_;
262 static JSClassRef Message_;
263 static JSClassRef Messages_;
264 static JSClassRef Selector_;
265 static JSClassRef Super_;
267 static JSClassRef ObjectiveC_Classes_;
268 static JSClassRef ObjectiveC_Protocols_;
271 static JSClassRef ObjectiveC_Image_Classes_;
272 static JSClassRef ObjectiveC_Images_;
276 static Class NSCFBoolean_;
277 static Class NSCFType_;
278 static Class NSMessageBuilder_;
279 static Class NSZombie_;
281 static Class NSBoolNumber_;
284 static Class NSArray_;
285 static Class NSDictionary_;
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 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
301 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
303 JSObjectRef global(CYGetGlobalObject(context));
304 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
307 sprintf(label, "i%p", self);
308 CYJSString name(label);
310 JSValueRef value(CYGetProperty(context, cy, name));
311 if (!JSValueIsUndefined(context, value))
314 JSClassRef _class(NULL);
315 JSValueRef prototype;
317 if (self == NSArray_)
318 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
319 else if (self == NSDictionary_)
320 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
322 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
324 JSObjectRef object(JSObjectMake(context, _class, NULL));
325 JSObjectSetPrototype(context, object, prototype);
326 CYSetProperty(context, cy, name, object);
330 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
331 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
332 if (_class == NSArray_)
334 if (Class super = class_getSuperclass(_class))
335 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
337 JSObjectSetPrototype(context, value, Array_prototype_);*/
341 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
342 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
346 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
347 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
351 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
352 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
353 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
357 Instance::~Instance() {
358 if ((flags_ & Transient) == 0)
359 // XXX: does this handle background threads correctly?
360 // XXX: this simply does not work on the console because I'm stupid
361 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
364 struct Message_privateData :
369 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
370 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
376 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
377 Instance::Flags flags;
380 flags = Instance::Transient;
382 flags = Instance::None;
383 object = [object retain];
386 return Instance::Make(context, object, flags);
389 @interface NSMethodSignature (Cycript)
390 - (NSString *) _typeString;
393 @interface NSObject (Cycript)
395 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
396 - (JSType) cy$JSType;
398 - (NSObject *) cy$toJSON:(NSString *)key;
399 - (NSString *) cy$toCYON;
400 - (NSString *) cy$toKey;
402 - (bool) cy$hasProperty:(NSString *)name;
403 - (NSObject *) cy$getProperty:(NSString *)name;
404 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
405 - (bool) cy$deleteProperty:(NSString *)name;
406 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
411 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
414 NSString *CYCastNSCYON(id value) {
420 Class _class(object_getClass(value));
421 SEL sel(@selector(cy$toCYON));
423 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
424 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
425 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
426 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
427 string = [value cy$toCYON];
432 else if (value == NSZombie_)
433 string = @"_NSZombie_";
434 else if (_class == NSZombie_)
435 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
436 // XXX: frowny /in/ the pants
437 else if (value == NSMessageBuilder_ || value == Object_)
441 string = [NSString stringWithFormat:@"%@", value];
446 string = @"undefined";
453 struct PropertyAttributes {
458 const char *variable;
471 PropertyAttributes(objc_property_t property) :
483 name = property_getName(property);
484 const char *attributes(property_getAttributes(property));
486 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
488 case 'R': readonly = true; break;
489 case 'C': copy = true; break;
490 case '&': retain = true; break;
491 case 'N': nonatomic = true; break;
492 case 'G': getter_ = token + 1; break;
493 case 'S': setter_ = token + 1; break;
494 case 'V': variable = token + 1; break;
498 /*if (variable == NULL) {
499 variable = property_getName(property);
500 size_t size(strlen(variable));
501 char *name(new(pool_) char[size + 2]);
503 memcpy(name + 1, variable, size);
504 name[size + 1] = '\0';
509 const char *Getter() {
511 getter_ = apr_pstrdup(pool_, name);
515 const char *Setter() {
516 if (setter_ == NULL && !readonly) {
517 size_t length(strlen(name));
519 char *temp(new(pool_) char[length + 5]);
525 temp[3] = toupper(name[0]);
526 memcpy(temp + 4, name + 1, length - 1);
529 temp[length + 3] = ':';
530 temp[length + 4] = '\0';
541 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
542 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
547 @interface CYWebUndefined : NSObject {
550 + (CYWebUndefined *) undefined;
554 @implementation CYWebUndefined
556 + (CYWebUndefined *) undefined {
557 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
563 #define WebUndefined CYWebUndefined
566 /* Bridge: CYJSObject {{{ */
567 @interface CYJSObject : NSMutableDictionary {
569 JSContextRef context_;
572 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
574 - (NSObject *) cy$toJSON:(NSString *)key;
576 - (NSUInteger) count;
577 - (id) objectForKey:(id)key;
578 - (NSEnumerator *) keyEnumerator;
579 - (void) setObject:(id)object forKey:(id)key;
580 - (void) removeObjectForKey:(id)key;
584 /* Bridge: CYJSArray {{{ */
585 @interface CYJSArray : NSMutableArray {
587 JSContextRef context_;
590 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
592 - (NSUInteger) count;
593 - (id) objectAtIndex:(NSUInteger)index;
595 - (void) addObject:(id)anObject;
596 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
597 - (void) removeLastObject;
598 - (void) removeObjectAtIndex:(NSUInteger)index;
599 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
604 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
605 JSObjectRef Array(CYGetCachedObject(context, Array_s));
606 JSValueRef exception(NULL);
607 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
608 CYThrow(context, exception);
609 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
610 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
613 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
614 if (!JSValueIsObjectOfClass(context, object, Instance_))
615 return CYCastNSObject_(pool, context, object);
617 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
618 return internal->GetValue();
622 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
623 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
627 @interface NSBoolNumber : NSNumber {
632 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
636 switch (JSType type = JSValueGetType(context, value)) {
637 case kJSTypeUndefined:
638 object = [WebUndefined undefined];
648 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
651 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
657 object = CYCopyNSNumber(context, value);
662 object = CYCopyNSString(context, value);
667 // XXX: this might could be more efficient
668 object = CYCastNSObject(pool, context, (JSObjectRef) value);
673 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
680 return CYPoolRelease(pool, object);
682 return [object retain];
685 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
686 return CYNSObject(pool, context, value, true);
689 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
690 return CYNSObject(pool, context, value, false);
693 /* Bridge: NSArray {{{ */
694 @implementation NSArray (Cycript)
696 - (NSString *) cy$toCYON {
697 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
698 [json appendString:@"["];
702 for (id object in self) {
704 for (size_t index(0), count([self count]); index != count; ++index) {
705 id object([self objectAtIndex:index]);
708 [json appendString:@","];
711 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
712 [json appendString:CYCastNSCYON(object)];
714 [json appendString:@","];
719 [json appendString:@"]"];
723 - (bool) cy$hasProperty:(NSString *)name {
724 if ([name isEqualToString:@"length"])
727 size_t index(CYGetIndex(name));
728 if (index == _not(size_t) || index >= [self count])
729 return [super cy$hasProperty:name];
734 - (NSObject *) cy$getProperty:(NSString *)name {
735 if ([name isEqualToString:@"length"]) {
736 NSUInteger count([self count]);
738 return [NSNumber numberWithUnsignedInteger:count];
740 return [NSNumber numberWithUnsignedInt:count];
744 size_t index(CYGetIndex(name));
745 if (index == _not(size_t) || index >= [self count])
746 return [super cy$getProperty:name];
748 return [self objectAtIndex:index];
751 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
752 [super cy$getPropertyNames:names inContext:context];
754 for (size_t index(0), count([self count]); index != count; ++index) {
755 id object([self objectAtIndex:index]);
756 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
758 sprintf(name, "%zu", index);
759 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
766 /* Bridge: NSBoolNumber {{{ */
768 @implementation NSBoolNumber (Cycript)
770 - (JSType) cy$JSType {
771 return kJSTypeBoolean;
774 - (NSObject *) cy$toJSON:(NSString *)key {
778 - (NSString *) cy$toCYON {
779 return [self boolValue] ? @"true" : @"false";
782 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
783 return CYCastJSValue(context, (bool) [self boolValue]);
789 /* Bridge: NSDictionary {{{ */
790 @implementation NSDictionary (Cycript)
792 - (NSString *) cy$toCYON {
793 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
794 [json appendString:@"{"];
798 for (NSObject *key in self) {
800 NSEnumerator *keys([self keyEnumerator]);
801 while (NSObject *key = [keys nextObject]) {
804 [json appendString:@","];
807 [json appendString:[key cy$toKey]];
808 [json appendString:@":"];
809 NSObject *object([self objectForKey:key]);
810 [json appendString:CYCastNSCYON(object)];
813 [json appendString:@"}"];
817 - (bool) cy$hasProperty:(NSString *)name {
818 return [self objectForKey:name] != nil;
821 - (NSObject *) cy$getProperty:(NSString *)name {
822 return [self objectForKey:name];
825 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
826 [super cy$getPropertyNames:names inContext:context];
829 for (NSObject *key in self) {
831 NSEnumerator *keys([self keyEnumerator]);
832 while (NSObject *key = [keys nextObject]) {
834 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
840 /* Bridge: NSMutableArray {{{ */
841 @implementation NSMutableArray (Cycript)
843 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
844 if ([name isEqualToString:@"length"]) {
845 // XXX: is this not intelligent?
846 NSNumber *number(reinterpret_cast<NSNumber *>(value));
848 NSUInteger size([number unsignedIntegerValue]);
850 NSUInteger size([number unsignedIntValue]);
852 NSUInteger count([self count]);
854 [self removeObjectsInRange:NSMakeRange(size, count - size)];
855 else if (size != count) {
856 WebUndefined *undefined([WebUndefined undefined]);
857 for (size_t i(count); i != size; ++i)
858 [self addObject:undefined];
863 size_t index(CYGetIndex(name));
864 if (index == _not(size_t))
865 return [super cy$setProperty:name to:value];
867 id object(value ?: [NSNull null]);
869 size_t count([self count]);
871 [self replaceObjectAtIndex:index withObject:object];
873 if (index != count) {
874 WebUndefined *undefined([WebUndefined undefined]);
875 for (size_t i(count); i != index; ++i)
876 [self addObject:undefined];
879 [self addObject:object];
885 - (bool) cy$deleteProperty:(NSString *)name {
886 size_t index(CYGetIndex(name));
887 if (index == _not(size_t) || index >= [self count])
888 return [super cy$deleteProperty:name];
889 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
895 /* Bridge: NSMutableDictionary {{{ */
896 @implementation NSMutableDictionary (Cycript)
898 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
899 [self setObject:(value ?: [NSNull null]) forKey:name];
903 - (bool) cy$deleteProperty:(NSString *)name {
904 if ([self objectForKey:name] == nil)
907 [self removeObjectForKey:name];
914 /* Bridge: NSNumber {{{ */
915 @implementation NSNumber (Cycript)
917 - (JSType) cy$JSType {
919 // XXX: this just seems stupid
920 if ([self class] == NSCFBoolean_)
921 return kJSTypeBoolean;
923 return kJSTypeNumber;
926 - (NSObject *) cy$toJSON:(NSString *)key {
930 - (NSString *) cy$toCYON {
931 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
934 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
935 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
940 /* Bridge: NSNull {{{ */
941 @implementation NSNull (Cycript)
943 - (JSType) cy$JSType {
947 - (NSObject *) cy$toJSON:(NSString *)key {
951 - (NSString *) cy$toCYON {
957 /* Bridge: NSObject {{{ */
958 @implementation NSObject (Cycript)
960 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
961 return CYMakeInstance(context, self, false);
964 - (JSType) cy$JSType {
965 return kJSTypeObject;
968 - (NSObject *) cy$toJSON:(NSString *)key {
969 return [self description];
972 - (NSString *) cy$toCYON {
973 return [[self cy$toJSON:@""] cy$toCYON];
976 - (NSString *) cy$toKey {
977 return [self cy$toCYON];
980 - (bool) cy$hasProperty:(NSString *)name {
984 - (NSObject *) cy$getProperty:(NSString *)name {
988 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
992 - (bool) cy$deleteProperty:(NSString *)name {
996 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1001 /* Bridge: NSProxy {{{ */
1002 @implementation NSProxy (Cycript)
1004 - (NSObject *) cy$toJSON:(NSString *)key {
1005 return [self description];
1008 - (NSString *) cy$toCYON {
1009 return [[self cy$toJSON:@""] cy$toCYON];
1014 /* Bridge: NSString {{{ */
1015 @implementation NSString (Cycript)
1017 - (JSType) cy$JSType {
1018 return kJSTypeString;
1021 - (NSObject *) cy$toJSON:(NSString *)key {
1025 - (NSString *) cy$toCYON {
1026 std::ostringstream str;
1027 CYUTF8String string(CYCastUTF8String(self));
1028 CYStringify(str, string.data, string.size);
1029 std::string value(str.str());
1030 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1033 - (NSString *) cy$toKey {
1034 if (CYIsKey(CYCastUTF8String(self)))
1036 return [self cy$toCYON];
1041 /* Bridge: WebUndefined {{{ */
1042 @implementation WebUndefined (Cycript)
1044 - (JSType) cy$JSType {
1045 return kJSTypeUndefined;
1048 - (NSObject *) cy$toJSON:(NSString *)key {
1052 - (NSString *) cy$toCYON {
1053 return @"undefined";
1056 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1057 return CYJSUndefined(context);
1058 } CYObjectiveCatch }
1063 static bool CYIsClass(id self) {
1065 // XXX: this is a lame object_isClass
1066 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1068 return GSObjCIsClass(self);
1072 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1073 id self(CYCastNSObject(pool, context, value));
1074 if (CYIsClass(self))
1075 return (Class) self;
1076 throw CYJSError(context, "got something that is not a Class");
1080 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1082 size_t size(JSPropertyNameArrayGetCount(names));
1083 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1084 for (size_t index(0); index != size; ++index)
1085 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1089 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1091 return CYJSNull(context);
1092 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1093 return [value cy$JSValueInContext:context];
1095 return CYMakeInstance(context, value, false);
1096 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1098 @implementation CYJSObject
1100 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1101 if ((self = [super init]) != nil) {
1103 context_ = CYGetJSContext(context);
1104 //XXX:JSGlobalContextRetain(context_);
1105 JSValueProtect(context_, object_);
1107 } CYObjectiveCatch }
1109 - (void) dealloc { CYObjectiveTry {
1110 JSValueUnprotect(context_, object_);
1111 //XXX:JSGlobalContextRelease(context_);
1113 } CYObjectiveCatch }
1115 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1116 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1117 if (!CYIsCallable(context_, toJSON))
1118 return [super cy$toJSON:key];
1120 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1121 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1122 // XXX: do I really want an NSNull here?!
1123 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1125 } CYObjectiveCatch }
1127 - (NSString *) cy$toCYON { CYObjectiveTry {
1129 JSValueRef exception(NULL);
1130 const char *cyon(CYPoolCCYON(pool, context_, object_));
1131 CYThrow(context_, exception);
1133 return [super cy$toCYON];
1135 return [NSString stringWithUTF8String:cyon];
1136 } CYObjectiveCatch }
1138 - (NSUInteger) count { CYObjectiveTry {
1139 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1140 size_t size(JSPropertyNameArrayGetCount(names));
1141 JSPropertyNameArrayRelease(names);
1143 } CYObjectiveCatch }
1145 - (id) objectForKey:(id)key { CYObjectiveTry {
1146 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1147 if (JSValueIsUndefined(context_, value))
1149 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1150 } CYObjectiveCatch }
1152 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1153 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1154 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1155 JSPropertyNameArrayRelease(names);
1157 } CYObjectiveCatch }
1159 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1160 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1161 } CYObjectiveCatch }
1163 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1164 JSValueRef exception(NULL);
1165 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1166 CYThrow(context_, exception);
1167 } CYObjectiveCatch }
1171 @implementation CYJSArray
1173 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1174 if ((self = [super init]) != nil) {
1176 context_ = CYGetJSContext(context);
1177 //XXX:JSGlobalContextRetain(context_);
1178 JSValueProtect(context_, object_);
1180 } CYObjectiveCatch }
1182 - (void) dealloc { CYObjectiveTry {
1183 JSValueUnprotect(context_, object_);
1184 //XXX:JSGlobalContextRelease(context_);
1186 } CYObjectiveCatch }
1188 - (NSUInteger) count { CYObjectiveTry {
1189 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1190 } CYObjectiveCatch }
1192 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1193 size_t bounds([self count]);
1194 if (index >= bounds)
1195 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1196 JSValueRef exception(NULL);
1197 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1198 CYThrow(context_, exception);
1199 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1200 } CYObjectiveCatch }
1202 - (void) addObject:(id)object { CYObjectiveTry {
1203 JSValueRef exception(NULL);
1204 JSValueRef arguments[1];
1205 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1206 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1207 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1208 CYThrow(context_, exception);
1209 } CYObjectiveCatch }
1211 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1212 size_t bounds([self count] + 1);
1213 if (index >= bounds)
1214 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1215 JSValueRef exception(NULL);
1216 JSValueRef arguments[3];
1217 arguments[0] = CYCastJSValue(context_, index);
1218 arguments[1] = CYCastJSValue(context_, 0);
1219 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1220 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1221 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1222 CYThrow(context_, exception);
1223 } CYObjectiveCatch }
1225 - (void) removeLastObject { CYObjectiveTry {
1226 JSValueRef exception(NULL);
1227 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1228 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1229 CYThrow(context_, exception);
1230 } CYObjectiveCatch }
1232 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1233 size_t bounds([self count]);
1234 if (index >= bounds)
1235 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1236 JSValueRef exception(NULL);
1237 JSValueRef arguments[2];
1238 arguments[0] = CYCastJSValue(context_, index);
1239 arguments[1] = CYCastJSValue(context_, 1);
1240 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1241 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1242 CYThrow(context_, exception);
1243 } CYObjectiveCatch }
1245 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1246 size_t bounds([self count]);
1247 if (index >= bounds)
1248 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1249 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1250 } CYObjectiveCatch }
1254 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1258 JSObjectRef object_;
1266 // XXX: delete object_? ;(
1269 static CYInternal *Get(id self) {
1270 CYInternal *internal(NULL);
1271 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1272 // XXX: do something epic? ;P
1278 static CYInternal *Set(id self) {
1279 CYInternal *internal(NULL);
1280 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1281 if (internal == NULL) {
1282 internal = new CYInternal();
1283 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1286 // XXX: do something epic? ;P
1292 bool HasProperty(JSContextRef context, JSStringRef name) {
1293 if (object_ == NULL)
1295 return JSObjectHasProperty(context, object_, name);
1298 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1299 if (object_ == NULL)
1301 return CYGetProperty(context, object_, name);
1304 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1305 if (object_ == NULL)
1306 object_ = JSObjectMake(context, NULL, NULL);
1307 CYSetProperty(context, object_, name, value);
1311 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1312 Selector_privateData *internal(new Selector_privateData(sel));
1313 return JSObjectMake(context, Selector_, internal);
1316 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1317 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1318 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1319 return reinterpret_cast<SEL>(internal->value_);
1321 return CYCastPointer<SEL>(context, value);
1324 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1325 return (void *) [[NSAutoreleasePool alloc] init];
1326 } CYSadCatch(NULL) }
1328 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1329 return [(NSAutoreleasePool *) handle release];
1332 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1334 return Instance::Make(context, nil);
1335 if (Class _class = objc_getClass(name.data))
1336 return CYMakeInstance(context, _class, true);
1338 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1340 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1341 ffi_call(cif, function, value, values);
1344 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1345 switch (type->primitive) {
1347 case sig::typename_P:
1348 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1351 case sig::selector_P:
1352 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1360 } CYSadCatch(false) }
1362 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1363 switch (type->primitive) {
1365 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1366 JSValueRef value(CYCastJSValue(context, object));
1372 case sig::typename_P:
1373 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1375 case sig::selector_P:
1376 if (SEL sel = *reinterpret_cast<SEL *>(data))
1377 return CYMakeSelector(context, sel);
1381 return CYJSNull(context);
1385 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1387 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1388 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1391 #if OBJC_API_VERSION >= 2
1393 method_getReturnType(method, type, sizeof(type));
1395 const char *type(method_getTypeEncoding(method));
1401 // XXX: possibly use a more "awesome" check?
1405 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1407 return method_getTypeEncoding(method);
1409 const char *name(sel_getName(sel));
1411 sqlite3_stmt *statement;
1413 _sqlcall(sqlite3_prepare(Bridge_,
1415 "\"bridge\".\"value\" "
1418 " \"bridge\".\"mode\" = -1 and"
1419 " \"bridge\".\"name\" = ?"
1421 , -1, &statement, NULL));
1424 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
1427 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1432 value = sqlite3_column_pooled(pool, statement, 0);
1435 _sqlcall(sqlite3_finalize(statement));
1443 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1444 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1446 JSContextRef context(internal->context_);
1448 size_t count(internal->cif_.nargs);
1449 JSValueRef values[count];
1451 for (size_t index(0); index != count; ++index)
1452 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1454 JSObjectRef _this(CYCastJSObject(context, values[0]));
1456 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1457 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1460 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1461 Message_privateData *internal(new Message_privateData(sel, type, imp));
1462 return JSObjectMake(context, Message_, internal);
1465 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1466 JSObjectRef function(CYCastJSObject(context, value));
1467 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1468 // XXX: see notes in Library.cpp about needing to leak
1469 return reinterpret_cast<IMP>(internal->GetValue());
1472 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1473 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1474 Class _class(internal->GetValue());
1477 const char *name(CYPoolCString(pool, context, property));
1479 if (SEL sel = sel_getUid(name))
1480 if (class_getInstanceMethod(_class, sel) != NULL)
1486 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1487 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1488 Class _class(internal->GetValue());
1491 const char *name(CYPoolCString(pool, context, property));
1493 if (SEL sel = sel_getUid(name))
1494 if (objc_method *method = class_getInstanceMethod(_class, sel))
1495 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1500 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1501 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1502 Class _class(internal->GetValue());
1505 const char *name(CYPoolCString(pool, context, property));
1507 SEL sel(sel_registerName(name));
1509 objc_method *method(class_getInstanceMethod(_class, sel));
1514 if (JSValueIsObjectOfClass(context, value, Message_)) {
1515 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1516 type = sig::Unparse(pool, &message->signature_);
1517 imp = reinterpret_cast<IMP>(message->GetValue());
1519 type = CYPoolTypeEncoding(pool, context, sel, method);
1520 imp = CYMakeMessage(context, value, type);
1524 method_setImplementation(method, imp);
1527 GSMethodList list(GSAllocMethodList(1));
1528 GSAppendMethodToList(list, sel, type, imp, YES);
1529 GSAddMethodList(_class, list, YES);
1530 GSFlushMethodCacheForClass(_class);
1532 class_addMethod(_class, sel, imp, type);
1539 #if 0 && OBJC_API_VERSION < 2
1540 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1541 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1542 Class _class(internal->GetValue());
1545 const char *name(CYPoolCString(pool, context, property));
1547 if (SEL sel = sel_getUid(name))
1548 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1549 objc_method_list list = {NULL, 1, {method}};
1550 class_removeMethods(_class, &list);
1558 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1559 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1560 Class _class(internal->GetValue());
1562 #if OBJC_API_VERSION >= 2
1564 objc_method **data(class_copyMethodList(_class, &size));
1565 for (size_t i(0); i != size; ++i)
1566 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1569 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1570 for (int i(0); i != methods->method_count; ++i)
1571 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1575 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1576 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1577 id self(internal->GetValue());
1579 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1583 NSString *name(CYCastNSString(pool, context, property));
1585 if (CYInternal *internal = CYInternal::Get(self))
1586 if (internal->HasProperty(context, property))
1589 Class _class(object_getClass(self));
1592 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1593 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1594 if ([self cy$hasProperty:name])
1596 } CYPoolCatch(false)
1598 const char *string(CYPoolCString(pool, context, name));
1601 if (class_getProperty(_class, string) != NULL)
1605 if (SEL sel = sel_getUid(string))
1606 if (CYImplements(self, _class, sel, true))
1612 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1614 id self(internal->GetValue());
1616 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1617 return Internal::Make(context, self, object);
1620 NSString *name(CYCastNSString(pool, context, property));
1622 if (CYInternal *internal = CYInternal::Get(self))
1623 if (JSValueRef value = internal->GetProperty(context, property))
1627 if (NSObject *data = [self cy$getProperty:name])
1628 return CYCastJSValue(context, data);
1631 const char *string(CYPoolCString(pool, context, name));
1632 Class _class(object_getClass(self));
1635 if (objc_property_t property = class_getProperty(_class, string)) {
1636 PropertyAttributes attributes(property);
1637 SEL sel(sel_registerName(attributes.Getter()));
1638 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1642 if (SEL sel = sel_getUid(string))
1643 if (CYImplements(self, _class, sel, true))
1644 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1649 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1650 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1651 id self(internal->GetValue());
1655 NSString *name(CYCastNSString(pool, context, property));
1656 NSObject *data(CYCastNSObject(pool, context, value));
1659 if ([self cy$setProperty:name to:data])
1663 const char *string(CYPoolCString(pool, context, name));
1664 Class _class(object_getClass(self));
1667 if (objc_property_t property = class_getProperty(_class, string)) {
1668 PropertyAttributes attributes(property);
1669 if (const char *setter = attributes.Setter()) {
1670 SEL sel(sel_registerName(setter));
1671 JSValueRef arguments[1] = {value};
1672 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1678 size_t length(strlen(string));
1680 char set[length + 5];
1686 if (string[0] != '\0') {
1687 set[3] = toupper(string[0]);
1688 memcpy(set + 4, string + 1, length - 1);
1691 set[length + 3] = ':';
1692 set[length + 4] = '\0';
1694 if (SEL sel = sel_getUid(set))
1695 if (CYImplements(self, _class, sel, false)) {
1696 JSValueRef arguments[1] = {value};
1697 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1700 if (CYInternal *internal = CYInternal::Set(self)) {
1701 internal->SetProperty(context, property, value);
1708 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1709 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1710 id self(internal->GetValue());
1713 NSString *name(CYCastNSString(NULL, context, property));
1714 return [self cy$deleteProperty:name];
1716 } CYCatch return /*XXX*/ NULL; }
1718 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1719 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1720 id self(internal->GetValue());
1723 Class _class(object_getClass(self));
1728 objc_property_t *data(class_copyPropertyList(_class, &size));
1729 for (size_t i(0); i != size; ++i)
1730 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1736 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1737 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1738 [self cy$getPropertyNames:names inContext:context];
1742 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1743 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1744 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1748 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1749 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1750 Class _class(internal->GetValue());
1751 if (!CYIsClass(_class))
1754 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1755 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1756 // XXX: this isn't always safe
1757 return [linternal->GetValue() isKindOfClass:_class];
1763 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1764 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1767 id self(internal->GetValue());
1768 const char *name(CYPoolCString(pool, context, property));
1770 if (object_getInstanceVariable(self, name, NULL) != NULL)
1776 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1777 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1780 id self(internal->GetValue());
1781 const char *name(CYPoolCString(pool, context, property));
1783 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1784 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1785 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1786 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1792 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1793 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1796 id self(internal->GetValue());
1797 const char *name(CYPoolCString(pool, context, property));
1799 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1800 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1801 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1808 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1809 if (Class super = class_getSuperclass(_class))
1810 Internal_getPropertyNames_(super, names);
1812 #if OBJC_API_VERSION >= 2
1814 objc_ivar **data(class_copyIvarList(_class, &size));
1815 for (size_t i(0); i != size; ++i)
1816 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1819 if (objc_ivar_list *ivars = _class->ivars)
1820 for (int i(0); i != ivars->ivar_count; ++i)
1821 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1825 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1826 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1829 id self(internal->GetValue());
1830 Class _class(object_getClass(self));
1832 Internal_getPropertyNames_(_class, names);
1835 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1836 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1837 return internal->GetOwner();
1840 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1842 NSString *name(CYCastNSString(pool, context, property));
1843 if (Class _class = NSClassFromString(name))
1844 return CYMakeInstance(context, _class, true);
1848 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1850 size_t size(objc_getClassList(NULL, 0));
1851 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1854 size_t writ(objc_getClassList(data, size));
1857 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1863 for (size_t i(0); i != writ; ++i)
1864 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1870 while (Class _class = objc_next_class(&state))
1871 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1875 #if OBJC_API_VERSION >= 2
1876 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1877 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1880 const char *name(CYPoolCString(pool, context, property));
1882 const char **data(objc_copyClassNamesForImage(internal, &size));
1884 for (size_t i(0); i != size; ++i)
1885 if (strcmp(name, data[i]) == 0) {
1886 if (Class _class = objc_getClass(name)) {
1887 value = CYMakeInstance(context, _class, true);
1898 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1899 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1901 const char **data(objc_copyClassNamesForImage(internal, &size));
1902 for (size_t i(0); i != size; ++i)
1903 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1907 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1909 const char *name(CYPoolCString(pool, context, property));
1911 const char **data(objc_copyImageNames(&size));
1912 for (size_t i(0); i != size; ++i)
1913 if (strcmp(name, data[i]) == 0) {
1922 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1923 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1927 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1929 const char **data(objc_copyImageNames(&size));
1930 for (size_t i(0); i != size; ++i)
1931 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1936 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1938 const char *name(CYPoolCString(pool, context, property));
1939 if (Protocol *protocol = objc_getProtocol(name))
1940 return CYMakeInstance(context, protocol, true);
1944 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1945 #if OBJC_API_VERSION >= 2
1947 Protocol **data(objc_copyProtocolList(&size));
1948 for (size_t i(0); i != size; ++i)
1949 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1957 static bool stret(ffi_type *ffi_type) {
1958 return ffi_type->type == FFI_TYPE_STRUCT && (
1959 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1960 struct_forward_array[ffi_type->size] != 0
1965 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 {
1969 _class = object_getClass(self);
1973 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
1974 imp = method_getImplementation(method);
1975 type = method_getTypeEncoding(method);
1980 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1982 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
1983 type = CYPoolCString(pool, context, [method _typeString]);
1991 sig::Signature signature;
1992 sig::Parse(pool, &signature, type, &Structor_);
1995 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1999 if (stret(cif.rtype))
2000 imp = class_getMethodImplementation_stret(_class, _cmd);
2002 imp = class_getMethodImplementation(_class, _cmd);
2004 objc_super super = {self, _class};
2005 imp = objc_msg_lookup_super(&super, _cmd);
2009 void (*function)() = reinterpret_cast<void (*)()>(imp);
2010 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2013 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2015 throw CYJSError(context, "too few arguments to objc_msgSend");
2025 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2026 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2027 self = internal->GetValue();
2028 _class = internal->class_;;
2029 uninitialized = false;
2030 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2031 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2032 self = internal->GetValue();
2034 uninitialized = internal->IsUninitialized();
2036 internal->value_ = nil;
2038 self = CYCastNSObject(pool, context, arguments[0]);
2040 uninitialized = false;
2044 return CYJSNull(context);
2046 _cmd = CYCastSEL(context, arguments[1]);
2048 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2051 /* Hook: objc_registerClassPair {{{ */
2052 #if defined(__APPLE__) && defined(__arm__)
2053 // XXX: replace this with associated objects
2055 MSHook(void, CYDealloc, id self, SEL sel) {
2056 CYInternal *internal;
2057 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2058 if (internal != NULL)
2060 _CYDealloc(self, sel);
2063 MSHook(void, objc_registerClassPair, Class _class) {
2064 Class super(class_getSuperclass(_class));
2065 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2066 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2067 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2070 _objc_registerClassPair(_class);
2073 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2075 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2077 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2078 if (value == NULL || !CYIsClass(value))
2079 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2080 Class _class((Class) value);
2081 $objc_registerClassPair(_class);
2082 return CYJSUndefined(context);
2087 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2088 JSValueRef setup[count + 2];
2091 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2092 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2095 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2097 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2099 // XXX: handle Instance::Uninitialized?
2100 id self(CYCastNSObject(pool, context, _this));
2104 setup[1] = &internal->sel_;
2106 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2109 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2111 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2113 id self(CYCastNSObject(pool, context, arguments[0]));
2114 Class _class(CYCastClass(pool, context, arguments[1]));
2115 return cy::Super::Make(context, self, _class);
2118 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2120 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2122 const char *name(CYPoolCString(pool, context, arguments[0]));
2123 return CYMakeSelector(context, sel_registerName(name));
2126 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2128 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2129 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2130 return Instance::Make(context, self);
2133 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2134 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2135 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2138 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2139 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2140 Type_privateData *typical(internal->GetType());
2145 if (typical == NULL) {
2149 type = typical->type_;
2150 ffi = typical->ffi_;
2153 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2156 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2157 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2158 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2161 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2162 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2163 id self(internal->GetValue());
2164 if (!CYIsClass(self))
2165 return CYJSUndefined(context);
2166 return CYGetClassPrototype(context, self);
2169 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2170 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2171 id self(internal->GetValue());
2172 if (!CYIsClass(self))
2173 return CYJSUndefined(context);
2174 return Messages::Make(context, (Class) self);
2177 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2178 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2181 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2182 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2185 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2186 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2189 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2196 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2197 // XXX: check for support of cy$toJSON?
2198 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2200 } CYCatch return /*XXX*/ NULL; }
2202 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2203 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2206 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2209 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2210 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2212 } CYCatch return /*XXX*/ NULL; }
2214 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2215 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2216 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2219 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2220 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2223 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2224 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2225 const char *name(sel_getName(internal->GetValue()));
2228 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2229 return CYCastJSValue(context, CYJSString(context, string));
2231 } CYCatch return /*XXX*/ NULL; }
2233 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2235 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2238 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2239 SEL sel(internal->GetValue());
2241 objc_method *method;
2242 if (Class _class = CYCastClass(pool, context, arguments[0]))
2243 method = class_getInstanceMethod(_class, sel);
2247 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2248 return CYCastJSValue(context, CYJSString(type));
2250 return CYJSNull(context);
2253 static JSStaticValue Selector_staticValues[2] = {
2254 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2255 {NULL, NULL, NULL, 0}
2258 static JSStaticValue Instance_staticValues[5] = {
2259 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2260 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2261 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2262 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2263 {NULL, NULL, NULL, 0}
2266 static JSStaticFunction Instance_staticFunctions[5] = {
2267 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2268 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2269 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2270 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2274 static JSStaticFunction Internal_staticFunctions[2] = {
2275 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2279 static JSStaticFunction Selector_staticFunctions[5] = {
2280 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2281 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2282 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2283 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2287 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2288 apr_pool_t *pool(CYGetGlobalPool());
2290 Object_type = new(pool) Type_privateData("@");
2291 Selector_type = new(pool) Type_privateData(":");
2294 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2295 NSCFType_ = objc_getClass("NSCFType");
2296 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2297 NSZombie_ = objc_getClass("_NSZombie_");
2299 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2302 NSArray_ = objc_getClass("NSArray");
2303 NSDictionary_ = objc_getClass("NSDictionary");
2304 Object_ = objc_getClass("Object");
2306 JSClassDefinition definition;
2308 definition = kJSClassDefinitionEmpty;
2309 definition.className = "Instance";
2310 definition.staticValues = Instance_staticValues;
2311 definition.staticFunctions = Instance_staticFunctions;
2312 definition.hasProperty = &Instance_hasProperty;
2313 definition.getProperty = &Instance_getProperty;
2314 definition.setProperty = &Instance_setProperty;
2315 definition.deleteProperty = &Instance_deleteProperty;
2316 definition.getPropertyNames = &Instance_getPropertyNames;
2317 definition.callAsConstructor = &Instance_callAsConstructor;
2318 definition.hasInstance = &Instance_hasInstance;
2319 definition.finalize = &CYFinalize;
2320 Instance_ = JSClassCreate(&definition);
2322 definition = kJSClassDefinitionEmpty;
2323 definition.className = "Internal";
2324 definition.staticFunctions = Internal_staticFunctions;
2325 definition.hasProperty = &Internal_hasProperty;
2326 definition.getProperty = &Internal_getProperty;
2327 definition.setProperty = &Internal_setProperty;
2328 definition.getPropertyNames = &Internal_getPropertyNames;
2329 definition.finalize = &CYFinalize;
2330 Internal_ = JSClassCreate(&definition);
2332 definition = kJSClassDefinitionEmpty;
2333 definition.className = "Message";
2334 definition.staticFunctions = cy::Functor::StaticFunctions;
2335 definition.callAsFunction = &Message_callAsFunction;
2336 definition.finalize = &CYFinalize;
2337 Message_ = JSClassCreate(&definition);
2339 definition = kJSClassDefinitionEmpty;
2340 definition.className = "Messages";
2341 definition.hasProperty = &Messages_hasProperty;
2342 definition.getProperty = &Messages_getProperty;
2343 definition.setProperty = &Messages_setProperty;
2344 #if 0 && OBJC_API_VERSION < 2
2345 definition.deleteProperty = &Messages_deleteProperty;
2347 definition.getPropertyNames = &Messages_getPropertyNames;
2348 definition.finalize = &CYFinalize;
2349 Messages_ = JSClassCreate(&definition);
2351 definition = kJSClassDefinitionEmpty;
2352 definition.className = "Selector";
2353 definition.staticValues = Selector_staticValues;
2354 definition.staticFunctions = Selector_staticFunctions;
2355 definition.callAsFunction = &Selector_callAsFunction;
2356 definition.finalize = &CYFinalize;
2357 Selector_ = JSClassCreate(&definition);
2359 definition = kJSClassDefinitionEmpty;
2360 definition.className = "Super";
2361 definition.staticFunctions = Internal_staticFunctions;
2362 definition.finalize = &CYFinalize;
2363 Super_ = JSClassCreate(&definition);
2365 definition = kJSClassDefinitionEmpty;
2366 definition.className = "ObjectiveC::Classes";
2367 definition.getProperty = &ObjectiveC_Classes_getProperty;
2368 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2369 ObjectiveC_Classes_ = JSClassCreate(&definition);
2371 #if OBJC_API_VERSION >= 2
2372 definition = kJSClassDefinitionEmpty;
2373 definition.className = "ObjectiveC::Images";
2374 definition.getProperty = &ObjectiveC_Images_getProperty;
2375 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2376 ObjectiveC_Images_ = JSClassCreate(&definition);
2378 definition = kJSClassDefinitionEmpty;
2379 definition.className = "ObjectiveC::Image::Classes";
2380 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2381 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2382 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2385 definition = kJSClassDefinitionEmpty;
2386 definition.className = "ObjectiveC::Protocols";
2387 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2388 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2389 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2391 #if defined(__APPLE__) && defined(__arm__)
2392 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2396 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2400 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2401 JSObjectRef global(CYGetGlobalObject(context));
2402 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2403 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2404 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2406 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2407 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2409 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2410 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2412 #if OBJC_API_VERSION >= 2
2413 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2416 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2417 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2418 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2419 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2421 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2422 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2424 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2425 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2426 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2428 #if defined(__APPLE__) && defined(__arm__)
2429 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2432 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2434 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2435 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2436 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2439 static CYHooks CYObjectiveCHooks = {
2440 &CYObjectiveC_ExecuteStart,
2441 &CYObjectiveC_ExecuteEnd,
2442 &CYObjectiveC_RuntimeProperty,
2443 &CYObjectiveC_CallFunction,
2444 &CYObjectiveC_Initialize,
2445 &CYObjectiveC_SetupContext,
2446 &CYObjectiveC_PoolFFI,
2447 &CYObjectiveC_FromFFI,
2450 struct CYObjectiveC {
2452 hooks_ = &CYObjectiveCHooks;