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 __NSMallocBlock__;
298 static Class NSCFBoolean_;
299 static Class NSCFType_;
300 static Class NSGenericDeallocHandler_;
301 static Class NSZombie_;
303 static std::set<Class> banned_;
305 static Class NSBoolNumber_;
308 static Class NSArray_;
309 static Class NSBlock_;
310 static Class NSDictionary_;
311 static Class NSString_;
312 static Class Object_;
314 static Type_privateData *Object_type;
315 static Type_privateData *Selector_type;
317 Type_privateData *Instance::GetType() const {
321 Type_privateData *Selector_privateData::GetType() const {
322 return Selector_type;
325 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
327 JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
329 return CYGetCachedObject(context, CYJSString("Instance_prototype"));
330 else if (meta && !class_isMetaClass(self))
331 return CYGetCachedObject(context, CYJSString("Class_prototype"));
333 JSObjectRef global(CYGetGlobalObject(context));
334 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
337 sprintf(label, "i%p", self);
338 CYJSString name(label);
340 JSValueRef value(CYGetProperty(context, cy, name));
341 if (!JSValueIsUndefined(context, value))
344 JSClassRef _class(NULL);
345 JSValueRef prototype;
347 if (self == NSArray_)
348 prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
349 else if (self == NSBlock_)
350 prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
351 else if (self == NSDictionary_)
352 prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
353 else if (self == NSString_)
354 prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
356 prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
358 JSObjectRef object(JSObjectMake(context, _class, NULL));
359 JSObjectSetPrototype(context, object, prototype);
360 CYSetProperty(context, cy, name, object);
365 _finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
366 return CYGetClassPrototype(context, self, class_isMetaClass(self));
369 JSObjectRef Messages::Make(JSContextRef context, Class _class) {
370 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
371 if (Class super = class_getSuperclass(_class))
372 JSObjectSetPrototype(context, value, Messages::Make(context, super));
376 JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
377 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
381 JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
382 JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
386 JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
387 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
388 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
392 Instance::~Instance() {
393 if ((flags_ & Transient) == 0)
394 // XXX: does this handle background threads correctly?
395 // XXX: this simply does not work on the console because I'm stupid
396 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
399 struct Message_privateData :
404 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
405 cy::Functor(type, reinterpret_cast<void (*)()>(value)),
411 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
412 Instance::Flags flags;
415 flags = Instance::Transient;
417 flags = Instance::None;
418 object = [object retain];
421 return Instance::Make(context, object, flags);
424 @interface NSMethodSignature (Cycript)
425 - (NSString *) _typeString;
428 @interface NSObject (Cycript)
430 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
431 - (JSType) cy$JSType;
433 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
434 - (NSString *) cy$toCYON:(bool)objective;
436 - (bool) cy$hasProperty:(NSString *)name;
437 - (NSObject *) cy$getProperty:(NSString *)name;
438 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
439 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
440 - (bool) cy$deleteProperty:(NSString *)name;
441 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
443 + (bool) cy$hasImplicitProperties;
449 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
452 NSString *CYCastNSCYON(id value, bool objective) {
458 Class _class(object_getClass(value));
459 SEL sel(@selector(cy$toCYON:));
461 if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
462 string = reinterpret_cast<NSString *(*)(id, SEL, bool)>(method_getImplementation(toCYON))(value, sel, objective);
463 else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
464 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
465 string = [value cy$toCYON:objective];
470 else if (value == NSZombie_)
471 string = @"_NSZombie_";
472 else if (_class == NSZombie_)
473 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
474 // XXX: frowny /in/ the pants
475 else if (banned_.find(value) != banned_.end())
479 string = [NSString stringWithFormat:@"%@", value];
484 string = @"undefined";
491 struct PropertyAttributes {
496 const char *variable;
509 PropertyAttributes(objc_property_t property) :
521 name = property_getName(property);
522 const char *attributes(property_getAttributes(property));
524 for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
525 if ((next = strchr(token, ',')) != NULL)
528 case 'R': readonly = true; break;
529 case 'C': copy = true; break;
530 case '&': retain = true; break;
531 case 'N': nonatomic = true; break;
532 case 'G': getter_ = token + 1; break;
533 case 'S': setter_ = token + 1; break;
534 case 'V': variable = token + 1; break;
538 /*if (variable == NULL) {
539 variable = property_getName(property);
540 size_t size(strlen(variable));
541 char *name(new(pool_) char[size + 2]);
543 memcpy(name + 1, variable, size);
544 name[size + 1] = '\0';
549 const char *Getter() {
551 getter_ = pool_.strdup(name);
555 const char *Setter() {
556 if (setter_ == NULL && !readonly) {
557 size_t length(strlen(name));
559 char *temp(new(pool_) char[length + 5]);
565 temp[3] = toupper(name[0]);
566 memcpy(temp + 4, name + 1, length - 1);
569 temp[length + 3] = ':';
570 temp[length + 4] = '\0';
580 @interface CYWebUndefined : NSObject {
583 + (CYWebUndefined *) undefined;
587 @implementation CYWebUndefined
589 + (CYWebUndefined *) undefined {
590 static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
596 #define WebUndefined CYWebUndefined
598 /* Bridge: CYJSObject {{{ */
599 @interface CYJSObject : NSMutableDictionary {
601 JSGlobalContextRef context_;
604 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
606 - (NSUInteger) count;
607 - (id) objectForKey:(id)key;
608 - (NSEnumerator *) keyEnumerator;
609 - (void) setObject:(id)object forKey:(id)key;
610 - (void) removeObjectForKey:(id)key;
614 /* Bridge: CYJSArray {{{ */
615 @interface CYJSArray : NSMutableArray {
617 JSGlobalContextRef context_;
620 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
622 - (NSUInteger) count;
623 - (id) objectAtIndex:(NSUInteger)index;
625 - (void) addObject:(id)anObject;
626 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
627 - (void) removeLastObject;
628 - (void) removeObjectAtIndex:(NSUInteger)index;
629 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
634 _finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
635 return JSValueIsObjectOfClass(context, value, Instance_);
638 _finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
639 return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
642 struct CYBlockDescriptor {
644 BlockDescriptor1 one_;
645 BlockDescriptor2 two_;
646 BlockDescriptor3 three_;
649 Closure_privateData *internal_;
652 void CYDisposeBlock(BlockLiteral *literal) {
653 delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
656 static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
657 JSObjectRef _this(CYCastJSObject(context, values[0]));
658 return CYCallAsFunction(context, function, _this, count - 1, values + 1);
661 static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
662 CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
665 NSObject *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
666 _assert(__NSMallocBlock__ != Nil);
667 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
669 CYBlockDescriptor *descriptor(new CYBlockDescriptor);
670 memset(&descriptor->d_, 0, sizeof(descriptor->d_));
672 descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
673 literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
675 literal->isa = __NSMallocBlock__;
676 literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
677 literal->reserved = 0;
678 literal->descriptor = descriptor;
680 descriptor->d_.one_.size = sizeof(descriptor->d_);
681 descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
682 descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
684 return reinterpret_cast<NSObject *>(literal);
687 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
688 if (CYJSValueIsNSObject(context, object)) {
689 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
690 return internal->GetValue();
693 bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
694 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
695 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
698 NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
699 return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
703 @interface NSBoolNumber : NSNumber {
708 id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
712 switch (JSType type = JSValueGetType(context, value)) {
713 case kJSTypeUndefined:
714 object = [WebUndefined undefined];
724 object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
727 object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
733 object = CYCopyNSNumber(context, value);
738 object = CYCopyNSString(context, value);
743 // XXX: this might could be more efficient
744 object = CYCastNSObject(pool, context, (JSObjectRef) value);
749 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
756 return CYPoolRelease(pool, object);
758 return [object retain];
761 NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
762 return CYNSObject(pool, context, value, true);
765 NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
766 return CYNSObject(&pool, context, value, false);
769 /* Bridge: NSArray {{{ */
770 @implementation NSArray (Cycript)
773 return [[self mutableCopy] autorelease];
776 - (NSString *) cy$toCYON:(bool)objective {
777 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
778 [json appendString:@"@["];
782 for (id object in self) {
784 for (size_t index(0), count([self count]); index != count; ++index) {
785 id object([self objectAtIndex:index]);
788 [json appendString:@","];
791 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
792 [json appendString:CYCastNSCYON(object, true)];
794 [json appendString:@","];
799 [json appendString:@"]"];
803 - (bool) cy$hasProperty:(NSString *)name {
804 if ([name isEqualToString:@"length"])
807 size_t index(CYGetIndex(name));
808 if (index == _not(size_t) || index >= [self count])
809 return [super cy$hasProperty:name];
814 - (NSObject *) cy$getProperty:(NSString *)name {
815 size_t index(CYGetIndex(name));
816 if (index == _not(size_t) || index >= [self count])
817 return [super cy$getProperty:name];
819 return [self objectAtIndex:index];
822 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
824 if ([name isEqualToString:@"length"])
825 return CYCastJSValue(context, [self count]);
828 return [super cy$getProperty:name inContext:context];
831 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
832 [super cy$getPropertyNames:names inContext:context];
834 for (size_t index(0), count([self count]); index != count; ++index) {
835 id object([self objectAtIndex:index]);
836 if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
838 sprintf(name, "%zu", index);
839 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
844 + (bool) cy$hasImplicitProperties {
850 /* Bridge: NSBlock {{{ */
857 /* Bridge: NSBoolNumber {{{ */
859 @implementation NSBoolNumber (Cycript)
861 - (JSType) cy$JSType {
862 return kJSTypeBoolean;
865 - (NSString *) cy$toCYON:(bool)objective {
866 NSString *value([self boolValue] ? @"true" : @"false");
867 return objective ? value : [NSString stringWithFormat:@"@%@", value];
870 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
871 return CYCastJSValue(context, (bool) [self boolValue]);
877 /* Bridge: NSDictionary {{{ */
878 @implementation NSDictionary (Cycript)
881 return [[self mutableCopy] autorelease];
884 - (NSString *) cy$toCYON:(bool)objective {
885 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
886 [json appendString:@"@{"];
890 for (NSObject *key in self) {
892 NSEnumerator *keys([self keyEnumerator]);
893 while (NSObject *key = [keys nextObject]) {
896 [json appendString:@","];
899 [json appendString:CYCastNSCYON(key, true)];
900 [json appendString:@":"];
901 NSObject *object([self objectForKey:key]);
902 [json appendString:CYCastNSCYON(object, true)];
905 [json appendString:@"}"];
909 - (bool) cy$hasProperty:(NSString *)name {
910 return [self objectForKey:name] != nil;
913 - (NSObject *) cy$getProperty:(NSString *)name {
914 return [self objectForKey:name];
917 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
918 [super cy$getPropertyNames:names inContext:context];
921 for (NSObject *key in self) {
923 NSEnumerator *keys([self keyEnumerator]);
924 while (NSObject *key = [keys nextObject]) {
926 JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
930 + (bool) cy$hasImplicitProperties {
936 /* Bridge: NSMutableArray {{{ */
937 @implementation NSMutableArray (Cycript)
939 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
940 if ([name isEqualToString:@"length"]) {
941 // XXX: is this not intelligent?
942 NSNumber *number(reinterpret_cast<NSNumber *>(value));
944 NSUInteger size([number unsignedIntegerValue]);
946 NSUInteger size([number unsignedIntValue]);
948 NSUInteger count([self count]);
950 [self removeObjectsInRange:NSMakeRange(size, count - size)];
951 else if (size != count) {
952 WebUndefined *undefined([WebUndefined undefined]);
953 for (size_t i(count); i != size; ++i)
954 [self addObject:undefined];
959 size_t index(CYGetIndex(name));
960 if (index == _not(size_t))
961 return [super cy$setProperty:name to:value];
963 id object(value ?: [NSNull null]);
965 size_t count([self count]);
967 [self replaceObjectAtIndex:index withObject:object];
969 if (index != count) {
970 WebUndefined *undefined([WebUndefined undefined]);
971 for (size_t i(count); i != index; ++i)
972 [self addObject:undefined];
975 [self addObject:object];
981 - (bool) cy$deleteProperty:(NSString *)name {
982 size_t index(CYGetIndex(name));
983 if (index == _not(size_t) || index >= [self count])
984 return [super cy$deleteProperty:name];
985 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
991 /* Bridge: NSMutableDictionary {{{ */
992 @implementation NSMutableDictionary (Cycript)
994 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
995 [self setObject:(value ?: [NSNull null]) forKey:name];
999 - (bool) cy$deleteProperty:(NSString *)name {
1000 if ([self objectForKey:name] == nil)
1003 [self removeObjectForKey:name];
1010 /* Bridge: NSNumber {{{ */
1011 @implementation NSNumber (Cycript)
1013 - (JSType) cy$JSType {
1015 // XXX: this just seems stupid
1016 if ([self class] == NSCFBoolean_)
1017 return kJSTypeBoolean;
1019 return kJSTypeNumber;
1022 - (NSString *) cy$toCYON:(bool)objective {
1023 NSString *value([self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false");
1024 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1027 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1028 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, static_cast<bool>([self boolValue]));
1029 } CYObjectiveCatch }
1033 /* Bridge: NSNull {{{ */
1034 @implementation NSNull (Cycript)
1036 - (JSType) cy$JSType {
1040 - (NSString *) cy$toCYON:(bool)objective {
1041 NSString *value(@"null");
1042 return objective ? value : [NSString stringWithFormat:@"@%@", value];
1045 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1046 return CYJSNull(context);
1047 } CYObjectiveCatch }
1051 /* Bridge: NSObject {{{ */
1052 @implementation NSObject (Cycript)
1058 - (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context {
1059 return [self cy$valueOfInContext:context];
1062 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1064 } CYObjectiveCatch }
1066 - (JSType) cy$JSType {
1067 return kJSTypeObject;
1070 - (NSString *) cy$toCYON:(bool)objective {
1071 return [[self description] cy$toCYON:objective];
1074 - (bool) cy$hasProperty:(NSString *)name {
1078 - (NSObject *) cy$getProperty:(NSString *)name {
1082 - (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context { CYObjectiveTry_ {
1083 if (NSObject *value = [self cy$getProperty:name])
1084 return CYCastJSValue(context, value);
1086 } CYObjectiveCatch }
1088 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1092 - (bool) cy$deleteProperty:(NSString *)name {
1096 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1099 + (bool) cy$hasImplicitProperties {
1105 /* Bridge: NSProxy {{{ */
1106 @implementation NSProxy (Cycript)
1108 - (NSString *) cy$toCYON:(bool)objective {
1109 return [[self description] cy$toCYON:objective];
1114 /* Bridge: NSString {{{ */
1115 @implementation NSString (Cycript)
1118 return [[self copy] autorelease];
1121 - (JSType) cy$JSType {
1122 return kJSTypeString;
1125 - (NSString *) cy$toCYON:(bool)objective {
1126 std::ostringstream str;
1129 CYUTF8String string(CYCastUTF8String(self));
1130 CYStringify(str, string.data, string.size);
1131 std::string value(str.str());
1132 return CYCastNSString(NULL, CYUTF8String(value.c_str(), value.size()));
1135 - (bool) cy$hasProperty:(NSString *)name {
1136 size_t index(CYGetIndex(name));
1137 if (index == _not(size_t) || index >= [self length])
1138 return [super cy$hasProperty:name];
1143 - (NSObject *) cy$getProperty:(NSString *)name {
1144 size_t index(CYGetIndex(name));
1145 if (index == _not(size_t) || index >= [self length])
1146 return [super cy$getProperty:name];
1148 return [self substringWithRange:NSMakeRange(index, 1)];
1151 - (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
1152 [super cy$getPropertyNames:names inContext:context];
1154 for (size_t index(0), length([self length]); index != length; ++index) {
1156 sprintf(name, "%zu", index);
1157 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1161 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1162 return CYCastJSValue(context, CYJSString(context, self));
1163 } CYObjectiveCatch }
1167 /* Bridge: WebUndefined {{{ */
1168 @implementation WebUndefined (Cycript)
1170 - (JSType) cy$JSType {
1171 return kJSTypeUndefined;
1174 - (NSString *) cy$toCYON:(bool)objective {
1175 NSString *value(@"undefined");
1176 return value; // XXX: maybe use the below code, adding @undefined?
1177 //return objective ? value : [NSString stringWithFormat:@"@%@", value];
1180 - (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
1181 return CYJSUndefined(context);
1182 } CYObjectiveCatch }
1187 static bool CYIsClass(id self) {
1189 return class_isMetaClass(object_getClass(self));
1191 return GSObjCIsClass(self);
1195 Class CYCastClass(CYPool &pool, JSContextRef context, JSValueRef value) {
1196 id self(CYCastNSObject(&pool, context, value));
1197 if (CYIsClass(self))
1198 return (Class) self;
1199 throw CYJSError(context, "got something that is not a Class");
1203 NSArray *CYCastNSArray(JSContextRef context, JSPropertyNameArrayRef names) {
1205 size_t size(JSPropertyNameArrayGetCount(names));
1206 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1207 for (size_t index(0); index != size; ++index)
1208 [array addObject:CYCastNSString(&pool, context, JSPropertyNameArrayGetNameAtIndex(names, index))];
1212 JSValueRef CYCastJSValue(JSContextRef context, NSObject *value) { CYPoolTry {
1214 return CYJSNull(context);
1216 return CYMakeInstance(context, value, false);
1217 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1219 @implementation CYJSObject
1221 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1222 if ((self = [super init]) != nil) {
1224 context_ = CYGetJSContext(context);
1225 JSGlobalContextRetain(context_);
1226 JSValueProtect(context_, object_);
1228 } CYObjectiveCatch }
1230 - (void) dealloc { CYObjectiveTry {
1231 JSValueUnprotect(context_, object_);
1232 JSGlobalContextRelease(context_);
1234 } CYObjectiveCatch }
1236 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1238 const char *cyon(CYPoolCCYON(pool, context, object_));
1240 return [super cy$toCYON:objective];
1242 return [NSString stringWithUTF8String:cyon];
1243 } CYObjectiveCatch }
1245 - (NSUInteger) count { CYObjectiveTry {
1246 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1247 size_t size(JSPropertyNameArrayGetCount(names));
1248 JSPropertyNameArrayRelease(names);
1250 } CYObjectiveCatch }
1252 - (id) objectForKey:(id)key { CYObjectiveTry {
1253 JSValueRef value(CYGetProperty(context, object_, CYJSString(context, (NSObject *) key)));
1254 if (JSValueIsUndefined(context, value))
1256 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1257 } CYObjectiveCatch }
1259 - (NSEnumerator *) keyEnumerator { CYObjectiveTry {
1260 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object_));
1261 NSEnumerator *enumerator([CYCastNSArray(context, names) objectEnumerator]);
1262 JSPropertyNameArrayRelease(names);
1264 } CYObjectiveCatch }
1266 - (void) setObject:(id)object forKey:(id)key { CYObjectiveTry {
1267 CYSetProperty(context, object_, CYJSString(context, (NSObject *) key), CYCastJSValue(context, (NSString *) object));
1268 } CYObjectiveCatch }
1270 - (void) removeObjectForKey:(id)key { CYObjectiveTry {
1271 (void) _jsccall(JSObjectDeleteProperty, context, object_, CYJSString(context, (NSObject *) key));
1272 } CYObjectiveCatch }
1276 @implementation CYJSArray
1278 - (NSString *) cy$toCYON:(bool)objective { CYObjectiveTry {
1280 return [NSString stringWithUTF8String:CYPoolCCYON(pool, context, object_)];
1281 } CYObjectiveCatch }
1283 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context { CYObjectiveTry_ {
1284 if ((self = [super init]) != nil) {
1286 context_ = CYGetJSContext(context);
1287 JSGlobalContextRetain(context_);
1288 JSValueProtect(context_, object_);
1290 } CYObjectiveCatch }
1292 - (void) dealloc { CYObjectiveTry {
1293 JSValueUnprotect(context_, object_);
1294 JSGlobalContextRelease(context_);
1296 } CYObjectiveCatch }
1298 - (NSUInteger) count { CYObjectiveTry {
1299 return CYArrayLength(context, object_);
1300 } CYObjectiveCatch }
1302 - (id) objectAtIndex:(NSUInteger)index { CYObjectiveTry {
1303 size_t bounds([self count]);
1304 if (index >= bounds)
1305 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1306 JSValueRef value(_jsccall(JSObjectGetPropertyAtIndex, context, object_, index));
1307 return CYCastNSObject(NULL, context, value) ?: [NSNull null];
1308 } CYObjectiveCatch }
1310 - (void) addObject:(id)object { CYObjectiveTry {
1311 CYArrayPush(context, object_, CYCastJSValue(context, (NSObject *) object));
1312 } CYObjectiveCatch }
1314 - (void) insertObject:(id)object atIndex:(NSUInteger)index { CYObjectiveTry {
1315 size_t bounds([self count] + 1);
1316 if (index >= bounds)
1317 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1318 JSValueRef arguments[3];
1319 arguments[0] = CYCastJSValue(context, index);
1320 arguments[1] = CYCastJSValue(context, 0);
1321 arguments[2] = CYCastJSValue(context, (NSObject *) object);
1322 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1323 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 3, arguments);
1324 } CYObjectiveCatch }
1326 - (void) removeLastObject { CYObjectiveTry {
1327 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1328 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, pop_s)), object_, 0, NULL);
1329 } CYObjectiveCatch }
1331 - (void) removeObjectAtIndex:(NSUInteger)index { CYObjectiveTry {
1332 size_t bounds([self count]);
1333 if (index >= bounds)
1334 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1335 JSValueRef arguments[2];
1336 arguments[0] = CYCastJSValue(context, index);
1337 arguments[1] = CYCastJSValue(context, 1);
1338 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1339 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, splice_s)), object_, 2, arguments);
1340 } CYObjectiveCatch }
1342 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { CYObjectiveTry {
1343 size_t bounds([self count]);
1344 if (index >= bounds)
1345 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", static_cast<size_t>(index), bounds] userInfo:nil];
1346 CYSetProperty(context, object_, index, CYCastJSValue(context, (NSObject *) object));
1347 } CYObjectiveCatch }
1351 // XXX: inherit from or replace with CYJSObject
1352 @interface CYInternal : NSObject {
1353 JSGlobalContextRef context_;
1354 JSObjectRef object_;
1359 @implementation CYInternal
1361 - (void) dealloc { CYObjectiveTry {
1362 JSValueUnprotect(context_, object_);
1363 JSGlobalContextRelease(context_);
1365 } CYObjectiveCatch }
1367 - (id) initInContext:(JSContextRef)context { CYObjectiveTry_ {
1368 if ((self = [super init]) != nil) {
1369 context_ = CYGetJSContext(context);
1370 JSGlobalContextRetain(context_);
1372 } CYObjectiveCatch }
1374 - (bool) hasProperty:(JSStringRef)name inContext:(JSContextRef)context {
1375 if (object_ == NULL)
1378 return JSObjectHasProperty(context, object_, name);
1381 - (JSValueRef) getProperty:(JSStringRef)name inContext:(JSContextRef)context {
1382 if (object_ == NULL)
1385 return CYGetProperty(context, object_, name);
1388 - (void) setProperty:(JSStringRef)name toValue:(JSValueRef)value inContext:(JSContextRef)context {
1389 @synchronized (self) {
1390 if (object_ == NULL) {
1391 object_ = JSObjectMake(context, NULL, NULL);
1392 JSValueProtect(context, object_);
1396 CYSetProperty(context, object_, name, value);
1399 + (CYInternal *) get:(id)object {
1400 if ($objc_getAssociatedObject == NULL)
1403 @synchronized (object) {
1404 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1411 + (CYInternal *) set:(id)object inContext:(JSContextRef)context {
1412 if ($objc_getAssociatedObject == NULL)
1415 @synchronized (object) {
1416 if (CYInternal *internal = $objc_getAssociatedObject(object, @selector(cy$internal)))
1419 if ($objc_setAssociatedObject == NULL)
1422 CYInternal *internal([[[CYInternal alloc] initInContext:context] autorelease]);
1423 objc_setAssociatedObject(object, @selector(cy$internal), internal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
1432 static JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1433 Selector_privateData *internal(new Selector_privateData(sel));
1434 return JSObjectMake(context, Selector_, internal);
1437 static SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1438 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1439 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1440 return reinterpret_cast<SEL>(internal->value_);
1442 return CYCastPointer<SEL>(context, value);
1445 void *CYObjectiveC_ExecuteStart(JSContextRef context) { CYSadTry {
1446 return (void *) [[NSAutoreleasePool alloc] init];
1447 } CYSadCatch(NULL) }
1449 void CYObjectiveC_ExecuteEnd(JSContextRef context, void *handle) { CYSadTry {
1450 return [(NSAutoreleasePool *) handle release];
1453 JSValueRef CYObjectiveC_RuntimeProperty(JSContextRef context, CYUTF8String name) { CYPoolTry {
1455 return Instance::Make(context, nil);
1456 if (Class _class = objc_getClass(name.data))
1457 return CYMakeInstance(context, _class, true);
1458 if (Protocol *protocol = objc_getProtocol(name.data))
1459 return CYMakeInstance(context, protocol, true);
1461 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1463 static void CYObjectiveC_CallFunction(JSContextRef context, ffi_cif *cif, void (*function)(), uint8_t *value, void **values) { CYSadTry {
1464 ffi_call(cif, function, value, values);
1467 static bool CYObjectiveC_PoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) { CYSadTry {
1468 // XXX: assigning to an indirect id * works for return values, but not for properties and fields
1470 switch (type->primitive) {
1471 case sig::block_P: {
1472 _assert(type->data.signature.count != 0);
1473 sig::Signature signature;
1474 sig::Copy(*pool, signature, type->data.signature);
1476 sig::Element *elements(new(*pool) sig::Element[++signature.count]);
1477 elements[0] = signature.elements[0];
1478 memcpy(elements + 2, signature.elements + 1, sizeof(sig::Element) * (signature.count - 2));
1479 signature.elements = elements;
1481 elements[1].name = NULL;
1482 elements[1].type = new(*pool) sig::Type();
1483 elements[1].offset = _not(size_t);
1485 memset(elements[1].type, 0, sizeof(sig::Type));
1486 elements[1].type->primitive = sig::object_P;
1488 JSObjectRef function(CYCastJSObject(context, value));
1489 *reinterpret_cast<id *>(data) = CYMakeBlock(context, function, signature);
1493 case sig::typename_P:
1494 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1497 case sig::selector_P:
1498 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1506 } CYSadCatch(false) }
1508 static JSValueRef CYObjectiveC_FromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) { CYPoolTry {
1509 switch (type->primitive) {
1510 // XXX: do something epic about blocks
1513 if (NSObject *object = *reinterpret_cast<NSObject **>(data)) {
1514 JSValueRef value(CYCastJSValue(context, object));
1520 case sig::typename_P:
1521 return CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1523 case sig::selector_P:
1524 if (SEL sel = *reinterpret_cast<SEL *>(data))
1525 return CYMakeSelector(context, sel);
1529 return CYJSNull(context);
1533 } CYPoolCatch(NULL) return /*XXX*/ NULL; }
1535 static bool CYImplements(id object, Class _class, SEL selector, bool devoid = false) {
1536 if (objc_method *method = class_getInstanceMethod(_class, selector)) {
1539 #if OBJC_API_VERSION >= 2
1541 method_getReturnType(method, type, sizeof(type));
1543 const char *type(method_getTypeEncoding(method));
1549 // XXX: possibly use a more "awesome" check?
1553 static const char *CYPoolTypeEncoding(CYPool &pool, JSContextRef context, SEL sel, objc_method *method) {
1555 return method_getTypeEncoding(method);
1557 const char *name(sel_getName(sel));
1558 size_t length(strlen(name));
1560 char keyed[length + 2];
1562 keyed[length + 1] = '\0';
1563 memcpy(keyed + 1, name, length);
1565 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1566 return entry->value_;
1571 static JSValueRef MessageAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
1572 JSObjectRef _this(CYCastJSObject(context, values[0]));
1573 return CYCallAsFunction(context, function, _this, count - 2, values + 2);
1576 static void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1577 CYExecuteClosure(cif, result, arguments, arg, &MessageAdapter_);
1580 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1581 Message_privateData *internal(new Message_privateData(sel, type, imp));
1582 return JSObjectMake(context, Message_, internal);
1585 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *encoding) {
1586 JSObjectRef function(CYCastJSObject(context, value));
1588 sig::Signature signature;
1589 sig::Parse(pool, &signature, encoding, &Structor_);
1590 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &MessageClosure_));
1591 // XXX: see notes in Library.cpp about needing to leak
1592 return reinterpret_cast<IMP>(internal->GetValue());
1595 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1596 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1597 Class _class(internal->GetValue());
1600 const char *name(CYPoolCString(pool, context, property));
1602 if (SEL sel = sel_getUid(name))
1603 if (class_getInstanceMethod(_class, sel) != NULL)
1609 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1610 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1611 Class _class(internal->GetValue());
1614 const char *name(CYPoolCString(pool, context, property));
1616 if (SEL sel = sel_getUid(name))
1617 if (objc_method *method = class_getInstanceMethod(_class, sel))
1618 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1623 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1624 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1625 Class _class(internal->GetValue());
1628 const char *name(CYPoolCString(pool, context, property));
1630 SEL sel(sel_registerName(name));
1632 objc_method *method(class_getInstanceMethod(_class, sel));
1637 if (JSValueIsObjectOfClass(context, value, Message_)) {
1638 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1639 type = sig::Unparse(pool, &message->signature_);
1640 imp = reinterpret_cast<IMP>(message->GetValue());
1642 type = CYPoolTypeEncoding(pool, context, sel, method);
1643 imp = CYMakeMessage(context, value, type);
1647 method_setImplementation(method, imp);
1650 GSMethodList list(GSAllocMethodList(1));
1651 GSAppendMethodToList(list, sel, type, imp, YES);
1652 GSAddMethodList(_class, list, YES);
1653 GSFlushMethodCacheForClass(_class);
1655 class_addMethod(_class, sel, imp, type);
1662 #if 0 && OBJC_API_VERSION < 2
1663 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1664 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1665 Class _class(internal->GetValue());
1668 const char *name(CYPoolCString(pool, context, property));
1670 if (SEL sel = sel_getUid(name))
1671 if (objc_method *method = class_getInstanceMethod(_class, sel)) {
1672 objc_method_list list = {NULL, 1, {method}};
1673 class_removeMethods(_class, &list);
1681 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1682 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
1683 Class _class(internal->GetValue());
1685 #if OBJC_API_VERSION >= 2
1687 objc_method **data(class_copyMethodList(_class, &size));
1688 for (size_t i(0); i != size; ++i)
1689 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1692 for (objc_method_list *methods(_class->methods); methods != NULL; methods = methods->method_next)
1693 for (int i(0); i != methods->method_count; ++i)
1694 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(&methods->method_list[i]))));
1698 static bool CYHasImplicitProperties(Class _class) {
1699 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1700 if (!CYImplements(_class, object_getClass(_class), @selector(cy$hasImplicitProperties)))
1702 return [_class cy$hasImplicitProperties];
1705 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1706 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1707 id self(internal->GetValue());
1709 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1713 NSString *name(CYCastNSString(&pool, context, property));
1715 if (CYInternal *internal = [CYInternal get:self])
1716 if ([internal hasProperty:property inContext:context])
1719 Class _class(object_getClass(self));
1722 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1723 if (CYImplements(self, _class, @selector(cy$hasProperty:)))
1724 if ([self cy$hasProperty:name])
1726 } CYPoolCatch(false)
1728 const char *string(CYPoolCString(pool, context, name));
1731 if (class_getProperty(_class, string) != NULL)
1735 if (CYHasImplicitProperties(_class))
1736 if (SEL sel = sel_getUid(string))
1737 if (CYImplements(self, _class, sel, true))
1743 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1744 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1745 id self(internal->GetValue());
1747 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1748 return Internal::Make(context, self, object);
1751 NSString *name(CYCastNSString(&pool, context, property));
1753 if (CYInternal *internal = [CYInternal get:self])
1754 if (JSValueRef value = [internal getProperty:property inContext:context])
1758 if (JSValueRef value = [self cy$getProperty:name inContext:context])
1762 const char *string(CYPoolCString(pool, context, name));
1763 Class _class(object_getClass(self));
1766 if (objc_property_t property = class_getProperty(_class, string)) {
1767 PropertyAttributes attributes(property);
1768 SEL sel(sel_registerName(attributes.Getter()));
1769 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1773 if (CYHasImplicitProperties(_class))
1774 if (SEL sel = sel_getUid(string))
1775 if (CYImplements(self, _class, sel, true))
1776 return CYSendMessage(pool, context, self, NULL, sel, 0, NULL, false);
1781 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1782 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1783 id self(internal->GetValue());
1787 NSString *name(CYCastNSString(&pool, context, property));
1788 NSObject *data(CYCastNSObject(&pool, context, value));
1791 if ([self cy$setProperty:name to:data])
1793 } CYPoolCatch(false)
1795 const char *string(CYPoolCString(pool, context, name));
1796 Class _class(object_getClass(self));
1799 if (objc_property_t property = class_getProperty(_class, string)) {
1800 PropertyAttributes attributes(property);
1801 if (const char *setter = attributes.Setter()) {
1802 SEL sel(sel_registerName(setter));
1803 JSValueRef arguments[1] = {value};
1804 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1810 size_t length(strlen(string));
1812 char set[length + 5];
1818 if (string[0] != '\0') {
1819 set[3] = toupper(string[0]);
1820 memcpy(set + 4, string + 1, length - 1);
1823 set[length + 3] = ':';
1824 set[length + 4] = '\0';
1826 if (SEL sel = sel_getUid(set))
1827 if (CYImplements(self, _class, sel)) {
1828 JSValueRef arguments[1] = {value};
1829 CYSendMessage(pool, context, self, NULL, sel, 1, arguments, false);
1833 if (CYInternal *internal = [CYInternal set:self inContext:context]) {
1834 [internal setProperty:property toValue:value inContext:context];
1841 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1842 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1843 id self(internal->GetValue());
1846 NSString *name(CYCastNSString(NULL, context, property));
1847 return [self cy$deleteProperty:name];
1848 } CYPoolCatch(false)
1849 } CYCatch(false) return /*XXX*/ false; }
1851 static void Instance_getPropertyNames_message(JSPropertyNameAccumulatorRef names, objc_method *method) {
1852 const char *name(sel_getName(method_getName(method)));
1853 if (strchr(name, ':') != NULL)
1856 const char *type(method_getTypeEncoding(method));
1857 if (type == NULL || *type == '\0' || *type == 'v')
1860 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1863 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1864 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1865 id self(internal->GetValue());
1868 Class _class(object_getClass(self));
1873 objc_property_t *data(class_copyPropertyList(_class, &size));
1874 for (size_t i(0); i != size; ++i)
1875 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1880 if (CYHasImplicitProperties(_class))
1881 for (Class current(_class); current != nil; current = class_getSuperclass(current)) {
1882 #if OBJC_API_VERSION >= 2
1884 objc_method **data(class_copyMethodList(current, &size));
1885 for (size_t i(0); i != size; ++i)
1886 Instance_getPropertyNames_message(names, data[i]);
1889 for (objc_method_list *methods(current->methods); methods != NULL; methods = methods->method_next)
1890 for (int i(0); i != methods->method_count; ++i)
1891 Instance_getPropertyNames_message(names, &methods->method_list[i]);
1896 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
1897 if (CYImplements(self, _class, @selector(cy$getPropertyNames:inContext:)))
1898 [self cy$getPropertyNames:names inContext:context];
1902 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1903 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1904 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
1908 static JSValueRef Instance_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1909 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1910 id self(internal->GetValue());
1912 if (![self isKindOfClass:NSBlock_])
1913 CYThrow("non-NSBlock object is not a function");
1914 // XXX: replace above logic with the following assertion
1915 //_assert([self isKindOfClass:NSBlock_]);
1916 // to do this, make it so FunctionInstance_ is the class of blocks
1917 // to do /that/, generalize the various "is exactly Instance_" checks
1918 // then, move Instance_callAsFunction to only be on FunctionInstance
1920 BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(self));
1922 if ((literal->flags & BLOCK_HAS_SIGNATURE) != 0) {
1923 uint8_t *descriptor(reinterpret_cast<uint8_t *>(literal->descriptor));
1924 descriptor += sizeof(BlockDescriptor1);
1925 if ((literal->flags & BLOCK_HAS_COPY_DISPOSE) != 0)
1926 descriptor += sizeof(BlockDescriptor2);
1927 BlockDescriptor3 *descriptor3(reinterpret_cast<BlockDescriptor3 *>(descriptor));
1929 if (const char *type = descriptor3->signature) {
1935 sig::Signature signature;
1936 sig::Parse(pool, &signature, type, &Structor_);
1939 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1941 void (*function)() = reinterpret_cast<void (*)()>(literal->invoke);
1942 return CYCallFunction(pool, context, 1, setup, count, arguments, false, &signature, &cif, function);
1947 CYThrow("NSBlock without signature field passed arguments");
1951 } CYPoolCatch(NULL);
1956 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) { CYTry {
1957 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
1958 Class _class(internal->GetValue());
1959 if (!CYIsClass(_class))
1962 if (CYJSValueIsNSObject(context, instance)) {
1963 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
1964 // XXX: this isn't always safe
1965 return [linternal->GetValue() isKindOfClass:_class];
1971 static JSValueRef Instance_box_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1973 throw CYJSError(context, "incorrect number of arguments to Instance");
1975 id value(CYCastNSObject(&pool, context, arguments[0]));
1977 value = [NSNull null];
1978 return CYCastJSValue(context, [value cy$box]);
1981 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1982 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
1985 id self(internal->GetValue());
1986 const char *name(CYPoolCString(pool, context, property));
1988 if (object_getInstanceVariable(self, name, NULL) != NULL)
1994 static void CYBitField(unsigned &length, unsigned &shift, id self, Ivar ivar, const char *encoding, unsigned offset) {
1995 length = CYCastDouble(encoding + 1);
1999 objc_ivar **ivars(class_copyIvarList(object_getClass(self), &size));
2000 for (size_t i(0); i != size; ++i)
2001 if (ivars[i] == ivar)
2003 else if (ivar_getOffset(ivars[i]) == offset) {
2004 const char *encoding(ivar_getTypeEncoding(ivars[i]));
2005 _assert(encoding[0] == 'b');
2006 shift += CYCastDouble(encoding + 1);
2011 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2012 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2015 id self(internal->GetValue());
2016 const char *name(CYPoolCString(pool, context, property));
2019 if (strcmp(name, "isa") == 0)
2020 return CYCastJSValue(context, object_getClass(self));
2023 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2024 ptrdiff_t offset(ivar_getOffset(ivar));
2025 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2027 const char *encoding(ivar_getTypeEncoding(ivar));
2028 if (encoding[0] == 'b') {
2029 unsigned length, shift;
2030 CYBitField(length, shift, self, ivar, encoding, offset);
2031 _assert(shift + length <= sizeof(uintptr_t) * 8);
2032 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2033 uintptr_t mask((1 << length) - 1);
2034 return CYCastJSValue(context, (field >> shift) & mask);
2036 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2037 return CYFromFFI(context, type.type_, type.GetFFI(), data);
2044 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
2045 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2048 id self(internal->GetValue());
2049 const char *name(CYPoolCString(pool, context, property));
2051 if (objc_ivar *ivar = object_getInstanceVariable(self, name, NULL)) {
2052 ptrdiff_t offset(ivar_getOffset(ivar));
2053 void *data(reinterpret_cast<uint8_t *>(self) + offset);
2055 const char *encoding(ivar_getTypeEncoding(ivar));
2056 if (encoding[0] == 'b') {
2057 unsigned length, shift;
2058 CYBitField(length, shift, self, ivar, encoding, offset);
2059 _assert(shift + length <= sizeof(uintptr_t) * 8);
2060 uintptr_t &field(*reinterpret_cast<uintptr_t *>(data));
2061 uintptr_t mask((1 << length) - 1);
2062 field = field & ~(mask << shift) | (uintptr_t(CYCastDouble(context, value)) & mask) << shift;
2064 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2065 CYPoolFFI(&pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2073 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2074 if (Class super = class_getSuperclass(_class))
2075 Internal_getPropertyNames_(super, names);
2077 #if OBJC_API_VERSION >= 2
2079 objc_ivar **data(class_copyIvarList(_class, &size));
2080 for (size_t i(0); i != size; ++i)
2081 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2084 if (objc_ivar_list *ivars = _class->ivars)
2085 for (int i(0); i != ivars->ivar_count; ++i)
2086 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(&ivars->ivar_list[i])));
2090 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2091 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2094 id self(internal->GetValue());
2095 Class _class(object_getClass(self));
2097 Internal_getPropertyNames_(_class, names);
2100 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2101 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2102 return internal->GetOwner();
2105 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2107 NSString *name(CYCastNSString(&pool, context, property));
2108 if (Class _class = NSClassFromString(name))
2109 return CYMakeInstance(context, _class, true);
2114 static Class *CYCopyClassList(size_t &size) {
2115 size = objc_getClassList(NULL, 0);
2116 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2119 size_t writ(objc_getClassList(data, size));
2125 Class *copy(reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ)));
2137 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2140 if (Class *data = CYCopyClassList(size)) {
2141 for (size_t i(0); i != size; ++i)
2142 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2147 while (Class _class = objc_next_class(&state))
2148 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(_class)));
2152 #if OBJC_API_VERSION >= 2
2153 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2154 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2157 const char *name(CYPoolCString(pool, context, property));
2159 const char **data(objc_copyClassNamesForImage(internal, &size));
2161 for (size_t i(0); i != size; ++i)
2162 if (strcmp(name, data[i]) == 0) {
2163 if (Class _class = objc_getClass(name)) {
2164 value = CYMakeInstance(context, _class, true);
2175 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2176 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2178 const char **data(objc_copyClassNamesForImage(internal, &size));
2179 for (size_t i(0); i != size; ++i)
2180 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2184 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2186 const char *name(CYPoolCString(pool, context, property));
2188 const char **data(objc_copyImageNames(&size));
2189 for (size_t i(0); i != size; ++i)
2190 if (strcmp(name, data[i]) == 0) {
2199 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2200 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2204 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2206 const char **data(objc_copyImageNames(&size));
2207 for (size_t i(0); i != size; ++i)
2208 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2213 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2215 const char *name(CYPoolCString(pool, context, property));
2216 if (Protocol *protocol = objc_getProtocol(name))
2217 return CYMakeInstance(context, protocol, true);
2221 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2222 #if OBJC_API_VERSION >= 2
2224 Protocol **data(objc_copyProtocolList(&size));
2225 for (size_t i(0); i != size; ++i)
2226 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2233 static JSValueRef ObjectiveC_Constants_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2235 CYUTF8String name(CYPoolUTF8String(pool, context, property));
2237 return Instance::Make(context, nil);
2241 static void ObjectiveC_Constants_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2242 JSPropertyNameAccumulatorAddName(names, CYJSString("nil"));
2246 static kern_return_t CYReadMemory(task_t task, vm_address_t address, vm_size_t size, void **data) {
2247 *data = reinterpret_cast<void *>(address);
2248 return KERN_SUCCESS;
2252 std::set<Class> query_;
2253 JSContextRef context_;
2254 JSObjectRef results_;
2257 struct CYObjectStruct {
2261 static void choose_(task_t task, void *baton, unsigned type, vm_range_t *ranges, unsigned count) {
2262 CYChoice *choice(reinterpret_cast<CYChoice *>(baton));
2263 JSContextRef context(choice->context_);
2265 for (unsigned i(0); i != count; ++i) {
2266 vm_range_t &range(ranges[i]);
2267 void *data(reinterpret_cast<void *>(range.address));
2268 size_t size(range.size);
2270 if (size < sizeof(CYObjectStruct))
2273 uintptr_t *pointers(reinterpret_cast<uintptr_t *>(data));
2275 Class isa(reinterpret_cast<Class>(pointers[0] & 0x1fffffff8));
2277 Class isa(reinterpret_cast<Class>(pointers[0]));
2280 std::set<Class>::const_iterator result(choice->query_.find(isa));
2281 if (result == choice->query_.end())
2284 // XXX: if (size < class_getInstanceSize(*result))
2285 if ((class_getInstanceSize(*result) + 15) / 16 * 16 != size)
2287 CYArrayPush(context, choice->results_, CYCastJSValue(context, reinterpret_cast<id>(data)));
2291 static JSValueRef choose(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2293 throw CYJSError(context, "choose() takes a class argument");
2296 Class _class(CYCastNSObject(&pool, context, arguments[0]));
2298 vm_address_t *zones(NULL);
2300 kern_return_t error(malloc_get_all_zones(0, &CYReadMemory, &zones, &size));
2301 _assert(error == KERN_SUCCESS);
2303 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
2304 JSObjectRef results(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2307 choice.context_ = context;
2308 choice.results_ = results;
2311 Class *classes(CYCopyClassList(number));
2312 _assert(classes != NULL);
2314 for (size_t i(0); i != number; ++i)
2315 for (Class current(classes[i]); current != Nil; current = class_getSuperclass(current))
2316 if (current == _class) {
2317 choice.query_.insert(classes[i]);
2323 for (unsigned i(0); i != size; ++i) {
2324 const malloc_zone_t *zone(reinterpret_cast<const malloc_zone_t *>(zones[i]));
2325 if (zone == NULL || zone->introspect == NULL)
2328 zone->introspect->enumerator(mach_task_self(), &choice, MALLOC_PTR_IN_USE_RANGE_TYPE, zones[i], &CYReadMemory, &choose_);
2336 #if defined(__i386__) || defined(__x86_64__)
2337 #define OBJC_MAX_STRUCT_BY_VALUE 8
2338 static int struct_forward_array[] = {
2339 0, 0, 0, 1, 0, 1, 1, 1, 0 };
2340 #elif defined(__arm__)
2341 #define OBJC_MAX_STRUCT_BY_VALUE 1
2342 static int struct_forward_array[] = {
2344 #elif defined(__arm64__)
2347 #error missing objc-runtime-info
2351 static bool stret(ffi_type *ffi_type) {
2352 return ffi_type->type == FFI_TYPE_STRUCT && (
2353 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2354 struct_forward_array[ffi_type->size] != 0
2360 JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class _class, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize) {
2364 _class = object_getClass(self);
2368 if (objc_method *method = class_getInstanceMethod(_class, _cmd)) {
2369 imp = method_getImplementation(method);
2370 type = method_getTypeEncoding(method);
2375 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2377 throw CYJSError(context, "unrecognized selector %s sent to object %p", sel_getName(_cmd), self);
2378 type = CYPoolCString(pool, context, [method _typeString]);
2386 sig::Signature signature;
2387 sig::Parse(pool, &signature, type, &Structor_);
2389 size_t used(count + 3);
2390 if (used > signature.count) {
2391 sig::Element *elements(new (pool) sig::Element[used]);
2392 memcpy(elements, signature.elements, used * sizeof(sig::Element));
2394 for (size_t index(signature.count); index != used; ++index) {
2395 sig::Element *element(&elements[index]);
2396 element->name = NULL;
2397 element->offset = _not(size_t);
2399 sig::Type *type(new (pool) sig::Type);
2400 memset(type, 0, sizeof(*type));
2401 type->primitive = sig::object_P;
2402 element->type = type;
2405 signature.elements = elements;
2406 signature.count = used;
2410 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2415 if (stret(cif.rtype))
2416 imp = class_getMethodImplementation_stret(_class, _cmd);
2419 imp = class_getMethodImplementation(_class, _cmd);
2421 objc_super super = {self, _class};
2422 imp = objc_msg_lookup_super(&super, _cmd);
2426 void (*function)() = reinterpret_cast<void (*)()>(imp);
2427 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, &signature, &cif, function);
2430 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
2432 throw CYJSError(context, "too few arguments to objc_msgSend");
2442 if (JSValueIsObjectOfClass(context, arguments[0], Super_)) {
2443 cy::Super *internal(reinterpret_cast<cy::Super *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2444 self = internal->GetValue();
2445 _class = internal->class_;;
2446 uninitialized = false;
2447 } else if (CYJSValueIsNSObject(context, arguments[0])) {
2448 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2449 self = internal->GetValue();
2451 uninitialized = internal->IsUninitialized();
2453 internal->value_ = nil;
2455 self = CYCastNSObject(&pool, context, arguments[0]);
2457 uninitialized = false;
2461 return CYJSNull(context);
2463 _cmd = CYCastSEL(context, arguments[1]);
2465 return CYSendMessage(pool, context, self, _class, _cmd, count - 2, arguments + 2, uninitialized);
2468 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2469 return $objc_msgSend(context, object, _this, count, arguments);
2472 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2473 JSValueRef setup[count + 2];
2476 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2477 return $objc_msgSend(context, NULL, NULL, count + 2, setup);
2480 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2482 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2484 // XXX: handle Instance::Uninitialized?
2485 id self(CYCastNSObject(&pool, context, _this));
2489 setup[1] = &internal->sel_;
2491 return CYCallFunction(pool, context, 2, setup, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
2494 static JSObjectRef Super_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2496 throw CYJSError(context, "incorrect number of arguments to Super constructor");
2498 id self(CYCastNSObject(&pool, context, arguments[0]));
2499 Class _class(CYCastClass(pool, context, arguments[1]));
2500 return cy::Super::Make(context, self, _class);
2503 static JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2505 throw CYJSError(context, "incorrect number of arguments to Selector constructor");
2507 const char *name(CYPoolCString(pool, context, arguments[0]));
2508 return CYMakeSelector(context, sel_registerName(name));
2511 static JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2513 throw CYJSError(context, "incorrect number of arguments to Instance constructor");
2514 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2515 return CYMakeInstance(context, self, false);
2518 static JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2519 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2520 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2523 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2524 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2525 Type_privateData *typical(internal->GetType());
2530 if (typical == NULL) {
2534 type = typical->type_;
2535 ffi = typical->ffi_;
2538 return CYMakePointer(context, &internal->value_, _not(size_t), type, ffi, object);
2541 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2542 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2543 return Instance::Make(context, (id) object_getClass(internal->GetValue()));
2546 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2547 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2548 id self(internal->GetValue());
2549 if (!CYIsClass(self))
2550 return CYJSUndefined(context);
2551 return CYGetClassPrototype(context, self);
2554 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
2555 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2556 id self(internal->GetValue());
2557 if (!CYIsClass(self))
2558 return CYJSUndefined(context);
2559 return Messages::Make(context, (Class) self);
2562 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2563 if (!CYJSValueIsNSObject(context, _this))
2566 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2567 return CYCastJSValue(context, CYJSString(context, CYCastNSCYON(internal->GetValue(), false)));
2570 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2571 if (!CYJSValueIsNSObject(context, _this))
2574 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2575 id value(internal->GetValue());
2582 key = CYCastNSString(NULL, context, CYJSString(context, arguments[0]));
2584 if (!CYImplements(value, object_getClass(value), @selector(cy$toJSON:inContext:)))
2585 return CYJSUndefined(context);
2586 else if (JSValueRef json = [value cy$toJSON:key inContext:context])
2589 return CYCastJSValue(context, CYJSString(context, [value description]));
2591 } CYCatch(NULL) return /*XXX*/ NULL; }
2593 static JSValueRef Instance_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2594 if (!CYJSValueIsNSObject(context, _this))
2597 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2598 id value(internal->GetValue());
2600 if (![value respondsToSelector:@selector(cy$valueOfInContext:)])
2603 if (JSValueRef result = [value cy$valueOfInContext:context])
2607 } CYCatch(NULL) return /*XXX*/ NULL; }
2609 static JSValueRef Instance_callAsFunction_toPointer(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2610 if (!CYJSValueIsNSObject(context, _this))
2613 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2614 // XXX: but... but... THIS ISN'T A POINTER! :(
2615 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->GetValue()));
2616 } CYCatch(NULL) return /*XXX*/ NULL; }
2618 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2619 if (!CYJSValueIsNSObject(context, _this))
2622 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2623 id value(internal->GetValue());
2626 // XXX: this seems like a stupid implementation; what if it crashes? why not use the CYONifier backend?
2627 return CYCastJSValue(context, CYJSString(context, [value description]));
2629 } CYCatch(NULL) return /*XXX*/ NULL; }
2631 static JSValueRef Class_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2632 if (!CYJSValueIsNSObject(context, _this))
2635 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2636 id value(internal->GetValue());
2638 if (!CYIsClass(value))
2639 CYThrow("non-Class object cannot be used as Type");
2641 // XXX: this is a very silly implementation
2643 std::ostringstream type;
2645 type << class_getName(value);
2649 return CYMakeType(context, type.str().c_str());
2651 } CYCatch(NULL) return /*XXX*/ NULL; }
2653 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2654 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2655 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2658 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2659 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2662 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2663 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2664 const char *name(sel_getName(internal->GetValue()));
2667 NSString *string([NSString stringWithFormat:@"@selector(%s)", name]);
2668 return CYCastJSValue(context, CYJSString(context, string));
2670 } CYCatch(NULL) return /*XXX*/ NULL; }
2672 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2674 throw CYJSError(context, "incorrect number of arguments to Selector.type");
2677 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2678 SEL sel(internal->GetValue());
2680 objc_method *method;
2681 if (Class _class = CYCastClass(pool, context, arguments[0]))
2682 method = class_getInstanceMethod(_class, sel);
2686 const char *encoding(CYPoolTypeEncoding(pool, context, sel, method));
2687 if (encoding == NULL)
2688 return CYJSNull(context);
2690 sig::Signature signature;
2691 sig::Parse(pool, &signature, encoding, &Structor_);
2692 return CYMakeType(context, &signature);
2695 static JSStaticValue Selector_staticValues[2] = {
2696 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2697 {NULL, NULL, NULL, 0}
2700 static JSStaticValue Instance_staticValues[5] = {
2701 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2702 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2703 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2704 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2705 {NULL, NULL, NULL, 0}
2708 static JSStaticFunction Instance_staticFunctions[7] = {
2709 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2710 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2711 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2712 {"valueOf", &Instance_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2713 {"toPointer", &Instance_callAsFunction_toPointer, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2714 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2718 static JSStaticFunction Class_staticFunctions[2] = {
2719 {"pointerTo", &Class_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2723 static JSStaticFunction Internal_staticFunctions[2] = {
2724 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2728 static JSStaticFunction Selector_staticFunctions[5] = {
2729 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2730 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2731 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2732 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2737 JSValueRef NSCFType$cy$toJSON$inContext$(id self, SEL sel, JSValueRef key, JSContextRef context) { CYObjectiveTry_ {
2738 return CYCastJSValue(context, [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease]);
2739 } CYObjectiveCatch }
2742 void CYObjectiveC_Initialize() { /*XXX*/ JSContextRef context(NULL); CYPoolTry {
2743 $objc_setAssociatedObject = reinterpret_cast<void (*)(id, void *, id value, objc_AssociationPolicy)>(dlsym(RTLD_DEFAULT, "objc_setAssociatedObject"));
2744 $objc_getAssociatedObject = reinterpret_cast<id (*)(id, void *)>(dlsym(RTLD_DEFAULT, "objc_getAssociatedObject"));
2745 $objc_removeAssociatedObjects = reinterpret_cast<void (*)(id)>(dlsym(RTLD_DEFAULT, "objc_removeAssociatedObjects"));
2747 CYPool &pool(CYGetGlobalPool());
2749 Object_type = new(pool) Type_privateData("@");
2750 Selector_type = new(pool) Type_privateData(":");
2752 NSArray_ = objc_getClass("NSArray");
2753 NSBlock_ = objc_getClass("NSBlock");
2754 NSDictionary_ = objc_getClass("NSDictionary");
2755 NSString_ = objc_getClass("NSString");
2756 Object_ = objc_getClass("Object");
2759 __NSMallocBlock__ = objc_getClass("__NSMallocBlock__");
2761 // XXX: apparently, iOS now has both of these
2762 NSCFBoolean_ = objc_getClass("__NSCFBoolean");
2763 if (NSCFBoolean_ == nil)
2764 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2766 NSCFType_ = objc_getClass("NSCFType");
2768 NSZombie_ = objc_getClass("_NSZombie_");
2770 banned_.insert(Object_);
2771 banned_.insert(objc_getClass("__NSAtom"));
2772 banned_.insert(objc_getClass("__NSGenericDeallocHandler"));
2773 banned_.insert(objc_getClass("NSMessageBuilder"));
2774 banned_.insert(objc_getClass("__NSMessageBuilder"));
2776 NSBoolNumber_ = objc_getClass("NSBoolNumber");
2779 JSClassDefinition definition;
2781 definition = kJSClassDefinitionEmpty;
2782 definition.className = "Instance";
2783 definition.staticValues = Instance_staticValues;
2784 definition.staticFunctions = Instance_staticFunctions;
2785 definition.hasProperty = &Instance_hasProperty;
2786 definition.getProperty = &Instance_getProperty;
2787 definition.setProperty = &Instance_setProperty;
2788 definition.deleteProperty = &Instance_deleteProperty;
2789 definition.getPropertyNames = &Instance_getPropertyNames;
2790 definition.callAsConstructor = &Instance_callAsConstructor;
2791 definition.callAsFunction = &Instance_callAsFunction;
2792 definition.hasInstance = &Instance_hasInstance;
2793 definition.finalize = &CYFinalize;
2794 Instance_ = JSClassCreate(&definition);
2796 definition.className = "ArrayInstance";
2797 ArrayInstance_ = JSClassCreate(&definition);
2799 definition.className = "FunctionInstance";
2800 FunctionInstance_ = JSClassCreate(&definition);
2802 definition.className = "ObjectInstance";
2803 ObjectInstance_ = JSClassCreate(&definition);
2805 definition.className = "StringInstance";
2806 StringInstance_ = JSClassCreate(&definition);
2808 definition = kJSClassDefinitionEmpty;
2809 definition.className = "Class";
2810 definition.staticFunctions = Class_staticFunctions;
2811 Class_ = JSClassCreate(&definition);
2813 definition = kJSClassDefinitionEmpty;
2814 definition.className = "Internal";
2815 definition.staticFunctions = Internal_staticFunctions;
2816 definition.hasProperty = &Internal_hasProperty;
2817 definition.getProperty = &Internal_getProperty;
2818 definition.setProperty = &Internal_setProperty;
2819 definition.getPropertyNames = &Internal_getPropertyNames;
2820 definition.finalize = &CYFinalize;
2821 Internal_ = JSClassCreate(&definition);
2823 definition = kJSClassDefinitionEmpty;
2824 definition.className = "Message";
2825 definition.staticFunctions = cy::Functor::StaticFunctions;
2826 definition.callAsFunction = &Message_callAsFunction;
2827 definition.finalize = &CYFinalize;
2828 Message_ = JSClassCreate(&definition);
2830 definition = kJSClassDefinitionEmpty;
2831 definition.className = "Messages";
2832 definition.hasProperty = &Messages_hasProperty;
2833 definition.getProperty = &Messages_getProperty;
2834 definition.setProperty = &Messages_setProperty;
2835 #if 0 && OBJC_API_VERSION < 2
2836 definition.deleteProperty = &Messages_deleteProperty;
2838 definition.getPropertyNames = &Messages_getPropertyNames;
2839 definition.finalize = &CYFinalize;
2840 Messages_ = JSClassCreate(&definition);
2842 definition = kJSClassDefinitionEmpty;
2843 definition.className = "Selector";
2844 definition.staticValues = Selector_staticValues;
2845 definition.staticFunctions = Selector_staticFunctions;
2846 definition.callAsFunction = &Selector_callAsFunction;
2847 definition.finalize = &CYFinalize;
2848 Selector_ = JSClassCreate(&definition);
2850 definition = kJSClassDefinitionEmpty;
2851 definition.className = "Super";
2852 definition.staticFunctions = Internal_staticFunctions;
2853 definition.finalize = &CYFinalize;
2854 Super_ = JSClassCreate(&definition);
2856 definition = kJSClassDefinitionEmpty;
2857 definition.className = "ObjectiveC::Classes";
2858 definition.getProperty = &ObjectiveC_Classes_getProperty;
2859 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2860 ObjectiveC_Classes_ = JSClassCreate(&definition);
2862 definition = kJSClassDefinitionEmpty;
2863 definition.className = "ObjectiveC::Constants";
2864 definition.getProperty = &ObjectiveC_Constants_getProperty;
2865 definition.getPropertyNames = &ObjectiveC_Constants_getPropertyNames;
2866 ObjectiveC_Constants_ = JSClassCreate(&definition);
2868 #if OBJC_API_VERSION >= 2
2869 definition = kJSClassDefinitionEmpty;
2870 definition.className = "ObjectiveC::Images";
2871 definition.getProperty = &ObjectiveC_Images_getProperty;
2872 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2873 ObjectiveC_Images_ = JSClassCreate(&definition);
2875 definition = kJSClassDefinitionEmpty;
2876 definition.className = "ObjectiveC::Image::Classes";
2877 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2878 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2879 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2882 definition = kJSClassDefinitionEmpty;
2883 definition.className = "ObjectiveC::Protocols";
2884 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2885 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2886 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2889 // XXX: this is horrible; there has to be a better way to do this
2891 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}32@0:8@16^{OpaqueJSContext=}24");
2893 class_addMethod(NSCFType_, @selector(cy$toJSON:inContext:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON$inContext$), "^{OpaqueJSValue=}16@0:4@8^{OpaqueJSContext=}12");
2898 void CYObjectiveC_SetupContext(JSContextRef context) { CYPoolTry {
2899 JSObjectRef global(CYGetGlobalObject(context));
2900 JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
2901 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
2902 JSObjectRef all(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("all"))));
2903 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
2905 JSObjectRef ObjectiveC(JSObjectMake(context, NULL, NULL));
2906 CYSetProperty(context, cycript, CYJSString("ObjectiveC"), ObjectiveC);
2908 JSObjectRef protocols(JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2909 CYSetProperty(context, ObjectiveC, CYJSString("protocols"), protocols);
2910 CYArrayPush(context, alls, protocols);
2912 JSObjectRef classes(JSObjectMake(context, ObjectiveC_Classes_, NULL));
2913 CYSetProperty(context, ObjectiveC, CYJSString("classes"), classes);
2914 CYArrayPush(context, alls, classes);
2916 JSObjectRef constants(JSObjectMake(context, ObjectiveC_Constants_, NULL));
2917 CYSetProperty(context, ObjectiveC, CYJSString("constants"), constants);
2918 CYArrayPush(context, alls, constants);
2920 #if OBJC_API_VERSION >= 2
2921 CYSetProperty(context, ObjectiveC, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2924 JSObjectRef Class(JSObjectMakeConstructor(context, Class_, NULL));
2925 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
2926 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
2927 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
2928 JSObjectRef Super(JSObjectMakeConstructor(context, Super_, &Super_new));
2930 JSObjectRef Instance_prototype(CYCastJSObject(context, CYGetProperty(context, Instance, prototype_s)));
2931 CYSetProperty(context, cy, CYJSString("Instance_prototype"), Instance_prototype);
2933 JSObjectRef ArrayInstance(JSObjectMakeConstructor(context, ArrayInstance_, NULL));
2934 JSObjectRef ArrayInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ArrayInstance, prototype_s)));
2935 CYSetProperty(context, cy, CYJSString("ArrayInstance_prototype"), ArrayInstance_prototype);
2936 JSObjectRef Array_prototype(CYGetCachedObject(context, CYJSString("Array_prototype")));
2937 JSObjectSetPrototype(context, ArrayInstance_prototype, Array_prototype);
2939 JSObjectRef FunctionInstance(JSObjectMakeConstructor(context, FunctionInstance_, NULL));
2940 JSObjectRef FunctionInstance_prototype(CYCastJSObject(context, CYGetProperty(context, FunctionInstance, prototype_s)));
2941 CYSetProperty(context, cy, CYJSString("FunctionInstance_prototype"), FunctionInstance_prototype);
2942 JSObjectRef Function_prototype(CYGetCachedObject(context, CYJSString("Function_prototype")));
2943 JSObjectSetPrototype(context, FunctionInstance_prototype, Function_prototype);
2945 JSObjectRef ObjectInstance(JSObjectMakeConstructor(context, ObjectInstance_, NULL));
2946 JSObjectRef ObjectInstance_prototype(CYCastJSObject(context, CYGetProperty(context, ObjectInstance, prototype_s)));
2947 CYSetProperty(context, cy, CYJSString("ObjectInstance_prototype"), ObjectInstance_prototype);
2948 JSObjectRef Object_prototype(CYGetCachedObject(context, CYJSString("Object_prototype")));
2949 JSObjectSetPrototype(context, ObjectInstance_prototype, Object_prototype);
2951 JSObjectRef StringInstance(JSObjectMakeConstructor(context, StringInstance_, NULL));
2952 JSObjectRef StringInstance_prototype(CYCastJSObject(context, CYGetProperty(context, StringInstance, prototype_s)));
2953 CYSetProperty(context, cy, CYJSString("StringInstance_prototype"), StringInstance_prototype);
2954 JSObjectRef String_prototype(CYGetCachedObject(context, CYJSString("String_prototype")));
2955 JSObjectSetPrototype(context, StringInstance_prototype, String_prototype);
2957 JSObjectRef Class_prototype(CYCastJSObject(context, CYGetProperty(context, Class, prototype_s)));
2958 CYSetProperty(context, cy, CYJSString("Class_prototype"), Class_prototype);
2959 JSObjectSetPrototype(context, Class_prototype, Instance_prototype);
2961 CYSetProperty(context, cycript, CYJSString("Instance"), Instance);
2962 CYSetProperty(context, cycript, CYJSString("Selector"), Selector);
2963 CYSetProperty(context, cycript, CYJSString("Super"), Super);
2965 JSObjectRef box(JSObjectMakeFunctionWithCallback(context, CYJSString("box"), &Instance_box_callAsFunction));
2966 CYSetProperty(context, Instance, CYJSString("box"), box);
2969 CYSetProperty(context, all, CYJSString("choose"), &choose, kJSPropertyAttributeDontEnum);
2972 CYSetProperty(context, all, CYJSString("objc_msgSend"), &$objc_msgSend, kJSPropertyAttributeDontEnum);
2974 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Message, prototype_s)), Function_prototype);
2975 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Selector, prototype_s)), Function_prototype);
2978 static CYHooks CYObjectiveCHooks = {
2979 &CYObjectiveC_ExecuteStart,
2980 &CYObjectiveC_ExecuteEnd,
2981 &CYObjectiveC_CallFunction,
2982 &CYObjectiveC_Initialize,
2983 &CYObjectiveC_SetupContext,
2984 &CYObjectiveC_PoolFFI,
2985 &CYObjectiveC_FromFFI,
2988 struct CYObjectiveC {
2990 hooks_ = &CYObjectiveCHooks;
2991 // XXX: evil magic juju to make this actually take effect on a Mac when compiled with autoconf/libtool doom!
2992 _assert(hooks_ != NULL);
2996 extern "C" void CydgetSetupContext(JSGlobalContextRef context) { CYObjectiveTry_ {
2997 CYSetupContext(context);
2998 } CYObjectiveCatch }
3000 extern "C" void CydgetMemoryParse(const uint16_t **data, size_t *size) { try {
3003 CYUTF8String utf8(CYPoolUTF8String(pool, CYUTF16String(*data, *size)));
3004 utf8 = CYPoolCode(pool, utf8);
3006 CYUTF16String utf16(CYPoolUTF16String(pool, CYUTF8String(utf8.data, utf8.size)));
3007 size_t bytes(utf16.size * sizeof(uint16_t));
3008 uint16_t *copy(reinterpret_cast<uint16_t *>(malloc(bytes)));
3009 memcpy(copy, utf16.data, bytes);
3013 } catch (const CYException &exception) {
3015 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"%s", exception.PoolCString(pool)] userInfo:nil];