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]; \
103 @catch (NSException *error ) { \
104 throw CYJSError(context, CYCastJSValue(context, error)); \
109 #define class_getSuperclass GSObjCSuper
110 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
111 #define class_getName GSNameFromClass
113 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
115 #define ivar_getName(ivar) ((ivar)->ivar_name)
116 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
117 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
119 #define method_getName(method) ((method)->method_name)
120 #define method_getImplementation(method) ((method)->method_imp)
121 #define method_getTypeEncoding(method) ((method)->method_types)
122 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
125 #define objc_getClass GSClassFromName
127 #define objc_getProtocol GSProtocolFromName
129 #define object_getClass GSObjCClass
131 #define object_getInstanceVariable(object, name, value) ({ \
132 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
134 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
138 #define object_setIvar(object, ivar, value) ({ \
139 void *data = (value); \
140 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
143 #define protocol_getName(protocol) [(protocol) name]
146 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
148 extern sqlite3 *Bridge_;
150 /* Objective-C Pool Release {{{ */
151 apr_status_t CYPoolRelease_(void *data) {
152 id object(reinterpret_cast<id>(data));
157 id CYPoolRelease_(apr_pool_t *pool, id object) {
160 else if (pool == NULL)
161 return [object autorelease];
163 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
168 template <typename Type_>
169 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
170 return (Type_) CYPoolRelease_(pool, (id) object);
173 /* Objective-C Strings {{{ */
174 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
176 return [value UTF8String];
178 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
179 char *string(new(pool) char[size]);
180 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
181 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
186 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
188 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
191 return CYCopyJSString(CYPoolCString(pool, context, value));
195 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
198 // XXX: this definition scares me; is anyone using this?!
199 NSString *string([value description]);
200 return CYCopyJSString(context, string);
203 NSString *CYCopyNSString(const CYUTF8String &value) {
205 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
207 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
211 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
213 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
216 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
220 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
221 return CYCopyNSString(context, CYJSString(context, value));
224 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
225 return CYPoolRelease(pool, CYCopyNSString(value));
228 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
229 const char *name(sel_getName(sel));
230 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
233 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
234 return CYPoolRelease(pool, CYCopyNSString(context, value));
237 CYUTF8String CYCastUTF8String(NSString *value) {
238 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
239 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
243 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
245 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
246 if (exception == NULL)
248 *exception = CYCastJSValue(context, error);
251 size_t CYGetIndex(NSString *value) {
252 return CYGetIndex(CYCastUTF8String(value));
255 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
256 return CYGetOffset(CYPoolCString(pool, context, value), index);
259 static JSClassRef Instance_;
260 static JSClassRef Internal_;
261 static JSClassRef Message_;
262 static JSClassRef Messages_;
263 static JSClassRef Selector_;
264 static JSClassRef Super_;
266 static JSClassRef ObjectiveC_Classes_;
267 static JSClassRef ObjectiveC_Protocols_;
270 static JSClassRef ObjectiveC_Image_Classes_;
271 static JSClassRef ObjectiveC_Images_;
275 static Class NSCFBoolean_;
276 static Class NSCFType_;
277 static Class NSMessageBuilder_;
278 static Class NSZombie_;
280 static Class NSBoolNumber_;
283 static Class NSArray_;
284 static Class NSDictionary_;
285 static Class Object_;
287 static Type_privateData *Object_type;
288 static Type_privateData *Selector_type;
290 Type_privateData *Instance::GetType() const {
294 Type_privateData *Selector_privateData::GetType() const {
295 return Selector_type;
298 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
300 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
302 JSObjectRef global(CYGetGlobalObject(context));
303 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
306 sprintf(label, "i%p", self);
307 CYJSString name(label);
309 JSValueRef value(CYGetProperty(context, cy, name));
310 if (!JSValueIsUndefined(context, value))
313 JSClassRef _class(NULL);
314 JSValueRef prototype;
316 if (self == NSArray_)
317 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
318 else if (self == NSDictionary_)
319 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
321 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
323 JSObjectRef object(JSObjectMake(context, _class, NULL));
324 JSObjectSetPrototype(context, object, prototype);
325 CYSetProperty(context, cy, name, object);
329 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
330 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
331 if (_class == NSArray_)
333 if (Class super = class_getSuperclass(_class))
334 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
336 JSObjectSetPrototype(context, value, Array_prototype_);*/
340 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
341 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
345 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
346 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
350 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
351 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
352 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
356 Instance::~Instance() {
357 if ((flags_ & Transient) == 0)
358 // XXX: does this handle background threads correctly?
359 // XXX: this simply does not work on the console because I'm stupid
360 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
363 struct Message_privateData :
368 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
369 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
375 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
376 Instance::Flags flags;
379 flags = Instance::Transient;
381 flags = Instance::None;
382 object = [object retain];
385 return Instance::Make(context, object, flags);
388 @interface NSMethodSignature (Cycript)
389 - (NSString *) _typeString;
392 @interface NSObject (Cycript)
394 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
395 - (JSType) cy$JSType;
397 - (NSObject *) cy$toJSON:(NSString *)key;
398 - (NSString *) cy$toCYON;
399 - (NSString *) cy$toKey;
401 - (bool) cy$hasProperty:(NSString *)name;
402 - (NSObject *) cy$getProperty:(NSString *)name;
403 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
404 - (bool) cy$deleteProperty:(NSString *)name;
405 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
410 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
413 NSString *CYCastNSCYON(id value) {
419 Class _class(object_getClass(value));
420 SEL sel(@selector(cy$toCYON));
422 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
423 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
424 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
425 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
426 string = [value cy$toCYON];
431 else if (value == NSZombie_)
432 string = @"_NSZombie_";
433 else if (_class == NSZombie_)
434 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
435 // XXX: frowny /in/ the pants
436 else if (value == NSMessageBuilder_ || value == Object_)
440 string = [NSString stringWithFormat:@"%@", value];
445 string = @"undefined";
452 struct PropertyAttributes {
457 const char *variable;
470 PropertyAttributes(objc_property_t property) :
482 name = property_getName(property);
483 const char *attributes(property_getAttributes(property));
485 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
487 case 'R': readonly = true; break;
488 case 'C': copy = true; break;
489 case '&': retain = true; break;
490 case 'N': nonatomic = true; break;
491 case 'G': getter_ = token + 1; break;
492 case 'S': setter_ = token + 1; break;
493 case 'V': variable = token + 1; break;
497 /*if (variable == NULL) {
498 variable = property_getName(property);
499 size_t size(strlen(variable));
500 char *name(new(pool_) char[size + 2]);
502 memcpy(name + 1, variable, size);
503 name[size + 1] = '\0';
508 const char *Getter() {
510 getter_ = apr_pstrdup(pool_, name);
514 const char *Setter() {
515 if (setter_ == NULL && !readonly) {
516 size_t length(strlen(name));
518 char *temp(new(pool_) char[length + 5]);
524 temp[3] = toupper(name[0]);
525 memcpy(temp + 4, name + 1, length - 1);
528 temp[length + 3] = ':';
529 temp[length + 4] = '\0';
540 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
541 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
546 @interface CYWebUndefined : NSObject {
549 + (CYWebUndefined *) undefined;
553 @implementation CYWebUndefined
555 + (CYWebUndefined *) undefined {
556 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
562 #define WebUndefined CYWebUndefined
565 /* Bridge: CYJSObject {{{ */
566 @interface CYJSObject : NSMutableDictionary {
568 JSContextRef context_;
571 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
573 - (NSObject *) cy$toJSON:(NSString *)key;
575 - (NSUInteger) count;
576 - (id) objectForKey:(id)key;
577 - (NSEnumerator *) keyEnumerator;
578 - (void) setObject:(id)object forKey:(id)key;
579 - (void) removeObjectForKey:(id)key;
583 /* Bridge: CYJSArray {{{ */
584 @interface CYJSArray : NSMutableArray {
586 JSContextRef context_;
589 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
591 - (NSUInteger) count;
592 - (id) objectAtIndex:(NSUInteger)index;
594 - (void) addObject:(id)anObject;
595 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
596 - (void) removeLastObject;
597 - (void) removeObjectAtIndex:(NSUInteger)index;
598 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
603 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
604 JSObjectRef Array(CYGetCachedObject(context, Array_s));
605 JSValueRef exception(NULL);
606 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
607 CYThrow(context, exception);
608 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
609 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
612 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
613 if (!JSValueIsObjectOfClass(context, object, Instance_))
614 return CYCastNSObject_(pool, context, object);
616 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
617 return internal->GetValue();
621 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
622 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
626 @interface NSBoolNumber : NSNumber {
631 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
635 switch (JSType type = JSValueGetType(context, value)) {
636 case kJSTypeUndefined:
637 object = [WebUndefined undefined];
647 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
650 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
656 object = CYCopyNSNumber(context, value);
661 object = CYCopyNSString(context, value);
666 // XXX: this might could be more efficient
667 object = CYCastNSObject(pool, context, (JSObjectRef) value);
672 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
679 return CYPoolRelease(pool, object);
681 return [object retain];
684 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
685 return CYNSObject(pool, context, value, true);
688 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
689 return CYNSObject(pool, context, value, false);
692 /* Bridge: NSArray {{{ */
693 @implementation NSArray (Cycript)
695 - (NSString *) cy$toCYON {
696 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
697 [json appendString:@"["];
701 for (id object in self) {
703 for (size_t index(0), count([self count]); index != count; ++index) {
704 id object([self objectAtIndex:index]);
707 [json appendString:@","];
710 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
711 [json appendString:CYCastNSCYON(object)];
713 [json appendString:@","];
718 [json appendString:@"]"];
722 - (bool) cy$hasProperty:(NSString *)name {
723 if ([name isEqualToString:@"length"])
726 size_t index(CYGetIndex(name));
727 if (index == _not(size_t) || index >= [self count])
728 return [super cy$hasProperty:name];
733 - (NSObject *) cy$getProperty:(NSString *)name {
734 if ([name isEqualToString:@"length"]) {
735 NSUInteger count([self count]);
737 return [NSNumber numberWithUnsignedInteger:count];
739 return [NSNumber numberWithUnsignedInt:count];
743 size_t index(CYGetIndex(name));
744 if (index == _not(size_t) || index >= [self count])
745 return [super cy$getProperty:name];
747 return [self objectAtIndex:index];
750 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
751 [super cy$getPropertyNames:names inContext:context];
753 for (size_t index(0), count([self count]); index != count; ++index) {
754 id object([self objectAtIndex:index]);
755 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
757 sprintf(name, "%zu", index);
758 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
765 /* Bridge: NSBoolNumber {{{ */
767 @implementation NSBoolNumber (Cycript)
769 - (JSType) cy$JSType {
770 return kJSTypeBoolean;
773 - (NSObject *) cy$toJSON:(NSString *)key {
777 - (NSString *) cy$toCYON {
778 return [self boolValue] ? @"true" : @"false";
781 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
782 return CYCastJSValue(context, (bool) [self boolValue]);
788 /* Bridge: NSDictionary {{{ */
789 @implementation NSDictionary (Cycript)
791 - (NSString *) cy$toCYON {
792 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
793 [json appendString:@"{"];
797 for (NSObject *key in self) {
799 NSEnumerator *keys([self keyEnumerator]);
800 while (NSObject *key = [keys nextObject]) {
803 [json appendString:@","];
806 [json appendString:[key cy$toKey]];
807 [json appendString:@":"];
808 NSObject *object([self objectForKey:key]);
809 [json appendString:CYCastNSCYON(object)];
812 [json appendString:@"}"];
816 - (bool) cy$hasProperty:(NSString *)name {
817 return [self objectForKey:name] != nil;
820 - (NSObject *) cy$getProperty:(NSString *)name {
821 return [self objectForKey:name];
824 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
825 [super cy$getPropertyNames:names inContext:context];
828 for (NSObject *key in self) {
830 NSEnumerator *keys([self keyEnumerator]);
831 while (NSObject *key = [keys nextObject]) {
833 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
839 /* Bridge: NSMutableArray {{{ */
840 @implementation NSMutableArray (Cycript)
842 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
843 if ([name isEqualToString:@"length"]) {
844 // XXX: is this not intelligent?
845 NSNumber *number(reinterpret_cast<NSNumber *>(value));
847 NSUInteger size([number unsignedIntegerValue]);
849 NSUInteger size([number unsignedIntValue]);
851 NSUInteger count([self count]);
853 [self removeObjectsInRange:NSMakeRange(size, count - size)];
854 else if (size != count) {
855 WebUndefined *undefined([WebUndefined undefined]);
856 for (size_t i(count); i != size; ++i)
857 [self addObject:undefined];
862 size_t index(CYGetIndex(name));
863 if (index == _not(size_t))
864 return [super cy$setProperty:name to:value];
866 id object(value ?: [NSNull null]);
868 size_t count([self count]);
870 [self replaceObjectAtIndex:index withObject:object];
872 if (index != count) {
873 WebUndefined *undefined([WebUndefined undefined]);
874 for (size_t i(count); i != index; ++i)
875 [self addObject:undefined];
878 [self addObject:object];
884 - (bool) cy$deleteProperty:(NSString *)name {
885 size_t index(CYGetIndex(name));
886 if (index == _not(size_t) || index >= [self count])
887 return [super cy$deleteProperty:name];
888 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
894 /* Bridge: NSMutableDictionary {{{ */
895 @implementation NSMutableDictionary (Cycript)
897 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
898 [self setObject:(value ?: [NSNull null]) forKey:name];
902 - (bool) cy$deleteProperty:(NSString *)name {
903 if ([self objectForKey:name] == nil)
906 [self removeObjectForKey:name];
913 /* Bridge: NSNumber {{{ */
914 @implementation NSNumber (Cycript)
916 - (JSType) cy$JSType {
918 // XXX: this just seems stupid
919 if ([self class] == NSCFBoolean_)
920 return kJSTypeBoolean;
922 return kJSTypeNumber;
925 - (NSObject *) cy$toJSON:(NSString *)key {
929 - (NSString *) cy$toCYON {
930 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
933 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
934 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
939 /* Bridge: NSNull {{{ */
940 @implementation NSNull (Cycript)
942 - (JSType) cy$JSType {
946 - (NSObject *) cy$toJSON:(NSString *)key {
950 - (NSString *) cy$toCYON {
956 /* Bridge: NSObject {{{ */
957 @implementation NSObject (Cycript)
959 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
960 return CYMakeInstance(context, self, false);
963 - (JSType) cy$JSType {
964 return kJSTypeObject;
967 - (NSObject *) cy$toJSON:(NSString *)key {
968 return [self description];
971 - (NSString *) cy$toCYON {
972 return [[self cy$toJSON:@""] cy$toCYON];
975 - (NSString *) cy$toKey {
976 return [self cy$toCYON];
979 - (bool) cy$hasProperty:(NSString *)name {
983 - (NSObject *) cy$getProperty:(NSString *)name {
987 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
991 - (bool) cy$deleteProperty:(NSString *)name {
995 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1000 /* Bridge: NSProxy {{{ */
1001 @implementation NSProxy (Cycript)
1003 - (NSObject *) cy$toJSON:(NSString *)key {
1004 return [self description];
1007 - (NSString *) cy$toCYON {
1008 return [[self cy$toJSON:@""] cy$toCYON];
1013 /* Bridge: NSString {{{ */
1014 @implementation NSString (Cycript)
1016 - (JSType) cy$JSType {
1017 return kJSTypeString;
1020 - (NSObject *) cy$toJSON:(NSString *)key {
1024 - (NSString *) cy$toCYON {
1025 std::ostringstream str;
1026 CYUTF8String string(CYCastUTF8String(self));
1027 CYStringify(str, string.data, string.size);
1028 std::string value(str.str());
1029 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1032 - (NSString *) cy$toKey {
1033 if (CYIsKey(CYCastUTF8String(self)))
1035 return [self cy$toCYON];
1040 /* Bridge: WebUndefined {{{ */
1041 @implementation WebUndefined (Cycript)
1043 - (JSType) cy$JSType {
1044 return kJSTypeUndefined;
1047 - (NSObject *) cy$toJSON:(NSString *)key {
1051 - (NSString *) cy$toCYON {
1052 return @"undefined";
1055 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1056 return CYJSUndefined(context);
1057 } CYObjectiveCatch }
1062 static bool CYIsClass(id self) {
1064 // XXX: this is a lame object_isClass
1065 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1067 return GSObjCIsClass(self);
1071 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1072 id self(CYCastNSObject(pool, context, value));
1073 if (CYIsClass(self))
1074 return (Class) self;
1075 throw CYJSError(context, "got something that is not a Class");
1079 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1081 size_t size(JSPropertyNameArrayGetCount(names));
1082 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1083 for (size_t index(0); index != size; ++index)
1084 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1088 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1090 return CYJSNull(context);
1091 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1092 return [value cy$JSValueInContext:context];
1094 return CYMakeInstance(context, value, false);
1095 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1097 @implementation CYJSObject
1099 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1100 if ((self = [super init]) != nil) {
1102 context_ = CYGetJSContext(context);
1103 //XXX:JSGlobalContextRetain(context_);
1104 JSValueProtect(context_, object_);
1106 } CYObjectiveCatch }
1108 - (void) dealloc { CYObjectiveTry {
1109 JSValueUnprotect(context_, object_);
1110 //XXX:JSGlobalContextRelease(context_);
1112 } CYObjectiveCatch }
1114 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1115 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1116 if (!CYIsCallable(context_, toJSON))
1117 return [super cy$toJSON:key];
1119 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1120 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1121 // XXX: do I really want an NSNull here?!
1122 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1124 } CYObjectiveCatch }
1126 - (NSString *) cy$toCYON { CYObjectiveTry {
1128 JSValueRef exception(NULL);
1129 const char *cyon(CYPoolCCYON(pool, context_, object_));
1130 CYThrow(context_, exception);
1132 return [super cy$toCYON];
1134 return [NSString stringWithUTF8String:cyon];
1135 } CYObjectiveCatch }
1137 - (NSUInteger) count { CYObjectiveTry {
1138 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1139 size_t size(JSPropertyNameArrayGetCount(names));
1140 JSPropertyNameArrayRelease(names);
1142 } CYObjectiveCatch }
1144 - (id) objectForKey:(id)key { CYObjectiveTry {
1145 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1146 if (JSValueIsUndefined(context_, value))
1148 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1149 } CYObjectiveCatch }
1151 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1152 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1153 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1154 JSPropertyNameArrayRelease(names);
1156 } CYObjectiveCatch }
1158 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1159 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1160 } CYObjectiveCatch }
1162 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1163 JSValueRef exception(NULL);
1164 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1165 CYThrow(context_, exception);
1166 } CYObjectiveCatch }
1170 @implementation CYJSArray
1172 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1173 if ((self = [super init]) != nil) {
1175 context_ = CYGetJSContext(context);
1176 //XXX:JSGlobalContextRetain(context_);
1177 JSValueProtect(context_, object_);
1179 } CYObjectiveCatch }
1181 - (void) dealloc { CYObjectiveTry {
1182 JSValueUnprotect(context_, object_);
1183 //XXX:JSGlobalContextRelease(context_);
1185 } CYObjectiveCatch }
1187 - (NSUInteger) count { CYObjectiveTry {
1188 return CYCastDouble(context_, CYGetProperty(context_, object_, length_s));
1189 } CYObjectiveCatch }
1191 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1192 size_t bounds([self count]);
1193 if (index >= bounds)
1194 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1195 JSValueRef exception(NULL);
1196 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1197 CYThrow(context_, exception);
1198 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1199 } CYObjectiveCatch }
1201 - (void) addObject:(id)object { CYObjectiveTry {
1202 JSValueRef exception(NULL);
1203 JSValueRef arguments[1];
1204 arguments[0] = CYCastJSValue(context_, (NSObject *) object);
1205 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1206 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, push_s)), object_, 1, arguments, &exception);
1207 CYThrow(context_, exception);
1208 } CYObjectiveCatch }
1210 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1211 size_t bounds([self count] + 1);
1212 if (index >= bounds)
1213 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1214 JSValueRef exception(NULL);
1215 JSValueRef arguments[3];
1216 arguments[0] = CYCastJSValue(context_, index);
1217 arguments[1] = CYCastJSValue(context_, 0);
1218 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1219 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1220 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1221 CYThrow(context_, exception);
1222 } CYObjectiveCatch }
1224 - (void) removeLastObject { CYObjectiveTry {
1225 JSValueRef exception(NULL);
1226 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1227 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1228 CYThrow(context_, exception);
1229 } CYObjectiveCatch }
1231 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1232 size_t bounds([self count]);
1233 if (index >= bounds)
1234 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1235 JSValueRef exception(NULL);
1236 JSValueRef arguments[2];
1237 arguments[0] = CYCastJSValue(context_, index);
1238 arguments[1] = CYCastJSValue(context_, 1);
1239 JSObjectRef Array(CYGetCachedObject(context_, Array_s));
1240 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1241 CYThrow(context_, exception);
1242 } CYObjectiveCatch }
1244 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1245 size_t bounds([self count]);
1246 if (index >= bounds)
1247 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1248 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1249 } CYObjectiveCatch }
1253 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1257 JSObjectRef object_;
1265 // XXX: delete object_? ;(
1268 static CYInternal *Get(id self) {
1269 CYInternal *internal(NULL);
1270 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1271 // XXX: do something epic? ;P
1277 static CYInternal *Set(id self) {
1278 CYInternal *internal(NULL);
1279 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1280 if (internal == NULL) {
1281 internal = new CYInternal();
1282 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1285 // XXX: do something epic? ;P
1291 bool HasProperty(JSContextRef context, JSStringRef name) {
1292 if (object_ == NULL)
1294 return JSObjectHasProperty(context, object_, name);
1297 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1298 if (object_ == NULL)
1300 return CYGetProperty(context, object_, name);
1303 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1304 if (object_ == NULL)
1305 object_ = JSObjectMake(context, NULL, NULL);
1306 CYSetProperty(context, object_, name, value);
1310 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1311 Selector_privateData *internal(new Selector_privateData(sel));
1312 return JSObjectMake(context, Selector_, internal);
1315 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1316 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1317 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1318 return reinterpret_cast<SEL>(internal->value_);
1320 return CYCastPointer<SEL>(context, value);
1323 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1324 return (void *) [[NSAutoreleasePool alloc] init];
1327 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1328 return [(NSAutoreleasePool *) handle release];
1331 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1333 return Instance::Make(context, nil);
1334 if (Class _class = objc_getClass(name.data))
1335 return CYMakeInstance(context, _class, true);
1337 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1339 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1340 ffi_call(cif, function, value, values);
1343 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1344 switch (type->primitive) {
1346 case sig::typename_P:
1347 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1350 case sig::selector_P:
1351 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1361 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1362 switch (type->primitive) {
1364 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1365 JSValueRef value(CYCastJSValue(context, object));
1371 case sig::typename_P:
1372 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1374 case sig::selector_P:
1375 if (SEL sel = *reinterpret_cast<SEL *>(data))
1376 return CYMakeSelector(context, sel);
1380 return CYJSNull(context);
1384 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1386 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1387 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1390 #if OBJC_API_VERSION >= 2
1392 method_getReturnType(method, type, sizeof(type));
1394 const char *type(method_getTypeEncoding(method));
1400 // XXX: possibly use a more "awesome" check?
1404 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1406 return method_getTypeEncoding(method);
1408 const char *name(sel_getName(sel));
1410 sqlite3_stmt *statement;
1412 _sqlcall(sqlite3_prepare(Bridge_,
1414 "\"bridge\".\"value\" "
1417 " \"bridge\".\"mode\" = -1 and"
1418 " \"bridge\".\"name\" = ?"
1420 , -1, &statement, NULL));
1423 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
1426 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1431 value = sqlite3_column_pooled(pool, statement, 0);
1434 _sqlcall(sqlite3_finalize(statement));
1442 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1443 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1445 JSContextRef context(internal->context_);
1447 size_t count(internal->cif_.nargs);
1448 JSValueRef values[count];
1450 for (size_t index(0); index != count; ++index)
1451 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1453 JSObjectRef _this(CYCastJSObject(context, values[0]));
1455 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1456 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1459 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1460 Message_privateData *internal(new Message_privateData(sel, type, imp));
1461 return JSObjectMake(context, Message_, internal);
1464 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1465 JSObjectRef function(CYCastJSObject(context, value));
1466 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1467 // XXX: see notes in Library.cpp about needing to leak
1468 return reinterpret_cast<IMP>(internal->GetValue());
1471 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1472 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1473 Class _class(internal->GetValue());
1476 const char *name(CYPoolCString(pool, context, property));
1478 if (SEL sel = sel_getUid(name))
1479 if (class_getInstanceMethod(_class, sel) != NULL)
1485 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1486 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1487 Class _class(internal->GetValue());
1490 const char *name(CYPoolCString(pool, context, property));
1492 if (SEL sel = sel_getUid(name))
1493 if (objc_method *method = class_getInstanceMethod(_class, sel))
1494 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1499 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1500 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1501 Class _class(internal->GetValue());
1504 const char *name(CYPoolCString(pool, context, property));
1506 SEL sel(sel_registerName(name));
1508 objc_method *method(class_getInstanceMethod(_class, sel));
1513 if (JSValueIsObjectOfClass(context, value, Message_)) {
1514 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1515 type = sig::Unparse(pool, &message->signature_);
1516 imp = reinterpret_cast<IMP>(message->GetValue());
1518 type = CYPoolTypeEncoding(pool, context, sel, method);
1519 imp = CYMakeMessage(context, value, type);
1523 method_setImplementation(method, imp);
1526 GSMethodList list(GSAllocMethodList(1));
1527 GSAppendMethodToList(list, sel, type, imp, YES);
1528 GSAddMethodList(_class, list, YES);
1529 GSFlushMethodCacheForClass(_class);
1531 class_addMethod(_class, sel, imp, type);
1538 #if 0 && OBJC_API_VERSION < 2
1539 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1540 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1541 Class _class(internal->GetValue());
1544 const char *name(CYPoolCString(pool, context, property));
1546 if (SEL sel = sel_getUid(name))
1547 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1548 objc_method_list list = {NULL, 1, {method}};
1549 class_removeMethods(_class, &list);
1557 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1558 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1559 Class _class(internal->GetValue());
1561 #if OBJC_API_VERSION >= 2
1563 objc_method **data(class_copyMethodList(_class, &size));
1564 for (size_t i(0); i != size; ++i)
1565 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1568 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1569 for (int i(0); i != methods->method_count; ++i)
1570 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1574 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1575 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1576 id self(internal->GetValue());
1578 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1582 NSString *name(CYCastNSString(pool, context, property));
1584 if (CYInternal *internal = CYInternal::Get(self))
1585 if (internal->HasProperty(context, property))
1588 Class _class(object_getClass(self));
1591 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1592 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1593 if ([self cy$hasProperty:name])
1595 } CYPoolCatch(false)
1597 const char *string(CYPoolCString(pool, context, name));
1600 if (class_getProperty(_class, string) != NULL)
1604 if (SEL sel = sel_getUid(string))
1605 if (CYImplements(self, _class, sel, true))
1611 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1612 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1613 id self(internal->GetValue());
1615 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1616 return Internal::Make(context, self, object);
1619 NSString *name(CYCastNSString(pool, context, property));
1621 if (CYInternal *internal = CYInternal::Get(self))
1622 if (JSValueRef value = internal->GetProperty(context, property))
1626 if (NSObject *data = [self cy$getProperty:name])
1627 return CYCastJSValue(context, data);
1630 const char *string(CYPoolCString(pool, context, name));
1631 Class _class(object_getClass(self));
1634 if (objc_property_t property = class_getProperty(_class, string)) {
1635 PropertyAttributes attributes(property);
1636 SEL sel(sel_registerName(attributes.Getter()));
1637 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1641 if (SEL sel = sel_getUid(string))
1642 if (CYImplements(self, _class, sel, true))
1643 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1648 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1649 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1650 id self(internal->GetValue());
1654 NSString *name(CYCastNSString(pool, context, property));
1655 NSObject *data(CYCastNSObject(pool, context, value));
1658 if ([self cy$setProperty:name to:data])
1662 const char *string(CYPoolCString(pool, context, name));
1663 Class _class(object_getClass(self));
1666 if (objc_property_t property = class_getProperty(_class, string)) {
1667 PropertyAttributes attributes(property);
1668 if (const char *setter = attributes.Setter()) {
1669 SEL sel(sel_registerName(setter));
1670 JSValueRef arguments[1] = {value};
1671 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1677 size_t length(strlen(string));
1679 char set[length + 5];
1685 if (string[0] != '\0') {
1686 set[3] = toupper(string[0]);
1687 memcpy(set + 4, string + 1, length - 1);
1690 set[length + 3] = ':';
1691 set[length + 4] = '\0';
1693 if (SEL sel = sel_getUid(set))
1694 if (CYImplements(self, _class, sel, false)) {
1695 JSValueRef arguments[1] = {value};
1696 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1699 if (CYInternal *internal = CYInternal::Set(self)) {
1700 internal->SetProperty(context, property, value);
1707 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1708 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1709 id self(internal->GetValue());
1712 NSString *name(CYCastNSString(NULL, context, property));
1713 return [self cy$deleteProperty:name];
1715 } CYCatch return /*XXX*/ NULL; }
1717 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1718 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1719 id self(internal->GetValue());
1722 Class _class(object_getClass(self));
1727 objc_property_t *data(class_copyPropertyList(_class, &size));
1728 for (size_t i(0); i != size; ++i)
1729 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1735 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1736 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1737 [self cy$getPropertyNames:names inContext:context];
1741 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1742 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1743 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1747 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1748 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1749 Class _class(internal->GetValue());
1750 if (!CYIsClass(_class))
1753 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1754 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1755 // XXX: this isn't always safe
1756 return [linternal->GetValue() isKindOfClass:_class];
1762 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1763 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1766 id self(internal->GetValue());
1767 const char *name(CYPoolCString(pool, context, property));
1769 if (object_getInstanceVariable(self, name, NULL) != NULL)
1775 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1776 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1779 id self(internal->GetValue());
1780 const char *name(CYPoolCString(pool, context, property));
1782 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1783 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1784 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1785 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1791 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1792 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1795 id self(internal->GetValue());
1796 const char *name(CYPoolCString(pool, context, property));
1798 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1799 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1800 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1807 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1808 if (Class super = class_getSuperclass(_class))
1809 Internal_getPropertyNames_(super, names);
1811 #if OBJC_API_VERSION >= 2
1813 objc_ivar **data(class_copyIvarList(_class, &size));
1814 for (size_t i(0); i != size; ++i)
1815 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1818 if (objc_ivar_list *ivars = _class->ivars)
1819 for (int i(0); i != ivars->ivar_count; ++i)
1820 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1824 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1825 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1828 id self(internal->GetValue());
1829 Class _class(object_getClass(self));
1831 Internal_getPropertyNames_(_class, names);
1834 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1835 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1836 return internal->GetOwner();
1839 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1841 NSString *name(CYCastNSString(pool, context, property));
1842 if (Class _class = NSClassFromString(name))
1843 return CYMakeInstance(context, _class, true);
1847 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1849 size_t size(objc_getClassList(NULL, 0));
1850 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1853 size_t writ(objc_getClassList(data, size));
1856 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1862 for (size_t i(0); i != writ; ++i)
1863 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1869 while (Class _class = objc_next_class(&state))
1870 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1874 #if OBJC_API_VERSION >= 2
1875 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1876 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1879 const char *name(CYPoolCString(pool, context, property));
1881 const char **data(objc_copyClassNamesForImage(internal, &size));
1883 for (size_t i(0); i != size; ++i)
1884 if (strcmp(name, data[i]) == 0) {
1885 if (Class _class = objc_getClass(name)) {
1886 value = CYMakeInstance(context, _class, true);
1897 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1898 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1900 const char **data(objc_copyClassNamesForImage(internal, &size));
1901 for (size_t i(0); i != size; ++i)
1902 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1906 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1908 const char *name(CYPoolCString(pool, context, property));
1910 const char **data(objc_copyImageNames(&size));
1911 for (size_t i(0); i != size; ++i)
1912 if (strcmp(name, data[i]) == 0) {
1921 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1922 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1926 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1928 const char **data(objc_copyImageNames(&size));
1929 for (size_t i(0); i != size; ++i)
1930 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1935 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1937 const char *name(CYPoolCString(pool, context, property));
1938 if (Protocol *protocol = objc_getProtocol(name))
1939 return CYMakeInstance(context, protocol, true);
1943 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1944 #if OBJC_API_VERSION >= 2
1946 Protocol **data(objc_copyProtocolList(&size));
1947 for (size_t i(0); i != size; ++i)
1948 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
1956 static bool stret(ffi_type *ffi_type) {
1957 return ffi_type->type == FFI_TYPE_STRUCT && (
1958 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1959 struct_forward_array[ffi_type->size] != 0
1964 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 {
1968 _class = object_getClass(self);
1972 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
1973 imp = method_getImplementation(method);
1974 type = method_getTypeEncoding(method);
1979 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1981 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
1982 type = CYPoolCString(pool, context, [method _typeString]);
1990 sig::Signature signature;
1991 sig::Parse(pool, &signature, type, &Structor_);
1994 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1998 if (stret(cif.rtype))
1999 imp = class_getMethodImplementation_stret(_class, _cmd);
2001 imp = class_getMethodImplementation(_class, _cmd);
2003 objc_super super = {self, _class};
2004 imp = objc_msg_lookup_super(&super, _cmd);
2008 void (*function)() = reinterpret_cast<void (*)()>(imp);
2009 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2012 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2014 throw CYJSError(context, "too few arguments to objc_msgSend");
2024 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2025 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2026 self = internal->GetValue();
2027 _class = internal->class_;;
2028 uninitialized = false;
2029 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2030 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2031 self = internal->GetValue();
2033 uninitialized = internal->IsUninitialized();
2035 internal->value_ = nil;
2037 self = CYCastNSObject(pool, context, arguments[0]);
2039 uninitialized = false;
2043 return CYJSNull(context);
2045 _cmd = CYCastSEL(context, arguments[1]);
2047 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2050 /* Hook: objc_registerClassPair {{{ */
2051 #if defined(__APPLE__) && defined(__arm__)
2052 // XXX: replace this with associated objects
2054 MSHook(void, CYDealloc, id self, SEL sel) {
2055 CYInternal *internal;
2056 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2057 if (internal != NULL)
2059 _CYDealloc(self, sel);
2062 MSHook(void, objc_registerClassPair, Class _class) {
2063 Class super(class_getSuperclass(_class));
2064 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2065 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2066 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2069 _objc_registerClassPair(_class);
2072 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2074 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2076 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2077 if (value == NULL || !CYIsClass(value))
2078 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2079 Class _class((Class) value);
2080 $objc_registerClassPair(_class);
2081 return CYJSUndefined(context);
2086 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2087 JSValueRef setup[count + 2];
2090 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2091 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2094 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2096 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2098 // XXX: handle Instance::Uninitialized?
2099 id self(CYCastNSObject(pool, context, _this));
2103 setup[1] = &internal->sel_;
2105 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2108 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2110 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2112 id self(CYCastNSObject(pool, context, arguments[0]));
2113 Class _class(CYCastClass(pool, context, arguments[1]));
2114 return cy::Super::Make(context, self, _class);
2117 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2119 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2121 const char *name(CYPoolCString(pool, context, arguments[0]));
2122 return CYMakeSelector(context, sel_registerName(name));
2125 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2127 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2128 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2129 return Instance::Make(context, self);
2132 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2133 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2134 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2137 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2138 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2139 Type_privateData *typical(internal->GetType());
2144 if (typical == NULL) {
2148 type = typical->type_;
2149 ffi = typical->ffi_;
2152 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2155 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2156 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2157 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2160 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2161 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2162 id self(internal->GetValue());
2163 if (!CYIsClass(self))
2164 return CYJSUndefined(context);
2165 return CYGetClassPrototype(context, self);
2168 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2169 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2170 id self(internal->GetValue());
2171 if (!CYIsClass(self))
2172 return CYJSUndefined(context);
2173 return Messages::Make(context, (Class) self);
2176 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2177 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2180 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2181 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2184 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2185 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2188 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2195 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2196 // XXX: check for support of cy$toJSON?
2197 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2199 } CYCatch return /*XXX*/ NULL; }
2201 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2202 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2205 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2208 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2209 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2211 } CYCatch return /*XXX*/ NULL; }
2213 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2214 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2215 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2218 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2219 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2222 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2223 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2224 const char *name(sel_getName(internal->GetValue()));
2227 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2228 return CYCastJSValue(context, CYJSString(context, string));
2230 } CYCatch return /*XXX*/ NULL; }
2232 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2234 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2237 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2238 SEL sel(internal->GetValue());
2240 objc_method *method;
2241 if (Class _class = CYCastClass(pool, context, arguments[0]))
2242 method = class_getInstanceMethod(_class, sel);
2246 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2247 return CYCastJSValue(context, CYJSString(type));
2249 return CYJSNull(context);
2252 static JSStaticValue Selector_staticValues[2] = {
2253 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2254 {NULL, NULL, NULL, 0}
2257 static JSStaticValue Instance_staticValues[5] = {
2258 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2259 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2260 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2261 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2262 {NULL, NULL, NULL, 0}
2265 static JSStaticFunction Instance_staticFunctions[5] = {
2266 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2267 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2268 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2269 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2273 static JSStaticFunction Internal_staticFunctions[2] = {
2274 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2278 static JSStaticFunction Selector_staticFunctions[5] = {
2279 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2280 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2281 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2282 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2286 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2287 apr_pool_t *pool(CYGetGlobalPool());
2289 Object_type = new(pool) Type_privateData("@");
2290 Selector_type = new(pool) Type_privateData(":");
2293 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2294 NSCFType_ = objc_getClass("NSCFType");
2295 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2296 NSZombie_ = objc_getClass("_NSZombie_");
2298 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2301 NSArray_ = objc_getClass("NSArray");
2302 NSDictionary_ = objc_getClass("NSDictionary");
2303 Object_ = objc_getClass("Object");
2305 JSClassDefinition definition;
2307 definition = kJSClassDefinitionEmpty;
2308 definition.className = "Instance";
2309 definition.staticValues = Instance_staticValues;
2310 definition.staticFunctions = Instance_staticFunctions;
2311 definition.hasProperty = &Instance_hasProperty;
2312 definition.getProperty = &Instance_getProperty;
2313 definition.setProperty = &Instance_setProperty;
2314 definition.deleteProperty = &Instance_deleteProperty;
2315 definition.getPropertyNames = &Instance_getPropertyNames;
2316 definition.callAsConstructor = &Instance_callAsConstructor;
2317 definition.hasInstance = &Instance_hasInstance;
2318 definition.finalize = &CYFinalize;
2319 Instance_ = JSClassCreate(&definition);
2321 definition = kJSClassDefinitionEmpty;
2322 definition.className = "Internal";
2323 definition.staticFunctions = Internal_staticFunctions;
2324 definition.hasProperty = &Internal_hasProperty;
2325 definition.getProperty = &Internal_getProperty;
2326 definition.setProperty = &Internal_setProperty;
2327 definition.getPropertyNames = &Internal_getPropertyNames;
2328 definition.finalize = &CYFinalize;
2329 Internal_ = JSClassCreate(&definition);
2331 definition = kJSClassDefinitionEmpty;
2332 definition.className = "Message";
2333 definition.staticFunctions = cy::Functor::StaticFunctions;
2334 definition.callAsFunction = &Message_callAsFunction;
2335 definition.finalize = &CYFinalize;
2336 Message_ = JSClassCreate(&definition);
2338 definition = kJSClassDefinitionEmpty;
2339 definition.className = "Messages";
2340 definition.hasProperty = &Messages_hasProperty;
2341 definition.getProperty = &Messages_getProperty;
2342 definition.setProperty = &Messages_setProperty;
2343 #if 0 && OBJC_API_VERSION < 2
2344 definition.deleteProperty = &Messages_deleteProperty;
2346 definition.getPropertyNames = &Messages_getPropertyNames;
2347 definition.finalize = &CYFinalize;
2348 Messages_ = JSClassCreate(&definition);
2350 definition = kJSClassDefinitionEmpty;
2351 definition.className = "Selector";
2352 definition.staticValues = Selector_staticValues;
2353 definition.staticFunctions = Selector_staticFunctions;
2354 definition.callAsFunction = &Selector_callAsFunction;
2355 definition.finalize = &CYFinalize;
2356 Selector_ = JSClassCreate(&definition);
2358 definition = kJSClassDefinitionEmpty;
2359 definition.className = "Super";
2360 definition.staticFunctions = Internal_staticFunctions;
2361 definition.finalize = &CYFinalize;
2362 Super_ = JSClassCreate(&definition);
2364 definition = kJSClassDefinitionEmpty;
2365 definition.className = "ObjectiveC::Classes";
2366 definition.getProperty = &ObjectiveC_Classes_getProperty;
2367 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2368 ObjectiveC_Classes_ = JSClassCreate(&definition);
2370 #if OBJC_API_VERSION >= 2
2371 definition = kJSClassDefinitionEmpty;
2372 definition.className = "ObjectiveC::Images";
2373 definition.getProperty = &ObjectiveC_Images_getProperty;
2374 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2375 ObjectiveC_Images_ = JSClassCreate(&definition);
2377 definition = kJSClassDefinitionEmpty;
2378 definition.className = "ObjectiveC::Image::Classes";
2379 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2380 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2381 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2384 definition = kJSClassDefinitionEmpty;
2385 definition.className = "ObjectiveC::Protocols";
2386 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2387 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2388 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2390 #if defined(__APPLE__) && defined(__arm__)
2391 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2395 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2399 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2400 JSObjectRef global(CYGetGlobalObject(context));
2401 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2403 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2404 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC);
2406 CYSetProperty(context, ObjectiveC, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2407 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2409 #if OBJC_API_VERSION >= 2
2410 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2413 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2414 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2415 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2416 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2418 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2419 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2421 CYSetProperty(context, global, CYJSString("Instance"), Instance);
2422 CYSetProperty(context, global, CYJSString("Selector"), Selector);
2423 CYSetProperty(context, global, CYJSString("Super"), Super);
2425 #if defined(__APPLE__) && defined(__arm__)
2426 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2429 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2431 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2432 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2433 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2436 static CYHooks CYObjectiveCHooks = {
2437 &CYObjectiveC_ExecuteStart,
2438 &CYObjectiveC_ExecuteEnd,
2439 &CYObjectiveC_RuntimeProperty,
2440 &CYObjectiveC_CallFunction,
2441 &CYObjectiveC_Initialize,
2442 &CYObjectiveC_SetupContext,
2443 &CYObjectiveC_PoolFFI,
2444 &CYObjectiveC_FromFFI,
2447 struct CYObjectiveC {
2449 hooks_ = &CYObjectiveCHooks;