1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2014 Jay Freeman (saurik)
5 /* GNU Affero General Public License, Version 3 {{{ */
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "cycript.hpp"
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/message.h>
27 #include <objc/runtime.h>
29 #include <Foundation/Foundation.h>
32 #include <CoreFoundation/CoreFoundation.h>
33 #include <JavaScriptCore/JSStringRefCF.h>
37 #include <malloc/malloc.h>
38 #include <mach/mach.h>
43 #include "JavaScript.hpp"
45 #include "Execute.hpp"
53 #define CYObjectiveTry_ { \
55 #define CYObjectiveTry { \
56 JSContextRef context(context_); \
58 #define CYObjectiveCatch \
59 catch (const CYException &error) { \
60 @throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
66 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
68 #define CYPoolCatch(value) \
69 @catch (NSException *error) { \
70 _saved = [error retain]; \
71 throw CYJSError(context, CYCastJSValue(context, error)); \
76 [_saved autorelease]; \
82 #define CYSadCatch(value) \
83 @catch (NSException *error ) { \
84 throw CYJSError(context, CYCastJSValue(context, error)); \
88 #define _oassert(test) \
90 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
98 void (*invoke)(void *, ...);
102 struct BlockDescriptor1 {
103 unsigned long int reserved;
104 unsigned long int size;
107 struct BlockDescriptor2 {
108 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
109 void (*dispose_helper)(BlockLiteral *src);
112 struct BlockDescriptor3 {
113 const char *signature;
118 BLOCK_DEALLOCATING = 0x0001,
119 BLOCK_REFCOUNT_MASK = 0xfffe,
120 BLOCK_NEEDS_FREE = 1 << 24,
121 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
122 BLOCK_HAS_CTOR = 1 << 26,
123 BLOCK_IS_GC = 1 << 27,
124 BLOCK_IS_GLOBAL = 1 << 28,
125 BLOCK_HAS_STRET = 1 << 29,
126 BLOCK_HAS_SIGNATURE = 1 << 30,
129 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
131 /* Objective-C Pool Release {{{ */
132 void CYPoolRelease_(void *data) {
133 id object(reinterpret_cast<id>(data));
137 id CYPoolRelease_(CYPool *pool, id object) {
140 else if (pool == NULL)
141 return [object autorelease];
143 pool->atexit(CYPoolRelease_);
148 template <typename Type_>
149 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
150 return (Type_) CYPoolRelease_(pool, (id) object);
153 /* Objective-C Strings {{{ */
154 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
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) {
164 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
168 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
171 // XXX: this definition scares me; is anyone using this?!
172 NSString *string([value description]);
174 return CYCopyJSString(context, string);
177 return CYCopyJSString(CYPoolCString(pool, context, string));
181 NSString *CYCopyNSString(const CYUTF8String &value) {
183 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
185 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
189 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
191 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
194 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
198 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
199 return CYCopyNSString(context, CYJSString(context, value));
202 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
203 return CYPoolRelease(pool, CYCopyNSString(value));
206 NSString *CYCastNSString(CYPool *pool, SEL sel) {
207 const char *name(sel_getName(sel));
208 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
211 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
212 return CYPoolRelease(pool, CYCopyNSString(context, value));
215 CYUTF8String CYCastUTF8String(NSString *value) {
216 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
217 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
221 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
223 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
224 if (exception == NULL)
226 *exception = CYCastJSValue(context, error);
229 size_t CYGetIndex(NSString *value) {
230 return CYGetIndex(CYCastUTF8String(value));
233 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
234 return CYGetOffset(CYPoolCString(pool, context, value), index);
237 static JSClassRef Instance_;
239 static JSClassRef ArrayInstance_;
240 static JSClassRef BooleanInstance_;
241 static JSClassRef FunctionInstance_;
242 static JSClassRef NumberInstance_;
243 static JSClassRef ObjectInstance_;
244 static JSClassRef StringInstance_;
246 static JSClassRef Class_;
247 static JSClassRef Internal_;
248 static JSClassRef Message_;
249 static JSClassRef Messages_;
250 static JSClassRef Selector_;
251 static JSClassRef Super_;
253 static JSClassRef ObjectiveC_Classes_;
254 static JSClassRef ObjectiveC_Constants_;
255 static JSClassRef ObjectiveC_Protocols_;
258 static JSClassRef ObjectiveC_Image_Classes_;
259 static JSClassRef ObjectiveC_Images_;
263 static Class __NSMallocBlock__;
264 static Class NSCFBoolean_;
265 static Class NSCFType_;
266 static Class NSGenericDeallocHandler_;
267 static Class NSZombie_;
269 static Class NSBoolNumber_;
272 static Class NSArray_;
273 static Class NSBlock_;
274 static Class NSDictionary_;
275 static Class NSNumber_;
276 static Class NSString_;
277 static Class Object_;
279 static Type_privateData *Object_type;
280 static Type_privateData *Selector_type;
282 Type_privateData *Instance::GetType() const {
286 Type_privateData *Selector_privateData::GetType() const {
287 return Selector_type;
290 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
292 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
294 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
295 else if (meta && !class_isMetaClass(self))
296 return CYGetCachedObject(context, CYJSString("Class_prototype"));
298 JSObjectRef global(CYGetGlobalObject(context));
299 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
302 sprintf(label, "i%p", self);
303 CYJSString name(label);
305 JSValueRef value(CYGetProperty(context, cy, name));
306 if (!JSValueIsUndefined(context, value))
309 JSClassRef _class(NULL);
310 JSValueRef prototype;
313 if (self == NSCFBoolean_)
315 if (self == NSBoolNumber_)
317 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
318 else if (self == NSArray_)
319 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
320 else if (self == NSBlock_)
321 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
322 else if (self == NSNumber_)
323 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
324 else if (self == NSDictionary_)
325 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
326 else if (self == NSString_)
327 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
329 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
331 JSObjectRef object(JSObjectMake(context, _class, NULL));
332 CYSetPrototype(context, object, prototype);
333 CYSetProperty(context, cy, name, object);
338 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
339 return CYGetClassPrototype(context, self, class_isMetaClass(self));
342 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
343 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
344 if (Class super = class_getSuperclass(_class))
345 CYSetPrototype(context, value, Messages::Make(context, super));
349 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
350 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
354 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
355 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
359 bool CYIsKindOfClass(id object, Class _class) {
360 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
366 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
367 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
368 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
372 Instance::~Instance() {
373 if ((flags_ & Permanent) == 0)
374 [GetValue() release];
377 struct Message_privateData :
382 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
383 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
389 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
390 _assert(object != nil);
393 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
395 if (weak != NULL && &JSWeakObjectMapGet != NULL)
396 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
400 if ((flags & Instance::Permanent) == 0)
401 object = [object retain];
403 JSObjectRef instance(Instance::Make(context, object, flags));
406 if (weak != NULL && &JSWeakObjectMapSet != NULL)
407 JSWeakObjectMapSet(context, weak, object, instance);
413 @interface NSMethodSignature (Cycript)
414 - (NSString *) _typeString;
417 @interface NSObject (Cycript)
419 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
420 - (JSType) cy$JSType;
422 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
423 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
425 - (bool) cy$hasProperty:(NSString *)name;
426 - (NSObject *) cy$getProperty:(NSString *)name;
427 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
428 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
429 - (bool) cy$deleteProperty:(NSString *)name;
430 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
432 + (bool) cy$hasImplicitProperties;
438 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
441 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
442 _assert(value != nil);
444 Class _class(object_getClass(value));
446 if (class_isMetaClass(_class)) {
447 const char *name(class_getName(value));
448 if (class_isMetaClass(value))
449 return [NSString stringWithFormat:@"object_getClass(%s)", name];
451 return [NSString stringWithUTF8String:name];
455 if (_class == NSZombie_)
456 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
459 SEL sel(@selector(cy$toCYON:inSet:));
461 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
462 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
463 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
464 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
465 return [value cy$toCYON:objective inSet:objects];
467 return [NSString stringWithFormat:@"%@", value];
470 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
472 return CYCastNSCYON(value, objective, *objects);
474 std::set<void *> objects;
475 return CYCastNSCYON(value, objective, objects);
480 struct PropertyAttributes {
485 const char *variable;
498 PropertyAttributes(objc_property_t property) :
510 name = property_getName(property);
511 const char *attributes(property_getAttributes(property));
513 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
514 if ((next = strchr(token, ',')) != NULL)
517 case 'R': readonly = true; break;
518 case 'C': copy = true; break;
519 case '&': retain = true; break;
520 case 'N': nonatomic = true; break;
521 case 'G': getter_ = token + 1; break;
522 case 'S': setter_ = token + 1; break;
523 case 'V': variable = token + 1; break;
527 /*if (variable == NULL) {
528 variable = property_getName(property);
529 size_t size(strlen(variable));
530 char *name(new(pool_) char[size + 2]);
532 memcpy(name + 1, variable, size);
533 name[size + 1] = '\0';
538 const char *Getter() {
540 getter_ = pool_.strdup(name);
544 const char *Setter() {
545 if (setter_ == NULL && !readonly) {
546 size_t length(strlen(name));
548 char *temp(new(pool_) char[length + 5]);
554 temp[3] = toupper(name[0]);
555 memcpy(temp + 4, name + 1, length - 1);
558 temp[length + 3] = ':';
559 temp[length + 4] = '\0';
569 @interface CYWebUndefined : NSObject {
572 + (CYWebUndefined *) undefined;
576 @implementation CYWebUndefined
578 + (CYWebUndefined *) undefined {
579 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
585 #define WebUndefined CYWebUndefined
587 /* Bridge: CYJSObject {{{ */
588 @interface CYJSObject : NSMutableDictionary {
590 JSGlobalContextRef context_;
593 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
595 - (NSUInteger) count;
596 - (id) objectForKey:(id)key;
597 - (NSEnumerator *) keyEnumerator;
598 - (void) setObject:(id)object forKey:(id)key;
599 - (void) removeObjectForKey:(id)key;
603 /* Bridge: CYJSArray {{{ */
604 @interface CYJSArray : NSMutableArray {
606 JSGlobalContextRef context_;
609 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
611 - (NSUInteger) count;
612 - (id) objectAtIndex:(NSUInteger)index;
614 - (void) addObject:(id)anObject;
615 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
616 - (void) removeLastObject;
617 - (void) removeObjectAtIndex:(NSUInteger)index;
618 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
623 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
624 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
627 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
628 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
632 struct CYBlockDescriptor {
634 BlockDescriptor1 one_;
635 BlockDescriptor2 two_;
636 BlockDescriptor3 three_;
639 Closure_privateData *internal_;
642 void CYDisposeBlock(BlockLiteral *literal) {
643 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
646 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
647 JSObjectRef _this(CYCastJSObject(context, values[0]));
648 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
651 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
652 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
655 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
656 _assert(__NSMallocBlock__ != Nil);
657 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
659 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
660 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
662 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
663 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
665 literal->isa = __NSMallocBlock__;
666 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
667 literal->reserved = 0;
668 literal->descriptor = descriptor;
670 descriptor->d_.one_.size = sizeof(descriptor->d_);
671 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
672 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
674 return reinterpret_cast<NSBlock *>(literal);
678 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
679 if (CYJSValueIsNSObject(context, object)) {
680 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
681 return internal->GetValue();
684 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
685 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
686 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
689 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
690 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
694 @interface NSBoolNumber : NSNumber {
699 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
703 switch (JSType type = JSValueGetType(context, value)) {
704 case kJSTypeUndefined:
705 object = [WebUndefined undefined];
715 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
718 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
724 object = CYCopyNSNumber(context, value);
729 object = CYCopyNSString(context, value);
734 // XXX: this might could be more efficient
735 object = CYCastNSObject(pool, context, (JSObjectRef) value);
740 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
747 return CYPoolRelease(pool, object);
749 return [object retain];
752 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
753 return CYNSObject(pool, context, value, true);
756 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
757 return CYNSObject(&pool, context, value, false);
760 /* Bridge: NSArray {{{ */
761 @implementation NSArray (Cycript)
764 return [[self mutableCopy] autorelease];
767 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
768 _oassert(objects.insert(self).second);
770 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
771 [json appendString:@"@["];
775 for (id object in self) {
777 for (size_t index(0), count([self count]); index != count; ++index) {
778 id object([self objectAtIndex:index]);
781 [json appendString:@","];
784 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
785 [json appendString:CYCastNSCYON(object, true, objects)];
787 [json appendString:@","];
792 [json appendString:@"]"];
796 - (bool) cy$hasProperty:(NSString *)name {
797 if ([name isEqualToString:@"length"])
800 size_t index(CYGetIndex(name));
801 if (index == _not(size_t) || index >= [self count])
802 return [super cy$hasProperty:name];
807 - (NSObject *) cy$getProperty:(NSString *)name {
808 size_t index(CYGetIndex(name));
809 if (index == _not(size_t) || index >= [self count])
810 return [super cy$getProperty:name];
812 return [self objectAtIndex:index];
815 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
817 if ([name isEqualToString:@"length"])
818 return CYCastJSValue(context, [self count]);
821 return [super cy$getProperty:name inContext:context];
824 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
825 [super cy$getPropertyNames:names inContext:context];
827 for (size_t index(0), count([self count]); index != count; ++index) {
828 id object([self objectAtIndex:index]);
829 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
831 sprintf(name, "%zu", index);
832 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
837 + (bool) cy$hasImplicitProperties {
843 /* Bridge: NSBlock {{{ */
850 /* Bridge: NSBoolNumber {{{ */
852 @implementation NSBoolNumber (Cycript)
854 - (JSType) cy$JSType {
855 return kJSTypeBoolean;
858 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
859 NSString *value([self boolValue] ? @"true" : @"false");
860 return objective ? value : [NSString stringWithFormat:@"@%@", value];
863 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
864 return CYCastJSValue(context, (bool) [self boolValue]);
870 /* Bridge: NSDictionary {{{ */
871 @implementation NSDictionary (Cycript)
874 return [[self mutableCopy] autorelease];
877 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
878 _oassert(objects.insert(self).second);
880 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
881 [json appendString:@"@{"];
885 for (NSObject *key in self) {
887 NSEnumerator *keys([self keyEnumerator]);
888 while (NSObject *key = [keys nextObject]) {
891 [json appendString:@","];
894 [json appendString:CYCastNSCYON(key, true, objects)];
895 [json appendString:@":"];
896 NSObject *object([self objectForKey:key]);
897 [json appendString:CYCastNSCYON(object, true, objects)];
900 [json appendString:@"}"];
904 - (bool) cy$hasProperty:(NSString *)name {
905 return [self objectForKey:name] != nil;
908 - (NSObject *) cy$getProperty:(NSString *)name {
909 return [self objectForKey:name];
912 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
913 [super cy$getPropertyNames:names inContext:context];
916 for (NSObject *key in self) {
918 NSEnumerator *keys([self keyEnumerator]);
919 while (NSObject *key = [keys nextObject]) {
921 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
925 + (bool) cy$hasImplicitProperties {
931 /* Bridge: NSMutableArray {{{ */
932 @implementation NSMutableArray (Cycript)
934 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
935 if ([name isEqualToString:@"length"]) {
936 // XXX: is this not intelligent?
937 NSNumber *number(reinterpret_cast<NSNumber *>(value));
939 NSUInteger size([number unsignedIntegerValue]);
941 NSUInteger size([number unsignedIntValue]);
943 NSUInteger count([self count]);
945 [self removeObjectsInRange:NSMakeRange(size, count - size)];
946 else if (size != count) {
947 WebUndefined *undefined([WebUndefined undefined]);
948 for (size_t i(count); i != size; ++i)
949 [self addObject:undefined];
954 size_t index(CYGetIndex(name));
955 if (index == _not(size_t))
956 return [super cy$setProperty:name to:value];
958 id object(value ?: [NSNull null]);
960 size_t count([self count]);
962 [self replaceObjectAtIndex:index withObject:object];
964 if (index != count) {
965 WebUndefined *undefined([WebUndefined undefined]);
966 for (size_t i(count); i != index; ++i)
967 [self addObject:undefined];
970 [self addObject:object];
976 - (bool) cy$deleteProperty:(NSString *)name {
977 size_t index(CYGetIndex(name));
978 if (index == _not(size_t) || index >= [self count])
979 return [super cy$deleteProperty:name];
980 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
986 /* Bridge: NSMutableDictionary {{{ */
987 @implementation NSMutableDictionary (Cycript)
989 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
990 [self setObject:(value ?: [NSNull null]) forKey:name];
994 - (bool) cy$deleteProperty:(NSString *)name {
995 if ([self objectForKey:name] == nil)
998 [self removeObjectForKey:name];
1005 /* Bridge: NSNumber {{{ */
1006 @implementation NSNumber (Cycript)
1008 - (JSType) cy$JSType {
1010 // XXX: this just seems stupid
1011 if ([self class] == NSCFBoolean_)
1012 return kJSTypeBoolean;
1014 return kJSTypeNumber;
1017 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1018 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1019 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1022 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1023 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1024 } CYObjectiveCatch }
1028 /* Bridge: NSNull {{{ */
1029 @implementation NSNull (Cycript)
1031 - (JSType) cy$JSType {
1035 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1036 NSString *value(@"null");
1037 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1040 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1041 return CYJSNull(context);
1042 } CYObjectiveCatch }
1046 /* Bridge: NSObject {{{ */
1047 @implementation NSObject (Cycript)
1053 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1054 return [self cy$valueOfInContext:context];
1057 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1059 } CYObjectiveCatch }
1061 - (JSType) cy$JSType {
1062 return kJSTypeObject;
1065 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1066 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1069 - (bool) cy$hasProperty:(NSString *)name {
1073 - (NSObject *) cy$getProperty:(NSString *)name {
1077 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1078 if (NSObject *value = [self cy$getProperty:name])
1079 return CYCastJSValue(context, value);
1081 } CYObjectiveCatch }
1083 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1087 - (bool) cy$deleteProperty:(NSString *)name {
1091 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1094 + (bool) cy$hasImplicitProperties {
1100 /* Bridge: NSProxy {{{ */
1101 @implementation NSProxy (Cycript)
1103 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1104 return [[self description] cy$toCYON:objective inSet:objects];
1109 /* Bridge: NSSet {{{ */
1110 @implementation NSSet (Cycript)
1112 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1113 _oassert(objects.insert(self).second);
1115 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1116 [json appendString:@"[NSSet setWithArray:"];
1117 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1118 [json appendString:@"]]"];
1124 /* Bridge: NSString {{{ */
1125 @implementation NSString (Cycript)
1128 return [[self copy] autorelease];
1131 - (JSType) cy$JSType {
1132 return kJSTypeString;
1135 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1136 std::ostringstream str;
1139 CYUTF8String string(CYCastUTF8String(self));
1140 CYStringify(str, string.data, string.size);
1141 std::string value(str.str());
1142 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1145 - (bool) cy$hasProperty:(NSString *)name {
1146 size_t index(CYGetIndex(name));
1147 if (index == _not(size_t) || index >= [self length])
1148 return [super cy$hasProperty:name];
1153 - (NSObject *) cy$getProperty:(NSString *)name {
1154 size_t index(CYGetIndex(name));
1155 if (index == _not(size_t) || index >= [self length])
1156 return [super cy$getProperty:name];
1158 return [self substringWithRange:NSMakeRange(index, 1)];
1161 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1162 [super cy$getPropertyNames:names inContext:context];
1164 for (size_t index(0), length([self length]); index != length; ++index) {
1166 sprintf(name, "%zu", index);
1167 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1171 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1172 return CYCastJSValue(context, CYJSString(context, self));
1173 } CYObjectiveCatch }
1177 /* Bridge: WebUndefined {{{ */
1178 @implementation WebUndefined (Cycript)
1180 - (JSType) cy$JSType {
1181 return kJSTypeUndefined;
1184 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1185 NSString *value(@"undefined");
1186 return value; // XXX: maybe use the below code, adding @undefined?
1187 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1190 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1191 return CYJSUndefined(context);
1192 } CYObjectiveCatch }
1197 static bool CYIsClass(id self) {
1199 return class_isMetaClass(object_getClass(self));
1201 return GSObjCIsClass(self);
1205 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1206 id self(CYCastNSObject(&pool, context, value));
1207 if (CYIsClass(self))
1208 return (Class) self;
1209 throw CYJSError(context, "got something that is not a Class");
1213 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1215 size_t size(JSPropertyNameArrayGetCount(names));
1216 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1217 for (size_t index(0); index != size; ++index)
1218 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1222 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1224 return CYJSNull(context);
1226 return CYMakeInstance(context, value);
1227 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1229 @implementation CYJSObject
1231 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1232 if ((self = [super init]) != nil) {
1234 context_ = CYGetJSContext(context);
1235 JSGlobalContextRetain(context_);
1236 JSValueProtect(context_, object_);
1238 } CYObjectiveCatch }
1240 - (void) dealloc { CYObjectiveTry {
1241 JSValueUnprotect(context_, object_);
1242 JSGlobalContextRelease(context_);
1244 } CYObjectiveCatch }
1246 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1248 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1250 return [super cy$toCYON:objective inSet:objects];
1252 return [NSString stringWithUTF8String:cyon];
1253 } CYObjectiveCatch }
1255 - (NSUInteger) count { CYObjectiveTry {
1256 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1257 size_t size(JSPropertyNameArrayGetCount(names));
1258 JSPropertyNameArrayRelease(names);
1260 } CYObjectiveCatch }
1262 - (id) objectForKey:(id)key { CYObjectiveTry {
1263 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1264 if (JSValueIsUndefined(context, value))
1266 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1267 } CYObjectiveCatch }
1269 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1270 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1271 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1272 JSPropertyNameArrayRelease(names);
1274 } CYObjectiveCatch }
1276 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1277 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1278 } CYObjectiveCatch }
1280 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1281 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1282 } CYObjectiveCatch }
1286 @implementation CYJSArray
1288 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1290 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1291 } CYObjectiveCatch }
1293 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1294 if ((self = [super init]) != nil) {
1296 context_ = CYGetJSContext(context);
1297 JSGlobalContextRetain(context_);
1298 JSValueProtect(context_, object_);
1300 } CYObjectiveCatch }
1302 - (void) dealloc { CYObjectiveTry {
1303 JSValueUnprotect(context_, object_);
1304 JSGlobalContextRelease(context_);
1306 } CYObjectiveCatch }
1308 - (NSUInteger) count { CYObjectiveTry {
1309 return CYArrayLength(context, object_);
1310 } CYObjectiveCatch }
1312 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1313 size_t bounds([self count]);
1314 if (index >= bounds)
1315 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1316 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1317 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1318 } CYObjectiveCatch }
1320 - (void) addObject:(id)object { CYObjectiveTry {
1321 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1322 } CYObjectiveCatch }
1324 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1325 size_t bounds([self count] + 1);
1326 if (index >= bounds)
1327 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1328 JSValueRef arguments[3];
1329 arguments[0] = CYCastJSValue(context, index);
1330 arguments[1] = CYCastJSValue(context, 0);
1331 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1332 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1333 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1334 } CYObjectiveCatch }
1336 - (void) removeLastObject { CYObjectiveTry {
1337 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1338 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1339 } CYObjectiveCatch }
1341 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1342 size_t bounds([self count]);
1343 if (index >= bounds)
1344 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1345 JSValueRef arguments[2];
1346 arguments[0] = CYCastJSValue(context, index);
1347 arguments[1] = CYCastJSValue(context, 1);
1348 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1349 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1350 } CYObjectiveCatch }
1352 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1353 size_t bounds([self count]);
1354 if (index >= bounds)
1355 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1356 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1357 } CYObjectiveCatch }
1361 // XXX: inherit from or replace with CYJSObject
1362 @interface CYInternal : NSObject {
1363 JSGlobalContextRef context_;
1364 JSObjectRef object_;
1369 @implementation CYInternal
1371 - (void) dealloc { CYObjectiveTry {
1372 JSValueUnprotect(context_, object_);
1373 JSGlobalContextRelease(context_);
1375 } CYObjectiveCatch }
1377 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1378 if ((self = [super init]) != nil) {
1379 context_ = CYGetJSContext(context);
1380 JSGlobalContextRetain(context_);
1382 } CYObjectiveCatch }
1384 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1385 if (object_ == NULL)
1388 return JSObjectHasProperty(context, object_, name);
1391 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1392 if (object_ == NULL)
1395 return CYGetProperty(context, object_, name);
1398 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1399 @synchronized (self) {
1400 if (object_ == NULL) {
1401 object_ = JSObjectMake(context, NULL, NULL);
1402 JSValueProtect(context, object_);
1406 CYSetProperty(context, object_, name, value);
1409 + (CYInternal *) get:(id)object {
1411 if (&objc_getAssociatedObject == NULL)
1414 @synchronized (object) {
1415 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1423 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1425 if (&objc_getAssociatedObject == NULL)
1428 @synchronized (object) {
1429 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1432 if (&objc_setAssociatedObject == NULL)
1435 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1436 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1446 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1447 Selector_privateData *internal(new Selector_privateData(sel));
1448 return JSObjectMake(context, Selector_, internal);
1451 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1452 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1453 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1454 return reinterpret_cast<SEL>(internal->value_);
1457 return sel_registerName(CYPoolCString(pool, context, value));
1461 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1462 return (void *) [[NSAutoreleasePool alloc] init];
1463 } CYSadCatch(NULL) }
1465 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1466 return [(NSAutoreleasePool *) handle release];
1469 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1470 ffi_call(cif, function, value, values);
1474 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1475 if (JSValueIsNull(context, value))
1477 JSObjectRef object(CYCastJSObject(context, value));
1479 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1480 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1482 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1483 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1487 _assert(JSObjectIsFunction(context, object));
1489 _assert(signature != NULL);
1490 _assert(signature->count != 0);
1492 sig::Signature modified;
1493 modified.count = signature->count + 1;
1494 modified.elements = new(pool) sig::Element[modified.count];
1496 modified.elements[0] = signature->elements[0];
1497 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1499 modified.elements[1].name = NULL;
1500 modified.elements[1].type = new(pool) sig::Type();
1501 modified.elements[1].offset = _not(size_t);
1503 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1504 modified.elements[1].type->primitive = sig::object_P;
1506 return CYMakeBlock(context, object, modified);
1510 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1511 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1513 switch (type->primitive) {
1516 // XXX: this function might not handle the idea of a null pool
1517 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1522 case sig::typename_P:
1523 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1526 case sig::selector_P:
1527 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1535 } CYSadCatch(false) }
1537 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1538 switch (type->primitive) {
1539 // XXX: do something epic about blocks
1542 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1543 JSObjectRef object(CYMakeInstance(context, value));
1546 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1548 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1549 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1550 _assert(internal->value_ == nil);
1551 internal->value_ = value;
1560 case sig::typename_P:
1561 if (Class value = *reinterpret_cast<Class *>(data))
1562 return CYMakeInstance(context, value, Instance::Permanent);
1565 case sig::selector_P:
1566 if (SEL value = *reinterpret_cast<SEL *>(data))
1567 return CYMakeSelector(context, value);
1571 return CYJSNull(context);
1575 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1577 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1578 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1581 #if OBJC_API_VERSION >= 2
1583 method_getReturnType(method, type, sizeof(type));
1585 const char *type(method_getTypeEncoding(method));
1591 // XXX: possibly use a more "awesome" check?
1595 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1596 JSObjectRef _this(CYCastJSObject(context, values[0]));
1597 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1600 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1601 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1604 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1605 Message_privateData *internal(new Message_privateData(sel, type, imp));
1606 return JSObjectMake(context, Message_, internal);
1609 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1610 JSObjectRef function(CYCastJSObject(context, value));
1612 sig::Signature signature;
1613 sig::Parse(pool, &signature, encoding, &Structor_);
1614 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1615 // XXX: see notes in Library.cpp about needing to leak
1616 return reinterpret_cast<IMP>(internal->GetValue());
1619 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1620 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1621 Class _class(internal->GetValue());
1624 const char *name(CYPoolCString(pool, context, property));
1626 if (SEL sel = sel_getUid(name))
1627 if (class_getInstanceMethod(_class, sel) != NULL)
1633 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1634 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1635 Class _class(internal->GetValue());
1638 const char *name(CYPoolCString(pool, context, property));
1640 if (SEL sel = sel_getUid(name))
1641 if (objc_method *method = class_getInstanceMethod(_class, sel))
1642 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1647 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1648 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1649 Class _class(internal->GetValue());
1652 const char *name(CYPoolCString(pool, context, property));
1653 SEL sel(sel_registerName(name));
1658 if (JSValueIsObjectOfClass(context, value, Message_)) {
1659 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1660 type = sig::Unparse(pool, &message->signature_);
1661 imp = reinterpret_cast<IMP>(message->GetValue());
1662 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1663 type = method_getTypeEncoding(method);
1664 imp = CYMakeMessage(context, value, type);
1665 } else _assert(false);
1667 objc_method *method(NULL);
1669 objc_method **methods(class_copyMethodList(_class, &size));
1670 for (size_t i(0); i != size; ++i)
1671 if (sel_isEqual(method_getName(methods[i]), sel)) {
1672 method = methods[i];
1678 method_setImplementation(method, imp);
1680 class_addMethod(_class, sel, imp, type);
1685 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1686 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1687 Class _class(internal->GetValue());
1690 objc_method **data(class_copyMethodList(_class, &size));
1691 for (size_t i(0); i != size; ++i)
1692 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1696 static bool CYHasImplicitProperties(Class _class) {
1697 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1698 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1700 return [_class cy$hasImplicitProperties];
1703 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1707 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1711 NSString *name(CYCastNSString(&pool, context, property));
1713 if (CYInternal *internal = [CYInternal get:self])
1714 if ([internal hasProperty:property inContext:context])
1717 Class _class(object_getClass(self));
1720 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1721 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1722 if ([self cy$hasProperty:name])
1724 } CYPoolCatch(false)
1726 const char *string(CYPoolCString(pool, context, name));
1729 if (class_getProperty(_class, string) != NULL)
1733 if (CYHasImplicitProperties(_class))
1734 if (SEL sel = sel_getUid(string))
1735 if (CYImplements(self, _class, sel, true))
1741 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1742 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1743 id self(internal->GetValue());
1745 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1746 return Internal::Make(context, self, object);
1749 NSString *name(CYCastNSString(&pool, context, property));
1751 if (CYInternal *internal = [CYInternal get:self])
1752 if (JSValueRef value = [internal getProperty:property inContext:context])
1756 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1760 const char *string(CYPoolCString(pool, context, name));
1761 Class _class(object_getClass(self));
1764 if (objc_property_t property = class_getProperty(_class, string)) {
1765 PropertyAttributes attributes(property);
1766 SEL sel(sel_registerName(attributes.Getter()));
1767 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1771 if (CYHasImplicitProperties(_class))
1772 if (SEL sel = sel_getUid(string))
1773 if (CYImplements(self, _class, sel, true))
1774 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1779 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1780 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1781 id self(internal->GetValue());
1785 NSString *name(CYCastNSString(&pool, context, property));
1786 NSObject *data(CYCastNSObject(&pool, context, value));
1789 if ([self cy$setProperty:name to:data])
1791 } CYPoolCatch(false)
1793 const char *string(CYPoolCString(pool, context, name));
1794 Class _class(object_getClass(self));
1797 if (objc_property_t property = class_getProperty(_class, string)) {
1798 PropertyAttributes attributes(property);
1799 if (const char *setter = attributes.Setter()) {
1800 SEL sel(sel_registerName(setter));
1801 JSValueRef arguments[1] = {value};
1802 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1808 size_t length(strlen(string));
1810 char set[length + 5];
1816 if (string[0] != '\0') {
1817 set[3] = toupper(string[0]);
1818 memcpy(set + 4, string + 1, length - 1);
1821 set[length + 3] = ':';
1822 set[length + 4] = '\0';
1824 if (SEL sel = sel_getUid(set))
1825 if (CYImplements(self, _class, sel)) {
1826 JSValueRef arguments[1] = {value};
1827 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1831 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1832 [internal setProperty:property toValue:value inContext:context];
1839 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1840 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1841 id self(internal->GetValue());
1844 NSString *name(CYCastNSString(NULL, context, property));
1845 return [self cy$deleteProperty:name];
1846 } CYPoolCatch(false)
1847 } CYCatch(false) return /*XXX*/ false; }
1849 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1850 const char *name(sel_getName(method_getName(method)));
1851 if (strchr(name, ':') != NULL)
1854 const char *type(method_getTypeEncoding(method));
1855 if (type == NULL || *type == '\0' || *type == 'v')
1858 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1861 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1862 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1863 id self(internal->GetValue());
1866 Class _class(object_getClass(self));
1871 objc_property_t *data(class_copyPropertyList(_class, &size));
1872 for (size_t i(0); i != size; ++i)
1873 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1878 if (CYHasImplicitProperties(_class))
1879 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1881 objc_method **data(class_copyMethodList(current, &size));
1882 for (size_t i(0); i != size; ++i)
1883 Instance_getPropertyNames_message(names, data[i]);
1888 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1889 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1890 [self cy$getPropertyNames:names inContext:context];
1894 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1895 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1896 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1900 static const char *CYBlockEncoding(NSBlock *self) {
1901 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1902 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1904 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1905 descriptor += sizeof(BlockDescriptor1);
1906 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1907 descriptor += sizeof(BlockDescriptor2);
1908 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1909 return descriptor3->signature;
1912 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1913 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1914 id self(internal->GetValue());
1916 if (const char *encoding = CYBlockEncoding(self)) {
1922 sig::Signature signature;
1923 sig::Parse(pool, &signature, encoding, &Structor_);
1926 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1928 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1929 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1930 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1934 CYThrow("NSBlock without signature field passed arguments");
1938 } CYPoolCatch(NULL);
1943 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1944 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1945 Class _class(internal->GetValue());
1946 if (!CYIsClass(_class))
1949 if (CYJSValueIsNSObject(context, instance)) {
1950 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1951 // XXX: this isn't always safe
1952 return [linternal->GetValue() isKindOfClass:_class];
1958 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1960 throw CYJSError(context, "incorrect number of arguments to Instance");
1962 id value(CYCastNSObject(&pool, context, arguments[0]));
1964 value = [NSNull null];
1965 return CYCastJSValue(context, [value cy$box]);
1968 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1969 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1972 id self(internal->GetValue());
1973 const char *name(CYPoolCString(pool, context, property));
1975 if (object_getInstanceVariable(self, name, NULL) != NULL)
1981 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1982 length = CYCastDouble(encoding + 1);
1986 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1987 for (size_t i(0); i != size; ++i)
1988 if (ivars[i] == ivar)
1990 else if (ivar_getOffset(ivars[i]) == offset) {
1991 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1992 _assert(encoding != NULL);
1993 _assert(encoding[0] == 'b');
1994 shift += CYCastDouble(encoding + 1);
1999 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2000 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2003 id self(internal->GetValue());
2004 const char *name(CYPoolCString(pool, context, property));
2007 if (strcmp(name, "isa") == 0)
2008 return CYCastJSValue(context, object_getClass(self));
2011 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2012 ptrdiff_t offset(ivar_getOffset(ivar));
2013 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2015 const char *encoding(ivar_getTypeEncoding(ivar));
2016 _assert(encoding != NULL);
2017 _assert(encoding[0] != '\0');
2018 if (encoding[0] == 'b') {
2019 unsigned length, shift;
2020 CYBitField(length, shift, self, ivar, encoding, offset);
2021 _assert(shift + length <= sizeof(uintptr_t) * 8);
2022 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2023 uintptr_t mask((1 << length) - 1);
2024 return CYCastJSValue(context, (field >> shift) & mask);
2026 auto type(new(pool) Type_privateData(encoding));
2027 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2034 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2035 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2038 id self(internal->GetValue());
2039 const char *name(CYPoolCString(pool, context, property));
2041 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2042 ptrdiff_t offset(ivar_getOffset(ivar));
2043 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2045 const char *encoding(ivar_getTypeEncoding(ivar));
2046 _assert(encoding != NULL);
2047 if (encoding[0] == 'b') {
2048 unsigned length, shift;
2049 CYBitField(length, shift, self, ivar, encoding, offset);
2050 _assert(shift + length <= sizeof(uintptr_t) * 8);
2051 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2052 uintptr_t mask((1 << length) - 1);
2053 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2055 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2056 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2064 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2065 if (Class super = class_getSuperclass(_class))
2066 Internal_getPropertyNames_(super, names);
2069 objc_ivar **data(class_copyIvarList(_class, &size));
2070 for (size_t i(0); i != size; ++i)
2071 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2075 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2076 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2079 id self(internal->GetValue());
2080 Class _class(object_getClass(self));
2082 Internal_getPropertyNames_(_class, names);
2085 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2086 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2087 return internal->GetOwner();
2090 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2092 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2095 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2097 NSString *name(CYCastNSString(&pool, context, property));
2098 if (Class _class = NSClassFromString(name))
2099 return CYMakeInstance(context, _class, Instance::Permanent);
2103 static Class *CYCopyClassList(size_t &size) {
2104 size = objc_getClassList(NULL, 0);
2105 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2108 size_t writ(objc_getClassList(data, size));
2114 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2125 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2127 if (Class *data = CYCopyClassList(size)) {
2128 for (size_t i(0); i != size; ++i)
2129 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2134 #if OBJC_API_VERSION >= 2
2135 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2136 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2139 const char *name(CYPoolCString(pool, context, property));
2141 const char **data(objc_copyClassNamesForImage(internal, &size));
2143 for (size_t i(0); i != size; ++i)
2144 if (strcmp(name, data[i]) == 0) {
2145 if (Class _class = objc_getClass(name)) {
2146 value = CYMakeInstance(context, _class, Instance::Permanent);
2157 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2158 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2160 const char **data(objc_copyClassNamesForImage(internal, &size));
2161 for (size_t i(0); i != size; ++i)
2162 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2166 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2168 const char *name(CYPoolCString(pool, context, property));
2170 const char **data(objc_copyImageNames(&size));
2171 for (size_t i(0); i != size; ++i)
2172 if (strcmp(name, data[i]) == 0) {
2181 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2182 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2186 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2188 const char **data(objc_copyImageNames(&size));
2189 for (size_t i(0); i != size; ++i)
2190 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2195 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2197 const char *name(CYPoolCString(pool, context, property));
2198 if (Protocol *protocol = objc_getProtocol(name))
2199 return CYMakeInstance(context, protocol, Instance::Permanent);
2203 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2204 #if OBJC_API_VERSION >= 2
2206 Protocol **data(objc_copyProtocolList(&size));
2207 for (size_t i(0); i != size; ++i)
2208 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2215 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2217 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2219 return CYJSNull(context);
2223 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2224 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2228 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2229 *data = reinterpret_cast<void *>(address);
2230 return KERN_SUCCESS;
2234 std::set<Class> query_;
2235 JSContextRef context_;
2236 JSObjectRef results_;
2239 struct CYObjectStruct {
2243 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2244 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2245 JSContextRef context(choice->context_);
2247 for (unsigned i(0); i != count; ++i) {
2248 vm_range_t &range(ranges[i]);
2249 void *data(reinterpret_cast<void *>(range.address));
2250 size_t size(range.size);
2252 if (size < sizeof(CYObjectStruct))
2255 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2257 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2259 Class isa(reinterpret_cast<Class>(pointers[0]));
2262 std::set<Class>::const_iterator result(choice->query_.find(isa));
2263 if (result == choice->query_.end())
2266 size_t needed(class_getInstanceSize(*result));
2267 // XXX: if (size < needed)
2269 size_t boundary(496);
2273 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2275 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2279 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2281 throw CYJSError(context, "choose() takes a class argument");
2283 CYGarbageCollect(context);
2286 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2288 vm_address_t *zones(NULL);
2290 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2291 _assert(error == KERN_SUCCESS);
2293 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2294 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2297 choice.context_ = context;
2298 choice.results_ = results;
2301 Class *classes(CYCopyClassList(number));
2302 _assert(classes != NULL);
2304 for (size_t i(0); i != number; ++i)
2305 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2306 if (current == _class) {
2307 choice.query_.insert(classes[i]);
2313 for (unsigned i(0); i != size; ++i) {
2314 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2315 if (zone == NULL || zone->introspect == NULL)
2318 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2326 #if defined(__i386__) || defined(__x86_64__)
2327 #define OBJC_MAX_STRUCT_BY_VALUE 8
2328 static int struct_forward_array[] = {
2329 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2330 #elif defined(__arm__)
2331 #define OBJC_MAX_STRUCT_BY_VALUE 1
2332 static int struct_forward_array[] = {
2334 #elif defined(__arm64__)
2337 #error missing objc-runtime-info
2341 static bool stret(ffi_type *ffi_type) {
2342 return ffi_type->type == FFI_TYPE_STRUCT && (
2343 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2344 struct_forward_array[ffi_type->size] != 0
2350 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2354 _class = object_getClass(self);
2358 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2359 imp = method_getImplementation(method);
2360 type = method_getTypeEncoding(method);
2365 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2367 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2368 type = CYPoolCString(pool, context, [method _typeString]);
2376 sig::Signature signature;
2377 sig::Parse(pool, &signature, type, &Structor_);
2379 size_t used(count + 3);
2380 if (used > signature.count) {
2381 sig::Element *elements(new (pool) sig::Element[used]);
2382 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2384 for (size_t index(signature.count); index != used; ++index) {
2385 sig::Element *element(&elements[index]);
2386 element->name = NULL;
2387 element->offset = _not(size_t);
2389 sig::Type *type(new (pool) sig::Type);
2390 memset(type, 0, sizeof(*type));
2391 type->primitive = sig::object_P;
2392 element->type = type;
2395 signature.elements = elements;
2396 signature.count = used;
2400 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2405 if (stret(cif.rtype))
2406 imp = class_getMethodImplementation_stret(_class, _cmd);
2409 imp = class_getMethodImplementation(_class, _cmd);
2411 objc_super super = {self, _class};
2412 imp = objc_msg_lookup_super(&super, _cmd);
2416 void (*function)() = reinterpret_cast<void (*)()>(imp);
2417 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2420 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2422 throw CYJSError(context, "too few arguments to objc_msgSend");
2432 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2433 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2434 self = internal->GetValue();
2435 _class = internal->class_;;
2436 uninitialized = false;
2437 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2438 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2439 self = internal->GetValue();
2441 uninitialized = internal->IsUninitialized();
2443 internal->value_ = nil;
2445 self = CYCastNSObject(&pool, context, arguments[0]);
2447 uninitialized = false;
2451 return CYJSNull(context);
2453 _cmd = CYCastSEL(context, arguments[1]);
2455 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2458 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2459 return $objc_msgSend(context, object, _this, count, arguments);
2462 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2463 JSValueRef setup[count + 2];
2466 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2467 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2470 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2472 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2474 // XXX: handle Instance::Uninitialized?
2475 id self(CYCastNSObject(&pool, context, _this));
2479 setup[1] = &internal->sel_;
2481 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2484 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2486 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2488 id self(CYCastNSObject(&pool, context, arguments[0]));
2489 Class _class(CYCastClass(pool, context, arguments[1]));
2490 return cy::Super::Make(context, self, _class);
2493 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2495 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2497 const char *name(CYPoolCString(pool, context, arguments[0]));
2498 return CYMakeSelector(context, sel_registerName(name));
2501 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2503 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2504 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2505 return CYMakeInstance(context, self);
2508 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2509 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2510 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2513 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2514 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2515 Type_privateData *typical(internal->GetType());
2520 if (typical == NULL) {
2524 type = typical->type_;
2525 ffi = typical->ffi_;
2528 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2531 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2532 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2533 const char *encoding(CYBlockEncoding(internal->GetValue()));
2534 if (encoding == NULL)
2535 return CYJSNull(context);
2536 // XXX: this should be stored on a FunctionInstance private value subclass
2538 sig::Signature signature;
2539 sig::Parse(pool, &signature, encoding, &Structor_);
2540 return CYMakeType(context, &signature);
2543 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2544 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2545 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2548 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2549 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2550 id self(internal->GetValue());
2551 if (!CYIsClass(self))
2552 return CYJSUndefined(context);
2553 return CYGetClassPrototype(context, self);
2556 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2557 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2558 id self(internal->GetValue());
2559 if (!CYIsClass(self))
2560 return CYJSUndefined(context);
2561 return Messages::Make(context, (Class) self);
2564 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2565 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2567 if (!CYJSValueIsNSObject(context, _this))
2570 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2571 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2574 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2575 if (!CYJSValueIsNSObject(context, _this))
2578 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2579 id value(internal->GetValue());
2586 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2588 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2589 return CYJSUndefined(context);
2590 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2593 return CYCastJSValue(context, CYJSString(context, [value description]));
2595 } CYCatch(NULL) return /*XXX*/ NULL; }
2597 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2598 if (!CYJSValueIsNSObject(context, _this))
2601 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2602 id value(internal->GetValue());
2603 _assert(value != nil);
2605 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2608 if (JSValueRef result = [value cy$valueOfInContext:context])
2612 } CYCatch(NULL) return /*XXX*/ NULL; }
2614 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2615 if (!CYJSValueIsNSObject(context, _this))
2618 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2619 // XXX: but... but... THIS ISN'T A POINTER! :(
2620 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2621 } CYCatch(NULL) return /*XXX*/ NULL; }
2623 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2624 if (!CYJSValueIsNSObject(context, _this))
2627 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2628 id value(internal->GetValue());
2631 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2632 return CYCastJSValue(context, CYJSString(context, [value description]));
2634 } CYCatch(NULL) return /*XXX*/ NULL; }
2636 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2637 if (!CYJSValueIsNSObject(context, _this))
2640 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2641 id value(internal->GetValue());
2643 if (!CYIsClass(value))
2644 CYThrow("non-Class object cannot be used as Type");
2647 memset(&type, 0, sizeof(type));
2648 type.primitive = sig::object_P;
2649 type.name = class_getName(value);
2650 return CYMakeType(context, &type);
2651 } CYCatch(NULL) return /*XXX*/ NULL; }
2653 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2654 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2655 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2658 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2659 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2662 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2663 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2664 const char *name(sel_getName(internal->GetValue()));
2667 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2668 return CYCastJSValue(context, CYJSString(context, string));
2670 } CYCatch(NULL) return /*XXX*/ NULL; }
2672 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2674 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2677 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2678 SEL sel(internal->GetValue());
2680 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2681 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2682 const char *encoding(method_getTypeEncoding(method));
2684 sig::Signature signature;
2685 sig::Parse(pool, &signature, encoding, &Structor_);
2686 return CYMakeType(context, &signature);
2689 static JSStaticValue Selector_staticValues[2] = {
2690 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2691 {NULL, NULL, NULL, 0}
2694 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2695 static JSStaticValue Instance_staticValues[5] = {
2696 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2697 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2698 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2699 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2700 {NULL, NULL, NULL, 0}
2703 static JSStaticValue FunctionInstance_staticValues[6] = {
2704 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 // XXX: this is sadly a duplicate of Instance_staticValues
2706 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2707 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2708 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2709 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2710 {NULL, NULL, NULL, 0}
2713 static JSStaticFunction Instance_staticFunctions[7] = {
2714 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2715 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2716 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2717 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2719 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2723 static JSStaticFunction Class_staticFunctions[2] = {
2724 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 static JSStaticFunction Internal_staticFunctions[2] = {
2729 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2733 static JSStaticFunction Selector_staticFunctions[5] = {
2734 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2736 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2742 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2743 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2744 } CYObjectiveCatch }
2747 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2748 CYPool &pool(CYGetGlobalPool());
2750 Object_type = new(pool) Type_privateData(sig::object_P);
2751 Selector_type = new(pool) Type_privateData(sig::selector_P);
2753 NSArray_ = objc_getClass("NSArray");
2754 NSBlock_ = objc_getClass("NSBlock");
2755 NSDictionary_ = objc_getClass("NSDictionary");
2756 NSNumber_ = objc_getClass("NSNumber");
2757 NSString_ = objc_getClass("NSString");
2758 Object_ = objc_getClass("Object");
2761 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2763 // XXX: apparently, iOS now has both of these
2764 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2765 if (NSCFBoolean_ == nil)
2766 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2768 NSCFType_ = objc_getClass("NSCFType");
2770 NSZombie_ = objc_getClass("_NSZombie_");
2772 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2775 JSClassDefinition definition;
2777 definition = kJSClassDefinitionEmpty;
2778 definition.className = "Instance";
2779 definition.staticValues = Instance_staticValues;
2780 definition.staticFunctions = Instance_staticFunctions;
2781 definition.hasProperty = &Instance_hasProperty;
2782 definition.getProperty = &Instance_getProperty;
2783 definition.setProperty = &Instance_setProperty;
2784 definition.deleteProperty = &Instance_deleteProperty;
2785 definition.getPropertyNames = &Instance_getPropertyNames;
2786 definition.callAsConstructor = &Instance_callAsConstructor;
2787 definition.hasInstance = &Instance_hasInstance;
2788 definition.finalize = &CYFinalize;
2789 Instance_ = JSClassCreate(&definition);
2791 definition.className = "ArrayInstance";
2792 ArrayInstance_ = JSClassCreate(&definition);
2794 definition.className = "BooleanInstance";
2795 BooleanInstance_ = JSClassCreate(&definition);
2797 definition.className = "NumberInstance";
2798 NumberInstance_ = JSClassCreate(&definition);
2800 definition.className = "ObjectInstance";
2801 ObjectInstance_ = JSClassCreate(&definition);
2803 definition.className = "StringInstance";
2804 StringInstance_ = JSClassCreate(&definition);
2806 definition.className = "FunctionInstance";
2807 definition.staticValues = FunctionInstance_staticValues;
2808 definition.callAsFunction = &FunctionInstance_callAsFunction;
2809 FunctionInstance_ = JSClassCreate(&definition);
2811 definition = kJSClassDefinitionEmpty;
2812 definition.className = "Class";
2813 definition.staticFunctions = Class_staticFunctions;
2814 Class_ = JSClassCreate(&definition);
2816 definition = kJSClassDefinitionEmpty;
2817 definition.className = "Internal";
2818 definition.staticFunctions = Internal_staticFunctions;
2819 definition.hasProperty = &Internal_hasProperty;
2820 definition.getProperty = &Internal_getProperty;
2821 definition.setProperty = &Internal_setProperty;
2822 definition.getPropertyNames = &Internal_getPropertyNames;
2823 definition.finalize = &CYFinalize;
2824 Internal_ = JSClassCreate(&definition);
2826 definition = kJSClassDefinitionEmpty;
2827 definition.className = "Message";
2828 definition.staticFunctions = cy::Functor::StaticFunctions;
2829 definition.staticValues = cy::Functor::StaticValues;
2830 definition.callAsFunction = &Message_callAsFunction;
2831 definition.finalize = &CYFinalize;
2832 Message_ = JSClassCreate(&definition);
2834 definition = kJSClassDefinitionEmpty;
2835 definition.className = "Messages";
2836 definition.hasProperty = &Messages_hasProperty;
2837 definition.getProperty = &Messages_getProperty;
2838 definition.setProperty = &Messages_setProperty;
2839 definition.getPropertyNames = &Messages_getPropertyNames;
2840 definition.finalize = &CYFinalize;
2841 Messages_ = JSClassCreate(&definition);
2843 definition = kJSClassDefinitionEmpty;
2844 definition.className = "Selector";
2845 definition.staticValues = Selector_staticValues;
2846 definition.staticFunctions = Selector_staticFunctions;
2847 definition.callAsFunction = &Selector_callAsFunction;
2848 definition.finalize = &CYFinalize;
2849 Selector_ = JSClassCreate(&definition);
2851 definition = kJSClassDefinitionEmpty;
2852 definition.className = "Super";
2853 definition.staticFunctions = Internal_staticFunctions;
2854 definition.finalize = &CYFinalize;
2855 Super_ = JSClassCreate(&definition);
2857 definition = kJSClassDefinitionEmpty;
2858 definition.className = "ObjectiveC::Classes";
2859 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2860 definition.getProperty = &ObjectiveC_Classes_getProperty;
2861 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2862 ObjectiveC_Classes_ = JSClassCreate(&definition);
2864 definition = kJSClassDefinitionEmpty;
2865 definition.className = "ObjectiveC::Constants";
2866 definition.getProperty = &ObjectiveC_Constants_getProperty;
2867 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2868 ObjectiveC_Constants_ = JSClassCreate(&definition);
2870 #if OBJC_API_VERSION >= 2
2871 definition = kJSClassDefinitionEmpty;
2872 definition.className = "ObjectiveC::Images";
2873 definition.getProperty = &ObjectiveC_Images_getProperty;
2874 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2875 ObjectiveC_Images_ = JSClassCreate(&definition);
2877 definition = kJSClassDefinitionEmpty;
2878 definition.className = "ObjectiveC::Image::Classes";
2879 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2880 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2881 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2884 definition = kJSClassDefinitionEmpty;
2885 definition.className = "ObjectiveC::Protocols";
2886 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2887 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2888 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2891 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2892 // XXX: this is horrible; there has to be a better way to do this
2894 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2896 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2902 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2903 JSObjectRef global(CYGetGlobalObject(context));
2904 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2905 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2906 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2907 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2909 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2910 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2912 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2913 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2914 CYArrayPush(context, alls, protocols);
2916 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2917 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2918 CYArrayPush(context, alls, classes);
2920 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2921 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2922 CYArrayPush(context, alls, constants);
2924 #if OBJC_API_VERSION >= 2
2925 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2928 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2929 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2930 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2931 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2932 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2934 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2935 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2937 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2938 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2939 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2940 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2941 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2943 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2944 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2945 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2946 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2947 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2949 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2950 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2951 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2952 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2953 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2955 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2956 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2957 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2958 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2959 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2961 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2962 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2963 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2964 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2965 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2967 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2968 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2969 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2970 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2971 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2973 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2974 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2975 CYSetPrototype(context, Class_prototype, Instance_prototype);
2977 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2978 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2979 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2981 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2982 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2985 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2988 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2990 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2991 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2994 static CYHook CYObjectiveCHook = {
2995 &CYObjectiveC_ExecuteStart,
2996 &CYObjectiveC_ExecuteEnd,
2997 &CYObjectiveC_CallFunction,
2998 &CYObjectiveC_Initialize,
2999 &CYObjectiveC_SetupContext,
3000 &CYObjectiveC_PoolFFI,
3001 &CYObjectiveC_FromFFI,
3004 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3006 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3007 CYSetupContext(context);
3008 } CYObjectiveCatch }
3010 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3013 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3014 CYStream stream(utf8.data, utf8.data + utf8.size);
3015 utf8 = CYPoolCode(pool, stream);
3017 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3018 size_t bytes(utf16.size * sizeof(uint16_t));
3019 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3020 memcpy(copy, utf16.data, bytes);
3024 } catch (const CYException &exception) {
3026 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];