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"
32 #include <malloc/malloc.h>
33 #include <mach/mach.h>
36 #include <objc/message.h>
37 #include <objc/runtime.h>
40 #include <CoreFoundation/CoreFoundation.h>
41 #include <JavaScriptCore/JSStringRefCF.h>
44 #include <Foundation/Foundation.h>
48 #include "JavaScript.hpp"
50 #include "Execute.hpp"
52 #include "ObjectiveC/Internal.hpp"
54 #define CYObjectiveTry_ { \
56 #define CYObjectiveTry { \
57 JSContextRef context(context_); \
59 #define CYObjectiveCatch \
60 catch (const CYException &error) { \
61 @throw CYCastNSObject(NULL, context, error.CastJSValue(context, "Error")); \
67 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
69 #define CYPoolCatch(value) \
70 @catch (NSException *error) { \
71 _saved = [error retain]; \
72 throw CYJSError(context, CYCastJSValue(context, error)); \
77 [_saved autorelease]; \
83 #define CYSadCatch(value) \
84 @catch (NSException *error ) { \
85 throw CYJSError(context, CYCastJSValue(context, error)); \
89 #define _oassert(test) \
91 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
99 void (*invoke)(void *, ...);
103 struct BlockDescriptor1 {
104 unsigned long int reserved;
105 unsigned long int size;
108 struct BlockDescriptor2 {
109 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
110 void (*dispose_helper)(BlockLiteral *src);
113 struct BlockDescriptor3 {
114 const char *signature;
119 BLOCK_DEALLOCATING = 0x0001,
120 BLOCK_REFCOUNT_MASK = 0xfffe,
121 BLOCK_NEEDS_FREE = 1 << 24,
122 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
123 BLOCK_HAS_CTOR = 1 << 26,
124 BLOCK_IS_GC = 1 << 27,
125 BLOCK_IS_GLOBAL = 1 << 28,
126 BLOCK_HAS_STRET = 1 << 29,
127 BLOCK_HAS_SIGNATURE = 1 << 30,
130 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
132 /* Objective-C Pool Release {{{ */
133 void CYPoolRelease_(void *data) {
134 id object(reinterpret_cast<id>(data));
138 id CYPoolRelease_(CYPool *pool, id object) {
141 else if (pool == NULL)
142 return [object autorelease];
144 pool->atexit(CYPoolRelease_);
149 template <typename Type_>
150 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
151 return (Type_) CYPoolRelease_(pool, (id) object);
154 /* Objective-C Strings {{{ */
155 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
156 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
157 char *string(new(pool) char[size]);
158 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
159 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
164 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
165 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
169 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
172 // XXX: this definition scares me; is anyone using this?!
173 NSString *string([value description]);
175 return CYCopyJSString(context, string);
178 return CYCopyJSString(CYPoolCString(pool, context, string));
182 NSString *CYCopyNSString(const CYUTF8String &value) {
184 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
186 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
190 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
192 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
195 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
199 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
200 return CYCopyNSString(context, CYJSString(context, value));
203 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
204 return CYPoolRelease(pool, CYCopyNSString(value));
207 NSString *CYCastNSString(CYPool *pool, SEL sel) {
208 const char *name(sel_getName(sel));
209 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
212 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
213 return CYPoolRelease(pool, CYCopyNSString(context, value));
216 CYUTF8String CYCastUTF8String(NSString *value) {
217 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
218 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
222 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
224 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
225 if (exception == NULL)
227 *exception = CYCastJSValue(context, error);
230 size_t CYGetIndex(NSString *value) {
231 return CYGetIndex(CYCastUTF8String(value));
234 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
235 return CYGetOffset(CYPoolCString(pool, context, value), index);
238 static JSClassRef Instance_;
240 static JSClassRef ArrayInstance_;
241 static JSClassRef BooleanInstance_;
242 static JSClassRef FunctionInstance_;
243 static JSClassRef NumberInstance_;
244 static JSClassRef ObjectInstance_;
245 static JSClassRef StringInstance_;
247 static JSClassRef Class_;
248 static JSClassRef Internal_;
249 static JSClassRef Message_;
250 static JSClassRef Messages_;
251 static JSClassRef Selector_;
252 static JSClassRef Super_;
254 static JSClassRef ObjectiveC_Classes_;
255 static JSClassRef ObjectiveC_Constants_;
256 static JSClassRef ObjectiveC_Protocols_;
259 static JSClassRef ObjectiveC_Image_Classes_;
260 static JSClassRef ObjectiveC_Images_;
264 static Class __NSMallocBlock__;
265 static Class NSCFBoolean_;
266 static Class NSCFType_;
267 static Class NSGenericDeallocHandler_;
269 static Class NSBoolNumber_;
272 static Class NSArray_;
273 static Class NSBlock_;
274 static Class NSDictionary_;
275 static Class NSNumber_;
276 static Class NSString_;
277 static Class NSZombie_;
278 static Class Object_;
280 static Type_privateData *Object_type;
281 static Type_privateData *Selector_type;
283 Type_privateData *Instance::GetType() const {
287 Type_privateData *Selector_privateData::GetType() const {
288 return Selector_type;
291 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
293 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
295 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
296 else if (meta && !class_isMetaClass(self))
297 return CYGetCachedObject(context, CYJSString("Class_prototype"));
299 JSObjectRef global(CYGetGlobalObject(context));
300 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
303 sprintf(label, "i%p", self);
304 CYJSString name(label);
306 JSValueRef value(CYGetProperty(context, cy, name));
307 if (!JSValueIsUndefined(context, value))
310 JSClassRef _class(NULL);
311 JSValueRef prototype;
314 if (self == NSCFBoolean_)
316 if (self == NSBoolNumber_)
318 prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
319 else if (self == NSArray_)
320 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
321 else if (self == NSBlock_)
322 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
323 else if (self == NSNumber_)
324 prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
325 else if (self == NSDictionary_)
326 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
327 else if (self == NSString_)
328 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
330 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
332 JSObjectRef object(JSObjectMake(context, _class, NULL));
333 CYSetPrototype(context, object, prototype);
334 CYSetProperty(context, cy, name, object);
339 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
340 return CYGetClassPrototype(context, self, class_isMetaClass(self));
343 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
344 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
345 if (Class super = class_getSuperclass(_class))
346 CYSetPrototype(context, value, Messages::Make(context, super));
350 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
351 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
355 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
356 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
360 bool CYIsKindOfClass(id object, Class _class) {
361 for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
367 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
368 JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
369 CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
373 Instance::~Instance() {
374 if ((flags_ & Permanent) == 0)
375 [GetValue() release];
378 struct Message_privateData :
383 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
384 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
390 JSObjectRef CYMakeInstance(JSContextRef context, id object, Instance::Flags flags = Instance::None) {
391 _assert(object != nil);
394 JSWeakObjectMapRef weak(CYCastPointer<JSWeakObjectMapRef>(context, CYGetCachedValue(context, weak_s)));
396 if (weak != NULL && &JSWeakObjectMapGet != NULL)
397 if (JSObjectRef instance = JSWeakObjectMapGet(context, weak, object))
401 if ((flags & Instance::Permanent) == 0)
402 object = [object retain];
404 JSObjectRef instance(Instance::Make(context, object, flags));
407 if (weak != NULL && &JSWeakObjectMapSet != NULL)
408 JSWeakObjectMapSet(context, weak, object, instance);
414 @interface NSMethodSignature (Cycript)
415 - (NSString *) _typeString;
418 @interface NSObject (Cycript)
420 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
421 - (JSType) cy$JSType;
423 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
424 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
426 - (bool) cy$hasProperty:(NSString *)name;
427 - (NSObject *) cy$getProperty:(NSString *)name;
428 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
429 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
430 - (bool) cy$deleteProperty:(NSString *)name;
431 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
433 + (bool) cy$hasImplicitProperties;
439 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
442 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
443 _assert(value != nil);
445 Class _class(object_getClass(value));
447 if (class_isMetaClass(_class)) {
448 const char *name(class_getName(value));
449 if (class_isMetaClass(value))
450 return [NSString stringWithFormat:@"object_getClass(%s)", name];
452 return [NSString stringWithUTF8String:name];
455 if (_class == NSZombie_)
456 return [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
458 SEL sel(@selector(cy$toCYON:inSet:));
460 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
461 return reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
462 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:)))
463 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
464 return [value cy$toCYON:objective inSet:objects];
466 return [NSString stringWithFormat:@"%@", value];
469 NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
471 return CYCastNSCYON(value, objective, *objects);
473 std::set<void *> objects;
474 return CYCastNSCYON(value, objective, objects);
478 struct PropertyAttributes {
483 const char *variable;
496 PropertyAttributes(objc_property_t property) :
508 name = property_getName(property);
509 const char *attributes(property_getAttributes(property));
511 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
512 if ((next = strchr(token, ',')) != NULL)
515 case 'R': readonly = true; break;
516 case 'C': copy = true; break;
517 case '&': retain = true; break;
518 case 'N': nonatomic = true; break;
519 case 'G': getter_ = token + 1; break;
520 case 'S': setter_ = token + 1; break;
521 case 'V': variable = token + 1; break;
525 /*if (variable == NULL) {
526 variable = property_getName(property);
527 size_t size(strlen(variable));
528 char *name(new(pool_) char[size + 2]);
530 memcpy(name + 1, variable, size);
531 name[size + 1] = '\0';
536 const char *Getter() {
538 getter_ = pool_.strdup(name);
542 const char *Setter() {
543 if (setter_ == NULL && !readonly) {
544 size_t length(strlen(name));
546 char *temp(new(pool_) char[length + 5]);
552 temp[3] = toupper(name[0]);
553 memcpy(temp + 4, name + 1, length - 1);
556 temp[length + 3] = ':';
557 temp[length + 4] = '\0';
566 @interface CYWebUndefined : NSObject {
569 + (CYWebUndefined *) undefined;
573 @implementation CYWebUndefined
575 + (CYWebUndefined *) undefined {
576 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
582 #define WebUndefined CYWebUndefined
584 /* Bridge: CYJSObject {{{ */
585 @interface CYJSObject : NSMutableDictionary {
587 JSGlobalContextRef context_;
590 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
592 - (NSUInteger) count;
593 - (id) objectForKey:(id)key;
594 - (NSEnumerator *) keyEnumerator;
595 - (void) setObject:(id)object forKey:(id)key;
596 - (void) removeObjectForKey:(id)key;
600 /* Bridge: CYJSArray {{{ */
601 @interface CYJSArray : NSMutableArray {
603 JSGlobalContextRef context_;
606 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
608 - (NSUInteger) count;
609 - (id) objectAtIndex:(NSUInteger)index;
611 - (void) addObject:(id)anObject;
612 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
613 - (void) removeLastObject;
614 - (void) removeObjectAtIndex:(NSUInteger)index;
615 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
620 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
621 return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
624 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
625 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
629 struct CYBlockDescriptor {
631 BlockDescriptor1 one_;
632 BlockDescriptor2 two_;
633 BlockDescriptor3 three_;
636 Closure_privateData *internal_;
639 void CYDisposeBlock(BlockLiteral *literal) {
640 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
643 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
644 JSObjectRef _this(CYCastJSObject(context, values[0]));
645 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
648 NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
649 _assert(__NSMallocBlock__ != Nil);
650 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
652 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
653 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
655 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockAdapter_);
656 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
658 literal->isa = __NSMallocBlock__;
659 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
660 literal->reserved = 0;
661 literal->descriptor = descriptor;
663 descriptor->d_.one_.size = sizeof(descriptor->d_);
664 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
665 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
667 return reinterpret_cast<NSBlock *>(literal);
671 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
672 if (CYJSValueIsNSObject(context, object)) {
673 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
674 return internal->GetValue();
677 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
678 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
679 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
682 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
683 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
687 @interface NSBoolNumber : NSNumber {
692 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
696 switch (JSType type = JSValueGetType(context, value)) {
697 case kJSTypeUndefined:
698 object = [WebUndefined undefined];
708 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
711 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
717 object = CYCopyNSNumber(context, value);
722 object = CYCopyNSString(context, value);
727 // XXX: this might could be more efficient
728 object = CYCastNSObject(pool, context, (JSObjectRef) value);
733 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
740 return CYPoolRelease(pool, object);
742 return [object retain];
745 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
746 return CYNSObject(pool, context, value, true);
749 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
750 return CYNSObject(&pool, context, value, false);
753 /* Bridge: NSArray {{{ */
754 @implementation NSArray (Cycript)
757 return [[self mutableCopy] autorelease];
760 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
761 _oassert(objects.insert(self).second);
763 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
764 [json appendString:@"@["];
768 for (id object in self) {
770 for (size_t index(0), count([self count]); index != count; ++index) {
771 id object([self objectAtIndex:index]);
774 [json appendString:@","];
777 if (object != nil && [object cy$JSType] != kJSTypeUndefined)
778 [json appendString:CYCastNSCYON(object, true, objects)];
780 [json appendString:@","];
785 [json appendString:@"]"];
789 - (bool) cy$hasProperty:(NSString *)name {
790 if ([name isEqualToString:@"length"])
793 size_t index(CYGetIndex(name));
794 if (index == _not(size_t) || index >= [self count])
795 return [super cy$hasProperty:name];
800 - (NSObject *) cy$getProperty:(NSString *)name {
801 size_t index(CYGetIndex(name));
802 if (index == _not(size_t) || index >= [self count])
803 return [super cy$getProperty:name];
805 return [self objectAtIndex:index];
808 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
810 if ([name isEqualToString:@"length"])
811 return CYCastJSValue(context, [self count]);
814 return [super cy$getProperty:name inContext:context];
817 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
818 [super cy$getPropertyNames:names inContext:context];
820 for (size_t index(0), count([self count]); index != count; ++index) {
821 id object([self objectAtIndex:index]);
822 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
824 sprintf(name, "%zu", index);
825 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
830 + (bool) cy$hasImplicitProperties {
836 /* Bridge: NSBlock {{{ */
843 /* Bridge: NSBoolNumber {{{ */
845 @implementation NSBoolNumber (Cycript)
847 - (JSType) cy$JSType {
848 return kJSTypeBoolean;
851 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
852 NSString *value([self boolValue] ? @"true" : @"false");
853 return objective ? value : [NSString stringWithFormat:@"@%@", value];
856 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
857 return CYCastJSValue(context, (bool) [self boolValue]);
863 /* Bridge: NSDictionary {{{ */
864 @implementation NSDictionary (Cycript)
867 return [[self mutableCopy] autorelease];
870 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
871 _oassert(objects.insert(self).second);
873 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
874 [json appendString:@"@{"];
878 for (NSObject *key in self) {
880 NSEnumerator *keys([self keyEnumerator]);
881 while (NSObject *key = [keys nextObject]) {
884 [json appendString:@","];
887 [json appendString:CYCastNSCYON(key, true, objects)];
888 [json appendString:@":"];
889 NSObject *object([self objectForKey:key]);
890 [json appendString:CYCastNSCYON(object, true, objects)];
893 [json appendString:@"}"];
897 - (bool) cy$hasProperty:(NSString *)name {
898 return [self objectForKey:name] != nil;
901 - (NSObject *) cy$getProperty:(NSString *)name {
902 return [self objectForKey:name];
905 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
906 [super cy$getPropertyNames:names inContext:context];
909 for (NSObject *key in self) {
911 NSEnumerator *keys([self keyEnumerator]);
912 while (NSObject *key = [keys nextObject]) {
914 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
918 + (bool) cy$hasImplicitProperties {
924 /* Bridge: NSMutableArray {{{ */
925 @implementation NSMutableArray (Cycript)
927 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
928 if ([name isEqualToString:@"length"]) {
929 // XXX: is this not intelligent?
930 NSNumber *number(reinterpret_cast<NSNumber *>(value));
931 NSUInteger size([number unsignedIntegerValue]);
932 NSUInteger count([self count]);
934 [self removeObjectsInRange:NSMakeRange(size, count - size)];
935 else if (size != count) {
936 WebUndefined *undefined([WebUndefined undefined]);
937 for (size_t i(count); i != size; ++i)
938 [self addObject:undefined];
943 size_t index(CYGetIndex(name));
944 if (index == _not(size_t))
945 return [super cy$setProperty:name to:value];
947 id object(value ?: [NSNull null]);
949 size_t count([self count]);
951 [self replaceObjectAtIndex:index withObject:object];
953 if (index != count) {
954 WebUndefined *undefined([WebUndefined undefined]);
955 for (size_t i(count); i != index; ++i)
956 [self addObject:undefined];
959 [self addObject:object];
965 - (bool) cy$deleteProperty:(NSString *)name {
966 size_t index(CYGetIndex(name));
967 if (index == _not(size_t) || index >= [self count])
968 return [super cy$deleteProperty:name];
969 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
975 /* Bridge: NSMutableDictionary {{{ */
976 @implementation NSMutableDictionary (Cycript)
978 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
979 [self setObject:(value ?: [NSNull null]) forKey:name];
983 - (bool) cy$deleteProperty:(NSString *)name {
984 if ([self objectForKey:name] == nil)
987 [self removeObjectForKey:name];
994 /* Bridge: NSNumber {{{ */
995 @implementation NSNumber (Cycript)
997 - (JSType) cy$JSType {
999 // XXX: this just seems stupid
1000 if ([self class] == NSCFBoolean_)
1001 return kJSTypeBoolean;
1003 return kJSTypeNumber;
1006 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1007 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1008 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1011 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1012 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1013 } CYObjectiveCatch }
1017 /* Bridge: NSNull {{{ */
1018 @implementation NSNull (Cycript)
1020 - (JSType) cy$JSType {
1024 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1025 NSString *value(@"null");
1026 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1029 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1030 return CYJSNull(context);
1031 } CYObjectiveCatch }
1035 /* Bridge: NSObject {{{ */
1036 @implementation NSObject (Cycript)
1042 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1043 return [self cy$valueOfInContext:context];
1046 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1048 } CYObjectiveCatch }
1050 - (JSType) cy$JSType {
1051 return kJSTypeObject;
1054 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1055 return [@"#" stringByAppendingString:[[self description] cy$toCYON:true inSet:objects]];
1058 - (bool) cy$hasProperty:(NSString *)name {
1062 - (NSObject *) cy$getProperty:(NSString *)name {
1066 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1067 if (NSObject *value = [self cy$getProperty:name])
1068 return CYCastJSValue(context, value);
1070 } CYObjectiveCatch }
1072 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1076 - (bool) cy$deleteProperty:(NSString *)name {
1080 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1083 + (bool) cy$hasImplicitProperties {
1089 /* Bridge: NSOrderedSet {{{ */
1091 @implementation NSOrderedSet (Cycript)
1093 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1094 _oassert(objects.insert(self).second);
1096 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1097 [json appendString:@"[NSOrderedSet orderedSetWithArray:"];
1098 [json appendString:CYCastNSCYON([self array], true, objects)];
1099 [json appendString:@"]]"];
1106 /* Bridge: NSProxy {{{ */
1107 @implementation NSProxy (Cycript)
1109 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1110 return [[self description] cy$toCYON:objective inSet:objects];
1115 /* Bridge: NSSet {{{ */
1116 @implementation NSSet (Cycript)
1118 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1119 _oassert(objects.insert(self).second);
1121 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
1122 [json appendString:@"[NSSet setWithArray:"];
1123 [json appendString:CYCastNSCYON([self allObjects], true, objects)];
1124 [json appendString:@"]]"];
1130 /* Bridge: NSString {{{ */
1131 @implementation NSString (Cycript)
1134 return [[self copy] autorelease];
1137 - (JSType) cy$JSType {
1138 return kJSTypeString;
1141 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1142 std::ostringstream str;
1145 CYUTF8String string(CYCastUTF8String(self));
1146 CYStringify(str, string.data, string.size);
1147 std::string value(str.str());
1148 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1151 - (bool) cy$hasProperty:(NSString *)name {
1152 size_t index(CYGetIndex(name));
1153 if (index == _not(size_t) || index >= [self length])
1154 return [super cy$hasProperty:name];
1159 - (NSObject *) cy$getProperty:(NSString *)name {
1160 size_t index(CYGetIndex(name));
1161 if (index == _not(size_t) || index >= [self length])
1162 return [super cy$getProperty:name];
1164 return [self substringWithRange:NSMakeRange(index, 1)];
1167 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1168 [super cy$getPropertyNames:names inContext:context];
1170 for (size_t index(0), length([self length]); index != length; ++index) {
1172 sprintf(name, "%zu", index);
1173 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1177 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1178 return CYCastJSValue(context, CYJSString(context, self));
1179 } CYObjectiveCatch }
1183 /* Bridge: WebUndefined {{{ */
1184 @implementation WebUndefined (Cycript)
1186 - (JSType) cy$JSType {
1187 return kJSTypeUndefined;
1190 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
1191 NSString *value(@"undefined");
1192 return value; // XXX: maybe use the below code, adding @undefined?
1193 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1196 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1197 return CYJSUndefined(context);
1198 } CYObjectiveCatch }
1203 static bool CYIsClass(id self) {
1204 return class_isMetaClass(object_getClass(self));
1207 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1208 id self(CYCastNSObject(&pool, context, value));
1209 if (CYIsClass(self))
1210 return (Class) self;
1211 throw CYJSError(context, "got something that is not a Class");
1215 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1217 size_t size(JSPropertyNameArrayGetCount(names));
1218 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1219 for (size_t index(0); index != size; ++index)
1220 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1224 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1226 return CYJSNull(context);
1228 return CYMakeInstance(context, value);
1229 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1231 @implementation CYJSObject
1233 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1234 if ((self = [super init]) != nil) {
1236 context_ = CYGetJSContext(context);
1237 JSGlobalContextRetain(context_);
1238 JSValueProtect(context_, object_);
1240 } CYObjectiveCatch }
1242 - (void) dealloc { CYObjectiveTry {
1243 JSValueUnprotect(context_, object_);
1244 JSGlobalContextRelease(context_);
1246 } CYObjectiveCatch }
1248 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1250 const char *cyon(CYPoolCCYON(pool, context, object_, objects));
1252 return [super cy$toCYON:objective inSet:objects];
1254 return [NSString stringWithUTF8String:cyon];
1255 } CYObjectiveCatch }
1257 - (NSUInteger) count { CYObjectiveTry {
1258 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1259 size_t size(JSPropertyNameArrayGetCount(names));
1260 JSPropertyNameArrayRelease(names);
1262 } CYObjectiveCatch }
1264 - (id) objectForKey:(id)key { CYObjectiveTry {
1265 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1266 if (JSValueIsUndefined(context, value))
1268 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1269 } CYObjectiveCatch }
1271 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1272 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1273 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1274 JSPropertyNameArrayRelease(names);
1276 } CYObjectiveCatch }
1278 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1279 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1280 } CYObjectiveCatch }
1282 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1283 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1284 } CYObjectiveCatch }
1288 @implementation CYJSArray
1290 - (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects { CYObjectiveTry {
1292 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_, objects)];
1293 } CYObjectiveCatch }
1295 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1296 if ((self = [super init]) != nil) {
1298 context_ = CYGetJSContext(context);
1299 JSGlobalContextRetain(context_);
1300 JSValueProtect(context_, object_);
1302 } CYObjectiveCatch }
1304 - (void) dealloc { CYObjectiveTry {
1305 JSValueUnprotect(context_, object_);
1306 JSGlobalContextRelease(context_);
1308 } CYObjectiveCatch }
1310 - (NSUInteger) count { CYObjectiveTry {
1311 return CYArrayLength(context, object_);
1312 } CYObjectiveCatch }
1314 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1315 size_t bounds([self count]);
1316 if (index >= bounds)
1317 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1318 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1319 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1320 } CYObjectiveCatch }
1322 - (void) addObject:(id)object { CYObjectiveTry {
1323 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1324 } CYObjectiveCatch }
1326 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1327 size_t bounds([self count] + 1);
1328 if (index >= bounds)
1329 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1330 JSValueRef arguments[3];
1331 arguments[0] = CYCastJSValue(context, index);
1332 arguments[1] = CYCastJSValue(context, 0);
1333 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1334 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1335 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1336 } CYObjectiveCatch }
1338 - (void) removeLastObject { CYObjectiveTry {
1339 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1340 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1341 } CYObjectiveCatch }
1343 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1344 size_t bounds([self count]);
1345 if (index >= bounds)
1346 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1347 JSValueRef arguments[2];
1348 arguments[0] = CYCastJSValue(context, index);
1349 arguments[1] = CYCastJSValue(context, 1);
1350 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1351 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1352 } CYObjectiveCatch }
1354 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1355 size_t bounds([self count]);
1356 if (index >= bounds)
1357 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1358 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1359 } CYObjectiveCatch }
1363 // XXX: inherit from or replace with CYJSObject
1364 @interface CYInternal : NSObject {
1365 JSGlobalContextRef context_;
1366 JSObjectRef object_;
1371 @implementation CYInternal
1373 - (void) dealloc { CYObjectiveTry {
1374 JSValueUnprotect(context_, object_);
1375 JSGlobalContextRelease(context_);
1377 } CYObjectiveCatch }
1379 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1380 if ((self = [super init]) != nil) {
1381 context_ = CYGetJSContext(context);
1382 JSGlobalContextRetain(context_);
1384 } CYObjectiveCatch }
1386 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1387 if (object_ == NULL)
1390 return JSObjectHasProperty(context, object_, name);
1393 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1394 if (object_ == NULL)
1397 return CYGetProperty(context, object_, name);
1400 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1401 @synchronized (self) {
1402 if (object_ == NULL) {
1403 object_ = JSObjectMake(context, NULL, NULL);
1404 JSValueProtect(context, object_);
1408 CYSetProperty(context, object_, name, value);
1411 + (CYInternal *) get:(id)object {
1413 if (&objc_getAssociatedObject == NULL)
1416 @synchronized (object) {
1417 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1425 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1427 if (&objc_getAssociatedObject == NULL)
1430 @synchronized (object) {
1431 if (CYInternal *internal = objc_getAssociatedObject(object, @selector(cy$internal)))
1434 if (&objc_setAssociatedObject == NULL)
1437 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1438 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1448 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1449 Selector_privateData *internal(new Selector_privateData(sel));
1450 return JSObjectMake(context, Selector_, internal);
1453 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1454 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1455 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1456 return reinterpret_cast<SEL>(internal->value_);
1459 return sel_registerName(CYPoolCString(pool, context, value));
1463 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1464 return (void *) [[NSAutoreleasePool alloc] init];
1465 } CYSadCatch(NULL) }
1467 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1468 return [(NSAutoreleasePool *) handle release];
1471 static void CYObjectiveC_CallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) { CYSadTry {
1472 CYCallFunction(pool, context, cif, function, value, values);
1476 static NSBlock *CYCastNSBlock(CYPool &pool, JSContextRef context, JSValueRef value, sig::Signature *signature) {
1477 if (JSValueIsNull(context, value))
1479 JSObjectRef object(CYCastJSObject(context, value));
1481 if (JSValueIsObjectOfClass(context, object, FunctionInstance_))
1482 return reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue();
1484 if (JSValueIsObjectOfClass(context, object, Instance_)) {
1485 _assert(reinterpret_cast<Instance *>(JSObjectGetPrivate(object))->GetValue() == nil);
1489 _assert(JSObjectIsFunction(context, object));
1491 _assert(signature != NULL);
1492 _assert(signature->count != 0);
1494 sig::Signature modified;
1495 modified.count = signature->count + 1;
1496 modified.elements = new(pool) sig::Element[modified.count];
1498 modified.elements[0] = signature->elements[0];
1499 memcpy(modified.elements + 2, signature->elements + 1, sizeof(sig::Element) * (signature->count - 1));
1501 modified.elements[1].name = NULL;
1502 modified.elements[1].type = new(pool) sig::Type();
1503 modified.elements[1].offset = _not(size_t);
1505 memset(modified.elements[1].type, 0, sizeof(sig::Type));
1506 modified.elements[1].type->primitive = sig::object_P;
1508 return CYMakeBlock(context, object, modified);
1512 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1513 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1515 switch (type->primitive) {
1518 // XXX: this function might not handle the idea of a null pool
1519 *reinterpret_cast<id *>(data) = CYCastNSBlock(*pool, context, value, &type->data.signature);
1524 case sig::typename_P:
1525 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1528 case sig::selector_P:
1529 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1537 } CYSadCatch(false) }
1539 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1540 switch (type->primitive) {
1541 // XXX: do something epic about blocks
1544 if (NSObject *value = *reinterpret_cast<NSObject **>(data)) {
1545 JSObjectRef object(CYMakeInstance(context, value));
1548 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1550 if ((internal->flags_ & Instance::Uninitialized) != 0) {
1551 internal->flags_ = static_cast<Instance::Flags>(internal->flags_ & ~Instance::Uninitialized);
1552 _assert(internal->value_ == nil);
1553 internal->value_ = value;
1562 case sig::typename_P:
1563 if (Class value = *reinterpret_cast<Class *>(data))
1564 return CYMakeInstance(context, value, Instance::Permanent);
1567 case sig::selector_P:
1568 if (SEL value = *reinterpret_cast<SEL *>(data))
1569 return CYMakeSelector(context, value);
1573 return CYJSNull(context);
1577 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1579 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1580 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1584 method_getReturnType(method, type, sizeof(type));
1589 // XXX: possibly use a more "awesome" check?
1593 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1594 JSObjectRef _this(CYCastJSObject(context, values[0]));
1595 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1598 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1599 Message_privateData *internal(new Message_privateData(sel, type, imp));
1600 return JSObjectMake(context, Message_, internal);
1603 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1604 JSObjectRef function(CYCastJSObject(context, value));
1606 sig::Signature signature;
1607 sig::Parse(pool, &signature, encoding, &Structor_);
1608 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageAdapter_));
1609 // XXX: see notes in Library.cpp about needing to leak
1610 return reinterpret_cast<IMP>(internal->GetValue());
1613 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1614 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1615 Class _class(internal->GetValue());
1618 const char *name(CYPoolCString(pool, context, property));
1620 if (SEL sel = sel_getUid(name))
1621 if (class_getInstanceMethod(_class, sel) != NULL)
1627 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1628 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1629 Class _class(internal->GetValue());
1632 const char *name(CYPoolCString(pool, context, property));
1634 if (SEL sel = sel_getUid(name))
1635 if (objc_method *method = class_getInstanceMethod(_class, sel))
1636 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1641 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1642 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1643 Class _class(internal->GetValue());
1646 const char *name(CYPoolCString(pool, context, property));
1647 SEL sel(sel_registerName(name));
1652 if (JSValueIsObjectOfClass(context, value, Message_)) {
1653 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1654 type = sig::Unparse(pool, &message->signature_);
1655 imp = reinterpret_cast<IMP>(message->GetValue());
1656 } else if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1657 type = method_getTypeEncoding(method);
1658 imp = CYMakeMessage(context, value, type);
1659 } else _assert(false);
1661 objc_method *method(NULL);
1663 objc_method **methods(class_copyMethodList(_class, &size));
1664 for (size_t i(0); i != size; ++i)
1665 if (sel_isEqual(method_getName(methods[i]), sel)) {
1666 method = methods[i];
1672 method_setImplementation(method, imp);
1674 class_addMethod(_class, sel, imp, type);
1679 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1680 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1681 Class _class(internal->GetValue());
1684 objc_method **data(class_copyMethodList(_class, &size));
1685 for (size_t i(0); i != size; ++i)
1686 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1690 static bool CYHasImplicitProperties(Class _class) {
1691 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1692 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1694 return [_class cy$hasImplicitProperties];
1697 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1698 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1699 id self(internal->GetValue());
1701 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1705 NSString *name(CYCastNSString(&pool, context, property));
1707 if (CYInternal *internal = [CYInternal get:self])
1708 if ([internal hasProperty:property inContext:context])
1711 Class _class(object_getClass(self));
1714 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1715 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1716 if ([self cy$hasProperty:name])
1718 } CYPoolCatch(false)
1720 const char *string(CYPoolCString(pool, context, name));
1722 if (class_getProperty(_class, string) != NULL)
1725 if (CYHasImplicitProperties(_class))
1726 if (SEL sel = sel_getUid(string))
1727 if (CYImplements(self, _class, sel, true))
1733 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1734 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1735 id self(internal->GetValue());
1737 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1738 return Internal::Make(context, self, object);
1741 NSString *name(CYCastNSString(&pool, context, property));
1743 if (CYInternal *internal = [CYInternal get:self])
1744 if (JSValueRef value = [internal getProperty:property inContext:context])
1748 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1752 const char *string(CYPoolCString(pool, context, name));
1753 Class _class(object_getClass(self));
1755 if (objc_property_t property = class_getProperty(_class, string)) {
1756 PropertyAttributes attributes(property);
1757 SEL sel(sel_registerName(attributes.Getter()));
1758 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1761 if (CYHasImplicitProperties(_class))
1762 if (SEL sel = sel_getUid(string))
1763 if (CYImplements(self, _class, sel, true))
1764 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1769 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1770 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1771 id self(internal->GetValue());
1775 NSString *name(CYCastNSString(&pool, context, property));
1776 NSObject *data(CYCastNSObject(&pool, context, value));
1779 if ([self cy$setProperty:name to:data])
1781 } CYPoolCatch(false)
1783 const char *string(CYPoolCString(pool, context, name));
1784 Class _class(object_getClass(self));
1786 if (objc_property_t property = class_getProperty(_class, string)) {
1787 PropertyAttributes attributes(property);
1788 if (const char *setter = attributes.Setter()) {
1789 SEL sel(sel_registerName(setter));
1790 JSValueRef arguments[1] = {value};
1791 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1796 size_t length(strlen(string));
1798 char set[length + 5];
1804 if (string[0] != '\0') {
1805 set[3] = toupper(string[0]);
1806 memcpy(set + 4, string + 1, length - 1);
1809 set[length + 3] = ':';
1810 set[length + 4] = '\0';
1812 if (SEL sel = sel_getUid(set))
1813 if (CYImplements(self, _class, sel)) {
1814 JSValueRef arguments[1] = {value};
1815 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1819 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1820 [internal setProperty:property toValue:value inContext:context];
1827 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1828 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1829 id self(internal->GetValue());
1832 NSString *name(CYCastNSString(NULL, context, property));
1833 return [self cy$deleteProperty:name];
1834 } CYPoolCatch(false)
1835 } CYCatch(false) return /*XXX*/ false; }
1837 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1838 const char *name(sel_getName(method_getName(method)));
1839 if (strchr(name, ':') != NULL)
1842 const char *type(method_getTypeEncoding(method));
1843 if (type == NULL || *type == '\0' || *type == 'v')
1846 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1849 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1850 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1851 id self(internal->GetValue());
1854 Class _class(object_getClass(self));
1858 objc_property_t *data(class_copyPropertyList(_class, &size));
1859 for (size_t i(0); i != size; ++i)
1860 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1864 if (CYHasImplicitProperties(_class))
1865 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1867 objc_method **data(class_copyMethodList(current, &size));
1868 for (size_t i(0); i != size; ++i)
1869 Instance_getPropertyNames_message(names, data[i]);
1874 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1875 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1876 [self cy$getPropertyNames:names inContext:context];
1880 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1881 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1882 JSObjectRef value(CYMakeInstance(context, [internal->GetValue() alloc], Instance::Uninitialized));
1886 static const char *CYBlockEncoding(NSBlock *self) {
1887 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1888 if ((literal->flags & BLOCK_HAS_SIGNATURE) == 0)
1890 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1891 descriptor += sizeof(BlockDescriptor1);
1892 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1893 descriptor += sizeof(BlockDescriptor2);
1894 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1895 return descriptor3->signature;
1898 static JSValueRef FunctionInstance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1899 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1900 id self(internal->GetValue());
1902 if (const char *encoding = CYBlockEncoding(self)) {
1908 sig::Signature signature;
1909 sig::Parse(pool, &signature, encoding, &Structor_);
1912 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1914 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1915 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1916 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1920 CYThrow("NSBlock without signature field passed arguments");
1924 } CYPoolCatch(NULL);
1929 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1930 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1931 Class _class(internal->GetValue());
1932 if (!CYIsClass(_class))
1935 if (CYJSValueIsNSObject(context, instance)) {
1936 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1937 // XXX: this isn't always safe
1938 return [linternal->GetValue() isKindOfClass:_class];
1944 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1946 throw CYJSError(context, "incorrect number of arguments to Instance");
1948 id value(CYCastNSObject(&pool, context, arguments[0]));
1950 value = [NSNull null];
1951 return CYCastJSValue(context, [value cy$box]);
1954 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1955 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1958 id self(internal->GetValue());
1959 const char *name(CYPoolCString(pool, context, property));
1961 if (object_getInstanceVariable(self, name, NULL) != NULL)
1967 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1968 length = CYCastDouble(encoding + 1);
1972 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1973 for (size_t i(0); i != size; ++i)
1974 if (ivars[i] == ivar)
1976 else if (ivar_getOffset(ivars[i]) == offset) {
1977 const char *encoding(ivar_getTypeEncoding(ivars[i]));
1978 _assert(encoding != NULL);
1979 _assert(encoding[0] == 'b');
1980 shift += CYCastDouble(encoding + 1);
1985 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1986 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1989 id self(internal->GetValue());
1990 const char *name(CYPoolCString(pool, context, property));
1992 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
1993 ptrdiff_t offset(ivar_getOffset(ivar));
1994 void *data(reinterpret_cast<uint8_t *>(self) + offset);
1996 const char *encoding(ivar_getTypeEncoding(ivar));
1997 _assert(encoding != NULL);
1998 _assert(encoding[0] != '\0');
1999 if (encoding[0] == 'b') {
2000 unsigned length, shift;
2001 CYBitField(length, shift, self, ivar, encoding, offset);
2002 _assert(shift + length <= sizeof(uintptr_t) * 8);
2003 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2004 uintptr_t mask((1 << length) - 1);
2005 return CYCastJSValue(context, (field >> shift) & mask);
2007 #if defined(__APPLE__) && defined(__LP64__)
2008 // XXX: maybe do even more verifications here
2009 if (strcmp(name, "isa") == 0)
2010 return CYCastJSValue(context, object_getClass(self));
2013 auto type(new(pool) Type_privateData(encoding));
2014 return CYFromFFI(context, type->type_, type->GetFFI(), data);
2021 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2022 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2025 id self(internal->GetValue());
2026 const char *name(CYPoolCString(pool, context, property));
2028 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2029 ptrdiff_t offset(ivar_getOffset(ivar));
2030 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2032 const char *encoding(ivar_getTypeEncoding(ivar));
2033 _assert(encoding != NULL);
2034 if (encoding[0] == 'b') {
2035 unsigned length, shift;
2036 CYBitField(length, shift, self, ivar, encoding, offset);
2037 _assert(shift + length <= sizeof(uintptr_t) * 8);
2038 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2039 uintptr_t mask((1 << length) - 1);
2040 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2042 auto type(new(pool) Type_privateData(ivar_getTypeEncoding(ivar)));
2043 CYPoolFFI(&pool, context, type->type_, type->GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2051 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2052 if (Class super = class_getSuperclass(_class))
2053 Internal_getPropertyNames_(super, names);
2056 objc_ivar **data(class_copyIvarList(_class, &size));
2057 for (size_t i(0); i != size; ++i)
2058 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2062 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2063 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2066 id self(internal->GetValue());
2067 Class _class(object_getClass(self));
2069 Internal_getPropertyNames_(_class, names);
2072 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2073 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2074 return internal->GetOwner();
2077 static bool ObjectiveC_Classes_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2079 return objc_getClass(CYPoolCString(pool, context, property)) != Nil;
2082 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2084 NSString *name(CYCastNSString(&pool, context, property));
2085 if (Class _class = NSClassFromString(name))
2086 return CYMakeInstance(context, _class, Instance::Permanent);
2090 static Class *CYCopyClassList(size_t &size) {
2091 size = objc_getClassList(NULL, 0);
2092 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2095 size_t writ(objc_getClassList(data, size));
2101 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2112 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2114 if (Class *data = CYCopyClassList(size)) {
2115 for (size_t i(0); i != size; ++i)
2116 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2122 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2123 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2126 const char *name(CYPoolCString(pool, context, property));
2128 const char **data(objc_copyClassNamesForImage(internal, &size));
2130 for (size_t i(0); i != size; ++i)
2131 if (strcmp(name, data[i]) == 0) {
2132 if (Class _class = objc_getClass(name)) {
2133 value = CYMakeInstance(context, _class, Instance::Permanent);
2144 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2145 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2147 const char **data(objc_copyClassNamesForImage(internal, &size));
2148 for (size_t i(0); i != size; ++i)
2149 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2153 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2155 const char *name(CYPoolCString(pool, context, property));
2157 const char **data(objc_copyImageNames(&size));
2158 for (size_t i(0); i != size; ++i)
2159 if (strcmp(name, data[i]) == 0) {
2168 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2169 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2173 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2175 const char **data(objc_copyImageNames(&size));
2176 for (size_t i(0); i != size; ++i)
2177 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2182 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2184 const char *name(CYPoolCString(pool, context, property));
2185 if (Protocol *protocol = objc_getProtocol(name))
2186 return CYMakeInstance(context, protocol, Instance::Permanent);
2190 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2192 Protocol **data(objc_copyProtocolList(&size));
2193 for (size_t i(0); i != size; ++i)
2194 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2198 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2200 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2202 return CYJSNull(context);
2206 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2207 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2211 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2212 *data = reinterpret_cast<void *>(address);
2213 return KERN_SUCCESS;
2217 std::set<Class> query_;
2218 JSContextRef context_;
2219 JSObjectRef results_;
2222 struct CYObjectStruct {
2226 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2227 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2228 JSContextRef context(choice->context_);
2230 for (unsigned i(0); i != count; ++i) {
2231 vm_range_t &range(ranges[i]);
2232 void *data(reinterpret_cast<void *>(range.address));
2233 size_t size(range.size);
2235 if (size < sizeof(CYObjectStruct))
2238 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2239 #if defined(__APPLE__) && defined(__LP64__)
2240 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2242 Class isa(reinterpret_cast<Class>(pointers[0]));
2245 std::set<Class>::const_iterator result(choice->query_.find(isa));
2246 if (result == choice->query_.end())
2249 size_t needed(class_getInstanceSize(*result));
2250 // XXX: if (size < needed)
2252 size_t boundary(496);
2256 if (needed <= boundary && (needed + 15) / 16 * 16 != size || needed > boundary && (needed + 511) / 512 * 512 != size)
2258 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2262 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2264 throw CYJSError(context, "choose() takes a class argument");
2266 CYGarbageCollect(context);
2269 id _class(CYCastNSObject(&pool, context, arguments[0]));
2271 vm_address_t *zones(NULL);
2273 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2274 _assert(error == KERN_SUCCESS);
2276 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2277 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2280 choice.context_ = context;
2281 choice.results_ = results;
2284 Class *classes(CYCopyClassList(number));
2285 _assert(classes != NULL);
2287 for (size_t i(0); i != number; ++i)
2288 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2289 if (current == _class) {
2290 choice.query_.insert(classes[i]);
2296 for (unsigned i(0); i != size; ++i) {
2297 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2298 if (zone == NULL || zone->introspect == NULL)
2301 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2309 #if defined(__i386__) || defined(__x86_64__)
2310 #define OBJC_MAX_STRUCT_BY_VALUE 8
2311 static int struct_forward_array[] = {
2312 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2313 #elif defined(__arm__)
2314 #define OBJC_MAX_STRUCT_BY_VALUE 1
2315 static int struct_forward_array[] = {
2317 #elif defined(__arm64__)
2320 #error missing objc-runtime-info
2324 static bool stret(ffi_type *ffi_type) {
2325 return ffi_type->type == FFI_TYPE_STRUCT && (
2326 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2327 struct_forward_array[ffi_type->size] != 0
2335 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2339 _class = object_getClass(self);
2343 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2344 imp = method_getImplementation(method);
2345 type = method_getTypeEncoding(method);
2350 if (NSMethodSignature *method = [self methodSignatureForSelector:_cmd])
2351 type = CYPoolCString(pool, context, [method _typeString]);
2357 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2364 sig::Signature signature;
2365 sig::Parse(pool, &signature, type, &Structor_);
2367 size_t used(count + 3);
2368 if (used > signature.count) {
2369 sig::Element *elements(new (pool) sig::Element[used]);
2370 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2372 for (size_t index(signature.count); index != used; ++index) {
2373 sig::Element *element(&elements[index]);
2374 element->name = NULL;
2375 element->offset = _not(size_t);
2377 sig::Type *type(new (pool) sig::Type);
2378 memset(type, 0, sizeof(*type));
2379 type->primitive = sig::object_P;
2380 element->type = type;
2383 signature.elements = elements;
2384 signature.count = used;
2388 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2392 if (stret(cif.rtype))
2393 imp = class_getMethodImplementation_stret(_class, _cmd);
2396 imp = class_getMethodImplementation(_class, _cmd);
2399 void (*function)() = reinterpret_cast<void (*)()>(imp);
2400 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2403 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2405 throw CYJSError(context, "too few arguments to objc_msgSend");
2415 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2416 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2417 self = internal->GetValue();
2418 _class = internal->class_;;
2419 uninitialized = false;
2420 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2421 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2422 self = internal->GetValue();
2424 uninitialized = internal->IsUninitialized();
2426 internal->value_ = nil;
2428 self = CYCastNSObject(&pool, context, arguments[0]);
2430 uninitialized = false;
2434 return CYJSNull(context);
2436 _cmd = CYCastSEL(context, arguments[1]);
2438 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2441 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2442 return $objc_msgSend(context, object, _this, count, arguments);
2445 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2446 JSValueRef setup[count + 2];
2449 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2450 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2453 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2455 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2457 // XXX: handle Instance::Uninitialized?
2458 id self(CYCastNSObject(&pool, context, _this));
2462 setup[1] = &internal->sel_;
2464 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2467 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2469 throw CYJSError(context, "incorrect number of arguments to objc_super constructor");
2471 id self(CYCastNSObject(&pool, context, arguments[0]));
2472 Class _class(CYCastClass(pool, context, arguments[1]));
2473 return cy::Super::Make(context, self, _class);
2476 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2478 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2480 const char *name(CYPoolCString(pool, context, arguments[0]));
2481 return CYMakeSelector(context, sel_registerName(name));
2484 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2486 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2487 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2488 return CYMakeInstance(context, self);
2491 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2492 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2493 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2496 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2497 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2498 Type_privateData *typical(internal->GetType());
2503 if (typical == NULL) {
2507 type = typical->type_;
2508 ffi = typical->ffi_;
2511 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2514 static JSValueRef FunctionInstance_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2515 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2516 const char *encoding(CYBlockEncoding(internal->GetValue()));
2517 if (encoding == NULL)
2518 return CYJSNull(context);
2519 // XXX: this should be stored on a FunctionInstance private value subclass
2521 sig::Signature signature;
2522 sig::Parse(pool, &signature, encoding, &Structor_);
2523 return CYMakeType(context, &signature);
2526 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2527 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2528 return CYMakeInstance(context, object_getClass(internal->GetValue()), Instance::Permanent);
2531 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2532 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2533 id self(internal->GetValue());
2534 if (!CYIsClass(self))
2535 return CYJSUndefined(context);
2536 return CYGetClassPrototype(context, self);
2539 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2540 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2541 id self(internal->GetValue());
2542 if (!CYIsClass(self))
2543 return CYJSUndefined(context);
2544 return Messages::Make(context, (Class) self);
2547 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2548 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
2550 if (!CYJSValueIsNSObject(context, _this))
2553 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2554 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false, objects)));
2557 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2558 if (!CYJSValueIsNSObject(context, _this))
2561 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2562 id value(internal->GetValue());
2569 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2571 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2572 return CYJSUndefined(context);
2573 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2576 return CYCastJSValue(context, CYJSString(context, [value description]));
2578 } CYCatch(NULL) return /*XXX*/ NULL; }
2580 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2581 if (!CYJSValueIsNSObject(context, _this))
2584 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2585 id value(internal->GetValue());
2586 _assert(value != nil);
2588 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2591 if (JSValueRef result = [value cy$valueOfInContext:context])
2595 } CYCatch(NULL) return /*XXX*/ NULL; }
2597 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2598 if (!CYJSValueIsNSObject(context, _this))
2601 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2602 // XXX: but... but... THIS ISN'T A POINTER! :(
2603 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2604 } CYCatch(NULL) return /*XXX*/ NULL; }
2606 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2607 if (!CYJSValueIsNSObject(context, _this))
2610 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2611 id value(internal->GetValue());
2614 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2615 return CYCastJSValue(context, CYJSString(context, [value description]));
2617 } CYCatch(NULL) return /*XXX*/ NULL; }
2619 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2620 if (!CYJSValueIsNSObject(context, _this))
2623 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2624 id value(internal->GetValue());
2626 if (!CYIsClass(value))
2627 CYThrow("non-Class object cannot be used as Type");
2630 memset(&type, 0, sizeof(type));
2631 type.primitive = sig::object_P;
2632 type.name = class_getName(value);
2633 return CYMakeType(context, &type);
2634 } CYCatch(NULL) return /*XXX*/ NULL; }
2636 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2637 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2638 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2641 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2642 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2645 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2646 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2647 const char *name(sel_getName(internal->GetValue()));
2650 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2651 return CYCastJSValue(context, CYJSString(context, string));
2653 } CYCatch(NULL) return /*XXX*/ NULL; }
2655 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2657 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2660 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2661 SEL sel(internal->GetValue());
2663 Class _class(_require(CYCastClass(pool, context, arguments[0])));
2664 objc_method *method(_require(class_getInstanceMethod(_class, sel)));
2665 const char *encoding(method_getTypeEncoding(method));
2667 sig::Signature signature;
2668 sig::Parse(pool, &signature, encoding, &Structor_);
2669 return CYMakeType(context, &signature);
2672 static JSStaticValue Selector_staticValues[2] = {
2673 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2674 {NULL, NULL, NULL, 0}
2677 // XXX: this is sadly duplicated in FunctionInstance_staticValues
2678 static JSStaticValue Instance_staticValues[5] = {
2679 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2680 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2681 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2682 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2683 {NULL, NULL, NULL, 0}
2686 static JSStaticValue FunctionInstance_staticValues[6] = {
2687 {"type", &FunctionInstance_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2688 // XXX: this is sadly a duplicate of Instance_staticValues
2689 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2690 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2691 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2692 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2693 {NULL, NULL, NULL, 0}
2696 static JSStaticFunction Instance_staticFunctions[7] = {
2697 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2698 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2699 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2700 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2701 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2702 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2706 static JSStaticFunction Class_staticFunctions[2] = {
2707 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2711 static JSStaticFunction Internal_staticFunctions[2] = {
2712 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2716 static JSStaticFunction Selector_staticFunctions[5] = {
2717 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2719 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2720 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2725 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2726 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2727 } CYObjectiveCatch }
2730 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2731 CYPool &pool(CYGetGlobalPool());
2733 Object_type = new(pool) Type_privateData(sig::object_P);
2734 Selector_type = new(pool) Type_privateData(sig::selector_P);
2736 NSArray_ = objc_getClass("NSArray");
2737 NSBlock_ = objc_getClass("NSBlock");
2738 NSDictionary_ = objc_getClass("NSDictionary");
2739 NSNumber_ = objc_getClass("NSNumber");
2740 NSString_ = objc_getClass("NSString");
2741 Object_ = objc_getClass("Object");
2744 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2746 // XXX: apparently, iOS now has both of these
2747 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2748 if (NSCFBoolean_ == nil)
2749 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2751 NSCFType_ = objc_getClass("NSCFType");
2753 NSZombie_ = objc_getClass("_NSZombie_");
2755 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2756 NSZombie_ = objc_getClass("NSZombie");
2759 JSClassDefinition definition;
2761 definition = kJSClassDefinitionEmpty;
2762 definition.className = "Instance";
2763 definition.staticValues = Instance_staticValues;
2764 definition.staticFunctions = Instance_staticFunctions;
2765 definition.hasProperty = &Instance_hasProperty;
2766 definition.getProperty = &Instance_getProperty;
2767 definition.setProperty = &Instance_setProperty;
2768 definition.deleteProperty = &Instance_deleteProperty;
2769 definition.getPropertyNames = &Instance_getPropertyNames;
2770 definition.callAsConstructor = &Instance_callAsConstructor;
2771 definition.hasInstance = &Instance_hasInstance;
2772 definition.finalize = &CYFinalize;
2773 Instance_ = JSClassCreate(&definition);
2775 definition.className = "ArrayInstance";
2776 ArrayInstance_ = JSClassCreate(&definition);
2778 definition.className = "BooleanInstance";
2779 BooleanInstance_ = JSClassCreate(&definition);
2781 definition.className = "NumberInstance";
2782 NumberInstance_ = JSClassCreate(&definition);
2784 definition.className = "ObjectInstance";
2785 ObjectInstance_ = JSClassCreate(&definition);
2787 definition.className = "StringInstance";
2788 StringInstance_ = JSClassCreate(&definition);
2790 definition.className = "FunctionInstance";
2791 definition.staticValues = FunctionInstance_staticValues;
2792 definition.callAsFunction = &FunctionInstance_callAsFunction;
2793 FunctionInstance_ = JSClassCreate(&definition);
2795 definition = kJSClassDefinitionEmpty;
2796 definition.className = "Class";
2797 definition.staticFunctions = Class_staticFunctions;
2798 Class_ = JSClassCreate(&definition);
2800 definition = kJSClassDefinitionEmpty;
2801 definition.className = "Internal";
2802 definition.staticFunctions = Internal_staticFunctions;
2803 definition.hasProperty = &Internal_hasProperty;
2804 definition.getProperty = &Internal_getProperty;
2805 definition.setProperty = &Internal_setProperty;
2806 definition.getPropertyNames = &Internal_getPropertyNames;
2807 definition.finalize = &CYFinalize;
2808 Internal_ = JSClassCreate(&definition);
2810 definition = kJSClassDefinitionEmpty;
2811 definition.className = "Message";
2812 definition.staticFunctions = cy::Functor::StaticFunctions;
2813 definition.staticValues = cy::Functor::StaticValues;
2814 definition.callAsFunction = &Message_callAsFunction;
2815 definition.finalize = &CYFinalize;
2816 Message_ = JSClassCreate(&definition);
2818 definition = kJSClassDefinitionEmpty;
2819 definition.className = "Messages";
2820 definition.hasProperty = &Messages_hasProperty;
2821 definition.getProperty = &Messages_getProperty;
2822 definition.setProperty = &Messages_setProperty;
2823 definition.getPropertyNames = &Messages_getPropertyNames;
2824 definition.finalize = &CYFinalize;
2825 Messages_ = JSClassCreate(&definition);
2827 definition = kJSClassDefinitionEmpty;
2828 definition.className = "Selector";
2829 definition.staticValues = Selector_staticValues;
2830 definition.staticFunctions = Selector_staticFunctions;
2831 definition.callAsFunction = &Selector_callAsFunction;
2832 definition.finalize = &CYFinalize;
2833 Selector_ = JSClassCreate(&definition);
2835 definition = kJSClassDefinitionEmpty;
2836 definition.className = "Super";
2837 definition.staticFunctions = Internal_staticFunctions;
2838 definition.finalize = &CYFinalize;
2839 Super_ = JSClassCreate(&definition);
2841 definition = kJSClassDefinitionEmpty;
2842 definition.className = "ObjectiveC::Classes";
2843 definition.hasProperty = &ObjectiveC_Classes_hasProperty;
2844 definition.getProperty = &ObjectiveC_Classes_getProperty;
2845 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2846 ObjectiveC_Classes_ = JSClassCreate(&definition);
2848 definition = kJSClassDefinitionEmpty;
2849 definition.className = "ObjectiveC::Constants";
2850 definition.getProperty = &ObjectiveC_Constants_getProperty;
2851 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2852 ObjectiveC_Constants_ = JSClassCreate(&definition);
2855 definition = kJSClassDefinitionEmpty;
2856 definition.className = "ObjectiveC::Images";
2857 definition.getProperty = &ObjectiveC_Images_getProperty;
2858 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2859 ObjectiveC_Images_ = JSClassCreate(&definition);
2861 definition = kJSClassDefinitionEmpty;
2862 definition.className = "ObjectiveC::Image::Classes";
2863 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2864 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2865 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2868 definition = kJSClassDefinitionEmpty;
2869 definition.className = "ObjectiveC::Protocols";
2870 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2871 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2872 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2875 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$),
2876 // XXX: this is horrible; there has to be a better way to do this
2878 "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24"
2880 "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12"
2886 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2887 JSObjectRef global(CYGetGlobalObject(context));
2888 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2889 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2890 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2891 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2893 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2894 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2896 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2897 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2898 CYArrayPush(context, alls, protocols);
2900 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2901 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2902 CYArrayPush(context, alls, classes);
2904 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2905 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2906 CYArrayPush(context, alls, constants);
2909 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2912 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2913 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2914 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2915 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2916 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2918 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2919 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2921 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2922 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2923 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2924 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2925 CYSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2927 JSObjectRef BooleanInstance(JSObjectMakeConstructor(context, BooleanInstance_, NULL));
2928 JSObjectRef BooleanInstance_prototype(CYCastJSObject(context, CYGetProperty(context, BooleanInstance, prototype_s)));
2929 CYSetProperty(context, cy, CYJSString("BooleanInstance_prototype"), BooleanInstance_prototype);
2930 JSObjectRef Boolean_prototype(CYGetCachedObject(context, CYJSString("Boolean_prototype")));
2931 CYSetPrototype(context, BooleanInstance_prototype, Boolean_prototype);
2933 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2934 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2935 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2936 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2937 CYSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2939 JSObjectRef NumberInstance(JSObjectMakeConstructor(context, NumberInstance_, NULL));
2940 JSObjectRef NumberInstance_prototype(CYCastJSObject(context, CYGetProperty(context, NumberInstance, prototype_s)));
2941 CYSetProperty(context, cy, CYJSString("NumberInstance_prototype"), NumberInstance_prototype);
2942 JSObjectRef Number_prototype(CYGetCachedObject(context, CYJSString("Number_prototype")));
2943 CYSetPrototype(context, NumberInstance_prototype, Number_prototype);
2945 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2946 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2947 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2948 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2949 CYSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2951 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2952 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2953 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2954 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2955 CYSetPrototype(context, StringInstance_prototype, String_prototype);
2957 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2958 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2959 CYSetPrototype(context, Class_prototype, Instance_prototype);
2961 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2962 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2963 CYSetProperty(context, cycript, CYJSString("objc_super"), Super);
2965 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2966 CYSetProperty(context, Instance, CYJSString("box"), box, kJSPropertyAttributeDontEnum);
2969 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2972 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2974 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2975 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2978 static void *CYObjectiveC_CastSymbol(const char *name) {
2980 #ifdef __GNU_LIBOBJC__
2981 else if (strcmp(name, "object_getClass") == 0)
2982 return reinterpret_cast<void *>(&object_getClass);
2987 static CYHook CYObjectiveCHook = {
2988 &CYObjectiveC_ExecuteStart,
2989 &CYObjectiveC_ExecuteEnd,
2990 &CYObjectiveC_CallFunction,
2991 &CYObjectiveC_Initialize,
2992 &CYObjectiveC_SetupContext,
2993 &CYObjectiveC_PoolFFI,
2994 &CYObjectiveC_FromFFI,
2995 &CYObjectiveC_CastSymbol,
2998 CYRegisterHook CYObjectiveC(&CYObjectiveCHook);
3000 _extern void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
3001 CYSetupContext(context);
3002 } CYObjectiveCatch }
3004 _extern void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3007 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3008 CYStream stream(utf8.data, utf8.data + utf8.size);
3009 utf8 = CYPoolCode(pool, stream);
3011 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3012 size_t bytes(utf16.size * sizeof(uint16_t));
3013 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3014 memcpy(copy, utf16.data, bytes);
3018 } catch (const CYException &exception) {
3020 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];