1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 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_;
268 static Class NSBoolNumber_;
271 static Class NSArray_;
272 static Class NSBlock_;
273 static Class NSDictionary_;
274 static Class NSNumber_;
275 static Class NSString_;
276 static Class NSZombie_;
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];
454 if (_class == NSZombie_)
455 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
457 SEL sel(@selector(cy$toCYON:inSet:));
459 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
460 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
461 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
462 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
463 return [value cy$toCYON:objective inSet:objects];
465 return [NSString stringWithFormat:@"%@", value];
468 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
470 return CYCastNSCYON(value, objective, *objects);
472 std::set<void *> objects;
473 return CYCastNSCYON(value, objective, objects);
477 struct PropertyAttributes {
482 const char *variable;
495 PropertyAttributes(objc_property_t property) :
507 name = property_getName(property);
508 const char *attributes(property_getAttributes(property));
510 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
511 if ((next = strchr(token, ',')) != NULL)
514 case 'R': readonly = true; break;
515 case 'C': copy = true; break;
516 case '&': retain = true; break;
517 case 'N': nonatomic = true; break;
518 case 'G': getter_ = token + 1; break;
519 case 'S': setter_ = token + 1; break;
520 case 'V': variable = token + 1; break;
524 /*if (variable == NULL) {
525 variable = property_getName(property);
526 size_t size(strlen(variable));
527 char *name(new(pool_) char[size + 2]);
529 memcpy(name + 1, variable, size);
530 name[size + 1] = '\0';
535 const char *Getter() {
537 getter_ = pool_.strdup(name);
541 const char *Setter() {
542 if (setter_ == NULL && !readonly) {
543 size_t length(strlen(name));
545 char *temp(new(pool_) char[length + 5]);
551 temp[3] = toupper(name[0]);
552 memcpy(temp + 4, name + 1, length - 1);
555 temp[length + 3] = ':';
556 temp[length + 4] = '\0';
565 @interface CYWebUndefined : NSObject {
568 + (CYWebUndefined *) undefined;
572 @implementation CYWebUndefined
574 + (CYWebUndefined *) undefined {
575 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
581 #define WebUndefined CYWebUndefined
583 /* Bridge: CYJSObject {{{ */
584 @interface CYJSObject : NSMutableDictionary {
586 JSGlobalContextRef context_;
589 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
591 - (NSUInteger) count;
592 - (id) objectForKey:(id)key;
593 - (NSEnumerator *) keyEnumerator;
594 - (void) setObject:(id)object forKey:(id)key;
595 - (void) removeObjectForKey:(id)key;
599 /* Bridge: CYJSArray {{{ */
600 @interface CYJSArray : NSMutableArray {
602 JSGlobalContextRef context_;
605 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
607 - (NSUInteger) count;
608 - (id) objectAtIndex:(NSUInteger)index;
610 - (void) addObject:(id)anObject;
611 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
612 - (void) removeLastObject;
613 - (void) removeObjectAtIndex:(NSUInteger)index;
614 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
619 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
620 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
623 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
624 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
628 struct CYBlockDescriptor {
630 BlockDescriptor1 one_;
631 BlockDescriptor2 two_;
632 BlockDescriptor3 three_;
635 Closure_privateData *internal_;
638 void CYDisposeBlock(BlockLiteral *literal) {
639 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
642 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
643 JSObjectRef _this(CYCastJSObject(context, values[0]));
644 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
647 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
648 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
651 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
652 _assert(__NSMallocBlock__ != Nil);
653 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
655 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
656 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
658 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
659 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
661 literal->isa = __NSMallocBlock__;
662 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
663 literal->reserved = 0;
664 literal->descriptor = descriptor;
666 descriptor->d_.one_.size = sizeof(descriptor->d_);
667 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
668 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
670 return reinterpret_cast<NSBlock *>(literal);
674 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
675 if (CYJSValueIsNSObject(context, object)) {
676 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
677 return internal->GetValue();
680 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
681 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
682 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
685 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
686 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
690 @interface NSBoolNumber : NSNumber {
695 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
699 switch (JSType type = JSValueGetType(context, value)) {
700 case kJSTypeUndefined:
701 object = [WebUndefined undefined];
711 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
714 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
720 object = CYCopyNSNumber(context, value);
725 object = CYCopyNSString(context, value);
730 // XXX: this might could be more efficient
731 object = CYCastNSObject(pool, context, (JSObjectRef) value);
736 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
743 return CYPoolRelease(pool, object);
745 return [object retain];
748 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
749 return CYNSObject(pool, context, value, true);
752 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
753 return CYNSObject(&pool, context, value, false);
756 /* Bridge: NSArray {{{ */
757 @implementation NSArray (Cycript)
760 return [[self mutableCopy] autorelease];
763 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
764 _oassert(objects.insert(self).second);
766 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
767 [json appendString:@"@["];
771 for (id object in self) {
773 for (size_t index(0), count([self count]); index != count; ++index) {
774 id object([self objectAtIndex:index]);
777 [json appendString:@","];
780 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
781 [json appendString:CYCastNSCYON(object, true, objects)];
783 [json appendString:@","];
788 [json appendString:@"]"];
792 - (bool) cy$hasProperty:(NSString *)name {
793 if ([name isEqualToString:@"length"])
796 size_t index(CYGetIndex(name));
797 if (index == _not(size_t) || index >= [self count])
798 return [super cy$hasProperty:name];
803 - (NSObject *) cy$getProperty:(NSString *)name {
804 size_t index(CYGetIndex(name));
805 if (index == _not(size_t) || index >= [self count])
806 return [super cy$getProperty:name];
808 return [self objectAtIndex:index];
811 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
813 if ([name isEqualToString:@"length"])
814 return CYCastJSValue(context, [self count]);
817 return [super cy$getProperty:name inContext:context];
820 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
821 [super cy$getPropertyNames:names inContext:context];
823 for (size_t index(0), count([self count]); index != count; ++index) {
824 id object([self objectAtIndex:index]);
825 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
827 sprintf(name, "%zu", index);
828 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
833 + (bool) cy$hasImplicitProperties {
839 /* Bridge: NSBlock {{{ */
846 /* Bridge: NSBoolNumber {{{ */
848 @implementation NSBoolNumber (Cycript)
850 - (JSType) cy$JSType {
851 return kJSTypeBoolean;
854 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
855 NSString *value([self boolValue] ? @"true" : @"false");
856 return objective ? value : [NSString stringWithFormat:@"@%@", value];
859 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
860 return CYCastJSValue(context, (bool) [self boolValue]);
866 /* Bridge: NSDictionary {{{ */
867 @implementation NSDictionary (Cycript)
870 return [[self mutableCopy] autorelease];
873 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
874 _oassert(objects.insert(self).second);
876 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
877 [json appendString:@"@{"];
881 for (NSObject *key in self) {
883 NSEnumerator *keys([self keyEnumerator]);
884 while (NSObject *key = [keys nextObject]) {
887 [json appendString:@","];
890 [json appendString:CYCastNSCYON(key, true, objects)];
891 [json appendString:@":"];
892 NSObject *object([self objectForKey:key]);
893 [json appendString:CYCastNSCYON(object, true, objects)];
896 [json appendString:@"}"];
900 - (bool) cy$hasProperty:(NSString *)name {
901 return [self objectForKey:name] != nil;
904 - (NSObject *) cy$getProperty:(NSString *)name {
905 return [self objectForKey:name];
908 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
909 [super cy$getPropertyNames:names inContext:context];
912 for (NSObject *key in self) {
914 NSEnumerator *keys([self keyEnumerator]);
915 while (NSObject *key = [keys nextObject]) {
917 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
921 + (bool) cy$hasImplicitProperties {
927 /* Bridge: NSMutableArray {{{ */
928 @implementation NSMutableArray (Cycript)
930 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
931 if ([name isEqualToString:@"length"]) {
932 // XXX: is this not intelligent?
933 NSNumber *number(reinterpret_cast<NSNumber *>(value));
934 NSUInteger size([number unsignedIntegerValue]);
935 NSUInteger count([self count]);
937 [self removeObjectsInRange:NSMakeRange(size, count - size)];
938 else if (size != count) {
939 WebUndefined *undefined([WebUndefined undefined]);
940 for (size_t i(count); i != size; ++i)
941 [self addObject:undefined];
946 size_t index(CYGetIndex(name));
947 if (index == _not(size_t))
948 return [super cy$setProperty:name to:value];
950 id object(value ?: [NSNull null]);
952 size_t count([self count]);
954 [self replaceObjectAtIndex:index withObject:object];
956 if (index != count) {
957 WebUndefined *undefined([WebUndefined undefined]);
958 for (size_t i(count); i != index; ++i)
959 [self addObject:undefined];
962 [self addObject:object];
968 - (bool) cy$deleteProperty:(NSString *)name {
969 size_t index(CYGetIndex(name));
970 if (index == _not(size_t) || index >= [self count])
971 return [super cy$deleteProperty:name];
972 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
978 /* Bridge: NSMutableDictionary {{{ */
979 @implementation NSMutableDictionary (Cycript)
981 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
982 [self setObject:(value ?: [NSNull null]) forKey:name];
986 - (bool) cy$deleteProperty:(NSString *)name {
987 if ([self objectForKey:name] == nil)
990 [self removeObjectForKey:name];
997 /* Bridge: NSNumber {{{ */
998 @implementation NSNumber (Cycript)
1000 - (JSType) cy$JSType {
1002 // XXX: this just seems stupid
1003 if ([self class] == NSCFBoolean_)
1004 return kJSTypeBoolean;
1006 return kJSTypeNumber;
1009 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1010 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1011 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1014 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1015 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1016 } CYObjectiveCatch }
1020 /* Bridge: NSNull {{{ */
1021 @implementation NSNull (Cycript)
1023 - (JSType) cy$JSType {
1027 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1028 NSString *value(@"null");
1029 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1032 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1033 return CYJSNull(context);
1034 } CYObjectiveCatch }
1038 /* Bridge: NSObject {{{ */
1039 @implementation NSObject (Cycript)
1045 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1046 return [self cy$valueOfInContext:context];
1049 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1051 } CYObjectiveCatch }
1053 - (JSType) cy$JSType {
1054 return kJSTypeObject;
1057 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1058 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1061 - (bool) cy$hasProperty:(NSString *)name {
1065 - (NSObject *) cy$getProperty:(NSString *)name {
1069 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1070 if (NSObject *value = [self cy$getProperty:name])
1071 return CYCastJSValue(context, value);
1073 } CYObjectiveCatch }
1075 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1079 - (bool) cy$deleteProperty:(NSString *)name {
1083 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1086 + (bool) cy$hasImplicitProperties {
1092 /* Bridge: NSProxy {{{ */
1093 @implementation NSProxy (Cycript)
1095 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1096 return [[self description] cy$toCYON:objective inSet:objects];
1101 /* Bridge: NSSet {{{ */
1102 @implementation NSSet (Cycript)
1104 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1105 _oassert(objects.insert(self).second);
1107 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1108 [json appendString:@"[NSSet setWithArray:"];
1109 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1110 [json appendString:@"]]"];
1116 /* Bridge: NSString {{{ */
1117 @implementation NSString (Cycript)
1120 return [[self copy] autorelease];
1123 - (JSType) cy$JSType {
1124 return kJSTypeString;
1127 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1128 std::ostringstream str;
1131 CYUTF8String string(CYCastUTF8String(self));
1132 CYStringify(str, string.data, string.size);
1133 std::string value(str.str());
1134 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1137 - (bool) cy$hasProperty:(NSString *)name {
1138 size_t index(CYGetIndex(name));
1139 if (index == _not(size_t) || index >= [self length])
1140 return [super cy$hasProperty:name];
1145 - (NSObject *) cy$getProperty:(NSString *)name {
1146 size_t index(CYGetIndex(name));
1147 if (index == _not(size_t) || index >= [self length])
1148 return [super cy$getProperty:name];
1150 return [self substringWithRange:NSMakeRange(index, 1)];
1153 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1154 [super cy$getPropertyNames:names inContext:context];
1156 for (size_t index(0), length([self length]); index != length; ++index) {
1158 sprintf(name, "%zu", index);
1159 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1163 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1164 return CYCastJSValue(context, CYJSString(context, self));
1165 } CYObjectiveCatch }
1169 /* Bridge: WebUndefined {{{ */
1170 @implementation WebUndefined (Cycript)
1172 - (JSType) cy$JSType {
1173 return kJSTypeUndefined;
1176 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1177 NSString *value(@"undefined");
1178 return value; // XXX: maybe use the below code, adding @undefined?
1179 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1182 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1183 return CYJSUndefined(context);
1184 } CYObjectiveCatch }
1189 static bool CYIsClass(id self) {
1190 return class_isMetaClass(object_getClass(self));
1193 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1194 id self(CYCastNSObject(&pool, context, value));
1195 if (CYIsClass(self))
1196 return (Class) self;
1197 throw CYJSError(context, "got something that is not a Class");
1201 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1203 size_t size(JSPropertyNameArrayGetCount(names));
1204 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1205 for (size_t index(0); index != size; ++index)
1206 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1210 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1212 return CYJSNull(context);
1214 return CYMakeInstance(context, value);
1215 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1217 @implementation CYJSObject
1219 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1220 if ((self = [super init]) != nil) {
1222 context_ = CYGetJSContext(context);
1223 JSGlobalContextRetain(context_);
1224 JSValueProtect(context_, object_);
1226 } CYObjectiveCatch }
1228 - (void) dealloc { CYObjectiveTry {
1229 JSValueUnprotect(context_, object_);
1230 JSGlobalContextRelease(context_);
1232 } CYObjectiveCatch }
1234 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1236 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1238 return [super cy$toCYON:objective inSet:objects];
1240 return [NSString stringWithUTF8String:cyon];
1241 } CYObjectiveCatch }
1243 - (NSUInteger) count { CYObjectiveTry {
1244 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1245 size_t size(JSPropertyNameArrayGetCount(names));
1246 JSPropertyNameArrayRelease(names);
1248 } CYObjectiveCatch }
1250 - (id) objectForKey:(id)key { CYObjectiveTry {
1251 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1252 if (JSValueIsUndefined(context, value))
1254 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1255 } CYObjectiveCatch }
1257 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1258 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1259 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1260 JSPropertyNameArrayRelease(names);
1262 } CYObjectiveCatch }
1264 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1265 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1266 } CYObjectiveCatch }
1268 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1269 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1270 } CYObjectiveCatch }
1274 @implementation CYJSArray
1276 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1278 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1279 } CYObjectiveCatch }
1281 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1282 if ((self = [super init]) != nil) {
1284 context_ = CYGetJSContext(context);
1285 JSGlobalContextRetain(context_);
1286 JSValueProtect(context_, object_);
1288 } CYObjectiveCatch }
1290 - (void) dealloc { CYObjectiveTry {
1291 JSValueUnprotect(context_, object_);
1292 JSGlobalContextRelease(context_);
1294 } CYObjectiveCatch }
1296 - (NSUInteger) count { CYObjectiveTry {
1297 return CYArrayLength(context, object_);
1298 } CYObjectiveCatch }
1300 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1301 size_t bounds([self count]);
1302 if (index >= bounds)
1303 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1304 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1305 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1306 } CYObjectiveCatch }
1308 - (void) addObject:(id)object { CYObjectiveTry {
1309 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1310 } CYObjectiveCatch }
1312 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1313 size_t bounds([self count] + 1);
1314 if (index >= bounds)
1315 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1316 JSValueRef arguments[3];
1317 arguments[0] = CYCastJSValue(context, index);
1318 arguments[1] = CYCastJSValue(context, 0);
1319 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1320 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1321 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1322 } CYObjectiveCatch }
1324 - (void) removeLastObject { CYObjectiveTry {
1325 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1326 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1327 } CYObjectiveCatch }
1329 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1330 size_t bounds([self count]);
1331 if (index >= bounds)
1332 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1333 JSValueRef arguments[2];
1334 arguments[0] = CYCastJSValue(context, index);
1335 arguments[1] = CYCastJSValue(context, 1);
1336 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1337 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1338 } CYObjectiveCatch }
1340 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1341 size_t bounds([self count]);
1342 if (index >= bounds)
1343 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1344 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1345 } CYObjectiveCatch }
1349 // XXX: inherit from or replace with CYJSObject
1350 @interface CYInternal : NSObject {
1351 JSGlobalContextRef context_;
1352 JSObjectRef object_;
1357 @implementation CYInternal
1359 - (void) dealloc { CYObjectiveTry {
1360 JSValueUnprotect(context_, object_);
1361 JSGlobalContextRelease(context_);
1363 } CYObjectiveCatch }
1365 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1366 if ((self = [super init]) != nil) {
1367 context_ = CYGetJSContext(context);
1368 JSGlobalContextRetain(context_);
1370 } CYObjectiveCatch }
1372 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1373 if (object_ == NULL)
1376 return JSObjectHasProperty(context, object_, name);
1379 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1380 if (object_ == NULL)
1383 return CYGetProperty(context, object_, name);
1386 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1387 @synchronized (self) {
1388 if (object_ == NULL) {
1389 object_ = JSObjectMake(context, NULL, NULL);
1390 JSValueProtect(context, object_);
1394 CYSetProperty(context, object_, name, value);
1397 + (CYInternal *) get:(id)object {
1399 if (&objc_getAssociatedObject == NULL)
1402 @synchronized (object) {
1403 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1411 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1413 if (&objc_getAssociatedObject == NULL)
1416 @synchronized (object) {
1417 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1420 if (&objc_setAssociatedObject == NULL)
1423 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1424 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1434 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1435 Selector_privateData *internal(new Selector_privateData(sel));
1436 return JSObjectMake(context, Selector_, internal);
1439 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1440 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1441 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1442 return reinterpret_cast<SEL>(internal->value_);
1445 return sel_registerName(CYPoolCString(pool, context, value));
1449 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1450 return (void *) [[NSAutoreleasePool alloc] init];
1451 } CYSadCatch(NULL) }
1453 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1454 return [(NSAutoreleasePool *) handle release];
1457 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1458 ffi_call(cif, function, value, values);
1462 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1463 if (JSValueIsNull(context, value))
1465 JSObjectRef object(CYCastJSObject(context, value));
1467 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1468 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1470 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1471 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1475 _assert(JSObjectIsFunction(context, object));
1477 _assert(signature != NULL);
1478 _assert(signature->count != 0);
1480 sig::Signature modified;
1481 modified.count = signature->count + 1;
1482 modified.elements = new(pool) sig::Element[modified.count];
1484 modified.elements[0] = signature->elements[0];
1485 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1487 modified.elements[1].name = NULL;
1488 modified.elements[1].type = new(pool) sig::Type();
1489 modified.elements[1].offset = _not(size_t);
1491 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1492 modified.elements[1].type->primitive = sig::object_P;
1494 return CYMakeBlock(context, object, modified);
1498 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1499 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1501 switch (type->primitive) {
1504 // XXX: this function might not handle the idea of a null pool
1505 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1510 case sig::typename_P:
1511 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1514 case sig::selector_P:
1515 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1523 } CYSadCatch(false) }
1525 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1526 switch (type->primitive) {
1527 // XXX: do something epic about blocks
1530 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1531 JSObjectRef object(CYMakeInstance(context, value));
1534 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1536 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1537 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1538 _assert(internal->value_ == nil);
1539 internal->value_ = value;
1548 case sig::typename_P:
1549 if (Class value = *reinterpret_cast<Class *>(data))
1550 return CYMakeInstance(context, value, Instance::Permanent);
1553 case sig::selector_P:
1554 if (SEL value = *reinterpret_cast<SEL *>(data))
1555 return CYMakeSelector(context, value);
1559 return CYJSNull(context);
1563 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1565 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1566 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1570 method_getReturnType(method, type, sizeof(type));
1575 // XXX: possibly use a more "awesome" check?
1579 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1580 JSObjectRef _this(CYCastJSObject(context, values[0]));
1581 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1584 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1585 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1588 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1589 Message_privateData *internal(new Message_privateData(sel, type, imp));
1590 return JSObjectMake(context, Message_, internal);
1593 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1594 JSObjectRef function(CYCastJSObject(context, value));
1596 sig::Signature signature;
1597 sig::Parse(pool, &signature, encoding, &Structor_);
1598 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1599 // XXX: see notes in Library.cpp about needing to leak
1600 return reinterpret_cast<IMP>(internal->GetValue());
1603 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1604 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1605 Class _class(internal->GetValue());
1608 const char *name(CYPoolCString(pool, context, property));
1610 if (SEL sel = sel_getUid(name))
1611 if (class_getInstanceMethod(_class, sel) != NULL)
1617 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1618 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1619 Class _class(internal->GetValue());
1622 const char *name(CYPoolCString(pool, context, property));
1624 if (SEL sel = sel_getUid(name))
1625 if (objc_method *method = class_getInstanceMethod(_class, sel))
1626 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1631 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1632 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1633 Class _class(internal->GetValue());
1636 const char *name(CYPoolCString(pool, context, property));
1637 SEL sel(sel_registerName(name));
1642 if (JSValueIsObjectOfClass(context, value, Message_)) {
1643 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1644 type = sig::Unparse(pool, &message->signature_);
1645 imp = reinterpret_cast<IMP>(message->GetValue());
1646 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1647 type = method_getTypeEncoding(method);
1648 imp = CYMakeMessage(context, value, type);
1649 } else _assert(false);
1651 objc_method *method(NULL);
1653 objc_method **methods(class_copyMethodList(_class, &size));
1654 for (size_t i(0); i != size; ++i)
1655 if (sel_isEqual(method_getName(methods[i]), sel)) {
1656 method = methods[i];
1662 method_setImplementation(method, imp);
1664 class_addMethod(_class, sel, imp, type);
1669 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1670 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1671 Class _class(internal->GetValue());
1674 objc_method **data(class_copyMethodList(_class, &size));
1675 for (size_t i(0); i != size; ++i)
1676 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1680 static bool CYHasImplicitProperties(Class _class) {
1681 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1682 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1684 return [_class cy$hasImplicitProperties];
1687 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1688 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1689 id self(internal->GetValue());
1691 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1695 NSString *name(CYCastNSString(&pool, context, property));
1697 if (CYInternal *internal = [CYInternal get:self])
1698 if ([internal hasProperty:property inContext:context])
1701 Class _class(object_getClass(self));
1704 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1705 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1706 if ([self cy$hasProperty:name])
1708 } CYPoolCatch(false)
1710 const char *string(CYPoolCString(pool, context, name));
1712 if (class_getProperty(_class, string) != NULL)
1715 if (CYHasImplicitProperties(_class))
1716 if (SEL sel = sel_getUid(string))
1717 if (CYImplements(self, _class, sel, true))
1723 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1724 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1725 id self(internal->GetValue());
1727 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1728 return Internal::Make(context, self, object);
1731 NSString *name(CYCastNSString(&pool, context, property));
1733 if (CYInternal *internal = [CYInternal get:self])
1734 if (JSValueRef value = [internal getProperty:property inContext:context])
1738 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1742 const char *string(CYPoolCString(pool, context, name));
1743 Class _class(object_getClass(self));
1745 if (objc_property_t property = class_getProperty(_class, string)) {
1746 PropertyAttributes attributes(property);
1747 SEL sel(sel_registerName(attributes.Getter()));
1748 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1751 if (CYHasImplicitProperties(_class))
1752 if (SEL sel = sel_getUid(string))
1753 if (CYImplements(self, _class, sel, true))
1754 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1759 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1760 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1761 id self(internal->GetValue());
1765 NSString *name(CYCastNSString(&pool, context, property));
1766 NSObject *data(CYCastNSObject(&pool, context, value));
1769 if ([self cy$setProperty:name to:data])
1771 } CYPoolCatch(false)
1773 const char *string(CYPoolCString(pool, context, name));
1774 Class _class(object_getClass(self));
1776 if (objc_property_t property = class_getProperty(_class, string)) {
1777 PropertyAttributes attributes(property);
1778 if (const char *setter = attributes.Setter()) {
1779 SEL sel(sel_registerName(setter));
1780 JSValueRef arguments[1] = {value};
1781 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1786 size_t length(strlen(string));
1788 char set[length + 5];
1794 if (string[0] != '\0') {
1795 set[3] = toupper(string[0]);
1796 memcpy(set + 4, string + 1, length - 1);
1799 set[length + 3] = ':';
1800 set[length + 4] = '\0';
1802 if (SEL sel = sel_getUid(set))
1803 if (CYImplements(self, _class, sel)) {
1804 JSValueRef arguments[1] = {value};
1805 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1809 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1810 [internal setProperty:property toValue:value inContext:context];
1817 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1818 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1819 id self(internal->GetValue());
1822 NSString *name(CYCastNSString(NULL, context, property));
1823 return [self cy$deleteProperty:name];
1824 } CYPoolCatch(false)
1825 } CYCatch(false) return /*XXX*/ false; }
1827 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1828 const char *name(sel_getName(method_getName(method)));
1829 if (strchr(name, ':') != NULL)
1832 const char *type(method_getTypeEncoding(method));
1833 if (type == NULL || *type == '\0' || *type == 'v')
1836 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1839 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1840 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1841 id self(internal->GetValue());
1844 Class _class(object_getClass(self));
1848 objc_property_t *data(class_copyPropertyList(_class, &size));
1849 for (size_t i(0); i != size; ++i)
1850 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1854 if (CYHasImplicitProperties(_class))
1855 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1857 objc_method **data(class_copyMethodList(current, &size));
1858 for (size_t i(0); i != size; ++i)
1859 Instance_getPropertyNames_message(names, data[i]);
1864 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1865 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1866 [self cy$getPropertyNames:names inContext:context];
1870 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1871 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1872 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1876 static const char *CYBlockEncoding(NSBlock *self) {
1877 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1878 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1880 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1881 descriptor += sizeof(BlockDescriptor1);
1882 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1883 descriptor += sizeof(BlockDescriptor2);
1884 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1885 return descriptor3->signature;
1888 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1889 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1890 id self(internal->GetValue());
1892 if (const char *encoding = CYBlockEncoding(self)) {
1898 sig::Signature signature;
1899 sig::Parse(pool, &signature, encoding, &Structor_);
1902 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1904 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1905 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1906 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1910 CYThrow("NSBlock without signature field passed arguments");
1914 } CYPoolCatch(NULL);
1919 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1920 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1921 Class _class(internal->GetValue());
1922 if (!CYIsClass(_class))
1925 if (CYJSValueIsNSObject(context, instance)) {
1926 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1927 // XXX: this isn't always safe
1928 return [linternal->GetValue() isKindOfClass:_class];
1934 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1936 throw CYJSError(context, "incorrect number of arguments to Instance");
1938 id value(CYCastNSObject(&pool, context, arguments[0]));
1940 value = [NSNull null];
1941 return CYCastJSValue(context, [value cy$box]);
1944 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1945 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1948 id self(internal->GetValue());
1949 const char *name(CYPoolCString(pool, context, property));
1951 if (object_getInstanceVariable(self, name, NULL) != NULL)
1957 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1958 length = CYCastDouble(encoding + 1);
1962 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1963 for (size_t i(0); i != size; ++i)
1964 if (ivars[i] == ivar)
1966 else if (ivar_getOffset(ivars[i]) == offset) {
1967 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1968 _assert(encoding != NULL);
1969 _assert(encoding[0] == 'b');
1970 shift += CYCastDouble(encoding + 1);
1975 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1976 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1979 id self(internal->GetValue());
1980 const char *name(CYPoolCString(pool, context, property));
1983 if (strcmp(name, "isa") == 0)
1984 return CYCastJSValue(context, object_getClass(self));
1987 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1988 ptrdiff_t offset(ivar_getOffset(ivar));
1989 void *data(reinterpret_cast<uint8_t *>(self) + offset);
1991 const char *encoding(ivar_getTypeEncoding(ivar));
1992 _assert(encoding != NULL);
1993 _assert(encoding[0] != '\0');
1994 if (encoding[0] == 'b') {
1995 unsigned length, shift;
1996 CYBitField(length, shift, self, ivar, encoding, offset);
1997 _assert(shift + length <= sizeof(uintptr_t) * 8);
1998 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
1999 uintptr_t mask((1 << length) - 1);
2000 return CYCastJSValue(context, (field >> shift) & mask);
2002 auto type(new(pool) Type_privateData(encoding));
2003 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2010 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2011 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2014 id self(internal->GetValue());
2015 const char *name(CYPoolCString(pool, context, property));
2017 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2018 ptrdiff_t offset(ivar_getOffset(ivar));
2019 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2021 const char *encoding(ivar_getTypeEncoding(ivar));
2022 _assert(encoding != NULL);
2023 if (encoding[0] == 'b') {
2024 unsigned length, shift;
2025 CYBitField(length, shift, self, ivar, encoding, offset);
2026 _assert(shift + length <= sizeof(uintptr_t) * 8);
2027 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2028 uintptr_t mask((1 << length) - 1);
2029 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2031 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2032 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2040 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2041 if (Class super = class_getSuperclass(_class))
2042 Internal_getPropertyNames_(super, names);
2045 objc_ivar **data(class_copyIvarList(_class, &size));
2046 for (size_t i(0); i != size; ++i)
2047 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2051 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2052 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2055 id self(internal->GetValue());
2056 Class _class(object_getClass(self));
2058 Internal_getPropertyNames_(_class, names);
2061 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2062 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2063 return internal->GetOwner();
2066 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2068 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2071 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2073 NSString *name(CYCastNSString(&pool, context, property));
2074 if (Class _class = NSClassFromString(name))
2075 return CYMakeInstance(context, _class, Instance::Permanent);
2079 static Class *CYCopyClassList(size_t &size) {
2080 size = objc_getClassList(NULL, 0);
2081 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2084 size_t writ(objc_getClassList(data, size));
2090 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2101 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2103 if (Class *data = CYCopyClassList(size)) {
2104 for (size_t i(0); i != size; ++i)
2105 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2111 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2112 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2115 const char *name(CYPoolCString(pool, context, property));
2117 const char **data(objc_copyClassNamesForImage(internal, &size));
2119 for (size_t i(0); i != size; ++i)
2120 if (strcmp(name, data[i]) == 0) {
2121 if (Class _class = objc_getClass(name)) {
2122 value = CYMakeInstance(context, _class, Instance::Permanent);
2133 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2134 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2136 const char **data(objc_copyClassNamesForImage(internal, &size));
2137 for (size_t i(0); i != size; ++i)
2138 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2142 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2144 const char *name(CYPoolCString(pool, context, property));
2146 const char **data(objc_copyImageNames(&size));
2147 for (size_t i(0); i != size; ++i)
2148 if (strcmp(name, data[i]) == 0) {
2157 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2158 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2162 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2164 const char **data(objc_copyImageNames(&size));
2165 for (size_t i(0); i != size; ++i)
2166 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2171 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2173 const char *name(CYPoolCString(pool, context, property));
2174 if (Protocol *protocol = objc_getProtocol(name))
2175 return CYMakeInstance(context, protocol, Instance::Permanent);
2179 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2181 Protocol **data(objc_copyProtocolList(&size));
2182 for (size_t i(0); i != size; ++i)
2183 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2187 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2189 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2191 return CYJSNull(context);
2195 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2196 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2200 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2201 *data = reinterpret_cast<void *>(address);
2202 return KERN_SUCCESS;
2206 std::set<Class> query_;
2207 JSContextRef context_;
2208 JSObjectRef results_;
2211 struct CYObjectStruct {
2215 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2216 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2217 JSContextRef context(choice->context_);
2219 for (unsigned i(0); i != count; ++i) {
2220 vm_range_t &range(ranges[i]);
2221 void *data(reinterpret_cast<void *>(range.address));
2222 size_t size(range.size);
2224 if (size < sizeof(CYObjectStruct))
2227 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2229 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2231 Class isa(reinterpret_cast<Class>(pointers[0]));
2234 std::set<Class>::const_iterator result(choice->query_.find(isa));
2235 if (result == choice->query_.end())
2238 size_t needed(class_getInstanceSize(*result));
2239 // XXX: if (size < needed)
2241 size_t boundary(496);
2245 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2247 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2251 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2253 throw CYJSError(context, "choose() takes a class argument");
2255 CYGarbageCollect(context);
2258 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2260 vm_address_t *zones(NULL);
2262 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2263 _assert(error == KERN_SUCCESS);
2265 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2266 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2269 choice.context_ = context;
2270 choice.results_ = results;
2273 Class *classes(CYCopyClassList(number));
2274 _assert(classes != NULL);
2276 for (size_t i(0); i != number; ++i)
2277 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2278 if (current == _class) {
2279 choice.query_.insert(classes[i]);
2285 for (unsigned i(0); i != size; ++i) {
2286 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2287 if (zone == NULL || zone->introspect == NULL)
2290 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2298 #if defined(__i386__) || defined(__x86_64__)
2299 #define OBJC_MAX_STRUCT_BY_VALUE 8
2300 static int struct_forward_array[] = {
2301 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2302 #elif defined(__arm__)
2303 #define OBJC_MAX_STRUCT_BY_VALUE 1
2304 static int struct_forward_array[] = {
2306 #elif defined(__arm64__)
2309 #error missing objc-runtime-info
2313 static bool stret(ffi_type *ffi_type) {
2314 return ffi_type->type == FFI_TYPE_STRUCT && (
2315 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2316 struct_forward_array[ffi_type->size] != 0
2324 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2328 _class = object_getClass(self);
2332 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2333 imp = method_getImplementation(method);
2334 type = method_getTypeEncoding(method);
2339 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2340 type = CYPoolCString(pool, context, [method _typeString]);
2346 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2353 sig::Signature signature;
2354 sig::Parse(pool, &signature, type, &Structor_);
2356 size_t used(count + 3);
2357 if (used > signature.count) {
2358 sig::Element *elements(new (pool) sig::Element[used]);
2359 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2361 for (size_t index(signature.count); index != used; ++index) {
2362 sig::Element *element(&elements[index]);
2363 element->name = NULL;
2364 element->offset = _not(size_t);
2366 sig::Type *type(new (pool) sig::Type);
2367 memset(type, 0, sizeof(*type));
2368 type->primitive = sig::object_P;
2369 element->type = type;
2372 signature.elements = elements;
2373 signature.count = used;
2377 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2381 if (stret(cif.rtype))
2382 imp = class_getMethodImplementation_stret(_class, _cmd);
2385 imp = class_getMethodImplementation(_class, _cmd);
2388 void (*function)() = reinterpret_cast<void (*)()>(imp);
2389 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2392 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2394 throw CYJSError(context, "too few arguments to objc_msgSend");
2404 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2405 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2406 self = internal->GetValue();
2407 _class = internal->class_;;
2408 uninitialized = false;
2409 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2410 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2411 self = internal->GetValue();
2413 uninitialized = internal->IsUninitialized();
2415 internal->value_ = nil;
2417 self = CYCastNSObject(&pool, context, arguments[0]);
2419 uninitialized = false;
2423 return CYJSNull(context);
2425 _cmd = CYCastSEL(context, arguments[1]);
2427 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2430 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2431 return $objc_msgSend(context, object, _this, count, arguments);
2434 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2435 JSValueRef setup[count + 2];
2438 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2439 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2442 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2444 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2446 // XXX: handle Instance::Uninitialized?
2447 id self(CYCastNSObject(&pool, context, _this));
2451 setup[1] = &internal->sel_;
2453 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2456 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2458 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2460 id self(CYCastNSObject(&pool, context, arguments[0]));
2461 Class _class(CYCastClass(pool, context, arguments[1]));
2462 return cy::Super::Make(context, self, _class);
2465 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2467 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2469 const char *name(CYPoolCString(pool, context, arguments[0]));
2470 return CYMakeSelector(context, sel_registerName(name));
2473 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2475 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2476 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2477 return CYMakeInstance(context, self);
2480 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2481 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2482 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2485 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2486 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2487 Type_privateData *typical(internal->GetType());
2492 if (typical == NULL) {
2496 type = typical->type_;
2497 ffi = typical->ffi_;
2500 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2503 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2504 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2505 const char *encoding(CYBlockEncoding(internal->GetValue()));
2506 if (encoding == NULL)
2507 return CYJSNull(context);
2508 // XXX: this should be stored on a FunctionInstance private value subclass
2510 sig::Signature signature;
2511 sig::Parse(pool, &signature, encoding, &Structor_);
2512 return CYMakeType(context, &signature);
2515 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2516 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2517 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2520 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2521 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2522 id self(internal->GetValue());
2523 if (!CYIsClass(self))
2524 return CYJSUndefined(context);
2525 return CYGetClassPrototype(context, self);
2528 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2529 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2530 id self(internal->GetValue());
2531 if (!CYIsClass(self))
2532 return CYJSUndefined(context);
2533 return Messages::Make(context, (Class) self);
2536 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2537 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2539 if (!CYJSValueIsNSObject(context, _this))
2542 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2543 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2546 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2547 if (!CYJSValueIsNSObject(context, _this))
2550 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2551 id value(internal->GetValue());
2558 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2560 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2561 return CYJSUndefined(context);
2562 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2565 return CYCastJSValue(context, CYJSString(context, [value description]));
2567 } CYCatch(NULL) return /*XXX*/ NULL; }
2569 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2570 if (!CYJSValueIsNSObject(context, _this))
2573 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2574 id value(internal->GetValue());
2575 _assert(value != nil);
2577 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2580 if (JSValueRef result = [value cy$valueOfInContext:context])
2584 } CYCatch(NULL) return /*XXX*/ NULL; }
2586 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2587 if (!CYJSValueIsNSObject(context, _this))
2590 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2591 // XXX: but... but... THIS ISN'T A POINTER! :(
2592 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2593 } CYCatch(NULL) return /*XXX*/ NULL; }
2595 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2596 if (!CYJSValueIsNSObject(context, _this))
2599 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2600 id value(internal->GetValue());
2603 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2604 return CYCastJSValue(context, CYJSString(context, [value description]));
2606 } CYCatch(NULL) return /*XXX*/ NULL; }
2608 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2609 if (!CYJSValueIsNSObject(context, _this))
2612 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2613 id value(internal->GetValue());
2615 if (!CYIsClass(value))
2616 CYThrow("non-Class object cannot be used as Type");
2619 memset(&type, 0, sizeof(type));
2620 type.primitive = sig::object_P;
2621 type.name = class_getName(value);
2622 return CYMakeType(context, &type);
2623 } CYCatch(NULL) return /*XXX*/ NULL; }
2625 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2626 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2627 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2630 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2631 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2634 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2635 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2636 const char *name(sel_getName(internal->GetValue()));
2639 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2640 return CYCastJSValue(context, CYJSString(context, string));
2642 } CYCatch(NULL) return /*XXX*/ NULL; }
2644 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2646 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2649 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2650 SEL sel(internal->GetValue());
2652 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2653 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2654 const char *encoding(method_getTypeEncoding(method));
2656 sig::Signature signature;
2657 sig::Parse(pool, &signature, encoding, &Structor_);
2658 return CYMakeType(context, &signature);
2661 static JSStaticValue Selector_staticValues[2] = {
2662 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2663 {NULL, NULL, NULL, 0}
2666 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2667 static JSStaticValue Instance_staticValues[5] = {
2668 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2669 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2670 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2671 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2672 {NULL, NULL, NULL, 0}
2675 static JSStaticValue FunctionInstance_staticValues[6] = {
2676 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2677 // XXX: this is sadly a duplicate of Instance_staticValues
2678 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2679 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2680 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2681 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2682 {NULL, NULL, NULL, 0}
2685 static JSStaticFunction Instance_staticFunctions[7] = {
2686 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2687 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2688 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2689 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2690 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2691 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2695 static JSStaticFunction Class_staticFunctions[2] = {
2696 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2700 static JSStaticFunction Internal_staticFunctions[2] = {
2701 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 static JSStaticFunction Selector_staticFunctions[5] = {
2706 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2707 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2708 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2709 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2714 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2715 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2716 } CYObjectiveCatch }
2719 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2720 CYPool &pool(CYGetGlobalPool());
2722 Object_type = new(pool) Type_privateData(sig::object_P);
2723 Selector_type = new(pool) Type_privateData(sig::selector_P);
2725 NSArray_ = objc_getClass("NSArray");
2726 NSBlock_ = objc_getClass("NSBlock");
2727 NSDictionary_ = objc_getClass("NSDictionary");
2728 NSNumber_ = objc_getClass("NSNumber");
2729 NSString_ = objc_getClass("NSString");
2730 Object_ = objc_getClass("Object");
2733 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2735 // XXX: apparently, iOS now has both of these
2736 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2737 if (NSCFBoolean_ == nil)
2738 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2740 NSCFType_ = objc_getClass("NSCFType");
2742 NSZombie_ = objc_getClass("_NSZombie_");
2744 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2745 NSZombie_ = objc_getClass("NSZombie");
2748 JSClassDefinition definition;
2750 definition = kJSClassDefinitionEmpty;
2751 definition.className = "Instance";
2752 definition.staticValues = Instance_staticValues;
2753 definition.staticFunctions = Instance_staticFunctions;
2754 definition.hasProperty = &Instance_hasProperty;
2755 definition.getProperty = &Instance_getProperty;
2756 definition.setProperty = &Instance_setProperty;
2757 definition.deleteProperty = &Instance_deleteProperty;
2758 definition.getPropertyNames = &Instance_getPropertyNames;
2759 definition.callAsConstructor = &Instance_callAsConstructor;
2760 definition.hasInstance = &Instance_hasInstance;
2761 definition.finalize = &CYFinalize;
2762 Instance_ = JSClassCreate(&definition);
2764 definition.className = "ArrayInstance";
2765 ArrayInstance_ = JSClassCreate(&definition);
2767 definition.className = "BooleanInstance";
2768 BooleanInstance_ = JSClassCreate(&definition);
2770 definition.className = "NumberInstance";
2771 NumberInstance_ = JSClassCreate(&definition);
2773 definition.className = "ObjectInstance";
2774 ObjectInstance_ = JSClassCreate(&definition);
2776 definition.className = "StringInstance";
2777 StringInstance_ = JSClassCreate(&definition);
2779 definition.className = "FunctionInstance";
2780 definition.staticValues = FunctionInstance_staticValues;
2781 definition.callAsFunction = &FunctionInstance_callAsFunction;
2782 FunctionInstance_ = JSClassCreate(&definition);
2784 definition = kJSClassDefinitionEmpty;
2785 definition.className = "Class";
2786 definition.staticFunctions = Class_staticFunctions;
2787 Class_ = JSClassCreate(&definition);
2789 definition = kJSClassDefinitionEmpty;
2790 definition.className = "Internal";
2791 definition.staticFunctions = Internal_staticFunctions;
2792 definition.hasProperty = &Internal_hasProperty;
2793 definition.getProperty = &Internal_getProperty;
2794 definition.setProperty = &Internal_setProperty;
2795 definition.getPropertyNames = &Internal_getPropertyNames;
2796 definition.finalize = &CYFinalize;
2797 Internal_ = JSClassCreate(&definition);
2799 definition = kJSClassDefinitionEmpty;
2800 definition.className = "Message";
2801 definition.staticFunctions = cy::Functor::StaticFunctions;
2802 definition.staticValues = cy::Functor::StaticValues;
2803 definition.callAsFunction = &Message_callAsFunction;
2804 definition.finalize = &CYFinalize;
2805 Message_ = JSClassCreate(&definition);
2807 definition = kJSClassDefinitionEmpty;
2808 definition.className = "Messages";
2809 definition.hasProperty = &Messages_hasProperty;
2810 definition.getProperty = &Messages_getProperty;
2811 definition.setProperty = &Messages_setProperty;
2812 definition.getPropertyNames = &Messages_getPropertyNames;
2813 definition.finalize = &CYFinalize;
2814 Messages_ = JSClassCreate(&definition);
2816 definition = kJSClassDefinitionEmpty;
2817 definition.className = "Selector";
2818 definition.staticValues = Selector_staticValues;
2819 definition.staticFunctions = Selector_staticFunctions;
2820 definition.callAsFunction = &Selector_callAsFunction;
2821 definition.finalize = &CYFinalize;
2822 Selector_ = JSClassCreate(&definition);
2824 definition = kJSClassDefinitionEmpty;
2825 definition.className = "Super";
2826 definition.staticFunctions = Internal_staticFunctions;
2827 definition.finalize = &CYFinalize;
2828 Super_ = JSClassCreate(&definition);
2830 definition = kJSClassDefinitionEmpty;
2831 definition.className = "ObjectiveC::Classes";
2832 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2833 definition.getProperty = &ObjectiveC_Classes_getProperty;
2834 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2835 ObjectiveC_Classes_ = JSClassCreate(&definition);
2837 definition = kJSClassDefinitionEmpty;
2838 definition.className = "ObjectiveC::Constants";
2839 definition.getProperty = &ObjectiveC_Constants_getProperty;
2840 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2841 ObjectiveC_Constants_ = JSClassCreate(&definition);
2844 definition = kJSClassDefinitionEmpty;
2845 definition.className = "ObjectiveC::Images";
2846 definition.getProperty = &ObjectiveC_Images_getProperty;
2847 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2848 ObjectiveC_Images_ = JSClassCreate(&definition);
2850 definition = kJSClassDefinitionEmpty;
2851 definition.className = "ObjectiveC::Image::Classes";
2852 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2853 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2854 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2857 definition = kJSClassDefinitionEmpty;
2858 definition.className = "ObjectiveC::Protocols";
2859 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2860 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2861 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2864 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2865 // XXX: this is horrible; there has to be a better way to do this
2867 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2869 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2875 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2876 JSObjectRef global(CYGetGlobalObject(context));
2877 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2878 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2879 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2880 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2882 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2883 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2885 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2886 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2887 CYArrayPush(context, alls, protocols);
2889 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2890 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2891 CYArrayPush(context, alls, classes);
2893 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2894 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2895 CYArrayPush(context, alls, constants);
2898 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2901 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2902 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2903 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2904 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2905 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2907 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2908 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2910 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2911 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2912 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2913 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2914 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2916 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2917 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2918 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2919 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2920 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2922 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2923 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2924 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2925 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2926 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2928 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2929 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2930 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2931 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2932 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2934 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2935 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2936 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2937 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2938 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2940 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2941 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2942 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2943 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2944 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2946 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2947 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2948 CYSetPrototype(context, Class_prototype, Instance_prototype);
2950 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2951 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2952 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2954 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2955 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2958 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2961 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2963 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2964 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2967 static void *CYObjectiveC_CastSymbol(const char *name) {
2969 #ifdef __GNU_LIBOBJC__
2970 else if (strcmp(name, "object_getClass") == 0)
2971 return reinterpret_cast<void *>(&object_getClass);
2976 static CYHook CYObjectiveCHook = {
2977 &CYObjectiveC_ExecuteStart,
2978 &CYObjectiveC_ExecuteEnd,
2979 &CYObjectiveC_CallFunction,
2980 &CYObjectiveC_Initialize,
2981 &CYObjectiveC_SetupContext,
2982 &CYObjectiveC_PoolFFI,
2983 &CYObjectiveC_FromFFI,
2984 &CYObjectiveC_CastSymbol,
2987 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
2989 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
2990 CYSetupContext(context);
2991 } CYObjectiveCatch }
2993 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
2996 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
2997 CYStream stream(utf8.data, utf8.data + utf8.size);
2998 utf8 = CYPoolCode(pool, stream);
3000 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3001 size_t bytes(utf16.size * sizeof(uint16_t));
3002 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3003 memcpy(copy, utf16.data, bytes);
3007 } catch (const CYException &exception) {
3009 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];