1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2010 Jay Freeman (saurik)
5 /* GNU Lesser General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
26 #include <Foundation/Foundation.h>
28 #include "ObjectiveC/Internal.hpp"
30 #include <objc/objc-api.h>
32 #include "cycript.hpp"
34 #include "ObjectiveC/Internal.hpp"
37 #include <CoreFoundation/CoreFoundation.h>
38 #include <JavaScriptCore/JSStringRefCF.h>
39 #include <WebKit/WebScriptObject.h>
40 #include <objc/runtime.h>
44 #include "JavaScript.hpp"
46 #include "Execute.hpp"
51 #define CYObjectiveTry_(context) { \
52 JSContextRef context_(context); \
54 #define CYObjectiveTry { \
56 #define CYObjectiveCatch \
57 catch (const CYException &error) { \
58 @throw CYCastNSObject(NULL, context_, error.CastJSValue(context_)); \
64 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
66 #define CYPoolCatch(value) \
67 @catch (NSException *error) { \
68 _saved = [error retain]; \
69 throw CYJSError(context, CYCastJSValue(context, error)); \
74 [_saved autorelease]; \
80 #define CYSadCatch(value) \
81 @catch (NSException *error ) { \
82 throw CYJSError(context, CYCastJSValue(context, error)); \
87 #define class_getSuperclass GSObjCSuper
88 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
89 #define class_getName GSNameFromClass
91 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
93 #define ivar_getName(ivar) ((ivar)->ivar_name)
94 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
95 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
97 #define method_getName(method) ((method)->method_name)
98 #define method_getImplementation(method) ((method)->method_imp)
99 #define method_getTypeEncoding(method) ((method)->method_types)
100 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
103 #define objc_getClass GSClassFromName
105 #define objc_getProtocol GSProtocolFromName
107 #define object_getClass GSObjCClass
109 #define object_getInstanceVariable(object, name, value) ({ \
110 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
111 _assert(value != NULL); \
113 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
117 #define object_setIvar(object, ivar, value) ({ \
118 void *data = (value); \
119 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
122 #define protocol_getName(protocol) [(protocol) name]
125 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception);
127 /* Objective-C Pool Release {{{ */
128 apr_status_t CYPoolRelease_(void *data) {
129 id object(reinterpret_cast<id>(data));
134 id CYPoolRelease_(apr_pool_t *pool, id object) {
137 else if (pool == NULL)
138 return [object autorelease];
140 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
145 template <typename Type_>
146 Type_ CYPoolRelease(apr_pool_t *pool, Type_ object) {
147 return (Type_) CYPoolRelease_(pool, (id) object);
150 /* Objective-C Strings {{{ */
151 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, NSString *value) {
153 return [value UTF8String];
155 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
156 char *string(new(pool) char[size]);
157 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
158 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
163 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
165 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
168 return CYCopyJSString(CYPoolCString(pool, context, value));
172 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
175 // XXX: this definition scares me; is anyone using this?!
176 NSString *string([value description]);
177 return CYCopyJSString(context, string);
180 NSString *CYCopyNSString(const CYUTF8String &value) {
182 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
184 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
188 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
190 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
193 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
197 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
198 return CYCopyNSString(context, CYJSString(context, value));
201 NSString *CYCastNSString(apr_pool_t *pool, const CYUTF8String &value) {
202 return CYPoolRelease(pool, CYCopyNSString(value));
205 NSString *CYCastNSString(apr_pool_t *pool, SEL sel) {
206 const char *name(sel_getName(sel));
207 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
210 NSString *CYCastNSString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
211 return CYPoolRelease(pool, CYCopyNSString(context, value));
214 CYUTF8String CYCastUTF8String(NSString *value) {
215 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
216 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
220 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
222 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
223 if (exception == NULL)
225 *exception = CYCastJSValue(context, error);
228 size_t CYGetIndex(NSString *value) {
229 return CYGetIndex(CYCastUTF8String(value));
232 bool CYGetOffset(apr_pool_t *pool, JSContextRef context, NSString *value, ssize_t &index) {
233 return CYGetOffset(CYPoolCString(pool, context, value), index);
236 static JSClassRef Instance_;
237 static JSClassRef Internal_;
238 static JSClassRef Message_;
239 static JSClassRef Messages_;
240 static JSClassRef Selector_;
241 static JSClassRef Super_;
243 static JSClassRef ObjectiveC_Classes_;
244 static JSClassRef ObjectiveC_Constants_;
245 static JSClassRef ObjectiveC_Protocols_;
248 static JSClassRef ObjectiveC_Image_Classes_;
249 static JSClassRef ObjectiveC_Images_;
253 static Class NSCFBoolean_;
254 static Class NSCFType_;
255 static Class NSGenericDeallocHandler_;
256 static Class NSMessageBuilder_;
257 static Class NSZombie_;
259 static Class NSBoolNumber_;
262 static Class NSArray_;
263 static Class NSDictionary_;
264 static Class NSString_;
265 static Class Object_;
267 static Type_privateData *Object_type;
268 static Type_privateData *Selector_type;
270 Type_privateData *Instance::GetType() const {
274 Type_privateData *Selector_privateData::GetType() const {
275 return Selector_type;
278 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
280 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
282 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
284 JSObjectRef global(CYGetGlobalObject(context));
285 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
288 sprintf(label, "i%p", self);
289 CYJSString name(label);
291 JSValueRef value(CYGetProperty(context, cy, name));
292 if (!JSValueIsUndefined(context, value))
295 JSClassRef _class(NULL);
296 JSValueRef prototype;
298 if (self == NSArray_)
299 prototype = CYGetCachedObject(context, CYJSString("Array_prototype"));
300 else if (self == NSDictionary_)
301 prototype = CYGetCachedObject(context, CYJSString("Object_prototype"));
302 else if (self == NSString_)
303 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
305 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
307 JSObjectRef object(JSObjectMake(context, _class, NULL));
308 JSObjectSetPrototype(context, object, prototype);
309 CYSetProperty(context, cy, name, object);
314 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
315 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
316 if (_class == NSArray_)
318 if (Class super = class_getSuperclass(_class))
319 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
321 JSObjectSetPrototype(context, value, Array_prototype_);*/
325 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
326 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
330 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
331 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
335 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
336 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
337 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
341 Instance::~Instance() {
342 if ((flags_ & Transient) == 0)
343 // XXX: does this handle background threads correctly?
344 // XXX: this simply does not work on the console because I'm stupid
345 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
348 struct Message_privateData :
353 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
354 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
360 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
361 Instance::Flags flags;
364 flags = Instance::Transient;
366 flags = Instance::None;
367 object = [object retain];
370 return Instance::Make(context, object, flags);
373 @interface NSMethodSignature (Cycript)
374 - (NSString *) _typeString;
377 @interface NSObject (Cycript)
379 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
380 - (JSType) cy$JSType;
382 - (NSObject *) cy$toJSON:(NSString *)key;
383 - (NSString *) cy$toCYON;
384 - (NSString *) cy$toKey;
386 - (bool) cy$hasProperty:(NSString *)name;
387 - (NSObject *) cy$getProperty:(NSString *)name;
388 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
389 - (bool) cy$deleteProperty:(NSString *)name;
390 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
392 + (bool) cy$hasImplicitProperties;
397 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
400 NSString *CYCastNSCYON(id value) {
406 Class _class(object_getClass(value));
407 SEL sel(@selector(cy$toCYON));
409 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
410 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
411 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
412 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
413 string = [value cy$toCYON];
418 else if (value == NSZombie_)
419 string = @"_NSZombie_";
420 else if (_class == NSZombie_)
421 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
422 // XXX: frowny /in/ the pants
423 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
427 string = [NSString stringWithFormat:@"%@", value];
432 string = @"undefined";
439 struct PropertyAttributes {
444 const char *variable;
457 PropertyAttributes(objc_property_t property) :
469 name = property_getName(property);
470 const char *attributes(property_getAttributes(property));
472 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
474 case 'R': readonly = true; break;
475 case 'C': copy = true; break;
476 case '&': retain = true; break;
477 case 'N': nonatomic = true; break;
478 case 'G': getter_ = token + 1; break;
479 case 'S': setter_ = token + 1; break;
480 case 'V': variable = token + 1; break;
484 /*if (variable == NULL) {
485 variable = property_getName(property);
486 size_t size(strlen(variable));
487 char *name(new(pool_) char[size + 2]);
489 memcpy(name + 1, variable, size);
490 name[size + 1] = '\0';
495 const char *Getter() {
497 getter_ = apr_pstrdup(pool_, name);
501 const char *Setter() {
502 if (setter_ == NULL && !readonly) {
503 size_t length(strlen(name));
505 char *temp(new(pool_) char[length + 5]);
511 temp[3] = toupper(name[0]);
512 memcpy(temp + 4, name + 1, length - 1);
515 temp[length + 3] = ':';
516 temp[length + 4] = '\0';
527 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
528 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
533 @interface CYWebUndefined : NSObject {
536 + (CYWebUndefined *) undefined;
540 @implementation CYWebUndefined
542 + (CYWebUndefined *) undefined {
543 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
549 #define WebUndefined CYWebUndefined
552 /* Bridge: CYJSObject {{{ */
553 @interface CYJSObject : NSMutableDictionary {
555 JSContextRef context_;
558 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
560 - (NSObject *) cy$toJSON:(NSString *)key;
562 - (NSUInteger) count;
563 - (id) objectForKey:(id)key;
564 - (NSEnumerator *) keyEnumerator;
565 - (void) setObject:(id)object forKey:(id)key;
566 - (void) removeObjectForKey:(id)key;
570 /* Bridge: CYJSArray {{{ */
571 @interface CYJSArray : NSMutableArray {
573 JSContextRef context_;
576 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
578 - (NSUInteger) count;
579 - (id) objectAtIndex:(NSUInteger)index;
581 - (void) addObject:(id)anObject;
582 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
583 - (void) removeLastObject;
584 - (void) removeObjectAtIndex:(NSUInteger)index;
585 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
590 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
591 JSObjectRef Array(CYGetCachedObject(context, Array_s));
592 JSValueRef exception(NULL);
593 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
594 CYThrow(context, exception);
595 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
596 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
599 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
600 if (!JSValueIsObjectOfClass(context, object, Instance_))
601 return CYCastNSObject_(pool, context, object);
603 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
604 return internal->GetValue();
608 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
609 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
613 @interface NSBoolNumber : NSNumber {
618 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
622 switch (JSType type = JSValueGetType(context, value)) {
623 case kJSTypeUndefined:
624 object = [WebUndefined undefined];
634 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
637 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
643 object = CYCopyNSNumber(context, value);
648 object = CYCopyNSString(context, value);
653 // XXX: this might could be more efficient
654 object = CYCastNSObject(pool, context, (JSObjectRef) value);
659 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
666 return CYPoolRelease(pool, object);
668 return [object retain];
671 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
672 return CYNSObject(pool, context, value, true);
675 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
676 return CYNSObject(pool, context, value, false);
679 /* Bridge: NSArray {{{ */
680 @implementation NSArray (Cycript)
682 - (NSString *) cy$toCYON {
683 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
684 [json appendString:@"["];
688 for (id object in self) {
690 for (size_t index(0), count([self count]); index != count; ++index) {
691 id object([self objectAtIndex:index]);
694 [json appendString:@","];
697 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
698 [json appendString:CYCastNSCYON(object)];
700 [json appendString:@","];
705 [json appendString:@"]"];
709 - (bool) cy$hasProperty:(NSString *)name {
710 if ([name isEqualToString:@"length"])
713 size_t index(CYGetIndex(name));
714 if (index == _not(size_t) || index >= [self count])
715 return [super cy$hasProperty:name];
720 - (NSObject *) cy$getProperty:(NSString *)name {
721 if ([name isEqualToString:@"length"]) {
722 NSUInteger count([self count]);
724 return [NSNumber numberWithUnsignedInteger:count];
726 return [NSNumber numberWithUnsignedInt:count];
730 size_t index(CYGetIndex(name));
731 if (index == _not(size_t) || index >= [self count])
732 return [super cy$getProperty:name];
734 return [self objectAtIndex:index];
737 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
738 [super cy$getPropertyNames:names inContext:context];
740 for (size_t index(0), count([self count]); index != count; ++index) {
741 id object([self objectAtIndex:index]);
742 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
744 sprintf(name, "%zu", index);
745 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
750 + (bool) cy$hasImplicitProperties {
756 /* Bridge: NSBoolNumber {{{ */
758 @implementation NSBoolNumber (Cycript)
760 - (JSType) cy$JSType {
761 return kJSTypeBoolean;
764 - (NSObject *) cy$toJSON:(NSString *)key {
768 - (NSString *) cy$toCYON {
769 return [self boolValue] ? @"true" : @"false";
772 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
773 return CYCastJSValue(context, (bool) [self boolValue]);
779 /* Bridge: NSDictionary {{{ */
780 @implementation NSDictionary (Cycript)
782 - (NSString *) cy$toCYON {
783 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
784 [json appendString:@"{"];
788 for (NSObject *key in self) {
790 NSEnumerator *keys([self keyEnumerator]);
791 while (NSObject *key = [keys nextObject]) {
794 [json appendString:@","];
797 [json appendString:[key cy$toKey]];
798 [json appendString:@":"];
799 NSObject *object([self objectForKey:key]);
800 [json appendString:CYCastNSCYON(object)];
803 [json appendString:@"}"];
807 - (bool) cy$hasProperty:(NSString *)name {
808 return [self objectForKey:name] != nil;
811 - (NSObject *) cy$getProperty:(NSString *)name {
812 return [self objectForKey:name];
815 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
816 [super cy$getPropertyNames:names inContext:context];
819 for (NSObject *key in self) {
821 NSEnumerator *keys([self keyEnumerator]);
822 while (NSObject *key = [keys nextObject]) {
824 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
828 + (bool) cy$hasImplicitProperties {
834 /* Bridge: NSMutableArray {{{ */
835 @implementation NSMutableArray (Cycript)
837 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
838 if ([name isEqualToString:@"length"]) {
839 // XXX: is this not intelligent?
840 NSNumber *number(reinterpret_cast<NSNumber *>(value));
842 NSUInteger size([number unsignedIntegerValue]);
844 NSUInteger size([number unsignedIntValue]);
846 NSUInteger count([self count]);
848 [self removeObjectsInRange:NSMakeRange(size, count - size)];
849 else if (size != count) {
850 WebUndefined *undefined([WebUndefined undefined]);
851 for (size_t i(count); i != size; ++i)
852 [self addObject:undefined];
857 size_t index(CYGetIndex(name));
858 if (index == _not(size_t))
859 return [super cy$setProperty:name to:value];
861 id object(value ?: [NSNull null]);
863 size_t count([self count]);
865 [self replaceObjectAtIndex:index withObject:object];
867 if (index != count) {
868 WebUndefined *undefined([WebUndefined undefined]);
869 for (size_t i(count); i != index; ++i)
870 [self addObject:undefined];
873 [self addObject:object];
879 - (bool) cy$deleteProperty:(NSString *)name {
880 size_t index(CYGetIndex(name));
881 if (index == _not(size_t) || index >= [self count])
882 return [super cy$deleteProperty:name];
883 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
889 /* Bridge: NSMutableDictionary {{{ */
890 @implementation NSMutableDictionary (Cycript)
892 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
893 [self setObject:(value ?: [NSNull null]) forKey:name];
897 - (bool) cy$deleteProperty:(NSString *)name {
898 if ([self objectForKey:name] == nil)
901 [self removeObjectForKey:name];
908 /* Bridge: NSNumber {{{ */
909 @implementation NSNumber (Cycript)
911 - (JSType) cy$JSType {
913 // XXX: this just seems stupid
914 if ([self class] == NSCFBoolean_)
915 return kJSTypeBoolean;
917 return kJSTypeNumber;
920 - (NSObject *) cy$toJSON:(NSString *)key {
924 - (NSString *) cy$toCYON {
925 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
928 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
929 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
934 /* Bridge: NSNull {{{ */
935 @implementation NSNull (Cycript)
937 - (JSType) cy$JSType {
941 - (NSObject *) cy$toJSON:(NSString *)key {
945 - (NSString *) cy$toCYON {
951 /* Bridge: NSObject {{{ */
952 @implementation NSObject (Cycript)
954 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
955 return CYMakeInstance(context, self, false);
958 - (JSType) cy$JSType {
959 return kJSTypeObject;
962 - (NSObject *) cy$toJSON:(NSString *)key {
963 return [self description];
966 - (NSString *) cy$toCYON {
967 return [[self cy$toJSON:@""] cy$toCYON];
970 - (NSString *) cy$toKey {
971 return [self cy$toCYON];
974 - (bool) cy$hasProperty:(NSString *)name {
978 - (NSObject *) cy$getProperty:(NSString *)name {
982 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
986 - (bool) cy$deleteProperty:(NSString *)name {
990 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
993 + (bool) cy$hasImplicitProperties {
999 /* Bridge: NSProxy {{{ */
1000 @implementation NSProxy (Cycript)
1002 - (NSObject *) cy$toJSON:(NSString *)key {
1003 return [self description];
1006 - (NSString *) cy$toCYON {
1007 return [[self cy$toJSON:@""] cy$toCYON];
1012 /* Bridge: NSString {{{ */
1013 @implementation NSString (Cycript)
1015 - (JSType) cy$JSType {
1016 return kJSTypeString;
1019 - (NSObject *) cy$toJSON:(NSString *)key {
1023 - (NSString *) cy$toCYON {
1024 std::ostringstream str;
1025 CYUTF8String string(CYCastUTF8String(self));
1026 CYStringify(str, string.data, string.size);
1027 std::string value(str.str());
1028 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1031 - (NSString *) cy$toKey {
1032 if (CYIsKey(CYCastUTF8String(self)))
1034 return [self cy$toCYON];
1037 - (bool) cy$hasProperty:(NSString *)name {
1038 if ([name isEqualToString:@"length"])
1041 size_t index(CYGetIndex(name));
1042 if (index == _not(size_t) || index >= [self length])
1043 return [super cy$hasProperty:name];
1048 - (NSObject *) cy$getProperty:(NSString *)name {
1049 if ([name isEqualToString:@"length"]) {
1050 NSUInteger count([self length]);
1052 return [NSNumber numberWithUnsignedInteger:count];
1054 return [NSNumber numberWithUnsignedInt:count];
1058 size_t index(CYGetIndex(name));
1059 if (index == _not(size_t) || index >= [self length])
1060 return [super cy$getProperty:name];
1062 return [self substringWithRange:NSMakeRange(index, 1)];
1065 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1066 [super cy$getPropertyNames:names inContext:context];
1068 for (size_t index(0), length([self length]); index != length; ++index) {
1070 sprintf(name, "%zu", index);
1071 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1075 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1076 + (bool) cy$hasImplicitProperties {
1082 /* Bridge: WebUndefined {{{ */
1083 @implementation WebUndefined (Cycript)
1085 - (JSType) cy$JSType {
1086 return kJSTypeUndefined;
1089 - (NSObject *) cy$toJSON:(NSString *)key {
1093 - (NSString *) cy$toCYON {
1094 return @"undefined";
1097 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1098 return CYJSUndefined(context);
1099 } CYObjectiveCatch }
1104 static bool CYIsClass(id self) {
1106 // XXX: this is a lame object_isClass
1107 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1109 return GSObjCIsClass(self);
1113 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1114 id self(CYCastNSObject(pool, context, value));
1115 if (CYIsClass(self))
1116 return (Class) self;
1117 throw CYJSError(context, "got something that is not a Class");
1121 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1123 size_t size(JSPropertyNameArrayGetCount(names));
1124 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1125 for (size_t index(0); index != size; ++index)
1126 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1130 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1132 return CYJSNull(context);
1133 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1134 return [value cy$JSValueInContext:context];
1136 return CYMakeInstance(context, value, false);
1137 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1139 @implementation CYJSObject
1141 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1142 if ((self = [super init]) != nil) {
1144 context_ = CYGetJSContext(context);
1145 //XXX:JSGlobalContextRetain(context_);
1146 JSValueProtect(context_, object_);
1148 } CYObjectiveCatch }
1150 - (void) dealloc { CYObjectiveTry {
1151 JSValueUnprotect(context_, object_);
1152 //XXX:JSGlobalContextRelease(context_);
1154 } CYObjectiveCatch }
1156 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1157 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1158 if (!CYIsCallable(context_, toJSON))
1159 return [super cy$toJSON:key];
1161 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1162 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1163 // XXX: do I really want an NSNull here?!
1164 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1166 } CYObjectiveCatch }
1168 - (NSString *) cy$toCYON { CYObjectiveTry {
1170 JSValueRef exception(NULL);
1171 const char *cyon(CYPoolCCYON(pool, context_, object_));
1172 CYThrow(context_, exception);
1174 return [super cy$toCYON];
1176 return [NSString stringWithUTF8String:cyon];
1177 } CYObjectiveCatch }
1179 - (NSUInteger) count { CYObjectiveTry {
1180 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1181 size_t size(JSPropertyNameArrayGetCount(names));
1182 JSPropertyNameArrayRelease(names);
1184 } CYObjectiveCatch }
1186 - (id) objectForKey:(id)key { CYObjectiveTry {
1187 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1188 if (JSValueIsUndefined(context_, value))
1190 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1191 } CYObjectiveCatch }
1193 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1194 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1195 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1196 JSPropertyNameArrayRelease(names);
1198 } CYObjectiveCatch }
1200 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1201 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1202 } CYObjectiveCatch }
1204 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1205 JSValueRef exception(NULL);
1206 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1207 CYThrow(context_, exception);
1208 } CYObjectiveCatch }
1212 @implementation CYJSArray
1214 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1215 if ((self = [super init]) != nil) {
1217 context_ = CYGetJSContext(context);
1218 //XXX:JSGlobalContextRetain(context_);
1219 JSValueProtect(context_, object_);
1221 } CYObjectiveCatch }
1223 - (void) dealloc { CYObjectiveTry {
1224 JSValueUnprotect(context_, object_);
1225 //XXX:JSGlobalContextRelease(context_);
1227 } CYObjectiveCatch }
1229 - (NSUInteger) count { CYObjectiveTry {
1230 return CYArrayLength(context_, object_);
1231 } CYObjectiveCatch }
1233 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1234 size_t bounds([self count]);
1235 if (index >= bounds)
1236 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1237 JSValueRef exception(NULL);
1238 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1239 CYThrow(context_, exception);
1240 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1241 } CYObjectiveCatch }
1243 - (void) addObject:(id)object { CYObjectiveTry {
1244 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1245 } CYObjectiveCatch }
1247 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1248 size_t bounds([self count] + 1);
1249 if (index >= bounds)
1250 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1251 JSValueRef exception(NULL);
1252 JSValueRef arguments[3];
1253 arguments[0] = CYCastJSValue(context_, index);
1254 arguments[1] = CYCastJSValue(context_, 0);
1255 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1256 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1257 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1258 CYThrow(context_, exception);
1259 } CYObjectiveCatch }
1261 - (void) removeLastObject { CYObjectiveTry {
1262 JSValueRef exception(NULL);
1263 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1264 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1265 CYThrow(context_, exception);
1266 } CYObjectiveCatch }
1268 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1269 size_t bounds([self count]);
1270 if (index >= bounds)
1271 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1272 JSValueRef exception(NULL);
1273 JSValueRef arguments[2];
1274 arguments[0] = CYCastJSValue(context_, index);
1275 arguments[1] = CYCastJSValue(context_, 1);
1276 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1277 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1278 CYThrow(context_, exception);
1279 } CYObjectiveCatch }
1281 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1282 size_t bounds([self count]);
1283 if (index >= bounds)
1284 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1285 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1286 } CYObjectiveCatch }
1290 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1294 JSObjectRef object_;
1302 // XXX: delete object_? ;(
1305 static CYInternal *Get(id self) {
1306 CYInternal *internal(NULL);
1307 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1308 // XXX: do something epic? ;P
1314 static CYInternal *Set(id self) {
1315 CYInternal *internal(NULL);
1316 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1317 if (internal == NULL) {
1318 internal = new CYInternal();
1319 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1322 // XXX: do something epic? ;P
1328 bool HasProperty(JSContextRef context, JSStringRef name) {
1329 if (object_ == NULL)
1331 return JSObjectHasProperty(context, object_, name);
1334 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1335 if (object_ == NULL)
1337 return CYGetProperty(context, object_, name);
1340 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1341 if (object_ == NULL)
1342 object_ = JSObjectMake(context, NULL, NULL);
1343 CYSetProperty(context, object_, name, value);
1347 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1348 Selector_privateData *internal(new Selector_privateData(sel));
1349 return JSObjectMake(context, Selector_, internal);
1352 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1353 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1354 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1355 return reinterpret_cast<SEL>(internal->value_);
1357 return CYCastPointer<SEL>(context, value);
1360 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1361 return (void *) [[NSAutoreleasePool alloc] init];
1362 } CYSadCatch(NULL) }
1364 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1365 return [(NSAutoreleasePool *) handle release];
1368 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1370 return Instance::Make(context, nil);
1371 if (Class _class = objc_getClass(name.data))
1372 return CYMakeInstance(context, _class, true);
1373 if (Protocol *protocol = objc_getProtocol(name.data))
1374 return CYMakeInstance(context, protocol, true);
1376 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1378 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1379 ffi_call(cif, function, value, values);
1382 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1383 switch (type->primitive) {
1384 // XXX: do something epic about blocks
1387 case sig::typename_P:
1388 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1391 case sig::selector_P:
1392 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1400 } CYSadCatch(false) }
1402 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1403 switch (type->primitive) {
1404 // XXX: do something epic about blocks
1407 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1408 JSValueRef value(CYCastJSValue(context, object));
1414 case sig::typename_P:
1415 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1417 case sig::selector_P:
1418 if (SEL sel = *reinterpret_cast<SEL *>(data))
1419 return CYMakeSelector(context, sel);
1423 return CYJSNull(context);
1427 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1429 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1430 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1433 #if OBJC_API_VERSION >= 2
1435 method_getReturnType(method, type, sizeof(type));
1437 const char *type(method_getTypeEncoding(method));
1443 // XXX: possibly use a more "awesome" check?
1447 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1449 return method_getTypeEncoding(method);
1451 const char *name(sel_getName(sel));
1452 size_t length(strlen(name));
1454 char keyed[length + 2];
1456 keyed[length + 1] = '\0';
1457 memcpy(keyed + 1, name, length);
1459 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1460 return entry->value_;
1465 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1466 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1468 JSContextRef context(internal->context_);
1470 size_t count(internal->cif_.nargs);
1471 JSValueRef values[count];
1473 for (size_t index(0); index != count; ++index)
1474 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1476 JSObjectRef _this(CYCastJSObject(context, values[0]));
1478 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1479 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1482 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1483 Message_privateData *internal(new Message_privateData(sel, type, imp));
1484 return JSObjectMake(context, Message_, internal);
1487 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1488 JSObjectRef function(CYCastJSObject(context, value));
1489 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1490 // XXX: see notes in Library.cpp about needing to leak
1491 return reinterpret_cast<IMP>(internal->GetValue());
1494 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1495 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1496 Class _class(internal->GetValue());
1499 const char *name(CYPoolCString(pool, context, property));
1501 if (SEL sel = sel_getUid(name))
1502 if (class_getInstanceMethod(_class, sel) != NULL)
1508 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1509 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1510 Class _class(internal->GetValue());
1513 const char *name(CYPoolCString(pool, context, property));
1515 if (SEL sel = sel_getUid(name))
1516 if (objc_method *method = class_getInstanceMethod(_class, sel))
1517 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1522 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1523 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1524 Class _class(internal->GetValue());
1527 const char *name(CYPoolCString(pool, context, property));
1529 SEL sel(sel_registerName(name));
1531 objc_method *method(class_getInstanceMethod(_class, sel));
1536 if (JSValueIsObjectOfClass(context, value, Message_)) {
1537 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1538 type = sig::Unparse(pool, &message->signature_);
1539 imp = reinterpret_cast<IMP>(message->GetValue());
1541 type = CYPoolTypeEncoding(pool, context, sel, method);
1542 imp = CYMakeMessage(context, value, type);
1546 method_setImplementation(method, imp);
1549 GSMethodList list(GSAllocMethodList(1));
1550 GSAppendMethodToList(list, sel, type, imp, YES);
1551 GSAddMethodList(_class, list, YES);
1552 GSFlushMethodCacheForClass(_class);
1554 class_addMethod(_class, sel, imp, type);
1561 #if 0 && OBJC_API_VERSION < 2
1562 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1563 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1564 Class _class(internal->GetValue());
1567 const char *name(CYPoolCString(pool, context, property));
1569 if (SEL sel = sel_getUid(name))
1570 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1571 objc_method_list list = {NULL, 1, {method}};
1572 class_removeMethods(_class, &list);
1580 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1581 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1582 Class _class(internal->GetValue());
1584 #if OBJC_API_VERSION >= 2
1586 objc_method **data(class_copyMethodList(_class, &size));
1587 for (size_t i(0); i != size; ++i)
1588 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1591 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1592 for (int i(0); i != methods->method_count; ++i)
1593 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1597 static bool CYHasImplicitProperties(Class _class) {
1598 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1599 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1601 return [_class cy$hasImplicitProperties];
1604 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1606 id self(internal->GetValue());
1608 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1612 NSString *name(CYCastNSString(pool, context, property));
1614 if (CYInternal *internal = CYInternal::Get(self))
1615 if (internal->HasProperty(context, property))
1618 Class _class(object_getClass(self));
1621 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1622 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1623 if ([self cy$hasProperty:name])
1625 } CYPoolCatch(false)
1627 const char *string(CYPoolCString(pool, context, name));
1630 if (class_getProperty(_class, string) != NULL)
1634 if (CYHasImplicitProperties(_class))
1635 if (SEL sel = sel_getUid(string))
1636 if (CYImplements(self, _class, sel, true))
1642 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1643 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1644 id self(internal->GetValue());
1646 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1647 return Internal::Make(context, self, object);
1650 NSString *name(CYCastNSString(pool, context, property));
1652 if (CYInternal *internal = CYInternal::Get(self))
1653 if (JSValueRef value = internal->GetProperty(context, property))
1657 if (NSObject *data = [self cy$getProperty:name])
1658 return CYCastJSValue(context, data);
1661 const char *string(CYPoolCString(pool, context, name));
1662 Class _class(object_getClass(self));
1665 if (objc_property_t property = class_getProperty(_class, string)) {
1666 PropertyAttributes attributes(property);
1667 SEL sel(sel_registerName(attributes.Getter()));
1668 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1672 if (CYHasImplicitProperties(_class))
1673 if (SEL sel = sel_getUid(string))
1674 if (CYImplements(self, _class, sel, true))
1675 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1680 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1681 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1682 id self(internal->GetValue());
1686 NSString *name(CYCastNSString(pool, context, property));
1687 NSObject *data(CYCastNSObject(pool, context, value));
1690 if ([self cy$setProperty:name to:data])
1694 const char *string(CYPoolCString(pool, context, name));
1695 Class _class(object_getClass(self));
1698 if (objc_property_t property = class_getProperty(_class, string)) {
1699 PropertyAttributes attributes(property);
1700 if (const char *setter = attributes.Setter()) {
1701 SEL sel(sel_registerName(setter));
1702 JSValueRef arguments[1] = {value};
1703 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1709 size_t length(strlen(string));
1711 char set[length + 5];
1717 if (string[0] != '\0') {
1718 set[3] = toupper(string[0]);
1719 memcpy(set + 4, string + 1, length - 1);
1722 set[length + 3] = ':';
1723 set[length + 4] = '\0';
1725 if (SEL sel = sel_getUid(set))
1726 if (CYImplements(self, _class, sel, false)) {
1727 JSValueRef arguments[1] = {value};
1728 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1731 if (CYInternal *internal = CYInternal::Set(self)) {
1732 internal->SetProperty(context, property, value);
1739 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1740 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1741 id self(internal->GetValue());
1744 NSString *name(CYCastNSString(NULL, context, property));
1745 return [self cy$deleteProperty:name];
1747 } CYCatch return /*XXX*/ NULL; }
1749 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1750 const char *name(sel_getName(method_getName(method)));
1751 if (strchr(name, ':') != NULL)
1754 const char *type(method_getTypeEncoding(method));
1755 if (type == NULL || *type == '\0' || *type == 'v')
1758 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1761 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1762 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1763 id self(internal->GetValue());
1766 Class _class(object_getClass(self));
1771 objc_property_t *data(class_copyPropertyList(_class, &size));
1772 for (size_t i(0); i != size; ++i)
1773 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1778 if (CYHasImplicitProperties(_class))
1779 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1780 #if OBJC_API_VERSION >= 2
1782 objc_method **data(class_copyMethodList(current, &size));
1783 for (size_t i(0); i != size; ++i)
1784 Instance_getPropertyNames_message(names, data[i]);
1787 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1788 for (int i(0); i != methods->method_count; ++i)
1789 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1794 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1795 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1796 [self cy$getPropertyNames:names inContext:context];
1800 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1801 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1802 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1806 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1807 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1808 Class _class(internal->GetValue());
1809 if (!CYIsClass(_class))
1812 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1813 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1814 // XXX: this isn't always safe
1815 return [linternal->GetValue() isKindOfClass:_class];
1821 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1822 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1825 id self(internal->GetValue());
1826 const char *name(CYPoolCString(pool, context, property));
1828 if (object_getInstanceVariable(self, name, NULL) != NULL)
1834 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1835 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1838 id self(internal->GetValue());
1839 const char *name(CYPoolCString(pool, context, property));
1841 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1842 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1843 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1844 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1850 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1851 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1854 id self(internal->GetValue());
1855 const char *name(CYPoolCString(pool, context, property));
1857 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1858 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1859 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1866 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1867 if (Class super = class_getSuperclass(_class))
1868 Internal_getPropertyNames_(super, names);
1870 #if OBJC_API_VERSION >= 2
1872 objc_ivar **data(class_copyIvarList(_class, &size));
1873 for (size_t i(0); i != size; ++i)
1874 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1877 if (objc_ivar_list *ivars = _class->ivars)
1878 for (int i(0); i != ivars->ivar_count; ++i)
1879 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1883 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1884 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1887 id self(internal->GetValue());
1888 Class _class(object_getClass(self));
1890 Internal_getPropertyNames_(_class, names);
1893 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1894 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1895 return internal->GetOwner();
1898 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1900 NSString *name(CYCastNSString(pool, context, property));
1901 if (Class _class = NSClassFromString(name))
1902 return CYMakeInstance(context, _class, true);
1906 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1908 size_t size(objc_getClassList(NULL, 0));
1909 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
1912 size_t writ(objc_getClassList(data, size));
1915 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
1921 for (size_t i(0); i != writ; ++i)
1922 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
1928 while (Class _class = objc_next_class(&state))
1929 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
1933 #if OBJC_API_VERSION >= 2
1934 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1935 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1938 const char *name(CYPoolCString(pool, context, property));
1940 const char **data(objc_copyClassNamesForImage(internal, &size));
1942 for (size_t i(0); i != size; ++i)
1943 if (strcmp(name, data[i]) == 0) {
1944 if (Class _class = objc_getClass(name)) {
1945 value = CYMakeInstance(context, _class, true);
1956 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1957 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
1959 const char **data(objc_copyClassNamesForImage(internal, &size));
1960 for (size_t i(0); i != size; ++i)
1961 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1965 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1967 const char *name(CYPoolCString(pool, context, property));
1969 const char **data(objc_copyImageNames(&size));
1970 for (size_t i(0); i != size; ++i)
1971 if (strcmp(name, data[i]) == 0) {
1980 JSObjectRef value(JSObjectMake(context, NULL, NULL));
1981 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
1985 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1987 const char **data(objc_copyImageNames(&size));
1988 for (size_t i(0); i != size; ++i)
1989 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
1994 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1996 const char *name(CYPoolCString(pool, context, property));
1997 if (Protocol *protocol = objc_getProtocol(name))
1998 return CYMakeInstance(context, protocol, true);
2002 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2003 #if OBJC_API_VERSION >= 2
2005 Protocol **data(objc_copyProtocolList(&size));
2006 for (size_t i(0); i != size; ++i)
2007 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2014 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2016 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2018 return Instance::Make(context, nil);
2022 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2023 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2027 static bool stret(ffi_type *ffi_type) {
2028 return ffi_type->type == FFI_TYPE_STRUCT && (
2029 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2030 struct_forward_array[ffi_type->size] != 0
2035 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 {
2039 _class = object_getClass(self);
2043 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2044 imp = method_getImplementation(method);
2045 type = method_getTypeEncoding(method);
2050 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2052 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2053 type = CYPoolCString(pool, context, [method _typeString]);
2061 sig::Signature signature;
2062 sig::Parse(pool, &signature, type, &Structor_);
2065 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2069 if (stret(cif.rtype))
2070 imp = class_getMethodImplementation_stret(_class, _cmd);
2072 imp = class_getMethodImplementation(_class, _cmd);
2074 objc_super super = {self, _class};
2075 imp = objc_msg_lookup_super(&super, _cmd);
2079 void (*function)() = reinterpret_cast<void (*)()>(imp);
2080 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2083 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2085 throw CYJSError(context, "too few arguments to objc_msgSend");
2095 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2096 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2097 self = internal->GetValue();
2098 _class = internal->class_;;
2099 uninitialized = false;
2100 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2101 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2102 self = internal->GetValue();
2104 uninitialized = internal->IsUninitialized();
2106 internal->value_ = nil;
2108 self = CYCastNSObject(pool, context, arguments[0]);
2110 uninitialized = false;
2114 return CYJSNull(context);
2116 _cmd = CYCastSEL(context, arguments[1]);
2118 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2121 /* Hook: objc_registerClassPair {{{ */
2122 #if defined(__APPLE__) && defined(__arm__) && 0
2123 // XXX: replace this with associated objects
2125 MSHook(void, CYDealloc, id self, SEL sel) {
2126 CYInternal *internal;
2127 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2128 if (internal != NULL)
2130 _CYDealloc(self, sel);
2133 MSHook(void, objc_registerClassPair, Class _class) {
2134 Class super(class_getSuperclass(_class));
2135 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2136 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2137 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2140 _objc_registerClassPair(_class);
2143 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2145 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2147 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2148 if (value == NULL || !CYIsClass(value))
2149 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2150 Class _class((Class) value);
2151 $objc_registerClassPair(_class);
2152 return CYJSUndefined(context);
2157 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2158 JSValueRef setup[count + 2];
2161 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2162 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2165 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2167 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2169 // XXX: handle Instance::Uninitialized?
2170 id self(CYCastNSObject(pool, context, _this));
2174 setup[1] = &internal->sel_;
2176 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2179 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2181 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2183 id self(CYCastNSObject(pool, context, arguments[0]));
2184 Class _class(CYCastClass(pool, context, arguments[1]));
2185 return cy::Super::Make(context, self, _class);
2188 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2190 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2192 const char *name(CYPoolCString(pool, context, arguments[0]));
2193 return CYMakeSelector(context, sel_registerName(name));
2196 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2198 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2199 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2200 return CYMakeInstance(context, self, false);
2203 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2204 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2205 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2208 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2209 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2210 Type_privateData *typical(internal->GetType());
2215 if (typical == NULL) {
2219 type = typical->type_;
2220 ffi = typical->ffi_;
2223 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2226 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2227 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2228 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2231 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2232 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2233 id self(internal->GetValue());
2234 if (!CYIsClass(self))
2235 return CYJSUndefined(context);
2236 return CYGetClassPrototype(context, self);
2239 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2240 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2241 id self(internal->GetValue());
2242 if (!CYIsClass(self))
2243 return CYJSUndefined(context);
2244 return Messages::Make(context, (Class) self);
2247 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2248 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2251 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2252 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2255 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2256 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2259 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2266 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2267 // XXX: check for support of cy$toJSON?
2268 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2270 } CYCatch return /*XXX*/ NULL; }
2273 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2274 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2277 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2278 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2279 } CYCatch return /*XXX*/ NULL; }
2282 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2283 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2286 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2287 // XXX: but... but... THIS ISN'T A POINTER! :(
2288 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2289 } CYCatch return /*XXX*/ NULL; }
2291 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2292 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2295 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2297 id value(internal->GetValue());
2299 return CYCastJSValue(context, "nil");
2302 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2303 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() description]));
2305 } CYCatch return /*XXX*/ NULL; }
2307 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2308 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2309 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2312 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2313 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2316 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2317 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2318 const char *name(sel_getName(internal->GetValue()));
2321 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2322 return CYCastJSValue(context, CYJSString(context, string));
2324 } CYCatch return /*XXX*/ NULL; }
2326 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2328 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2331 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2332 SEL sel(internal->GetValue());
2334 objc_method *method;
2335 if (Class _class = CYCastClass(pool, context, arguments[0]))
2336 method = class_getInstanceMethod(_class, sel);
2340 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2341 return CYCastJSValue(context, CYJSString(type));
2343 return CYJSNull(context);
2346 static JSStaticValue Selector_staticValues[2] = {
2347 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2348 {NULL, NULL, NULL, 0}
2351 static JSStaticValue Instance_staticValues[5] = {
2352 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2353 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2354 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2355 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2356 {NULL, NULL, NULL, 0}
2359 static JSStaticFunction Instance_staticFunctions[6] = {
2360 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2361 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2362 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2363 //{"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2364 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2365 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2369 static JSStaticFunction Internal_staticFunctions[2] = {
2370 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2374 static JSStaticFunction Selector_staticFunctions[5] = {
2375 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2376 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2377 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2378 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2382 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2383 apr_pool_t *pool(CYGetGlobalPool());
2385 Object_type = new(pool) Type_privateData("@");
2386 Selector_type = new(pool) Type_privateData(":");
2389 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2390 NSCFType_ = objc_getClass("NSCFType");
2391 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2392 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2393 NSZombie_ = objc_getClass("_NSZombie_");
2395 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2398 NSArray_ = objc_getClass("NSArray");
2399 NSDictionary_ = objc_getClass("NSDictionary");
2400 NSString_ = objc_getClass("NSString");
2401 Object_ = objc_getClass("Object");
2403 JSClassDefinition definition;
2405 definition = kJSClassDefinitionEmpty;
2406 definition.className = "Instance";
2407 definition.staticValues = Instance_staticValues;
2408 definition.staticFunctions = Instance_staticFunctions;
2409 definition.hasProperty = &Instance_hasProperty;
2410 definition.getProperty = &Instance_getProperty;
2411 definition.setProperty = &Instance_setProperty;
2412 definition.deleteProperty = &Instance_deleteProperty;
2413 definition.getPropertyNames = &Instance_getPropertyNames;
2414 definition.callAsConstructor = &Instance_callAsConstructor;
2415 definition.hasInstance = &Instance_hasInstance;
2416 definition.finalize = &CYFinalize;
2417 Instance_ = JSClassCreate(&definition);
2419 definition = kJSClassDefinitionEmpty;
2420 definition.className = "Internal";
2421 definition.staticFunctions = Internal_staticFunctions;
2422 definition.hasProperty = &Internal_hasProperty;
2423 definition.getProperty = &Internal_getProperty;
2424 definition.setProperty = &Internal_setProperty;
2425 definition.getPropertyNames = &Internal_getPropertyNames;
2426 definition.finalize = &CYFinalize;
2427 Internal_ = JSClassCreate(&definition);
2429 definition = kJSClassDefinitionEmpty;
2430 definition.className = "Message";
2431 definition.staticFunctions = cy::Functor::StaticFunctions;
2432 definition.callAsFunction = &Message_callAsFunction;
2433 definition.finalize = &CYFinalize;
2434 Message_ = JSClassCreate(&definition);
2436 definition = kJSClassDefinitionEmpty;
2437 definition.className = "Messages";
2438 definition.hasProperty = &Messages_hasProperty;
2439 definition.getProperty = &Messages_getProperty;
2440 definition.setProperty = &Messages_setProperty;
2441 #if 0 && OBJC_API_VERSION < 2
2442 definition.deleteProperty = &Messages_deleteProperty;
2444 definition.getPropertyNames = &Messages_getPropertyNames;
2445 definition.finalize = &CYFinalize;
2446 Messages_ = JSClassCreate(&definition);
2448 definition = kJSClassDefinitionEmpty;
2449 definition.className = "Selector";
2450 definition.staticValues = Selector_staticValues;
2451 definition.staticFunctions = Selector_staticFunctions;
2452 definition.callAsFunction = &Selector_callAsFunction;
2453 definition.finalize = &CYFinalize;
2454 Selector_ = JSClassCreate(&definition);
2456 definition = kJSClassDefinitionEmpty;
2457 definition.className = "Super";
2458 definition.staticFunctions = Internal_staticFunctions;
2459 definition.finalize = &CYFinalize;
2460 Super_ = JSClassCreate(&definition);
2462 definition = kJSClassDefinitionEmpty;
2463 definition.className = "ObjectiveC::Classes";
2464 definition.getProperty = &ObjectiveC_Classes_getProperty;
2465 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2466 ObjectiveC_Classes_ = JSClassCreate(&definition);
2468 definition = kJSClassDefinitionEmpty;
2469 definition.className = "ObjectiveC::Constants";
2470 definition.getProperty = &ObjectiveC_Constants_getProperty;
2471 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2472 ObjectiveC_Constants_ = JSClassCreate(&definition);
2474 #if OBJC_API_VERSION >= 2
2475 definition = kJSClassDefinitionEmpty;
2476 definition.className = "ObjectiveC::Images";
2477 definition.getProperty = &ObjectiveC_Images_getProperty;
2478 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2479 ObjectiveC_Images_ = JSClassCreate(&definition);
2481 definition = kJSClassDefinitionEmpty;
2482 definition.className = "ObjectiveC::Image::Classes";
2483 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2484 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2485 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2488 definition = kJSClassDefinitionEmpty;
2489 definition.className = "ObjectiveC::Protocols";
2490 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2491 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2492 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2494 #if defined(__APPLE__) && defined(__arm__) && 0
2495 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2499 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2503 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2504 JSObjectRef global(CYGetGlobalObject(context));
2505 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2506 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2507 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2508 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2510 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2511 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2513 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2514 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2515 CYArrayPush(context, alls, protocols);
2517 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2518 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2519 CYArrayPush(context, alls, classes);
2521 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2522 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2523 CYArrayPush(context, alls, constants);
2525 #if OBJC_API_VERSION >= 2
2526 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2529 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2530 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2531 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2532 JSObjectRef StringInstance(JSObjectMakeConstructor(context, Instance_, NULL));
2533 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2535 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2536 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2538 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2539 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2541 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2542 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2544 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2545 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2546 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2548 #if defined(__APPLE__) && defined(__arm__) && 0
2549 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2552 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2554 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2555 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2556 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2559 static CYHooks CYObjectiveCHooks = {
2560 &CYObjectiveC_ExecuteStart,
2561 &CYObjectiveC_ExecuteEnd,
2562 &CYObjectiveC_CallFunction,
2563 &CYObjectiveC_Initialize,
2564 &CYObjectiveC_SetupContext,
2565 &CYObjectiveC_PoolFFI,
2566 &CYObjectiveC_FromFFI,
2569 struct CYObjectiveC {
2571 hooks_ = &CYObjectiveCHooks;
2572 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2573 _assert(hooks_ != NULL);