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_;
238 static JSClassRef ArrayInstance_;
239 static JSClassRef FunctionInstance_;
240 static JSClassRef ObjectInstance_;
241 static JSClassRef StringInstance_;
243 static JSClassRef Internal_;
244 static JSClassRef Message_;
245 static JSClassRef Messages_;
246 static JSClassRef Selector_;
247 static JSClassRef Super_;
249 static JSClassRef ObjectiveC_Classes_;
250 static JSClassRef ObjectiveC_Constants_;
251 static JSClassRef ObjectiveC_Protocols_;
254 static JSClassRef ObjectiveC_Image_Classes_;
255 static JSClassRef ObjectiveC_Images_;
259 static Class NSCFBoolean_;
260 static Class NSCFType_;
261 static Class NSGenericDeallocHandler_;
262 static Class NSMessageBuilder_;
263 static Class NSZombie_;
265 static Class NSBoolNumber_;
268 static Class NSArray_;
269 static Class NSBlock_;
270 static Class NSDictionary_;
271 static Class NSString_;
272 static Class Object_;
274 static Type_privateData *Object_type;
275 static Type_privateData *Selector_type;
277 Type_privateData *Instance::GetType() const {
281 Type_privateData *Selector_privateData::GetType() const {
282 return Selector_type;
285 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
287 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
289 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
291 JSObjectRef global(CYGetGlobalObject(context));
292 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
295 sprintf(label, "i%p", self);
296 CYJSString name(label);
298 JSValueRef value(CYGetProperty(context, cy, name));
299 if (!JSValueIsUndefined(context, value))
302 JSClassRef _class(NULL);
303 JSValueRef prototype;
305 if (self == NSArray_)
306 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
307 else if (self == NSBlock_)
308 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
309 else if (self == NSDictionary_)
310 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
311 else if (self == NSString_)
312 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
314 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
316 JSObjectRef object(JSObjectMake(context, _class, NULL));
317 JSObjectSetPrototype(context, object, prototype);
318 CYSetProperty(context, cy, name, object);
323 JSObjectRef Messages::Make(JSContextRef context, Class _class, bool array) {
324 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
325 if (_class == NSArray_)
327 if (Class super = class_getSuperclass(_class))
328 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
330 JSObjectSetPrototype(context, value, Array_prototype_);*/
334 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
335 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
339 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
340 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
344 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
345 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
346 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
350 Instance::~Instance() {
351 if ((flags_ & Transient) == 0)
352 // XXX: does this handle background threads correctly?
353 // XXX: this simply does not work on the console because I'm stupid
354 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
357 struct Message_privateData :
362 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
363 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
369 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
370 Instance::Flags flags;
373 flags = Instance::Transient;
375 flags = Instance::None;
376 object = [object retain];
379 return Instance::Make(context, object, flags);
382 @interface NSMethodSignature (Cycript)
383 - (NSString *) _typeString;
386 @interface NSObject (Cycript)
388 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
389 - (JSType) cy$JSType;
391 - (NSObject *) cy$toJSON:(NSString *)key;
392 - (NSString *) cy$toCYON;
394 - (bool) cy$hasProperty:(NSString *)name;
395 - (NSObject *) cy$getProperty:(NSString *)name;
396 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
397 - (bool) cy$deleteProperty:(NSString *)name;
398 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
400 + (bool) cy$hasImplicitProperties;
406 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
409 NSString *CYCastNSCYON(id value) {
415 Class _class(object_getClass(value));
416 SEL sel(@selector(cy$toCYON));
418 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
419 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
420 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
421 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
422 string = [value cy$toCYON];
427 else if (value == NSZombie_)
428 string = @"_NSZombie_";
429 else if (_class == NSZombie_)
430 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
431 // XXX: frowny /in/ the pants
432 else if (value == NSGenericDeallocHandler_ || value == NSMessageBuilder_ || value == Object_)
436 string = [NSString stringWithFormat:@"%@", value];
441 string = @"undefined";
448 struct PropertyAttributes {
453 const char *variable;
466 PropertyAttributes(objc_property_t property) :
478 name = property_getName(property);
479 const char *attributes(property_getAttributes(property));
481 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
483 case 'R': readonly = true; break;
484 case 'C': copy = true; break;
485 case '&': retain = true; break;
486 case 'N': nonatomic = true; break;
487 case 'G': getter_ = token + 1; break;
488 case 'S': setter_ = token + 1; break;
489 case 'V': variable = token + 1; break;
493 /*if (variable == NULL) {
494 variable = property_getName(property);
495 size_t size(strlen(variable));
496 char *name(new(pool_) char[size + 2]);
498 memcpy(name + 1, variable, size);
499 name[size + 1] = '\0';
504 const char *Getter() {
506 getter_ = apr_pstrdup(pool_, name);
510 const char *Setter() {
511 if (setter_ == NULL && !readonly) {
512 size_t length(strlen(name));
514 char *temp(new(pool_) char[length + 5]);
520 temp[3] = toupper(name[0]);
521 memcpy(temp + 4, name + 1, length - 1);
524 temp[length + 3] = ':';
525 temp[length + 4] = '\0';
536 NSObject *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
537 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
542 @interface CYWebUndefined : NSObject {
545 + (CYWebUndefined *) undefined;
549 @implementation CYWebUndefined
551 + (CYWebUndefined *) undefined {
552 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
558 #define WebUndefined CYWebUndefined
561 /* Bridge: CYJSObject {{{ */
562 @interface CYJSObject : NSMutableDictionary {
564 JSContextRef context_;
567 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
569 - (NSObject *) cy$toJSON:(NSString *)key;
571 - (NSUInteger) count;
572 - (id) objectForKey:(id)key;
573 - (NSEnumerator *) keyEnumerator;
574 - (void) setObject:(id)object forKey:(id)key;
575 - (void) removeObjectForKey:(id)key;
579 /* Bridge: CYJSArray {{{ */
580 @interface CYJSArray : NSMutableArray {
582 JSContextRef context_;
585 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
587 - (NSUInteger) count;
588 - (id) objectAtIndex:(NSUInteger)index;
590 - (void) addObject:(id)anObject;
591 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
592 - (void) removeLastObject;
593 - (void) removeObjectAtIndex:(NSUInteger)index;
594 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
599 NSObject *CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
600 JSObjectRef Array(CYGetCachedObject(context, Array_s));
601 JSValueRef exception(NULL);
602 bool array(JSValueIsInstanceOfConstructor(context, object, Array, &exception));
603 CYThrow(context, exception);
604 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
605 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
608 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
609 if (!JSValueIsObjectOfClass(context, object, Instance_))
610 return CYCastNSObject_(pool, context, object);
612 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
613 return internal->GetValue();
617 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
618 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
622 @interface NSBoolNumber : NSNumber {
627 id CYNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
631 switch (JSType type = JSValueGetType(context, value)) {
632 case kJSTypeUndefined:
633 object = [WebUndefined undefined];
643 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
646 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
652 object = CYCopyNSNumber(context, value);
657 object = CYCopyNSString(context, value);
662 // XXX: this might could be more efficient
663 object = CYCastNSObject(pool, context, (JSObjectRef) value);
668 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
675 return CYPoolRelease(pool, object);
677 return [object retain];
680 NSObject *CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
681 return CYNSObject(pool, context, value, true);
684 NSObject *CYCopyNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
685 return CYNSObject(pool, context, value, false);
688 /* Bridge: NSArray {{{ */
689 @implementation NSArray (Cycript)
692 return [[self mutableCopy] autorelease];
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));
763 + (bool) cy$hasImplicitProperties {
769 /* Bridge: NSBlock {{{ */
776 /* Bridge: NSBoolNumber {{{ */
778 @implementation NSBoolNumber (Cycript)
780 - (JSType) cy$JSType {
781 return kJSTypeBoolean;
784 - (NSObject *) cy$toJSON:(NSString *)key {
788 - (NSString *) cy$toCYON {
789 return [self boolValue] ? @"@true" : @"@false";
792 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
793 return CYCastJSValue(context, (bool) [self boolValue]);
799 /* Bridge: NSDictionary {{{ */
800 @implementation NSDictionary (Cycript)
803 return [[self mutableCopy] autorelease];
806 - (NSString *) cy$toCYON {
807 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
808 [json appendString:@"@{"];
812 for (NSObject *key in self) {
814 NSEnumerator *keys([self keyEnumerator]);
815 while (NSObject *key = [keys nextObject]) {
818 [json appendString:@","];
821 [json appendString:CYCastNSCYON(key)];
822 [json appendString:@":"];
823 NSObject *object([self objectForKey:key]);
824 [json appendString:CYCastNSCYON(object)];
827 [json appendString:@"}"];
831 - (bool) cy$hasProperty:(NSString *)name {
832 return [self objectForKey:name] != nil;
835 - (NSObject *) cy$getProperty:(NSString *)name {
836 return [self objectForKey:name];
839 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
840 [super cy$getPropertyNames:names inContext:context];
843 for (NSObject *key in self) {
845 NSEnumerator *keys([self keyEnumerator]);
846 while (NSObject *key = [keys nextObject]) {
848 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
852 + (bool) cy$hasImplicitProperties {
858 /* Bridge: NSMutableArray {{{ */
859 @implementation NSMutableArray (Cycript)
861 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
862 if ([name isEqualToString:@"length"]) {
863 // XXX: is this not intelligent?
864 NSNumber *number(reinterpret_cast<NSNumber *>(value));
866 NSUInteger size([number unsignedIntegerValue]);
868 NSUInteger size([number unsignedIntValue]);
870 NSUInteger count([self count]);
872 [self removeObjectsInRange:NSMakeRange(size, count - size)];
873 else if (size != count) {
874 WebUndefined *undefined([WebUndefined undefined]);
875 for (size_t i(count); i != size; ++i)
876 [self addObject:undefined];
881 size_t index(CYGetIndex(name));
882 if (index == _not(size_t))
883 return [super cy$setProperty:name to:value];
885 id object(value ?: [NSNull null]);
887 size_t count([self count]);
889 [self replaceObjectAtIndex:index withObject:object];
891 if (index != count) {
892 WebUndefined *undefined([WebUndefined undefined]);
893 for (size_t i(count); i != index; ++i)
894 [self addObject:undefined];
897 [self addObject:object];
903 - (bool) cy$deleteProperty:(NSString *)name {
904 size_t index(CYGetIndex(name));
905 if (index == _not(size_t) || index >= [self count])
906 return [super cy$deleteProperty:name];
907 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
913 /* Bridge: NSMutableDictionary {{{ */
914 @implementation NSMutableDictionary (Cycript)
916 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
917 [self setObject:(value ?: [NSNull null]) forKey:name];
921 - (bool) cy$deleteProperty:(NSString *)name {
922 if ([self objectForKey:name] == nil)
925 [self removeObjectForKey:name];
932 /* Bridge: NSNumber {{{ */
933 @implementation NSNumber (Cycript)
935 - (JSType) cy$JSType {
937 // XXX: this just seems stupid
938 if ([self class] == NSCFBoolean_)
939 return kJSTypeBoolean;
941 return kJSTypeNumber;
944 - (NSObject *) cy$toJSON:(NSString *)key {
948 - (NSString *) cy$toCYON {
949 return [self cy$JSType] != kJSTypeBoolean ? [NSString stringWithFormat:@"@%@", self] : [self boolValue] ? @"@true" : @"@false";
952 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
953 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
958 /* Bridge: NSNull {{{ */
959 @implementation NSNull (Cycript)
961 - (JSType) cy$JSType {
965 - (NSObject *) cy$toJSON:(NSString *)key {
969 - (NSString *) cy$toCYON {
975 /* Bridge: NSObject {{{ */
976 @implementation NSObject (Cycript)
982 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
986 - (JSType) cy$JSType {
987 return kJSTypeObject;
990 - (NSObject *) cy$toJSON:(NSString *)key {
991 return [self description];
994 - (NSString *) cy$toCYON {
995 return [[self cy$toJSON:@""] cy$toCYON];
998 - (bool) cy$hasProperty:(NSString *)name {
1002 - (NSObject *) cy$getProperty:(NSString *)name {
1006 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1010 - (bool) cy$deleteProperty:(NSString *)name {
1014 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1017 + (bool) cy$hasImplicitProperties {
1023 /* Bridge: NSProxy {{{ */
1024 @implementation NSProxy (Cycript)
1026 - (NSObject *) cy$toJSON:(NSString *)key {
1027 return [self description];
1030 - (NSString *) cy$toCYON {
1031 return [[self cy$toJSON:@""] cy$toCYON];
1036 /* Bridge: NSString {{{ */
1037 @implementation NSString (Cycript)
1040 return [[self copy] autorelease];
1043 - (JSType) cy$JSType {
1044 return kJSTypeString;
1047 - (NSObject *) cy$toJSON:(NSString *)key {
1051 - (NSString *) cy$toCYON {
1052 std::ostringstream str;
1054 CYUTF8String string(CYCastUTF8String(self));
1055 CYStringify(str, string.data, string.size);
1056 std::string value(str.str());
1057 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1060 - (bool) cy$hasProperty:(NSString *)name {
1061 if ([name isEqualToString:@"length"])
1064 size_t index(CYGetIndex(name));
1065 if (index == _not(size_t) || index >= [self length])
1066 return [super cy$hasProperty:name];
1071 - (NSObject *) cy$getProperty:(NSString *)name {
1072 if ([name isEqualToString:@"length"]) {
1073 NSUInteger count([self length]);
1075 return [NSNumber numberWithUnsignedInteger:count];
1077 return [NSNumber numberWithUnsignedInt:count];
1081 size_t index(CYGetIndex(name));
1082 if (index == _not(size_t) || index >= [self length])
1083 return [super cy$getProperty:name];
1085 return [self substringWithRange:NSMakeRange(index, 1)];
1088 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1089 [super cy$getPropertyNames:names inContext:context];
1091 for (size_t index(0), length([self length]); index != length; ++index) {
1093 sprintf(name, "%zu", index);
1094 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1098 // XXX: this might be overly restrictive for NSString; I think I need a half-way between /injecting/ implicit properties and /accepting/ implicit properties
1099 + (bool) cy$hasImplicitProperties {
1103 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1104 return CYCastJSValue(context, CYJSString(context, self));
1105 } CYObjectiveCatch }
1109 /* Bridge: WebUndefined {{{ */
1110 @implementation WebUndefined (Cycript)
1112 - (JSType) cy$JSType {
1113 return kJSTypeUndefined;
1116 - (NSObject *) cy$toJSON:(NSString *)key {
1120 - (NSString *) cy$toCYON {
1121 return @"undefined";
1124 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_(context) {
1125 return CYJSUndefined(context);
1126 } CYObjectiveCatch }
1131 static bool CYIsClass(id self) {
1133 // XXX: this is a lame object_isClass
1134 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
1136 return GSObjCIsClass(self);
1140 Class CYCastClass(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1141 id self(CYCastNSObject(pool, context, value));
1142 if (CYIsClass(self))
1143 return (Class) self;
1144 throw CYJSError(context, "got something that is not a Class");
1148 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1150 size_t size(JSPropertyNameArrayGetCount(names));
1151 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1152 for (size_t index(0); index != size; ++index)
1153 [array addObject:CYCastNSString(pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1157 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1159 return CYJSNull(context);
1161 return CYMakeInstance(context, value, false);
1162 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1164 @implementation CYJSObject
1166 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1167 if ((self = [super init]) != nil) {
1169 context_ = CYGetJSContext(context);
1170 //XXX:JSGlobalContextRetain(context_);
1171 JSValueProtect(context_, object_);
1173 } CYObjectiveCatch }
1175 - (void) dealloc { CYObjectiveTry {
1176 JSValueUnprotect(context_, object_);
1177 //XXX:JSGlobalContextRelease(context_);
1179 } CYObjectiveCatch }
1181 - (NSObject *) cy$toJSON:(NSString *)key { CYObjectiveTry {
1182 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_s));
1183 if (!CYIsCallable(context_, toJSON))
1184 return [super cy$toJSON:key];
1186 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1187 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1188 // XXX: do I really want an NSNull here?!
1189 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1191 } CYObjectiveCatch }
1193 - (NSString *) cy$toCYON { CYObjectiveTry {
1195 JSValueRef exception(NULL);
1196 const char *cyon(CYPoolCCYON(pool, context_, object_));
1197 CYThrow(context_, exception);
1199 return [super cy$toCYON];
1201 return [NSString stringWithUTF8String:cyon];
1202 } CYObjectiveCatch }
1204 - (NSUInteger) count { CYObjectiveTry {
1205 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1206 size_t size(JSPropertyNameArrayGetCount(names));
1207 JSPropertyNameArrayRelease(names);
1209 } CYObjectiveCatch }
1211 - (id) objectForKey:(id)key { CYObjectiveTry {
1212 JSValueRef value(CYGetProperty(context_, object_, CYJSString(context_, (NSObject *) key)));
1213 if (JSValueIsUndefined(context_, value))
1215 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1216 } CYObjectiveCatch }
1218 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1219 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1220 NSEnumerator *enumerator([CYCastNSArray(context_, names) objectEnumerator]);
1221 JSPropertyNameArrayRelease(names);
1223 } CYObjectiveCatch }
1225 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1226 CYSetProperty(context_, object_, CYJSString(context_, (NSObject *) key), CYCastJSValue(context_, (NSString *) object));
1227 } CYObjectiveCatch }
1229 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1230 JSValueRef exception(NULL);
1231 (void) JSObjectDeleteProperty(context_, object_, CYJSString(context_, (NSObject *) key), &exception);
1232 CYThrow(context_, exception);
1233 } CYObjectiveCatch }
1237 @implementation CYJSArray
1239 - (NSString *) cy$toCYON {
1241 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context_, object_)];
1244 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry {
1245 if ((self = [super init]) != nil) {
1247 context_ = CYGetJSContext(context);
1248 //XXX:JSGlobalContextRetain(context_);
1249 JSValueProtect(context_, object_);
1251 } CYObjectiveCatch }
1253 - (void) dealloc { CYObjectiveTry {
1254 JSValueUnprotect(context_, object_);
1255 //XXX:JSGlobalContextRelease(context_);
1257 } CYObjectiveCatch }
1259 - (NSUInteger) count { CYObjectiveTry {
1260 return CYArrayLength(context_, object_);
1261 } CYObjectiveCatch }
1263 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1264 size_t bounds([self count]);
1265 if (index >= bounds)
1266 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1267 JSValueRef exception(NULL);
1268 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1269 CYThrow(context_, exception);
1270 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1271 } CYObjectiveCatch }
1273 - (void) addObject:(id)object { CYObjectiveTry {
1274 CYArrayPush(context_, object_, CYCastJSValue(context_, (NSObject *) object));
1275 } CYObjectiveCatch }
1277 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1278 size_t bounds([self count] + 1);
1279 if (index >= bounds)
1280 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1281 JSValueRef exception(NULL);
1282 JSValueRef arguments[3];
1283 arguments[0] = CYCastJSValue(context_, index);
1284 arguments[1] = CYCastJSValue(context_, 0);
1285 arguments[2] = CYCastJSValue(context_, (NSObject *) object);
1286 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1287 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 3, arguments, &exception);
1288 CYThrow(context_, exception);
1289 } CYObjectiveCatch }
1291 - (void) removeLastObject { CYObjectiveTry {
1292 JSValueRef exception(NULL);
1293 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1294 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, pop_s)), object_, 0, NULL, &exception);
1295 CYThrow(context_, exception);
1296 } CYObjectiveCatch }
1298 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1299 size_t bounds([self count]);
1300 if (index >= bounds)
1301 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1302 JSValueRef exception(NULL);
1303 JSValueRef arguments[2];
1304 arguments[0] = CYCastJSValue(context_, index);
1305 arguments[1] = CYCastJSValue(context_, 1);
1306 JSObjectRef Array(CYGetCachedObject(context_, CYJSString("Array_prototype")));
1307 JSObjectCallAsFunction(context_, CYCastJSObject(context_, CYGetProperty(context_, Array, splice_s)), object_, 2, arguments, &exception);
1308 CYThrow(context_, exception);
1309 } CYObjectiveCatch }
1311 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1312 size_t bounds([self count]);
1313 if (index >= bounds)
1314 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1315 CYSetProperty(context_, object_, index, CYCastJSValue(context_, (NSObject *) object));
1316 } CYObjectiveCatch }
1320 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1324 JSObjectRef object_;
1332 // XXX: delete object_? ;(
1335 static CYInternal *Get(id self) {
1336 CYInternal *internal(NULL);
1337 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1338 // XXX: do something epic? ;P
1344 static CYInternal *Set(id self) {
1345 CYInternal *internal(NULL);
1346 if (objc_ivar *ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1347 if (internal == NULL) {
1348 internal = new CYInternal();
1349 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1352 // XXX: do something epic? ;P
1358 bool HasProperty(JSContextRef context, JSStringRef name) {
1359 if (object_ == NULL)
1361 return JSObjectHasProperty(context, object_, name);
1364 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1365 if (object_ == NULL)
1367 return CYGetProperty(context, object_, name);
1370 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1371 if (object_ == NULL)
1372 object_ = JSObjectMake(context, NULL, NULL);
1373 CYSetProperty(context, object_, name, value);
1377 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1378 Selector_privateData *internal(new Selector_privateData(sel));
1379 return JSObjectMake(context, Selector_, internal);
1382 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1383 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1384 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1385 return reinterpret_cast<SEL>(internal->value_);
1387 return CYCastPointer<SEL>(context, value);
1390 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1391 return (void *) [[NSAutoreleasePool alloc] init];
1392 } CYSadCatch(NULL) }
1394 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1395 return [(NSAutoreleasePool *) handle release];
1398 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1400 return Instance::Make(context, nil);
1401 if (Class _class = objc_getClass(name.data))
1402 return CYMakeInstance(context, _class, true);
1403 if (Protocol *protocol = objc_getProtocol(name.data))
1404 return CYMakeInstance(context, protocol, true);
1406 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1408 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1409 ffi_call(cif, function, value, values);
1412 static bool CYObjectiveC_PoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1413 switch (type->primitive) {
1414 // XXX: do something epic about blocks
1417 case sig::typename_P:
1418 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1421 case sig::selector_P:
1422 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1430 } CYSadCatch(false) }
1432 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1433 switch (type->primitive) {
1434 // XXX: do something epic about blocks
1437 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1438 JSValueRef value(CYCastJSValue(context, object));
1444 case sig::typename_P:
1445 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1447 case sig::selector_P:
1448 if (SEL sel = *reinterpret_cast<SEL *>(data))
1449 return CYMakeSelector(context, sel);
1453 return CYJSNull(context);
1457 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1459 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1460 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1463 #if OBJC_API_VERSION >= 2
1465 method_getReturnType(method, type, sizeof(type));
1467 const char *type(method_getTypeEncoding(method));
1473 // XXX: possibly use a more "awesome" check?
1477 static const char *CYPoolTypeEncoding(apr_pool_t *pool, JSContextRef context, SEL sel, objc_method *method) {
1479 return method_getTypeEncoding(method);
1481 const char *name(sel_getName(sel));
1482 size_t length(strlen(name));
1484 char keyed[length + 2];
1486 keyed[length + 1] = '\0';
1487 memcpy(keyed + 1, name, length);
1489 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1490 return entry->value_;
1495 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1496 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1498 JSContextRef context(internal->context_);
1500 size_t count(internal->cif_.nargs);
1501 JSValueRef values[count];
1503 for (size_t index(0); index != count; ++index)
1504 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1506 JSObjectRef _this(CYCastJSObject(context, values[0]));
1508 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1509 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1512 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1513 Message_privateData *internal(new Message_privateData(sel, type, imp));
1514 return JSObjectMake(context, Message_, internal);
1517 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1518 JSObjectRef function(CYCastJSObject(context, value));
1519 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1520 // XXX: see notes in Library.cpp about needing to leak
1521 return reinterpret_cast<IMP>(internal->GetValue());
1524 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1525 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1526 Class _class(internal->GetValue());
1529 const char *name(CYPoolCString(pool, context, property));
1531 if (SEL sel = sel_getUid(name))
1532 if (class_getInstanceMethod(_class, sel) != NULL)
1538 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1539 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1540 Class _class(internal->GetValue());
1543 const char *name(CYPoolCString(pool, context, property));
1545 if (SEL sel = sel_getUid(name))
1546 if (objc_method *method = class_getInstanceMethod(_class, sel))
1547 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1552 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1553 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1554 Class _class(internal->GetValue());
1557 const char *name(CYPoolCString(pool, context, property));
1559 SEL sel(sel_registerName(name));
1561 objc_method *method(class_getInstanceMethod(_class, sel));
1566 if (JSValueIsObjectOfClass(context, value, Message_)) {
1567 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1568 type = sig::Unparse(pool, &message->signature_);
1569 imp = reinterpret_cast<IMP>(message->GetValue());
1571 type = CYPoolTypeEncoding(pool, context, sel, method);
1572 imp = CYMakeMessage(context, value, type);
1576 method_setImplementation(method, imp);
1579 GSMethodList list(GSAllocMethodList(1));
1580 GSAppendMethodToList(list, sel, type, imp, YES);
1581 GSAddMethodList(_class, list, YES);
1582 GSFlushMethodCacheForClass(_class);
1584 class_addMethod(_class, sel, imp, type);
1591 #if 0 && OBJC_API_VERSION < 2
1592 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1593 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1594 Class _class(internal->GetValue());
1597 const char *name(CYPoolCString(pool, context, property));
1599 if (SEL sel = sel_getUid(name))
1600 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1601 objc_method_list list = {NULL, 1, {method}};
1602 class_removeMethods(_class, &list);
1610 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1611 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1612 Class _class(internal->GetValue());
1614 #if OBJC_API_VERSION >= 2
1616 objc_method **data(class_copyMethodList(_class, &size));
1617 for (size_t i(0); i != size; ++i)
1618 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1621 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1622 for (int i(0); i != methods->method_count; ++i)
1623 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1627 static bool CYHasImplicitProperties(Class _class) {
1628 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1629 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties), false))
1631 return [_class cy$hasImplicitProperties];
1634 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1635 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1636 id self(internal->GetValue());
1638 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1642 NSString *name(CYCastNSString(pool, context, property));
1644 if (CYInternal *internal = CYInternal::Get(self))
1645 if (internal->HasProperty(context, property))
1648 Class _class(object_getClass(self));
1651 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1652 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
1653 if ([self cy$hasProperty:name])
1655 } CYPoolCatch(false)
1657 const char *string(CYPoolCString(pool, context, name));
1660 if (class_getProperty(_class, string) != NULL)
1664 if (CYHasImplicitProperties(_class))
1665 if (SEL sel = sel_getUid(string))
1666 if (CYImplements(self, _class, sel, true))
1672 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1673 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1674 id self(internal->GetValue());
1676 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1677 return Internal::Make(context, self, object);
1680 NSString *name(CYCastNSString(pool, context, property));
1682 if (CYInternal *internal = CYInternal::Get(self))
1683 if (JSValueRef value = internal->GetProperty(context, property))
1687 if (NSObject *data = [self cy$getProperty:name])
1688 return CYCastJSValue(context, data);
1691 const char *string(CYPoolCString(pool, context, name));
1692 Class _class(object_getClass(self));
1695 if (objc_property_t property = class_getProperty(_class, string)) {
1696 PropertyAttributes attributes(property);
1697 SEL sel(sel_registerName(attributes.Getter()));
1698 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1702 if (CYHasImplicitProperties(_class))
1703 if (SEL sel = sel_getUid(string))
1704 if (CYImplements(self, _class, sel, true))
1705 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false, exception);
1710 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1711 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1712 id self(internal->GetValue());
1716 NSString *name(CYCastNSString(pool, context, property));
1717 NSObject *data(CYCastNSObject(pool, context, value));
1720 if ([self cy$setProperty:name to:data])
1724 const char *string(CYPoolCString(pool, context, name));
1725 Class _class(object_getClass(self));
1728 if (objc_property_t property = class_getProperty(_class, string)) {
1729 PropertyAttributes attributes(property);
1730 if (const char *setter = attributes.Setter()) {
1731 SEL sel(sel_registerName(setter));
1732 JSValueRef arguments[1] = {value};
1733 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1739 size_t length(strlen(string));
1741 char set[length + 5];
1747 if (string[0] != '\0') {
1748 set[3] = toupper(string[0]);
1749 memcpy(set + 4, string + 1, length - 1);
1752 set[length + 3] = ':';
1753 set[length + 4] = '\0';
1755 if (SEL sel = sel_getUid(set))
1756 if (CYImplements(self, _class, sel, false)) {
1757 JSValueRef arguments[1] = {value};
1758 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false, exception);
1761 if (CYInternal *internal = CYInternal::Set(self)) {
1762 internal->SetProperty(context, property, value);
1769 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1770 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1771 id self(internal->GetValue());
1774 NSString *name(CYCastNSString(NULL, context, property));
1775 return [self cy$deleteProperty:name];
1777 } CYCatch return /*XXX*/ NULL; }
1779 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1780 const char *name(sel_getName(method_getName(method)));
1781 if (strchr(name, ':') != NULL)
1784 const char *type(method_getTypeEncoding(method));
1785 if (type == NULL || *type == '\0' || *type == 'v')
1788 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1791 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1792 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1793 id self(internal->GetValue());
1796 Class _class(object_getClass(self));
1801 objc_property_t *data(class_copyPropertyList(_class, &size));
1802 for (size_t i(0); i != size; ++i)
1803 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1808 if (CYHasImplicitProperties(_class))
1809 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1810 #if OBJC_API_VERSION >= 2
1812 objc_method **data(class_copyMethodList(current, &size));
1813 for (size_t i(0); i != size; ++i)
1814 Instance_getPropertyNames_message(names, data[i]);
1817 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1818 for (int i(0); i != methods->method_count; ++i)
1819 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1824 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1825 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:), false))
1826 [self cy$getPropertyNames:names inContext:context];
1830 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1831 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1832 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1836 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1837 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1838 id self(internal->GetValue());
1840 if (![self isKindOfClass:NSBlock_])
1841 CYThrow("non-NSBlock object is not a function");
1843 struct BlockDescriptor1 {
1844 unsigned long int reserved;
1845 unsigned long int size;
1848 struct BlockDescriptor2 {
1849 void (*copy_helper)(void *dst, void *src);
1850 void (*dispose_helper)(void *src);
1853 struct BlockDescriptor3 {
1854 const char *signature;
1858 struct BlockLiteral {
1862 void (*invoke)(void *, ...);
1864 } *literal = reinterpret_cast<BlockLiteral *>(self);
1867 BLOCK_DEALLOCATING = 0x0001,
1868 BLOCK_REFCOUNT_MASK = 0xfffe,
1869 BLOCK_NEEDS_FREE = 1 << 24,
1870 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
1871 BLOCK_HAS_CTOR = 1 << 26,
1872 BLOCK_IS_GC = 1 << 27,
1873 BLOCK_IS_GLOBAL = 1 << 28,
1874 BLOCK_HAS_STRET = 1 << 29,
1875 BLOCK_HAS_SIGNATURE = 1 << 30,
1878 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1879 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1880 descriptor += sizeof(BlockDescriptor1);
1881 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1882 descriptor += sizeof(BlockDescriptor2);
1883 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1885 if (const char *type = descriptor3->signature) {
1891 sig::Signature signature;
1892 sig::Parse(pool, &signature, type, &Structor_);
1895 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1897 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1898 return CYCallFunction(pool, context, 1, setup, count, arguments, false, exception, &signature, &cif, function);
1903 CYThrow("NSBlock without signature field passed arguments");
1907 } CYPoolCatch(NULL);
1912 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1913 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1914 Class _class(internal->GetValue());
1915 if (!CYIsClass(_class))
1918 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
1919 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1920 // XXX: this isn't always safe
1921 return [linternal->GetValue() isKindOfClass:_class];
1927 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1929 throw CYJSError(context, "incorrect number of arguments to Instance");
1931 id value(CYCastNSObject(pool, context, arguments[0]));
1933 value = [NSNull null];
1934 return CYCastJSValue(context, [value cy$box]);
1937 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1938 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1941 id self(internal->GetValue());
1942 const char *name(CYPoolCString(pool, context, property));
1944 if (object_getInstanceVariable(self, name, NULL) != NULL)
1950 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1951 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1954 id self(internal->GetValue());
1955 const char *name(CYPoolCString(pool, context, property));
1957 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1958 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1959 // XXX: if this fails and throws an exception the person we are throwing it to gets the wrong exception
1960 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1966 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1967 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1970 id self(internal->GetValue());
1971 const char *name(CYPoolCString(pool, context, property));
1973 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1974 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1975 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1982 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
1983 if (Class super = class_getSuperclass(_class))
1984 Internal_getPropertyNames_(super, names);
1986 #if OBJC_API_VERSION >= 2
1988 objc_ivar **data(class_copyIvarList(_class, &size));
1989 for (size_t i(0); i != size; ++i)
1990 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1993 if (objc_ivar_list *ivars = _class->ivars)
1994 for (int i(0); i != ivars->ivar_count; ++i)
1995 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
1999 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2000 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2003 id self(internal->GetValue());
2004 Class _class(object_getClass(self));
2006 Internal_getPropertyNames_(_class, names);
2009 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2010 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2011 return internal->GetOwner();
2014 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2016 NSString *name(CYCastNSString(pool, context, property));
2017 if (Class _class = NSClassFromString(name))
2018 return CYMakeInstance(context, _class, true);
2022 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2024 size_t size(objc_getClassList(NULL, 0));
2025 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2028 size_t writ(objc_getClassList(data, size));
2031 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2037 for (size_t i(0); i != writ; ++i)
2038 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2044 while (Class _class = objc_next_class(&state))
2045 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2049 #if OBJC_API_VERSION >= 2
2050 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2051 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2054 const char *name(CYPoolCString(pool, context, property));
2056 const char **data(objc_copyClassNamesForImage(internal, &size));
2058 for (size_t i(0); i != size; ++i)
2059 if (strcmp(name, data[i]) == 0) {
2060 if (Class _class = objc_getClass(name)) {
2061 value = CYMakeInstance(context, _class, true);
2072 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2073 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2075 const char **data(objc_copyClassNamesForImage(internal, &size));
2076 for (size_t i(0); i != size; ++i)
2077 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2081 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2083 const char *name(CYPoolCString(pool, context, property));
2085 const char **data(objc_copyImageNames(&size));
2086 for (size_t i(0); i != size; ++i)
2087 if (strcmp(name, data[i]) == 0) {
2096 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2097 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2101 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2103 const char **data(objc_copyImageNames(&size));
2104 for (size_t i(0); i != size; ++i)
2105 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2110 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2112 const char *name(CYPoolCString(pool, context, property));
2113 if (Protocol *protocol = objc_getProtocol(name))
2114 return CYMakeInstance(context, protocol, true);
2118 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2119 #if OBJC_API_VERSION >= 2
2121 Protocol **data(objc_copyProtocolList(&size));
2122 for (size_t i(0); i != size; ++i)
2123 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2130 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2132 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2134 return Instance::Make(context, nil);
2138 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2139 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2143 static bool stret(ffi_type *ffi_type) {
2144 return ffi_type->type == FFI_TYPE_STRUCT && (
2145 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2146 struct_forward_array[ffi_type->size] != 0
2151 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 {
2155 _class = object_getClass(self);
2159 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2160 imp = method_getImplementation(method);
2161 type = method_getTypeEncoding(method);
2166 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2168 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2169 type = CYPoolCString(pool, context, [method _typeString]);
2177 sig::Signature signature;
2178 sig::Parse(pool, &signature, type, &Structor_);
2180 size_t used(count + 3);
2181 if (used > signature.count) {
2182 sig::Element *elements(new (pool) sig::Element[used]);
2183 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2185 for (size_t index(signature.count); index != used; ++index) {
2186 sig::Element *element(&elements[index]);
2187 element->name = NULL;
2188 element->offset = _not(size_t);
2190 sig::Type *type(new (pool) sig::Type);
2191 memset(type, 0, sizeof(*type));
2192 type->primitive = sig::object_P;
2193 element->type = type;
2196 signature.elements = elements;
2197 signature.count = used;
2201 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2205 if (stret(cif.rtype))
2206 imp = class_getMethodImplementation_stret(_class, _cmd);
2208 imp = class_getMethodImplementation(_class, _cmd);
2210 objc_super super = {self, _class};
2211 imp = objc_msg_lookup_super(&super, _cmd);
2215 void (*function)() = reinterpret_cast<void (*)()>(imp);
2216 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2219 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2221 throw CYJSError(context, "too few arguments to objc_msgSend");
2231 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2232 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2233 self = internal->GetValue();
2234 _class = internal->class_;;
2235 uninitialized = false;
2236 } else if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2237 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2238 self = internal->GetValue();
2240 uninitialized = internal->IsUninitialized();
2242 internal->value_ = nil;
2244 self = CYCastNSObject(pool, context, arguments[0]);
2246 uninitialized = false;
2250 return CYJSNull(context);
2252 _cmd = CYCastSEL(context, arguments[1]);
2254 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized, exception);
2257 /* Hook: objc_registerClassPair {{{ */
2258 #if defined(__APPLE__) && defined(__arm__) && 0
2259 // XXX: replace this with associated objects
2261 MSHook(void, CYDealloc, id self, SEL sel) {
2262 CYInternal *internal;
2263 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2264 if (internal != NULL)
2266 _CYDealloc(self, sel);
2269 MSHook(void, objc_registerClassPair, Class _class) {
2270 Class super(class_getSuperclass(_class));
2271 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2272 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2273 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2276 _objc_registerClassPair(_class);
2279 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2281 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2283 NSObject *value(CYCastNSObject(pool, context, arguments[0]));
2284 if (value == NULL || !CYIsClass(value))
2285 throw CYJSError(context, "incorrect number of arguments to objc_registerClassPair");
2286 Class _class((Class) value);
2287 $objc_registerClassPair(_class);
2288 return CYJSUndefined(context);
2293 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2294 JSValueRef setup[count + 2];
2297 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2298 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2301 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2303 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2305 // XXX: handle Instance::Uninitialized?
2306 id self(CYCastNSObject(pool, context, _this));
2310 setup[1] = &internal->sel_;
2312 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2315 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2317 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2319 id self(CYCastNSObject(pool, context, arguments[0]));
2320 Class _class(CYCastClass(pool, context, arguments[1]));
2321 return cy::Super::Make(context, self, _class);
2324 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2326 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2328 const char *name(CYPoolCString(pool, context, arguments[0]));
2329 return CYMakeSelector(context, sel_registerName(name));
2332 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2334 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2335 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2336 return CYMakeInstance(context, self, false);
2339 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2340 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2341 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2344 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2345 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2346 Type_privateData *typical(internal->GetType());
2351 if (typical == NULL) {
2355 type = typical->type_;
2356 ffi = typical->ffi_;
2359 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2362 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2363 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2364 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2367 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2368 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2369 id self(internal->GetValue());
2370 if (!CYIsClass(self))
2371 return CYJSUndefined(context);
2372 return CYGetClassPrototype(context, self);
2375 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2376 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2377 id self(internal->GetValue());
2378 if (!CYIsClass(self))
2379 return CYJSUndefined(context);
2380 return Messages::Make(context, (Class) self);
2383 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2384 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2387 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2388 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue())));
2391 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2392 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2395 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2402 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2403 // XXX: check for support of cy$toJSON?
2404 return CYCastJSValue(context, CYJSString(context, [internal->GetValue() cy$toJSON:key]));
2406 } CYCatch return /*XXX*/ NULL; }
2408 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2409 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2412 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2413 id value(internal->GetValue());
2415 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2418 if (JSValueRef result = [value cy$valueOfInContext:context])
2422 } CYCatch return /*XXX*/ NULL; }
2424 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2425 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2428 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2429 // XXX: but... but... THIS ISN'T A POINTER! :(
2430 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2431 } CYCatch return /*XXX*/ NULL; }
2433 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2434 if (!JSValueIsObjectOfClass(context, _this, Instance_))
2437 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2438 id value(internal->GetValue());
2441 return CYCastJSValue(context, "nil");
2444 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2445 return CYCastJSValue(context, CYJSString(context, [value description]));
2447 } CYCatch return /*XXX*/ NULL; }
2449 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2450 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2451 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2454 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2455 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2458 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2459 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2460 const char *name(sel_getName(internal->GetValue()));
2463 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2464 return CYCastJSValue(context, CYJSString(context, string));
2466 } CYCatch return /*XXX*/ NULL; }
2468 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2470 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2473 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2474 SEL sel(internal->GetValue());
2476 objc_method *method;
2477 if (Class _class = CYCastClass(pool, context, arguments[0]))
2478 method = class_getInstanceMethod(_class, sel);
2482 if (const char *type = CYPoolTypeEncoding(pool, context, sel, method))
2483 return CYCastJSValue(context, CYJSString(type));
2485 return CYJSNull(context);
2488 static JSStaticValue Selector_staticValues[2] = {
2489 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2490 {NULL, NULL, NULL, 0}
2493 static JSStaticValue Instance_staticValues[5] = {
2494 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2495 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2496 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2497 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2498 {NULL, NULL, NULL, 0}
2501 static JSStaticFunction Instance_staticFunctions[7] = {
2502 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2503 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2504 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2505 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2506 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2507 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2511 static JSStaticFunction Internal_staticFunctions[2] = {
2512 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2516 static JSStaticFunction Selector_staticFunctions[5] = {
2517 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2518 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2519 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2520 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2524 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2525 apr_pool_t *pool(CYGetGlobalPool());
2527 Object_type = new(pool) Type_privateData("@");
2528 Selector_type = new(pool) Type_privateData(":");
2531 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2532 if (NSCFBoolean_ == nil)
2533 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2535 NSCFType_ = objc_getClass("NSCFType");
2536 NSGenericDeallocHandler_ = objc_getClass("__NSGenericDeallocHandler");
2537 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2538 NSZombie_ = objc_getClass("_NSZombie_");
2540 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2543 NSArray_ = objc_getClass("NSArray");
2544 NSBlock_ = objc_getClass("NSBlock");
2545 NSDictionary_ = objc_getClass("NSDictionary");
2546 NSString_ = objc_getClass("NSString");
2547 Object_ = objc_getClass("Object");
2549 JSClassDefinition definition;
2551 definition = kJSClassDefinitionEmpty;
2552 definition.className = "Instance";
2553 definition.staticValues = Instance_staticValues;
2554 definition.staticFunctions = Instance_staticFunctions;
2555 definition.hasProperty = &Instance_hasProperty;
2556 definition.getProperty = &Instance_getProperty;
2557 definition.setProperty = &Instance_setProperty;
2558 definition.deleteProperty = &Instance_deleteProperty;
2559 definition.getPropertyNames = &Instance_getPropertyNames;
2560 definition.callAsConstructor = &Instance_callAsConstructor;
2561 definition.callAsFunction = &Instance_callAsFunction;
2562 definition.hasInstance = &Instance_hasInstance;
2563 definition.finalize = &CYFinalize;
2564 Instance_ = JSClassCreate(&definition);
2566 definition.className = "ArrayInstance";
2567 ArrayInstance_ = JSClassCreate(&definition);
2569 definition.className = "FunctionInstance";
2570 FunctionInstance_ = JSClassCreate(&definition);
2572 definition.className = "ObjectInstance";
2573 ObjectInstance_ = JSClassCreate(&definition);
2575 definition.className = "StringInstance";
2576 StringInstance_ = JSClassCreate(&definition);
2578 definition = kJSClassDefinitionEmpty;
2579 definition.className = "Internal";
2580 definition.staticFunctions = Internal_staticFunctions;
2581 definition.hasProperty = &Internal_hasProperty;
2582 definition.getProperty = &Internal_getProperty;
2583 definition.setProperty = &Internal_setProperty;
2584 definition.getPropertyNames = &Internal_getPropertyNames;
2585 definition.finalize = &CYFinalize;
2586 Internal_ = JSClassCreate(&definition);
2588 definition = kJSClassDefinitionEmpty;
2589 definition.className = "Message";
2590 definition.staticFunctions = cy::Functor::StaticFunctions;
2591 definition.callAsFunction = &Message_callAsFunction;
2592 definition.finalize = &CYFinalize;
2593 Message_ = JSClassCreate(&definition);
2595 definition = kJSClassDefinitionEmpty;
2596 definition.className = "Messages";
2597 definition.hasProperty = &Messages_hasProperty;
2598 definition.getProperty = &Messages_getProperty;
2599 definition.setProperty = &Messages_setProperty;
2600 #if 0 && OBJC_API_VERSION < 2
2601 definition.deleteProperty = &Messages_deleteProperty;
2603 definition.getPropertyNames = &Messages_getPropertyNames;
2604 definition.finalize = &CYFinalize;
2605 Messages_ = JSClassCreate(&definition);
2607 definition = kJSClassDefinitionEmpty;
2608 definition.className = "Selector";
2609 definition.staticValues = Selector_staticValues;
2610 definition.staticFunctions = Selector_staticFunctions;
2611 definition.callAsFunction = &Selector_callAsFunction;
2612 definition.finalize = &CYFinalize;
2613 Selector_ = JSClassCreate(&definition);
2615 definition = kJSClassDefinitionEmpty;
2616 definition.className = "Super";
2617 definition.staticFunctions = Internal_staticFunctions;
2618 definition.finalize = &CYFinalize;
2619 Super_ = JSClassCreate(&definition);
2621 definition = kJSClassDefinitionEmpty;
2622 definition.className = "ObjectiveC::Classes";
2623 definition.getProperty = &ObjectiveC_Classes_getProperty;
2624 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2625 ObjectiveC_Classes_ = JSClassCreate(&definition);
2627 definition = kJSClassDefinitionEmpty;
2628 definition.className = "ObjectiveC::Constants";
2629 definition.getProperty = &ObjectiveC_Constants_getProperty;
2630 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2631 ObjectiveC_Constants_ = JSClassCreate(&definition);
2633 #if OBJC_API_VERSION >= 2
2634 definition = kJSClassDefinitionEmpty;
2635 definition.className = "ObjectiveC::Images";
2636 definition.getProperty = &ObjectiveC_Images_getProperty;
2637 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2638 ObjectiveC_Images_ = JSClassCreate(&definition);
2640 definition = kJSClassDefinitionEmpty;
2641 definition.className = "ObjectiveC::Image::Classes";
2642 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2643 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2644 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2647 definition = kJSClassDefinitionEmpty;
2648 definition.className = "ObjectiveC::Protocols";
2649 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2650 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2651 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2653 #if defined(__APPLE__) && defined(__arm__) && 0
2654 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2658 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2662 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2663 JSObjectRef global(CYGetGlobalObject(context));
2664 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2665 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2666 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2667 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2669 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2670 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2672 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2673 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2674 CYArrayPush(context, alls, protocols);
2676 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2677 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2678 CYArrayPush(context, alls, classes);
2680 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2681 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2682 CYArrayPush(context, alls, constants);
2684 #if OBJC_API_VERSION >= 2
2685 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2688 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2689 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2690 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2691 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2693 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2694 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2696 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2697 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2698 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2699 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2700 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2702 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2703 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2704 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2705 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2706 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2708 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2709 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2710 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2711 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2712 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2714 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2715 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2716 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2717 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2718 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2720 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2721 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2722 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2724 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2725 CYSetProperty(context, Instance, CYJSString("box"), box);
2727 #if defined(__APPLE__) && defined(__arm__) && 0
2728 CYSetProperty(context, all, CYJSString("objc_registerClassPair"), &objc_registerClassPair_, kJSPropertyAttributeDontEnum);
2731 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2733 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2734 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2737 static CYHooks CYObjectiveCHooks = {
2738 &CYObjectiveC_ExecuteStart,
2739 &CYObjectiveC_ExecuteEnd,
2740 &CYObjectiveC_CallFunction,
2741 &CYObjectiveC_Initialize,
2742 &CYObjectiveC_SetupContext,
2743 &CYObjectiveC_PoolFFI,
2744 &CYObjectiveC_FromFFI,
2747 struct CYObjectiveC {
2749 hooks_ = &CYObjectiveCHooks;
2750 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2751 _assert(hooks_ != NULL);