1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
22 #include <Foundation/Foundation.h>
24 #include "ObjectiveC/Internal.hpp"
26 #include <objc/objc-api.h>
28 #include "cycript.hpp"
30 #include "ObjectiveC/Internal.hpp"
33 #include <CoreFoundation/CoreFoundation.h>
34 #include <JavaScriptCore/JSStringRefCF.h>
35 #include <objc/runtime.h>
39 #include <malloc/malloc.h>
40 #include <mach/mach.h>
44 #include "JavaScript.hpp"
46 #include "Execute.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)); \
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)); \
90 #define class_getSuperclass GSObjCSuper
91 #define class_getInstanceVariable GSCGetInstanceVariableDefinition
92 #define class_getName GSNameFromClass
94 #define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
96 #define ivar_getName(ivar) ((ivar)->ivar_name)
97 #define ivar_getOffset(ivar) ((ivar)->ivar_offset)
98 #define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
100 #define method_getName(method) ((method)->method_name)
101 #define method_getImplementation(method) ((method)->method_imp)
102 #define method_getTypeEncoding(method) ((method)->method_types)
103 #define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
106 #define objc_getClass GSClassFromName
108 #define objc_getProtocol GSProtocolFromName
110 #define object_getClass GSObjCClass
112 #define object_getInstanceVariable(object, name, value) ({ \
113 objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
114 _assert(value != NULL); \
116 GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
120 #define object_setIvar(object, ivar, value) ({ \
121 void *data = (value); \
122 GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
125 #define protocol_getName(protocol) [(protocol) name]
128 static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
129 static id (*$objc_getAssociatedObject)(id object, void *key);
130 static void (*$objc_removeAssociatedObjects)(id object);
132 struct BlockLiteral {
136 void (*invoke)(void *, ...);
140 struct BlockDescriptor1 {
141 unsigned long int reserved;
142 unsigned long int size;
145 struct BlockDescriptor2 {
146 void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
147 void (*dispose_helper)(BlockLiteral *src);
150 struct BlockDescriptor3 {
151 const char *signature;
156 BLOCK_DEALLOCATING = 0x0001,
157 BLOCK_REFCOUNT_MASK = 0xfffe,
158 BLOCK_NEEDS_FREE = 1 << 24,
159 BLOCK_HAS_COPY_DISPOSE = 1 << 25,
160 BLOCK_HAS_CTOR = 1 << 26,
161 BLOCK_IS_GC = 1 << 27,
162 BLOCK_IS_GLOBAL = 1 << 28,
163 BLOCK_HAS_STRET = 1 << 29,
164 BLOCK_HAS_SIGNATURE = 1 << 30,
167 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
169 /* Objective-C Pool Release {{{ */
170 void CYPoolRelease_(void *data) {
171 id object(reinterpret_cast<id>(data));
175 id CYPoolRelease_(CYPool *pool, id object) {
178 else if (pool == NULL)
179 return [object autorelease];
181 pool->atexit(CYPoolRelease_);
186 template <typename Type_>
187 Type_ CYPoolRelease(CYPool *pool, Type_ object) {
188 return (Type_) CYPoolRelease_(pool, (id) object);
191 /* Objective-C Strings {{{ */
192 const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
193 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
194 char *string(new(pool) char[size]);
195 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
196 throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
200 JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
202 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
205 return CYCopyJSString(CYPoolCString(pool, context, value));
209 JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
212 // XXX: this definition scares me; is anyone using this?!
213 NSString *string([value description]);
214 return CYCopyJSString(context, string);
217 NSString *CYCopyNSString(const CYUTF8String &value) {
219 return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
221 return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
225 NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
227 return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
230 return CYCopyNSString(CYPoolUTF8String(pool, context, value));
234 NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
235 return CYCopyNSString(context, CYJSString(context, value));
238 NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
239 return CYPoolRelease(pool, CYCopyNSString(value));
242 NSString *CYCastNSString(CYPool *pool, SEL sel) {
243 const char *name(sel_getName(sel));
244 return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
247 NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
248 return CYPoolRelease(pool, CYCopyNSString(context, value));
251 CYUTF8String CYCastUTF8String(NSString *value) {
252 NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
253 return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
257 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
259 void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
260 if (exception == NULL)
262 *exception = CYCastJSValue(context, error);
265 size_t CYGetIndex(NSString *value) {
266 return CYGetIndex(CYCastUTF8String(value));
269 bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
270 return CYGetOffset(CYPoolCString(pool, context, value), index);
273 static JSClassRef Instance_;
275 static JSClassRef ArrayInstance_;
276 static JSClassRef FunctionInstance_;
277 static JSClassRef ObjectInstance_;
278 static JSClassRef StringInstance_;
280 static JSClassRef Class_;
281 static JSClassRef Internal_;
282 static JSClassRef Message_;
283 static JSClassRef Messages_;
284 static JSClassRef Selector_;
285 static JSClassRef Super_;
287 static JSClassRef ObjectiveC_Classes_;
288 static JSClassRef ObjectiveC_Constants_;
289 static JSClassRef ObjectiveC_Protocols_;
292 static JSClassRef ObjectiveC_Image_Classes_;
293 static JSClassRef ObjectiveC_Images_;
297 static Class NSCFBoolean_;
298 static Class NSCFType_;
299 static Class NSGenericDeallocHandler_;
300 static Class NSZombie_;
302 static std::set<Class> banned_;
304 static Class NSBoolNumber_;
307 static Class NSArray_;
308 static Class NSBlock_;
309 static Class NSDictionary_;
310 static Class NSString_;
311 static Class Object_;
313 static Type_privateData *Object_type;
314 static Type_privateData *Selector_type;
316 Type_privateData *Instance::GetType() const {
320 Type_privateData *Selector_privateData::GetType() const {
321 return Selector_type;
324 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
326 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
328 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
329 else if (meta && !class_isMetaClass(self))
330 return CYGetCachedObject(context, CYJSString("Class_prototype"));
332 JSObjectRef global(CYGetGlobalObject(context));
333 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
336 sprintf(label, "i%p", self);
337 CYJSString name(label);
339 JSValueRef value(CYGetProperty(context, cy, name));
340 if (!JSValueIsUndefined(context, value))
343 JSClassRef _class(NULL);
344 JSValueRef prototype;
346 if (self == NSArray_)
347 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
348 else if (self == NSBlock_)
349 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
350 else if (self == NSDictionary_)
351 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
352 else if (self == NSString_)
353 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
355 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
357 JSObjectRef object(JSObjectMake(context, _class, NULL));
358 JSObjectSetPrototype(context, object, prototype);
359 CYSetProperty(context, cy, name, object);
364 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
365 return CYGetClassPrototype(context, self, class_isMetaClass(self));
368 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
369 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
370 if (Class super = class_getSuperclass(_class))
371 JSObjectSetPrototype(context, value, Messages::Make(context, super));
375 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
376 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
380 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
381 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
385 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
386 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
387 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
391 Instance::~Instance() {
392 if ((flags_ & Transient) == 0)
393 // XXX: does this handle background threads correctly?
394 // XXX: this simply does not work on the console because I'm stupid
395 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
398 struct Message_privateData :
403 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
404 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
410 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
411 Instance::Flags flags;
414 flags = Instance::Transient;
416 flags = Instance::None;
417 object = [object retain];
420 return Instance::Make(context, object, flags);
423 @interface NSMethodSignature (Cycript)
424 - (NSString *) _typeString;
427 @interface NSObject (Cycript)
429 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
430 - (JSType) cy$JSType;
432 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
433 - (NSString *) cy$toCYON:(bool)objective;
435 - (bool) cy$hasProperty:(NSString *)name;
436 - (NSObject *) cy$getProperty:(NSString *)name;
437 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
438 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
439 - (bool) cy$deleteProperty:(NSString *)name;
440 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
442 + (bool) cy$hasImplicitProperties;
448 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
451 NSString *CYCastNSCYON(id value, bool objective) {
457 Class _class(object_getClass(value));
458 SEL sel(@selector(cy$toCYON:));
460 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
461 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
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 string = [value cy$toCYON:objective];
469 else if (value == NSZombie_)
470 string = @"_NSZombie_";
471 else if (_class == NSZombie_)
472 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
473 // XXX: frowny /in/ the pants
474 else if (banned_.find(value) != banned_.end())
478 string = [NSString stringWithFormat:@"%@", value];
483 string = @"undefined";
490 struct PropertyAttributes {
495 const char *variable;
508 PropertyAttributes(objc_property_t property) :
520 name = property_getName(property);
521 const char *attributes(property_getAttributes(property));
523 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
524 if ((next = strchr(token, ',')) != NULL)
527 case 'R': readonly = true; break;
528 case 'C': copy = true; break;
529 case '&': retain = true; break;
530 case 'N': nonatomic = true; break;
531 case 'G': getter_ = token + 1; break;
532 case 'S': setter_ = token + 1; break;
533 case 'V': variable = token + 1; break;
537 /*if (variable == NULL) {
538 variable = property_getName(property);
539 size_t size(strlen(variable));
540 char *name(new(pool_) char[size + 2]);
542 memcpy(name + 1, variable, size);
543 name[size + 1] = '\0';
548 const char *Getter() {
550 getter_ = pool_.strdup(name);
554 const char *Setter() {
555 if (setter_ == NULL && !readonly) {
556 size_t length(strlen(name));
558 char *temp(new(pool_) char[length + 5]);
564 temp[3] = toupper(name[0]);
565 memcpy(temp + 4, name + 1, length - 1);
568 temp[length + 3] = ':';
569 temp[length + 4] = '\0';
579 @interface CYWebUndefined : NSObject {
582 + (CYWebUndefined *) undefined;
586 @implementation CYWebUndefined
588 + (CYWebUndefined *) undefined {
589 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
595 #define WebUndefined CYWebUndefined
597 /* Bridge: CYJSObject {{{ */
598 @interface CYJSObject : NSMutableDictionary {
600 JSGlobalContextRef context_;
603 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
605 - (NSUInteger) count;
606 - (id) objectForKey:(id)key;
607 - (NSEnumerator *) keyEnumerator;
608 - (void) setObject:(id)object forKey:(id)key;
609 - (void) removeObjectForKey:(id)key;
613 /* Bridge: CYJSArray {{{ */
614 @interface CYJSArray : NSMutableArray {
616 JSGlobalContextRef context_;
619 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
621 - (NSUInteger) count;
622 - (id) objectAtIndex:(NSUInteger)index;
624 - (void) addObject:(id)anObject;
625 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
626 - (void) removeLastObject;
627 - (void) removeObjectAtIndex:(NSUInteger)index;
628 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
633 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
634 return JSValueIsObjectOfClass(context, value, Instance_);
637 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
638 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
641 struct CYBlockDescriptor {
643 BlockDescriptor1 one_;
644 BlockDescriptor2 two_;
645 BlockDescriptor3 three_;
648 Closure_privateData *internal_;
651 void CYDisposeBlock(BlockLiteral *literal) {
652 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
655 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
656 JSObjectRef _this(CYCastJSObject(context, values[0]));
657 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
660 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
661 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
664 NSObject *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
665 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
667 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
668 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
670 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
671 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
673 literal->isa = objc_getClass("__NSMallocBlock__");
674 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
675 literal->reserved = 0;
676 literal->descriptor = descriptor;
678 descriptor->d_.one_.size = sizeof(descriptor->d_);
679 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
680 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
682 return reinterpret_cast<NSObject *>(literal);
685 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
686 if (CYJSValueIsNSObject(context, object)) {
687 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
688 return internal->GetValue();
691 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
692 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
693 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
696 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
697 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
701 @interface NSBoolNumber : NSNumber {
706 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
710 switch (JSType type = JSValueGetType(context, value)) {
711 case kJSTypeUndefined:
712 object = [WebUndefined undefined];
722 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
725 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
731 object = CYCopyNSNumber(context, value);
736 object = CYCopyNSString(context, value);
741 // XXX: this might could be more efficient
742 object = CYCastNSObject(pool, context, (JSObjectRef) value);
747 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
754 return CYPoolRelease(pool, object);
756 return [object retain];
759 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
760 return CYNSObject(pool, context, value, true);
763 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
764 return CYNSObject(&pool, context, value, false);
767 /* Bridge: NSArray {{{ */
768 @implementation NSArray (Cycript)
771 return [[self mutableCopy] autorelease];
774 - (NSString *) cy$toCYON:(bool)objective {
775 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
776 [json appendString:@"@["];
780 for (id object in self) {
782 for (size_t index(0), count([self count]); index != count; ++index) {
783 id object([self objectAtIndex:index]);
786 [json appendString:@","];
789 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
790 [json appendString:CYCastNSCYON(object, true)];
792 [json appendString:@","];
797 [json appendString:@"]"];
801 - (bool) cy$hasProperty:(NSString *)name {
802 if ([name isEqualToString:@"length"])
805 size_t index(CYGetIndex(name));
806 if (index == _not(size_t) || index >= [self count])
807 return [super cy$hasProperty:name];
812 - (NSObject *) cy$getProperty:(NSString *)name {
813 size_t index(CYGetIndex(name));
814 if (index == _not(size_t) || index >= [self count])
815 return [super cy$getProperty:name];
817 return [self objectAtIndex:index];
820 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
822 if ([name isEqualToString:@"length"])
823 return CYCastJSValue(context, [self count]);
826 return [super cy$getProperty:name inContext:context];
829 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
830 [super cy$getPropertyNames:names inContext:context];
832 for (size_t index(0), count([self count]); index != count; ++index) {
833 id object([self objectAtIndex:index]);
834 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
836 sprintf(name, "%zu", index);
837 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
842 + (bool) cy$hasImplicitProperties {
848 /* Bridge: NSBlock {{{ */
855 /* Bridge: NSBoolNumber {{{ */
857 @implementation NSBoolNumber (Cycript)
859 - (JSType) cy$JSType {
860 return kJSTypeBoolean;
863 - (NSString *) cy$toCYON:(bool)objective {
864 NSString *value([self boolValue] ? @"true" : @"false");
865 return objective ? value : [NSString stringWithFormat:@"@%@", value];
868 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
869 return CYCastJSValue(context, (bool) [self boolValue]);
875 /* Bridge: NSDictionary {{{ */
876 @implementation NSDictionary (Cycript)
879 return [[self mutableCopy] autorelease];
882 - (NSString *) cy$toCYON:(bool)objective {
883 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
884 [json appendString:@"@{"];
888 for (NSObject *key in self) {
890 NSEnumerator *keys([self keyEnumerator]);
891 while (NSObject *key = [keys nextObject]) {
894 [json appendString:@","];
897 [json appendString:CYCastNSCYON(key, true)];
898 [json appendString:@":"];
899 NSObject *object([self objectForKey:key]);
900 [json appendString:CYCastNSCYON(object, true)];
903 [json appendString:@"}"];
907 - (bool) cy$hasProperty:(NSString *)name {
908 return [self objectForKey:name] != nil;
911 - (NSObject *) cy$getProperty:(NSString *)name {
912 return [self objectForKey:name];
915 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
916 [super cy$getPropertyNames:names inContext:context];
919 for (NSObject *key in self) {
921 NSEnumerator *keys([self keyEnumerator]);
922 while (NSObject *key = [keys nextObject]) {
924 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
928 + (bool) cy$hasImplicitProperties {
934 /* Bridge: NSMutableArray {{{ */
935 @implementation NSMutableArray (Cycript)
937 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
938 if ([name isEqualToString:@"length"]) {
939 // XXX: is this not intelligent?
940 NSNumber *number(reinterpret_cast<NSNumber *>(value));
942 NSUInteger size([number unsignedIntegerValue]);
944 NSUInteger size([number unsignedIntValue]);
946 NSUInteger count([self count]);
948 [self removeObjectsInRange:NSMakeRange(size, count - size)];
949 else if (size != count) {
950 WebUndefined *undefined([WebUndefined undefined]);
951 for (size_t i(count); i != size; ++i)
952 [self addObject:undefined];
957 size_t index(CYGetIndex(name));
958 if (index == _not(size_t))
959 return [super cy$setProperty:name to:value];
961 id object(value ?: [NSNull null]);
963 size_t count([self count]);
965 [self replaceObjectAtIndex:index withObject:object];
967 if (index != count) {
968 WebUndefined *undefined([WebUndefined undefined]);
969 for (size_t i(count); i != index; ++i)
970 [self addObject:undefined];
973 [self addObject:object];
979 - (bool) cy$deleteProperty:(NSString *)name {
980 size_t index(CYGetIndex(name));
981 if (index == _not(size_t) || index >= [self count])
982 return [super cy$deleteProperty:name];
983 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
989 /* Bridge: NSMutableDictionary {{{ */
990 @implementation NSMutableDictionary (Cycript)
992 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
993 [self setObject:(value ?: [NSNull null]) forKey:name];
997 - (bool) cy$deleteProperty:(NSString *)name {
998 if ([self objectForKey:name] == nil)
1001 [self removeObjectForKey:name];
1008 /* Bridge: NSNumber {{{ */
1009 @implementation NSNumber (Cycript)
1011 - (JSType) cy$JSType {
1013 // XXX: this just seems stupid
1014 if ([self class] == NSCFBoolean_)
1015 return kJSTypeBoolean;
1017 return kJSTypeNumber;
1020 - (NSString *) cy$toCYON:(bool)objective {
1021 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1022 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1025 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1026 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1027 } CYObjectiveCatch }
1031 /* Bridge: NSNull {{{ */
1032 @implementation NSNull (Cycript)
1034 - (JSType) cy$JSType {
1038 - (NSString *) cy$toCYON:(bool)objective {
1039 NSString *value(@"null");
1040 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1043 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1044 return CYJSNull(context);
1045 } CYObjectiveCatch }
1049 /* Bridge: NSObject {{{ */
1050 @implementation NSObject (Cycript)
1056 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1057 return [self cy$valueOfInContext:context];
1060 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1062 } CYObjectiveCatch }
1064 - (JSType) cy$JSType {
1065 return kJSTypeObject;
1068 - (NSString *) cy$toCYON:(bool)objective {
1069 return [[self description] cy$toCYON:objective];
1072 - (bool) cy$hasProperty:(NSString *)name {
1076 - (NSObject *) cy$getProperty:(NSString *)name {
1080 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1081 if (NSObject *value = [self cy$getProperty:name])
1082 return CYCastJSValue(context, value);
1084 } CYObjectiveCatch }
1086 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1090 - (bool) cy$deleteProperty:(NSString *)name {
1094 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1097 + (bool) cy$hasImplicitProperties {
1103 /* Bridge: NSProxy {{{ */
1104 @implementation NSProxy (Cycript)
1106 - (NSString *) cy$toCYON:(bool)objective {
1107 return [[self description] cy$toCYON:objective];
1112 /* Bridge: NSString {{{ */
1113 @implementation NSString (Cycript)
1116 return [[self copy] autorelease];
1119 - (JSType) cy$JSType {
1120 return kJSTypeString;
1123 - (NSString *) cy$toCYON:(bool)objective {
1124 std::ostringstream str;
1127 CYUTF8String string(CYCastUTF8String(self));
1128 CYStringify(str, string.data, string.size);
1129 std::string value(str.str());
1130 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1133 - (bool) cy$hasProperty:(NSString *)name {
1134 size_t index(CYGetIndex(name));
1135 if (index == _not(size_t) || index >= [self length])
1136 return [super cy$hasProperty:name];
1141 - (NSObject *) cy$getProperty:(NSString *)name {
1142 size_t index(CYGetIndex(name));
1143 if (index == _not(size_t) || index >= [self length])
1144 return [super cy$getProperty:name];
1146 return [self substringWithRange:NSMakeRange(index, 1)];
1149 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1150 [super cy$getPropertyNames:names inContext:context];
1152 for (size_t index(0), length([self length]); index != length; ++index) {
1154 sprintf(name, "%zu", index);
1155 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1159 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1160 return CYCastJSValue(context, CYJSString(context, self));
1161 } CYObjectiveCatch }
1165 /* Bridge: WebUndefined {{{ */
1166 @implementation WebUndefined (Cycript)
1168 - (JSType) cy$JSType {
1169 return kJSTypeUndefined;
1172 - (NSString *) cy$toCYON:(bool)objective {
1173 NSString *value(@"undefined");
1174 return value; // XXX: maybe use the below code, adding @undefined?
1175 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1178 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1179 return CYJSUndefined(context);
1180 } CYObjectiveCatch }
1185 static bool CYIsClass(id self) {
1187 return class_isMetaClass(object_getClass(self));
1189 return GSObjCIsClass(self);
1193 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1194 id self(CYCastNSObject(&pool, context, value));
1195 if (CYIsClass(self))
1196 return (Class) self;
1197 throw CYJSError(context, "got something that is not a Class");
1201 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1203 size_t size(JSPropertyNameArrayGetCount(names));
1204 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1205 for (size_t index(0); index != size; ++index)
1206 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1210 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1212 return CYJSNull(context);
1214 return CYMakeInstance(context, value, false);
1215 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1217 @implementation CYJSObject
1219 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1220 if ((self = [super init]) != nil) {
1222 context_ = CYGetJSContext(context);
1223 JSGlobalContextRetain(context_);
1224 JSValueProtect(context_, object_);
1226 } CYObjectiveCatch }
1228 - (void) dealloc { CYObjectiveTry {
1229 JSValueUnprotect(context_, object_);
1230 JSGlobalContextRelease(context_);
1232 } CYObjectiveCatch }
1234 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1236 const char *cyon(CYPoolCCYON(pool, context, object_));
1238 return [super cy$toCYON:objective];
1240 return [NSString stringWithUTF8String:cyon];
1241 } CYObjectiveCatch }
1243 - (NSUInteger) count { CYObjectiveTry {
1244 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1245 size_t size(JSPropertyNameArrayGetCount(names));
1246 JSPropertyNameArrayRelease(names);
1248 } CYObjectiveCatch }
1250 - (id) objectForKey:(id)key { CYObjectiveTry {
1251 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1252 if (JSValueIsUndefined(context, value))
1254 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1255 } CYObjectiveCatch }
1257 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1258 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1259 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1260 JSPropertyNameArrayRelease(names);
1262 } CYObjectiveCatch }
1264 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1265 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1266 } CYObjectiveCatch }
1268 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1269 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1270 } CYObjectiveCatch }
1274 @implementation CYJSArray
1276 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1278 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1279 } CYObjectiveCatch }
1281 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1282 if ((self = [super init]) != nil) {
1284 context_ = CYGetJSContext(context);
1285 JSGlobalContextRetain(context_);
1286 JSValueProtect(context_, object_);
1288 } CYObjectiveCatch }
1290 - (void) dealloc { CYObjectiveTry {
1291 JSValueUnprotect(context_, object_);
1292 JSGlobalContextRelease(context_);
1294 } CYObjectiveCatch }
1296 - (NSUInteger) count { CYObjectiveTry {
1297 return CYArrayLength(context, object_);
1298 } CYObjectiveCatch }
1300 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1301 size_t bounds([self count]);
1302 if (index >= bounds)
1303 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1304 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1305 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1306 } CYObjectiveCatch }
1308 - (void) addObject:(id)object { CYObjectiveTry {
1309 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1310 } CYObjectiveCatch }
1312 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1313 size_t bounds([self count] + 1);
1314 if (index >= bounds)
1315 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1316 JSValueRef arguments[3];
1317 arguments[0] = CYCastJSValue(context, index);
1318 arguments[1] = CYCastJSValue(context, 0);
1319 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1320 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1321 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1322 } CYObjectiveCatch }
1324 - (void) removeLastObject { CYObjectiveTry {
1325 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1326 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1327 } CYObjectiveCatch }
1329 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1330 size_t bounds([self count]);
1331 if (index >= bounds)
1332 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1333 JSValueRef arguments[2];
1334 arguments[0] = CYCastJSValue(context, index);
1335 arguments[1] = CYCastJSValue(context, 1);
1336 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1337 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1338 } CYObjectiveCatch }
1340 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1341 size_t bounds([self count]);
1342 if (index >= bounds)
1343 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1344 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1345 } CYObjectiveCatch }
1349 // XXX: inherit from or replace with CYJSObject
1350 @interface CYInternal : NSObject {
1351 JSGlobalContextRef context_;
1352 JSObjectRef object_;
1357 @implementation CYInternal
1359 - (void) dealloc { CYObjectiveTry {
1360 JSValueUnprotect(context_, object_);
1361 JSGlobalContextRelease(context_);
1363 } CYObjectiveCatch }
1365 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1366 if ((self = [super init]) != nil) {
1367 context_ = CYGetJSContext(context);
1368 JSGlobalContextRetain(context_);
1370 } CYObjectiveCatch }
1372 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1373 if (object_ == NULL)
1376 return JSObjectHasProperty(context, object_, name);
1379 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1380 if (object_ == NULL)
1383 return CYGetProperty(context, object_, name);
1386 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1387 @synchronized (self) {
1388 if (object_ == NULL) {
1389 object_ = JSObjectMake(context, NULL, NULL);
1390 JSValueProtect(context, object_);
1394 CYSetProperty(context, object_, name, value);
1397 + (CYInternal *) get:(id)object {
1398 if ($objc_getAssociatedObject == NULL)
1401 @synchronized (object) {
1402 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1409 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1410 if ($objc_getAssociatedObject == NULL)
1413 @synchronized (object) {
1414 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1417 if ($objc_setAssociatedObject == NULL)
1420 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1421 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1430 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1431 Selector_privateData *internal(new Selector_privateData(sel));
1432 return JSObjectMake(context, Selector_, internal);
1435 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1436 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1437 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1438 return reinterpret_cast<SEL>(internal->value_);
1440 return CYCastPointer<SEL>(context, value);
1443 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1444 return (void *) [[NSAutoreleasePool alloc] init];
1445 } CYSadCatch(NULL) }
1447 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1448 return [(NSAutoreleasePool *) handle release];
1451 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1453 return Instance::Make(context, nil);
1454 if (Class _class = objc_getClass(name.data))
1455 return CYMakeInstance(context, _class, true);
1456 if (Protocol *protocol = objc_getProtocol(name.data))
1457 return CYMakeInstance(context, protocol, true);
1459 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1461 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1462 ffi_call(cif, function, value, values);
1465 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1466 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1468 switch (type->primitive) {
1469 case sig::block_P: {
1470 _assert(type->data.signature.count != 0);
1471 sig::Signature signature;
1472 sig::Copy(*pool, signature, type->data.signature);
1474 sig::Element *elements(new(*pool) sig::Element[++signature.count]);
1475 elements[0] = signature.elements[0];
1476 memcpy(elements + 2, signature.elements + 1, sizeof(sig::Element) * (signature.count - 2));
1477 signature.elements = elements;
1479 elements[1].name = NULL;
1480 elements[1].type = new(*pool) sig::Type();
1481 elements[1].offset = _not(size_t);
1483 memset(elements[1].type, 0, sizeof(sig::Type));
1484 elements[1].type->primitive = sig::object_P;
1486 JSObjectRef function(CYCastJSObject(context, value));
1487 *reinterpret_cast<id *>(data) = CYMakeBlock(context, function, signature);
1491 case sig::typename_P:
1492 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1495 case sig::selector_P:
1496 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1504 } CYSadCatch(false) }
1506 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1507 switch (type->primitive) {
1508 // XXX: do something epic about blocks
1511 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1512 JSValueRef value(CYCastJSValue(context, object));
1518 case sig::typename_P:
1519 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1521 case sig::selector_P:
1522 if (SEL sel = *reinterpret_cast<SEL *>(data))
1523 return CYMakeSelector(context, sel);
1527 return CYJSNull(context);
1531 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1533 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1534 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1537 #if OBJC_API_VERSION >= 2
1539 method_getReturnType(method, type, sizeof(type));
1541 const char *type(method_getTypeEncoding(method));
1547 // XXX: possibly use a more "awesome" check?
1551 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1553 return method_getTypeEncoding(method);
1555 const char *name(sel_getName(sel));
1556 size_t length(strlen(name));
1558 char keyed[length + 2];
1560 keyed[length + 1] = '\0';
1561 memcpy(keyed + 1, name, length);
1563 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1564 return entry->value_;
1569 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1570 JSObjectRef _this(CYCastJSObject(context, values[0]));
1571 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1574 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1575 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1578 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1579 Message_privateData *internal(new Message_privateData(sel, type, imp));
1580 return JSObjectMake(context, Message_, internal);
1583 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1584 JSObjectRef function(CYCastJSObject(context, value));
1586 sig::Signature signature;
1587 sig::Parse(pool, &signature, encoding, &Structor_);
1588 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1589 // XXX: see notes in Library.cpp about needing to leak
1590 return reinterpret_cast<IMP>(internal->GetValue());
1593 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1594 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1595 Class _class(internal->GetValue());
1598 const char *name(CYPoolCString(pool, context, property));
1600 if (SEL sel = sel_getUid(name))
1601 if (class_getInstanceMethod(_class, sel) != NULL)
1607 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1608 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1609 Class _class(internal->GetValue());
1612 const char *name(CYPoolCString(pool, context, property));
1614 if (SEL sel = sel_getUid(name))
1615 if (objc_method *method = class_getInstanceMethod(_class, sel))
1616 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1621 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1622 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1623 Class _class(internal->GetValue());
1626 const char *name(CYPoolCString(pool, context, property));
1628 SEL sel(sel_registerName(name));
1630 objc_method *method(class_getInstanceMethod(_class, sel));
1635 if (JSValueIsObjectOfClass(context, value, Message_)) {
1636 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1637 type = sig::Unparse(pool, &message->signature_);
1638 imp = reinterpret_cast<IMP>(message->GetValue());
1640 type = CYPoolTypeEncoding(pool, context, sel, method);
1641 imp = CYMakeMessage(context, value, type);
1645 method_setImplementation(method, imp);
1648 GSMethodList list(GSAllocMethodList(1));
1649 GSAppendMethodToList(list, sel, type, imp, YES);
1650 GSAddMethodList(_class, list, YES);
1651 GSFlushMethodCacheForClass(_class);
1653 class_addMethod(_class, sel, imp, type);
1660 #if 0 && OBJC_API_VERSION < 2
1661 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1662 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1663 Class _class(internal->GetValue());
1666 const char *name(CYPoolCString(pool, context, property));
1668 if (SEL sel = sel_getUid(name))
1669 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1670 objc_method_list list = {NULL, 1, {method}};
1671 class_removeMethods(_class, &list);
1679 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1680 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1681 Class _class(internal->GetValue());
1683 #if OBJC_API_VERSION >= 2
1685 objc_method **data(class_copyMethodList(_class, &size));
1686 for (size_t i(0); i != size; ++i)
1687 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1690 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1691 for (int i(0); i != methods->method_count; ++i)
1692 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1696 static bool CYHasImplicitProperties(Class _class) {
1697 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1698 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1700 return [_class cy$hasImplicitProperties];
1703 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1704 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1705 id self(internal->GetValue());
1707 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1711 NSString *name(CYCastNSString(&pool, context, property));
1713 if (CYInternal *internal = [CYInternal get:self])
1714 if ([internal hasProperty:property inContext:context])
1717 Class _class(object_getClass(self));
1720 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1721 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1722 if ([self cy$hasProperty:name])
1724 } CYPoolCatch(false)
1726 const char *string(CYPoolCString(pool, context, name));
1729 if (class_getProperty(_class, string) != NULL)
1733 if (CYHasImplicitProperties(_class))
1734 if (SEL sel = sel_getUid(string))
1735 if (CYImplements(self, _class, sel, true))
1741 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1742 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1743 id self(internal->GetValue());
1745 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1746 return Internal::Make(context, self, object);
1749 NSString *name(CYCastNSString(&pool, context, property));
1751 if (CYInternal *internal = [CYInternal get:self])
1752 if (JSValueRef value = [internal getProperty:property inContext:context])
1756 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1760 const char *string(CYPoolCString(pool, context, name));
1761 Class _class(object_getClass(self));
1764 if (objc_property_t property = class_getProperty(_class, string)) {
1765 PropertyAttributes attributes(property);
1766 SEL sel(sel_registerName(attributes.Getter()));
1767 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1771 if (CYHasImplicitProperties(_class))
1772 if (SEL sel = sel_getUid(string))
1773 if (CYImplements(self, _class, sel, true))
1774 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1779 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1780 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1781 id self(internal->GetValue());
1785 NSString *name(CYCastNSString(&pool, context, property));
1786 NSObject *data(CYCastNSObject(&pool, context, value));
1789 if ([self cy$setProperty:name to:data])
1791 } CYPoolCatch(false)
1793 const char *string(CYPoolCString(pool, context, name));
1794 Class _class(object_getClass(self));
1797 if (objc_property_t property = class_getProperty(_class, string)) {
1798 PropertyAttributes attributes(property);
1799 if (const char *setter = attributes.Setter()) {
1800 SEL sel(sel_registerName(setter));
1801 JSValueRef arguments[1] = {value};
1802 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1808 size_t length(strlen(string));
1810 char set[length + 5];
1816 if (string[0] != '\0') {
1817 set[3] = toupper(string[0]);
1818 memcpy(set + 4, string + 1, length - 1);
1821 set[length + 3] = ':';
1822 set[length + 4] = '\0';
1824 if (SEL sel = sel_getUid(set))
1825 if (CYImplements(self, _class, sel)) {
1826 JSValueRef arguments[1] = {value};
1827 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1831 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1832 [internal setProperty:property toValue:value inContext:context];
1839 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1840 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1841 id self(internal->GetValue());
1844 NSString *name(CYCastNSString(NULL, context, property));
1845 return [self cy$deleteProperty:name];
1846 } CYPoolCatch(false)
1847 } CYCatch(false) return /*XXX*/ false; }
1849 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1850 const char *name(sel_getName(method_getName(method)));
1851 if (strchr(name, ':') != NULL)
1854 const char *type(method_getTypeEncoding(method));
1855 if (type == NULL || *type == '\0' || *type == 'v')
1858 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1861 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1862 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1863 id self(internal->GetValue());
1866 Class _class(object_getClass(self));
1871 objc_property_t *data(class_copyPropertyList(_class, &size));
1872 for (size_t i(0); i != size; ++i)
1873 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1878 if (CYHasImplicitProperties(_class))
1879 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1880 #if OBJC_API_VERSION >= 2
1882 objc_method **data(class_copyMethodList(current, &size));
1883 for (size_t i(0); i != size; ++i)
1884 Instance_getPropertyNames_message(names, data[i]);
1887 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1888 for (int i(0); i != methods->method_count; ++i)
1889 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1894 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1895 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1896 [self cy$getPropertyNames:names inContext:context];
1900 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1901 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1902 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1906 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1907 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1908 id self(internal->GetValue());
1910 if (![self isKindOfClass:NSBlock_])
1911 CYThrow("non-NSBlock object is not a function");
1912 // XXX: replace above logic with the following assertion
1913 //_assert([self isKindOfClass:NSBlock_]);
1914 // to do this, make it so FunctionInstance_ is the class of blocks
1915 // to do /that/, generalize the various "is exactly Instance_" checks
1916 // then, move Instance_callAsFunction to only be on FunctionInstance
1918 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1920 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1921 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1922 descriptor += sizeof(BlockDescriptor1);
1923 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1924 descriptor += sizeof(BlockDescriptor2);
1925 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1927 if (const char *type = descriptor3->signature) {
1933 sig::Signature signature;
1934 sig::Parse(pool, &signature, type, &Structor_);
1937 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1939 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1940 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1945 CYThrow("NSBlock without signature field passed arguments");
1949 } CYPoolCatch(NULL);
1954 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1955 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1956 Class _class(internal->GetValue());
1957 if (!CYIsClass(_class))
1960 if (CYJSValueIsNSObject(context, instance)) {
1961 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1962 // XXX: this isn't always safe
1963 return [linternal->GetValue() isKindOfClass:_class];
1969 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1971 throw CYJSError(context, "incorrect number of arguments to Instance");
1973 id value(CYCastNSObject(&pool, context, arguments[0]));
1975 value = [NSNull null];
1976 return CYCastJSValue(context, [value cy$box]);
1979 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1980 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1983 id self(internal->GetValue());
1984 const char *name(CYPoolCString(pool, context, property));
1986 if (object_getInstanceVariable(self, name, NULL) != NULL)
1992 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1993 length = CYCastDouble(encoding + 1);
1997 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
1998 for (size_t i(0); i != size; ++i)
1999 if (ivars[i] == ivar)
2001 else if (ivar_getOffset(ivars[i]) == offset) {
2002 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2003 _assert(encoding[0] == 'b');
2004 shift += CYCastDouble(encoding + 1);
2009 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2010 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2013 id self(internal->GetValue());
2014 const char *name(CYPoolCString(pool, context, property));
2017 if (strcmp(name, "isa") == 0)
2018 return CYCastJSValue(context, object_getClass(self));
2021 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2022 ptrdiff_t offset(ivar_getOffset(ivar));
2023 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2025 const char *encoding(ivar_getTypeEncoding(ivar));
2026 if (encoding[0] == 'b') {
2027 unsigned length, shift;
2028 CYBitField(length, shift, self, ivar, encoding, offset);
2029 _assert(shift + length <= sizeof(uintptr_t) * 8);
2030 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2031 uintptr_t mask((1 << length) - 1);
2032 return CYCastJSValue(context, (field >> shift) & mask);
2034 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2035 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2042 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2043 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2046 id self(internal->GetValue());
2047 const char *name(CYPoolCString(pool, context, property));
2049 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2050 ptrdiff_t offset(ivar_getOffset(ivar));
2051 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2053 const char *encoding(ivar_getTypeEncoding(ivar));
2054 if (encoding[0] == 'b') {
2055 unsigned length, shift;
2056 CYBitField(length, shift, self, ivar, encoding, offset);
2057 _assert(shift + length <= sizeof(uintptr_t) * 8);
2058 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2059 uintptr_t mask((1 << length) - 1);
2060 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2062 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2063 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2071 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2072 if (Class super = class_getSuperclass(_class))
2073 Internal_getPropertyNames_(super, names);
2075 #if OBJC_API_VERSION >= 2
2077 objc_ivar **data(class_copyIvarList(_class, &size));
2078 for (size_t i(0); i != size; ++i)
2079 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2082 if (objc_ivar_list *ivars = _class->ivars)
2083 for (int i(0); i != ivars->ivar_count; ++i)
2084 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2088 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2089 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2092 id self(internal->GetValue());
2093 Class _class(object_getClass(self));
2095 Internal_getPropertyNames_(_class, names);
2098 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2099 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2100 return internal->GetOwner();
2103 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2105 NSString *name(CYCastNSString(&pool, context, property));
2106 if (Class _class = NSClassFromString(name))
2107 return CYMakeInstance(context, _class, true);
2112 static Class *CYCopyClassList(size_t &size) {
2113 size = objc_getClassList(NULL, 0);
2114 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2117 size_t writ(objc_getClassList(data, size));
2123 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2135 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2138 if (Class *data = CYCopyClassList(size)) {
2139 for (size_t i(0); i != size; ++i)
2140 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2145 while (Class _class = objc_next_class(&state))
2146 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2150 #if OBJC_API_VERSION >= 2
2151 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2152 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2155 const char *name(CYPoolCString(pool, context, property));
2157 const char **data(objc_copyClassNamesForImage(internal, &size));
2159 for (size_t i(0); i != size; ++i)
2160 if (strcmp(name, data[i]) == 0) {
2161 if (Class _class = objc_getClass(name)) {
2162 value = CYMakeInstance(context, _class, true);
2173 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2174 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2176 const char **data(objc_copyClassNamesForImage(internal, &size));
2177 for (size_t i(0); i != size; ++i)
2178 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2182 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2184 const char *name(CYPoolCString(pool, context, property));
2186 const char **data(objc_copyImageNames(&size));
2187 for (size_t i(0); i != size; ++i)
2188 if (strcmp(name, data[i]) == 0) {
2197 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2198 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2202 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2204 const char **data(objc_copyImageNames(&size));
2205 for (size_t i(0); i != size; ++i)
2206 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2211 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2213 const char *name(CYPoolCString(pool, context, property));
2214 if (Protocol *protocol = objc_getProtocol(name))
2215 return CYMakeInstance(context, protocol, true);
2219 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2220 #if OBJC_API_VERSION >= 2
2222 Protocol **data(objc_copyProtocolList(&size));
2223 for (size_t i(0); i != size; ++i)
2224 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2231 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2233 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2235 return Instance::Make(context, nil);
2239 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2240 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2244 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2245 *data = reinterpret_cast<void *>(address);
2246 return KERN_SUCCESS;
2250 std::set<Class> query_;
2251 JSContextRef context_;
2252 JSObjectRef results_;
2255 struct CYObjectStruct {
2259 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2260 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2261 JSContextRef context(choice->context_);
2263 for (unsigned i(0); i != count; ++i) {
2264 vm_range_t &range(ranges[i]);
2265 void *data(reinterpret_cast<void *>(range.address));
2266 size_t size(range.size);
2268 if (size < sizeof(CYObjectStruct))
2271 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2273 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2275 Class isa(reinterpret_cast<Class>(pointers[0]));
2278 std::set<Class>::const_iterator result(choice->query_.find(isa));
2279 if (result == choice->query_.end())
2282 // XXX: if (size < class_getInstanceSize(*result))
2283 if ((class_getInstanceSize(*result) + 15) / 16 * 16 != size)
2285 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2289 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2291 throw CYJSError(context, "choose() takes a class argument");
2294 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2296 vm_address_t *zones(NULL);
2298 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2299 _assert(error == KERN_SUCCESS);
2301 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2302 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2305 choice.context_ = context;
2306 choice.results_ = results;
2309 Class *classes(CYCopyClassList(number));
2310 _assert(classes != NULL);
2312 for (size_t i(0); i != number; ++i)
2313 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2314 if (current == _class) {
2315 choice.query_.insert(classes[i]);
2321 for (unsigned i(0); i != size; ++i) {
2322 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2323 if (zone == NULL || zone->introspect == NULL)
2326 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2334 #if defined(__i386__) || defined(__x86_64__)
2335 #define OBJC_MAX_STRUCT_BY_VALUE 8
2336 static int struct_forward_array[] = {
2337 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2338 #elif defined(__arm__)
2339 #define OBJC_MAX_STRUCT_BY_VALUE 1
2340 static int struct_forward_array[] = {
2342 #elif defined(__arm64__)
2345 #error missing objc-runtime-info
2349 static bool stret(ffi_type *ffi_type) {
2350 return ffi_type->type == FFI_TYPE_STRUCT && (
2351 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2352 struct_forward_array[ffi_type->size] != 0
2358 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2362 _class = object_getClass(self);
2366 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2367 imp = method_getImplementation(method);
2368 type = method_getTypeEncoding(method);
2373 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2375 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2376 type = CYPoolCString(pool, context, [method _typeString]);
2384 sig::Signature signature;
2385 sig::Parse(pool, &signature, type, &Structor_);
2387 size_t used(count + 3);
2388 if (used > signature.count) {
2389 sig::Element *elements(new (pool) sig::Element[used]);
2390 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2392 for (size_t index(signature.count); index != used; ++index) {
2393 sig::Element *element(&elements[index]);
2394 element->name = NULL;
2395 element->offset = _not(size_t);
2397 sig::Type *type(new (pool) sig::Type);
2398 memset(type, 0, sizeof(*type));
2399 type->primitive = sig::object_P;
2400 element->type = type;
2403 signature.elements = elements;
2404 signature.count = used;
2408 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2413 if (stret(cif.rtype))
2414 imp = class_getMethodImplementation_stret(_class, _cmd);
2417 imp = class_getMethodImplementation(_class, _cmd);
2419 objc_super super = {self, _class};
2420 imp = objc_msg_lookup_super(&super, _cmd);
2424 void (*function)() = reinterpret_cast<void (*)()>(imp);
2425 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2428 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2430 throw CYJSError(context, "too few arguments to objc_msgSend");
2440 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2441 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2442 self = internal->GetValue();
2443 _class = internal->class_;;
2444 uninitialized = false;
2445 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2446 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2447 self = internal->GetValue();
2449 uninitialized = internal->IsUninitialized();
2451 internal->value_ = nil;
2453 self = CYCastNSObject(&pool, context, arguments[0]);
2455 uninitialized = false;
2459 return CYJSNull(context);
2461 _cmd = CYCastSEL(context, arguments[1]);
2463 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2466 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2467 return $objc_msgSend(context, object, _this, count, arguments);
2470 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2471 JSValueRef setup[count + 2];
2474 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2475 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2478 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2480 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2482 // XXX: handle Instance::Uninitialized?
2483 id self(CYCastNSObject(&pool, context, _this));
2487 setup[1] = &internal->sel_;
2489 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2492 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2494 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2496 id self(CYCastNSObject(&pool, context, arguments[0]));
2497 Class _class(CYCastClass(pool, context, arguments[1]));
2498 return cy::Super::Make(context, self, _class);
2501 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2503 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2505 const char *name(CYPoolCString(pool, context, arguments[0]));
2506 return CYMakeSelector(context, sel_registerName(name));
2509 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2511 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2512 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2513 return CYMakeInstance(context, self, false);
2516 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2517 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2518 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2521 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2522 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2523 Type_privateData *typical(internal->GetType());
2528 if (typical == NULL) {
2532 type = typical->type_;
2533 ffi = typical->ffi_;
2536 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2539 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2540 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2541 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2544 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2545 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2546 id self(internal->GetValue());
2547 if (!CYIsClass(self))
2548 return CYJSUndefined(context);
2549 return CYGetClassPrototype(context, self);
2552 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2553 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2554 id self(internal->GetValue());
2555 if (!CYIsClass(self))
2556 return CYJSUndefined(context);
2557 return Messages::Make(context, (Class) self);
2560 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2561 if (!CYJSValueIsNSObject(context, _this))
2564 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2565 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2568 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2569 if (!CYJSValueIsNSObject(context, _this))
2572 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2573 id value(internal->GetValue());
2580 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2582 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2583 return CYJSUndefined(context);
2584 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2587 return CYCastJSValue(context, CYJSString(context, [value description]));
2589 } CYCatch(NULL) return /*XXX*/ NULL; }
2591 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2592 if (!CYJSValueIsNSObject(context, _this))
2595 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2596 id value(internal->GetValue());
2598 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2601 if (JSValueRef result = [value cy$valueOfInContext:context])
2605 } CYCatch(NULL) return /*XXX*/ NULL; }
2607 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2608 if (!CYJSValueIsNSObject(context, _this))
2611 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2612 // XXX: but... but... THIS ISN'T A POINTER! :(
2613 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2614 } CYCatch(NULL) return /*XXX*/ NULL; }
2616 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2617 if (!CYJSValueIsNSObject(context, _this))
2620 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2621 id value(internal->GetValue());
2624 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2625 return CYCastJSValue(context, CYJSString(context, [value description]));
2627 } CYCatch(NULL) return /*XXX*/ NULL; }
2629 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2630 if (!CYJSValueIsNSObject(context, _this))
2633 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2634 id value(internal->GetValue());
2636 if (!CYIsClass(value))
2637 CYThrow("non-Class object cannot be used as Type");
2639 // XXX: this is a very silly implementation
2641 std::ostringstream type;
2643 type << class_getName(value);
2647 return CYMakeType(context, type.str().c_str());
2649 } CYCatch(NULL) return /*XXX*/ NULL; }
2651 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2652 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2653 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2656 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2657 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2660 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2661 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2662 const char *name(sel_getName(internal->GetValue()));
2665 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2666 return CYCastJSValue(context, CYJSString(context, string));
2668 } CYCatch(NULL) return /*XXX*/ NULL; }
2670 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2672 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2675 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2676 SEL sel(internal->GetValue());
2678 objc_method *method;
2679 if (Class _class = CYCastClass(pool, context, arguments[0]))
2680 method = class_getInstanceMethod(_class, sel);
2684 const char *encoding(CYPoolTypeEncoding(pool, context, sel, method));
2685 if (encoding == NULL)
2686 return CYJSNull(context);
2688 sig::Signature signature;
2689 sig::Parse(pool, &signature, encoding, &Structor_);
2690 return CYMakeType(context, &signature);
2693 static JSStaticValue Selector_staticValues[2] = {
2694 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2695 {NULL, NULL, NULL, 0}
2698 static JSStaticValue Instance_staticValues[5] = {
2699 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2700 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2701 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2702 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2703 {NULL, NULL, NULL, 0}
2706 static JSStaticFunction Instance_staticFunctions[7] = {
2707 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2708 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2709 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2710 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2711 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2712 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2716 static JSStaticFunction Class_staticFunctions[2] = {
2717 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2721 static JSStaticFunction Internal_staticFunctions[2] = {
2722 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2726 static JSStaticFunction Selector_staticFunctions[5] = {
2727 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2729 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2730 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2735 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2736 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2737 } CYObjectiveCatch }
2740 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2741 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2742 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2743 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2745 CYPool &pool(CYGetGlobalPool());
2747 Object_type = new(pool) Type_privateData("@");
2748 Selector_type = new(pool) Type_privateData(":");
2750 NSArray_ = objc_getClass("NSArray");
2751 NSBlock_ = objc_getClass("NSBlock");
2752 NSDictionary_ = objc_getClass("NSDictionary");
2753 NSString_ = objc_getClass("NSString");
2754 Object_ = objc_getClass("Object");
2757 // XXX: apparently, iOS now has both of these
2758 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2759 if (NSCFBoolean_ == nil)
2760 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2762 NSCFType_ = objc_getClass("NSCFType");
2764 NSZombie_ = objc_getClass("_NSZombie_");
2766 banned_.insert(Object_);
2767 banned_.insert(objc_getClass("__NSAtom"));
2768 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2769 banned_.insert(objc_getClass("NSMessageBuilder"));
2770 banned_.insert(objc_getClass("__NSMessageBuilder"));
2772 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2775 JSClassDefinition definition;
2777 definition = kJSClassDefinitionEmpty;
2778 definition.className = "Instance";
2779 definition.staticValues = Instance_staticValues;
2780 definition.staticFunctions = Instance_staticFunctions;
2781 definition.hasProperty = &Instance_hasProperty;
2782 definition.getProperty = &Instance_getProperty;
2783 definition.setProperty = &Instance_setProperty;
2784 definition.deleteProperty = &Instance_deleteProperty;
2785 definition.getPropertyNames = &Instance_getPropertyNames;
2786 definition.callAsConstructor = &Instance_callAsConstructor;
2787 definition.callAsFunction = &Instance_callAsFunction;
2788 definition.hasInstance = &Instance_hasInstance;
2789 definition.finalize = &CYFinalize;
2790 Instance_ = JSClassCreate(&definition);
2792 definition.className = "ArrayInstance";
2793 ArrayInstance_ = JSClassCreate(&definition);
2795 definition.className = "FunctionInstance";
2796 FunctionInstance_ = JSClassCreate(&definition);
2798 definition.className = "ObjectInstance";
2799 ObjectInstance_ = JSClassCreate(&definition);
2801 definition.className = "StringInstance";
2802 StringInstance_ = JSClassCreate(&definition);
2804 definition = kJSClassDefinitionEmpty;
2805 definition.className = "Class";
2806 definition.staticFunctions = Class_staticFunctions;
2807 Class_ = JSClassCreate(&definition);
2809 definition = kJSClassDefinitionEmpty;
2810 definition.className = "Internal";
2811 definition.staticFunctions = Internal_staticFunctions;
2812 definition.hasProperty = &Internal_hasProperty;
2813 definition.getProperty = &Internal_getProperty;
2814 definition.setProperty = &Internal_setProperty;
2815 definition.getPropertyNames = &Internal_getPropertyNames;
2816 definition.finalize = &CYFinalize;
2817 Internal_ = JSClassCreate(&definition);
2819 definition = kJSClassDefinitionEmpty;
2820 definition.className = "Message";
2821 definition.staticFunctions = cy::Functor::StaticFunctions;
2822 definition.callAsFunction = &Message_callAsFunction;
2823 definition.finalize = &CYFinalize;
2824 Message_ = JSClassCreate(&definition);
2826 definition = kJSClassDefinitionEmpty;
2827 definition.className = "Messages";
2828 definition.hasProperty = &Messages_hasProperty;
2829 definition.getProperty = &Messages_getProperty;
2830 definition.setProperty = &Messages_setProperty;
2831 #if 0 && OBJC_API_VERSION < 2
2832 definition.deleteProperty = &Messages_deleteProperty;
2834 definition.getPropertyNames = &Messages_getPropertyNames;
2835 definition.finalize = &CYFinalize;
2836 Messages_ = JSClassCreate(&definition);
2838 definition = kJSClassDefinitionEmpty;
2839 definition.className = "Selector";
2840 definition.staticValues = Selector_staticValues;
2841 definition.staticFunctions = Selector_staticFunctions;
2842 definition.callAsFunction = &Selector_callAsFunction;
2843 definition.finalize = &CYFinalize;
2844 Selector_ = JSClassCreate(&definition);
2846 definition = kJSClassDefinitionEmpty;
2847 definition.className = "Super";
2848 definition.staticFunctions = Internal_staticFunctions;
2849 definition.finalize = &CYFinalize;
2850 Super_ = JSClassCreate(&definition);
2852 definition = kJSClassDefinitionEmpty;
2853 definition.className = "ObjectiveC::Classes";
2854 definition.getProperty = &ObjectiveC_Classes_getProperty;
2855 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2856 ObjectiveC_Classes_ = JSClassCreate(&definition);
2858 definition = kJSClassDefinitionEmpty;
2859 definition.className = "ObjectiveC::Constants";
2860 definition.getProperty = &ObjectiveC_Constants_getProperty;
2861 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2862 ObjectiveC_Constants_ = JSClassCreate(&definition);
2864 #if OBJC_API_VERSION >= 2
2865 definition = kJSClassDefinitionEmpty;
2866 definition.className = "ObjectiveC::Images";
2867 definition.getProperty = &ObjectiveC_Images_getProperty;
2868 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2869 ObjectiveC_Images_ = JSClassCreate(&definition);
2871 definition = kJSClassDefinitionEmpty;
2872 definition.className = "ObjectiveC::Image::Classes";
2873 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2874 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2875 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2878 definition = kJSClassDefinitionEmpty;
2879 definition.className = "ObjectiveC::Protocols";
2880 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2881 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2882 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2885 // XXX: this is horrible; there has to be a better way to do this
2887 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2889 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2894 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2895 JSObjectRef global(CYGetGlobalObject(context));
2896 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2897 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2898 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2899 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2901 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2902 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2904 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2905 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2906 CYArrayPush(context, alls, protocols);
2908 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2909 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2910 CYArrayPush(context, alls, classes);
2912 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2913 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2914 CYArrayPush(context, alls, constants);
2916 #if OBJC_API_VERSION >= 2
2917 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2920 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2921 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2922 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2923 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2924 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2926 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2927 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2929 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2930 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2931 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2932 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2933 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2935 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2936 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2937 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2938 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2939 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2941 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2942 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2943 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2944 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2945 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2947 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2948 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2949 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2950 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2951 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2953 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2954 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2955 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2957 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2958 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2959 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2961 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2962 CYSetProperty(context, Instance, CYJSString("box"), box);
2965 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2968 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2970 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2971 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2974 static CYHooks CYObjectiveCHooks = {
2975 &CYObjectiveC_ExecuteStart,
2976 &CYObjectiveC_ExecuteEnd,
2977 &CYObjectiveC_CallFunction,
2978 &CYObjectiveC_Initialize,
2979 &CYObjectiveC_SetupContext,
2980 &CYObjectiveC_PoolFFI,
2981 &CYObjectiveC_FromFFI,
2984 struct CYObjectiveC {
2986 hooks_ = &CYObjectiveCHooks;
2987 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2988 _assert(hooks_ != NULL);
2992 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
2993 CYSetupContext(context);
2994 } CYObjectiveCatch }
2996 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
2999 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3000 utf8 = CYPoolCode(pool, utf8);
3002 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3003 size_t bytes(utf16.size * sizeof(uint16_t));
3004 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3005 memcpy(copy, utf16.data, bytes);
3009 } catch (const CYException &exception) {
3011 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];